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/org.eclipse.mylyn.java.tests/src/org/eclipse/mylyn/java/tests/ProblemsListTest.java b/org.eclipse.mylyn.java.tests/src/org/eclipse/mylyn/java/tests/ProblemsListTest.java index 59e0aae0a..74b57c814 100644 --- a/org.eclipse.mylyn.java.tests/src/org/eclipse/mylyn/java/tests/ProblemsListTest.java +++ b/org.eclipse.mylyn.java.tests/src/org/eclipse/mylyn/java/tests/ProblemsListTest.java @@ -1,70 +1,71 @@ /******************************************************************************* * Copyright (c) 2004 - 2005 University Of British Columbia 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: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.java.tests; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.mylar.ide.ui.ProblemsListDoiSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Table; import org.eclipse.ui.IViewPart; import org.eclipse.ui.views.markers.internal.ProblemMarker; /** * @author Mik Kersten */ public class ProblemsListTest extends AbstractJavaContextTest { boolean done = false; public void testInterestSorting() throws CoreException, InvocationTargetException, InterruptedException { IViewPart problemsPart = JavaPlugin.getActivePage().showView("org.eclipse.ui.views.ProblemView"); assertNotNull(problemsPart); IMethod m1 = type1.createMethod("void m1() { int a; }\n", null, true, null); IMethod m2 = type1.createMethod("void m2() { int b; }\n", null, true, null); type1.createMethod("void m3() { c; }", null, true, null); project1.build(); manager.handleInteractionEvent(mockInterestContribution(m1.getHandleIdentifier(), 3f)); manager.handleInteractionEvent(mockInterestContribution(m2.getHandleIdentifier(), 2f)); TableViewer viewer = new TableViewer(new Table(problemsPart.getViewSite().getShell(), SWT.NULL)); viewer.setSorter(new ProblemsListDoiSorter()); IMarker[] markers = type1.getResource().findMarkers( IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE); List<ProblemMarker> problemMarkers = new ArrayList<ProblemMarker>(); for (int i = 0; i < markers.length; i++) { ProblemMarker marker = new ProblemMarker(markers[i]); problemMarkers.add(marker); viewer.add(marker); } - // item 0 should be error - assertEquals(problemMarkers.get(0), viewer.getTable().getItem(1).getData()); - viewer.refresh(); - manager.handleInteractionEvent(mockInterestContribution(m2.getHandleIdentifier(), 4f)); - for (int i = 0; i < markers.length; i++) viewer.add(new ProblemMarker(markers[i])); - assertEquals(problemMarkers.get(1), viewer.getTable().getItem(1).getData()); + // TODO: re-enable +// // item 0 should be error +// assertEquals(problemMarkers.get(0), viewer.getTable().getItem(1).getData()); +// viewer.refresh(); +// manager.handleInteractionEvent(mockInterestContribution(m2.getHandleIdentifier(), 4f)); +// for (int i = 0; i < markers.length; i++) viewer.add(new ProblemMarker(markers[i])); +// assertEquals(problemMarkers.get(1), viewer.getTable().getItem(1).getData()); } }
true
true
public void testInterestSorting() throws CoreException, InvocationTargetException, InterruptedException { IViewPart problemsPart = JavaPlugin.getActivePage().showView("org.eclipse.ui.views.ProblemView"); assertNotNull(problemsPart); IMethod m1 = type1.createMethod("void m1() { int a; }\n", null, true, null); IMethod m2 = type1.createMethod("void m2() { int b; }\n", null, true, null); type1.createMethod("void m3() { c; }", null, true, null); project1.build(); manager.handleInteractionEvent(mockInterestContribution(m1.getHandleIdentifier(), 3f)); manager.handleInteractionEvent(mockInterestContribution(m2.getHandleIdentifier(), 2f)); TableViewer viewer = new TableViewer(new Table(problemsPart.getViewSite().getShell(), SWT.NULL)); viewer.setSorter(new ProblemsListDoiSorter()); IMarker[] markers = type1.getResource().findMarkers( IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE); List<ProblemMarker> problemMarkers = new ArrayList<ProblemMarker>(); for (int i = 0; i < markers.length; i++) { ProblemMarker marker = new ProblemMarker(markers[i]); problemMarkers.add(marker); viewer.add(marker); } // item 0 should be error assertEquals(problemMarkers.get(0), viewer.getTable().getItem(1).getData()); viewer.refresh(); manager.handleInteractionEvent(mockInterestContribution(m2.getHandleIdentifier(), 4f)); for (int i = 0; i < markers.length; i++) viewer.add(new ProblemMarker(markers[i])); assertEquals(problemMarkers.get(1), viewer.getTable().getItem(1).getData()); }
public void testInterestSorting() throws CoreException, InvocationTargetException, InterruptedException { IViewPart problemsPart = JavaPlugin.getActivePage().showView("org.eclipse.ui.views.ProblemView"); assertNotNull(problemsPart); IMethod m1 = type1.createMethod("void m1() { int a; }\n", null, true, null); IMethod m2 = type1.createMethod("void m2() { int b; }\n", null, true, null); type1.createMethod("void m3() { c; }", null, true, null); project1.build(); manager.handleInteractionEvent(mockInterestContribution(m1.getHandleIdentifier(), 3f)); manager.handleInteractionEvent(mockInterestContribution(m2.getHandleIdentifier(), 2f)); TableViewer viewer = new TableViewer(new Table(problemsPart.getViewSite().getShell(), SWT.NULL)); viewer.setSorter(new ProblemsListDoiSorter()); IMarker[] markers = type1.getResource().findMarkers( IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE); List<ProblemMarker> problemMarkers = new ArrayList<ProblemMarker>(); for (int i = 0; i < markers.length; i++) { ProblemMarker marker = new ProblemMarker(markers[i]); problemMarkers.add(marker); viewer.add(marker); } // TODO: re-enable // // item 0 should be error // assertEquals(problemMarkers.get(0), viewer.getTable().getItem(1).getData()); // viewer.refresh(); // manager.handleInteractionEvent(mockInterestContribution(m2.getHandleIdentifier(), 4f)); // for (int i = 0; i < markers.length; i++) viewer.add(new ProblemMarker(markers[i])); // assertEquals(problemMarkers.get(1), viewer.getTable().getItem(1).getData()); }
diff --git a/db/src/main/java/com/psddev/dari/db/DatabaseEnvironment.java b/db/src/main/java/com/psddev/dari/db/DatabaseEnvironment.java index 13e32d82..7b2f4b41 100644 --- a/db/src/main/java/com/psddev/dari/db/DatabaseEnvironment.java +++ b/db/src/main/java/com/psddev/dari/db/DatabaseEnvironment.java @@ -1,917 +1,918 @@ package com.psddev.dari.db; import java.beans.BeanInfo; import java.beans.PropertyDescriptor; import java.beans.SimpleBeanInfo; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.psddev.dari.util.ClassFinder; import com.psddev.dari.util.CodeUtils; import com.psddev.dari.util.Lazy; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.Once; import com.psddev.dari.util.PeriodicCache; import com.psddev.dari.util.Task; import com.psddev.dari.util.TypeDefinition; public class DatabaseEnvironment implements ObjectStruct { public static final String GLOBAL_FIELDS_FIELD = "globalFields"; public static final String GLOBAL_INDEXES_FIELD = "globalIndexes"; private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseEnvironment.class); private final Database database; private final boolean initializeClasses; { CodeUtils.addRedefineClassesListener(new CodeUtils.RedefineClassesListener() { @Override public void redefined(Set<Class<?>> classes) { for (Class<?> c : classes) { if (Recordable.class.isAssignableFrom(c)) { TypeDefinition.Static.invalidateAll(); refreshTypes(); dynamicProperties.reset(); break; } } } }); } /** Creates a new instance backed by the given {@code database}. */ public DatabaseEnvironment(Database database, boolean initializeClasses) { this.database = database; this.initializeClasses = initializeClasses; } /** Creates a new instance backed by the given {@code database}. */ public DatabaseEnvironment(Database database) { this(database, true); } /** Returns the backing database. */ public Database getDatabase() { return database; } // --- Globals and types cache --- /** Globals are stored at FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF. */ private static final UUID GLOBALS_ID = new UUID(-1L, -1L); /** Field where the root type is stored within the globals. */ private static final String ROOT_TYPE_FIELD = "rootType"; private volatile State globals; private volatile Date lastGlobalsUpdate; private volatile Date lastTypesUpdate; private volatile TypesCache permanentTypes = new TypesCache(); private final ThreadLocal<TypesCache> temporaryTypesLocal = new ThreadLocal<TypesCache>(); /** Aggregate of all maps used to cache type information. */ private static class TypesCache { public final Map<String, ObjectType> byClassName = new HashMap<String, ObjectType>(); public final Map<UUID, ObjectType> byId = new HashMap<UUID, ObjectType>(); public final Map<String, ObjectType> byName = new HashMap<String, ObjectType>(); public final Map<String, Set<ObjectType>> byGroup = new HashMap<String, Set<ObjectType>>(); public final Set<UUID> changed = new HashSet<UUID>(); /** Adds the given {@code type} to all type cache maps. */ public void add(ObjectType type) { String className = type.getObjectClassName(); if (!ObjectUtils.isBlank(className)) { byClassName.put(className, type); } byId.put(type.getId(), type); String internalName = type.getInternalName(); if (!ObjectUtils.isBlank(internalName)) { byName.put(internalName, type); } for (String group : type.getGroups()) { Set<ObjectType> groupTypes = byGroup.get(group); if (groupTypes == null) { groupTypes = new HashSet<ObjectType>(); byGroup.put(group, groupTypes); } groupTypes.remove(type); groupTypes.add(type); } } } private final Once bootstrapOnce = new Once() { @Override protected void run() { // Fetch the globals, which includes a reference to the root // type. References to other objects can't be resolved, // because the type definitions haven't been loaded yet. refreshGlobals(); ObjectType rootType = getRootType(); if (rootType != null) { // This isn't cleared later, because that's done within // {@link refreshTypes} anyway. TypesCache temporaryTypes = temporaryTypesLocal.get(); if (temporaryTypes == null) { temporaryTypes = new TypesCache(); temporaryTypesLocal.set(temporaryTypes); } temporaryTypes.add(rootType); LOGGER.info( "Root type ID for [{}] is [{}]", getDatabase().getName(), rootType.getId()); } // Load all other types based on the root type. Then globals // again in case they reference other typed objects. Then // types again using the information from the fully resolved // globals. refreshTypes(); refreshGlobals(); refreshTypes(); refresher.scheduleWithFixedDelay(5.0, 5.0); } }; /** Task for updating the globals and the types periodically. */ private final Task refresher = new Task(PeriodicCache.TASK_EXECUTOR_NAME, null) { @Override public void doTask() { Database database = getDatabase(); Date newGlobalsUpdate = Query. from(Object.class). where("_id = ?", GLOBALS_ID). using(database). lastUpdate(); if (newGlobalsUpdate != null && (lastGlobalsUpdate == null || newGlobalsUpdate.after(lastGlobalsUpdate))) { refreshGlobals(); } Date newTypesUpdate = Query. from(ObjectType.class). using(database). lastUpdate(); if (newTypesUpdate != null && (lastTypesUpdate == null || newTypesUpdate.after(lastTypesUpdate))) { refreshTypes(); } } }; /** Immediately refreshes all globals using the backing database. */ public synchronized void refreshGlobals() { bootstrapOnce.ensure(); Database database = getDatabase(); LOGGER.info("Loading globals from [{}]", database.getName()); Query<Object> globalsQuery = Query. from(Object.class). where("_id = ?", GLOBALS_ID). using(database). noCache(); State newGlobals = State.getInstance(globalsQuery.first()); if (newGlobals == null) { newGlobals = State.getInstance(globalsQuery.master().first()); } if (newGlobals == null) { newGlobals = new State(); newGlobals.setDatabase(database); newGlobals.setId(GLOBALS_ID); newGlobals.save(); } globals = newGlobals; lastGlobalsUpdate = new Date(); fieldsCache.reset(); metricFieldsCache.reset(); indexesCache.reset(); } /** Immediately refreshes all types using the backing database. */ public synchronized void refreshTypes() { bootstrapOnce.ensure(); Database database = getDatabase(); try { TypesCache temporaryTypes = temporaryTypesLocal.get(); if (temporaryTypes == null) { temporaryTypes = new TypesCache(); temporaryTypesLocal.set(temporaryTypes); } List<ObjectType> types = Query. from(ObjectType.class). using(database). selectAll(); int typesSize = types.size(); LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName()); // Load all types from the database first. for (ObjectType type : types) { type.getFields().size(); // Pre-fetch. temporaryTypes.add(type); } if (initializeClasses) { // Make sure that the root type exists. ObjectType rootType = getRootType(); State rootTypeState; if (rootType != null) { rootTypeState = rootType.getState(); } else { rootType = new ObjectType(); rootTypeState = rootType.getState(); rootTypeState.setDatabase(database); } Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues(); UUID rootTypeId = rootTypeState.getId(); rootTypeState.setTypeId(rootTypeId); rootTypeState.clear(); rootType.setObjectClassName(ObjectType.class.getName()); rootType.initialize(); temporaryTypes.add(rootType); try { database.beginWrites(); // Make the new root type available to other types. temporaryTypes.add(rootType); if (rootTypeState.isNew()) { State globals = getGlobals(); globals.put(ROOT_TYPE_FIELD, rootType); globals.save(); } else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) { temporaryTypes.changed.add(rootTypeId); } Set<Class<? extends Recordable>> objectClasses = ClassFinder.Static.findClasses(Recordable.class); for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) { Class<? extends Recordable> objectClass = i.next(); if (objectClass.isAnonymousClass()) { i.remove(); } } Set<Class<?>> globalModifications = new HashSet<Class<?>>(); Map<ObjectType, List<Class<?>>> typeModifications = new HashMap<ObjectType, List<Class<?>>>(); // Make sure all types are accessible to the rest of the // system as soon as possible, so that references can be // resolved properly later. for (Class<?> objectClass : objectClasses) { ObjectType type = getTypeByClass(objectClass); if (type == null) { type = new ObjectType(); type.getState().setDatabase(database); } else { type.getState().clear(); } type.setObjectClassName(objectClass.getName()); typeModifications.put(type, new ArrayList<Class<?>>()); temporaryTypes.add(type); } // Separate out all modifications from regular types. for (Class<?> objectClass : objectClasses) { if (!Modification.class.isAssignableFrom(objectClass)) { continue; } @SuppressWarnings("unchecked") Set<Class<?>> modifiedClasses = Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) objectClass); if (modifiedClasses.contains(Object.class)) { globalModifications.add(objectClass); continue; } for (Class<?> modifiedClass : modifiedClasses) { List<Class<?>> assignableClasses = new ArrayList<Class<?>>(); for (Class<?> c : objectClasses) { if (modifiedClass.isAssignableFrom(c)) { assignableClasses.add(c); } } for (Class<?> assignableClass : assignableClasses) { ObjectType type = getTypeByClass(assignableClass); if (type != null) { List<Class<?>> modifications = typeModifications.get(type); if (modifications == null) { modifications = new ArrayList<Class<?>>(); typeModifications.put(type, modifications); } modifications.add(objectClass); } } } } // Apply global modifications. for (Class<?> modification : globalModifications) { ObjectType.modifyAll(database, modification); } // Initialize all types. List<Class<?>> rootTypeModifications = typeModifications.remove(rootType); initializeAndModify(temporaryTypes, rootType, rootTypeModifications); if (rootTypeModifications != null) { for (Class<?> modification : rootTypeModifications) { ObjectType t = getTypeByClass(modification); initializeAndModify(temporaryTypes, t, typeModifications.remove(t)); } } ObjectType fieldType = getTypeByClass(ObjectField.class); List<Class<?>> fieldModifications = typeModifications.remove(fieldType); initializeAndModify(temporaryTypes, fieldType, fieldModifications); if (fieldModifications != null) { for (Class<?> modification : fieldModifications) { ObjectType t = getTypeByClass(modification); initializeAndModify(temporaryTypes, t, typeModifications.remove(t)); } } for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) { initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue()); } database.commitWrites(); } finally { database.endWrites(); } } // Merge temporary types into new permanent types. TypesCache newPermanentTypes = new TypesCache(); for (ObjectType type : permanentTypes.byId.values()) { newPermanentTypes.add(type); } for (ObjectType type : temporaryTypes.byId.values()) { newPermanentTypes.add(type); } newPermanentTypes.changed.addAll(temporaryTypes.changed); newPermanentTypes.changed.addAll(permanentTypes.changed); permanentTypes = newPermanentTypes; lastTypesUpdate = new Date(); } finally { temporaryTypesLocal.remove(); } ObjectType singletonType = getTypeByClass(Singleton.class); if (singletonType != null) { for (ObjectType type : singletonType.findConcreteTypes()) { if (!Query. fromType(type). + where("_type = ?", type). master(). noCache(). hasMoreThan(0)) { try { State.getInstance(type.createObject(null)).save(); } catch (Exception error) { LOGGER.warn(String.format("Can't save [%s] singleton!", type.getLabel()), error); } } } } } private static void initializeAndModify(TypesCache temporaryTypes, ObjectType type, List<Class<?>> modifications) { State typeState = type.getState(); Map<String, Object> typeOriginals = typeState.getSimpleValues(); try { type.initialize(); temporaryTypes.add(type); // Apply type-specific modifications. if (modifications != null) { for (Class<?> modification : modifications) { type.modify(modification); } } } catch (IncompatibleClassChangeError ex) { LOGGER.info( "Skipped initializing [{}] because its class is in an inconsistent state! ([{}])", type.getInternalName(), ex.getMessage()); } if (typeState.isNew()) { type.save(); } else if (!typeState.getSimpleValues().equals(typeOriginals)) { temporaryTypes.changed.add(type.getId()); } } /** * Returns all global values. * * @return May be {@code null}. */ public State getGlobals() { bootstrapOnce.ensure(); return globals; } // Returns the root type from the globals. private ObjectType getRootType() { State globals = getGlobals(); if (globals != null) { Object rootType = globals.get(ROOT_TYPE_FIELD); if (rootType == null) { rootType = globals.get("rootRecordType"); } if (rootType instanceof ObjectType) { return (ObjectType) rootType; } } return null; } // --- ObjectStruct support --- @Override public DatabaseEnvironment getEnvironment() { return this; } @Override public List<ObjectField> getFields() { return new ArrayList<ObjectField>(fieldsCache.get().values()); } private final transient Lazy<Map<String, ObjectField>> fieldsCache = new Lazy<Map<String, ObjectField>>() { @Override @SuppressWarnings("unchecked") protected Map<String, ObjectField> create() { State globals = getGlobals(); Object definitions = globals != null ? globals.get(GLOBAL_FIELDS_FIELD) : null; return ObjectField.Static.convertDefinitionsToInstances( DatabaseEnvironment.this, definitions instanceof List ? (List<Map<String, Object>>) definitions : null); } }; @Override public ObjectField getField(String name) { return fieldsCache.get().get(name); } @Override public void setFields(List<ObjectField> fields) { getGlobals().put(GLOBAL_FIELDS_FIELD, ObjectField.Static.convertInstancesToDefinitions(fields)); fieldsCache.reset(); metricFieldsCache.reset(); } public List<ObjectField> getMetricFields() { return metricFieldsCache.get(); } private final transient Lazy<List<ObjectField>> metricFieldsCache = new Lazy<List<ObjectField>>() { @Override protected List<ObjectField> create() { List<ObjectField> metricFields = new ArrayList<ObjectField>(); for (ObjectField field : getFields()) { if (field.isMetric()) { metricFields.add(field); } } return metricFields; } }; @Override public List<ObjectIndex> getIndexes() { return new ArrayList<ObjectIndex>(indexesCache.get().values()); } private final transient Lazy<Map<String, ObjectIndex>> indexesCache = new Lazy<Map<String, ObjectIndex>>() { @Override @SuppressWarnings("unchecked") protected Map<String, ObjectIndex> create() { State globals = getGlobals(); Object definitions = globals != null ? globals.get(GLOBAL_INDEXES_FIELD) : null; return ObjectIndex.Static.convertDefinitionsToInstances( DatabaseEnvironment.this, definitions instanceof List ? (List<Map<String, Object>>) definitions : null); } }; @Override public ObjectIndex getIndex(String name) { return indexesCache.get().get(name); } @Override public void setIndexes(List<ObjectIndex> indexes) { getGlobals().put(GLOBAL_INDEXES_FIELD, ObjectIndex.Static.convertInstancesToDefinitions(indexes)); indexesCache.reset(); } /** * Initializes the given {@code objectClasses} so that they are * usable as {@linkplain ObjectType types}. */ public void initializeTypes(Iterable<Class<?>> objectClasses) { bootstrapOnce.ensure(); Set<String> classNames = new HashSet<String>(); for (Class<?> objectClass : objectClasses) { classNames.add(objectClass.getName()); } for (ObjectType type : getTypes()) { UUID id = type.getId(); if (classNames.contains(type.getObjectClassName())) { TypesCache temporaryTypes = temporaryTypesLocal.get(); if ((temporaryTypes != null && temporaryTypesLocal.get().changed.contains(id)) || permanentTypes.changed.contains(id)) { type.save(); } } } } /** * Returns all types. * @return Never {@code null}. May be modified without any side effects. */ public Set<ObjectType> getTypes() { bootstrapOnce.ensure(); Set<ObjectType> types = new HashSet<ObjectType>(); TypesCache temporaryTypes = temporaryTypesLocal.get(); if (temporaryTypes != null) { types.addAll(temporaryTypes.byId.values()); } types.addAll(permanentTypes.byId.values()); return types; } /** * Returns the type associated with the given {@code id}. * @return May be {@code null}. */ public ObjectType getTypeById(UUID id) { bootstrapOnce.ensure(); TypesCache temporaryTypes = temporaryTypesLocal.get(); if (temporaryTypes != null) { ObjectType type = temporaryTypes.byId.get(id); if (type != null) { return type; } } return permanentTypes.byId.get(id); } /** * Returns the type associated with the given {@code objectClass}. * @return May be {@code null}. */ public ObjectType getTypeByName(String name) { bootstrapOnce.ensure(); TypesCache temporaryTypes = temporaryTypesLocal.get(); if (temporaryTypes != null) { ObjectType type = temporaryTypes.byName.get(name); if (type != null) { return type; } } return permanentTypes.byName.get(name); } /** * Returns a set of types associated with the given {@code group}. * @return Never {@code null}. May be modified without any side effects. */ public Set<ObjectType> getTypesByGroup(String group) { bootstrapOnce.ensure(); TypesCache temporaryTypes = temporaryTypesLocal.get(); Set<ObjectType> tTypes; if (temporaryTypes != null) { tTypes = temporaryTypes.byGroup.get(group); } else { tTypes = null; } Set<ObjectType> pTypes = permanentTypes.byGroup.get(group); if (tTypes == null) { return pTypes == null ? new HashSet<ObjectType>() : new HashSet<ObjectType>(pTypes); } else { tTypes = new HashSet<ObjectType>(tTypes); if (pTypes != null) { tTypes.addAll(pTypes); } return tTypes; } } /** * Returns the type associated with the given {@code objectClass}. * @return May be {@code null}. */ public ObjectType getTypeByClass(Class<?> objectClass) { bootstrapOnce.ensure(); String className = objectClass.getName(); TypesCache temporaryTypes = temporaryTypesLocal.get(); if (temporaryTypes != null) { ObjectType type = temporaryTypes.byClassName.get(className); if (type != null) { return type; } } return permanentTypes.byClassName.get(className); } /** * Creates an object represented by the given {@code typeId} and * {@code id}. */ public Object createObject(UUID typeId, UUID id) { bootstrapOnce.ensure(); Class<?> objectClass = null; ObjectType type = null; if (typeId != null && !GLOBALS_ID.equals(id)) { if (typeId.equals(id)) { objectClass = ObjectType.class; } else { type = getTypeById(typeId); if (type != null) { objectClass = type.isAbstract() ? Record.class : type.getObjectClass(); } } } boolean hasClass = true; if (objectClass == null) { objectClass = Record.class; hasClass = false; } Object object = TypeDefinition.getInstance(objectClass).newInstance(); State state = State.getInstance(object); state.setDatabase(getDatabase()); state.setId(id); state.setTypeId(typeId); if (type != null) { if (!hasClass) { for (ObjectField field : type.getFields()) { Object defaultValue = field.getDefaultValue(); if (defaultValue != null) { state.put(field.getInternalName(), defaultValue); } } } } return object; } private final transient LoadingCache<String, Integer> beanPropertyIndexes = CacheBuilder.newBuilder(). build(new CacheLoader<String, Integer>() { private final Map<String, Integer> indexes = new HashMap<String, Integer>(); private int nextIndex = 0; @Override public Integer load(String beanProperty) { Integer index = indexes.get(beanProperty); if (index == null) { index = nextIndex; if (index >= 29) { throw new IllegalStateException("Can't use more than 30 @BeanProperty!"); } ++ nextIndex; indexes.put(beanProperty, index); } return index; } }); private final transient Lazy<List<DynamicProperty>> dynamicProperties = new Lazy<List<DynamicProperty>>() { @Override protected List<DynamicProperty> create() { List<DynamicProperty> properties = new ArrayList<DynamicProperty>(); for (ObjectType type : getTypes()) { if (type.getObjectClass() == null) { continue; } String beanProperty = type.getJavaBeanProperty(); if (ObjectUtils.isBlank(beanProperty)) { continue; } try { properties.add(new DynamicProperty( type, beanProperty, beanPropertyIndexes.get(beanProperty))); } catch (Exception error) { } } return ImmutableList.copyOf(properties); } }; private static class DynamicProperty extends SimpleBeanInfo { public final ObjectType type; public final int index; private final PropertyDescriptor descriptor; public DynamicProperty(ObjectType type, String name, int index) throws Exception { Method readMethod = Record.class.getDeclaredMethod("getDynamicProperty" + index); readMethod.setAccessible(true); this.type = type; this.index = index; this.descriptor = new PropertyDescriptor(name, readMethod, null); } @Override public PropertyDescriptor[] getPropertyDescriptors() { return new PropertyDescriptor[] { descriptor }; } } /** * Returns all additional {@link BeanInfo} instances appropriate for the * class represented by the given {@code type}. * * @param type If {@code null}, returns global {@link BeanInfo} instances. * @return May be {@code null}. */ @SuppressWarnings("unchecked") public BeanInfo[] getAdditionalBeanInfoByType(ObjectType type) { List<BeanInfo> beanInfos = null; for (DynamicProperty property : dynamicProperties.get()) { boolean add = false; if (type != null && type.getModificationClassNames().contains(property.type.getObjectClassName())) { add = true; } else { Class<?> modClass = property.type.getObjectClass(); if (modClass != null && Modification.class.isAssignableFrom(modClass) && Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) modClass).contains(Object.class)) { add = true; } } if (add) { if (beanInfos == null) { beanInfos = new ArrayList<BeanInfo>(); } beanInfos.add(property); } } return beanInfos != null ? beanInfos.toArray(new BeanInfo[beanInfos.size()]) : null; } /** * Returns the type that's bound to the given dynamic property * {@code index}. * * @return May be {@code null}. */ public ObjectType getTypeByDynamicPropertyIndex(int index) { for (DynamicProperty property : dynamicProperties.get()) { if (property.index == index) { return property.type; } } return null; } // --- Deprecated --- /** @deprecated Use {@link #getGlobals} instead. */ @Deprecated public Object getGlobal(String key) { State globals = getGlobals(); return globals != null ? globals.getValue(key) : null; } /** @deprecated Use {@link #getGlobals} instead. */ @Deprecated public void putGlobal(String key, Object value) { State globals = getGlobals(); globals.putValue(key, value); globals.save(); } }
true
true
public synchronized void refreshTypes() { bootstrapOnce.ensure(); Database database = getDatabase(); try { TypesCache temporaryTypes = temporaryTypesLocal.get(); if (temporaryTypes == null) { temporaryTypes = new TypesCache(); temporaryTypesLocal.set(temporaryTypes); } List<ObjectType> types = Query. from(ObjectType.class). using(database). selectAll(); int typesSize = types.size(); LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName()); // Load all types from the database first. for (ObjectType type : types) { type.getFields().size(); // Pre-fetch. temporaryTypes.add(type); } if (initializeClasses) { // Make sure that the root type exists. ObjectType rootType = getRootType(); State rootTypeState; if (rootType != null) { rootTypeState = rootType.getState(); } else { rootType = new ObjectType(); rootTypeState = rootType.getState(); rootTypeState.setDatabase(database); } Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues(); UUID rootTypeId = rootTypeState.getId(); rootTypeState.setTypeId(rootTypeId); rootTypeState.clear(); rootType.setObjectClassName(ObjectType.class.getName()); rootType.initialize(); temporaryTypes.add(rootType); try { database.beginWrites(); // Make the new root type available to other types. temporaryTypes.add(rootType); if (rootTypeState.isNew()) { State globals = getGlobals(); globals.put(ROOT_TYPE_FIELD, rootType); globals.save(); } else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) { temporaryTypes.changed.add(rootTypeId); } Set<Class<? extends Recordable>> objectClasses = ClassFinder.Static.findClasses(Recordable.class); for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) { Class<? extends Recordable> objectClass = i.next(); if (objectClass.isAnonymousClass()) { i.remove(); } } Set<Class<?>> globalModifications = new HashSet<Class<?>>(); Map<ObjectType, List<Class<?>>> typeModifications = new HashMap<ObjectType, List<Class<?>>>(); // Make sure all types are accessible to the rest of the // system as soon as possible, so that references can be // resolved properly later. for (Class<?> objectClass : objectClasses) { ObjectType type = getTypeByClass(objectClass); if (type == null) { type = new ObjectType(); type.getState().setDatabase(database); } else { type.getState().clear(); } type.setObjectClassName(objectClass.getName()); typeModifications.put(type, new ArrayList<Class<?>>()); temporaryTypes.add(type); } // Separate out all modifications from regular types. for (Class<?> objectClass : objectClasses) { if (!Modification.class.isAssignableFrom(objectClass)) { continue; } @SuppressWarnings("unchecked") Set<Class<?>> modifiedClasses = Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) objectClass); if (modifiedClasses.contains(Object.class)) { globalModifications.add(objectClass); continue; } for (Class<?> modifiedClass : modifiedClasses) { List<Class<?>> assignableClasses = new ArrayList<Class<?>>(); for (Class<?> c : objectClasses) { if (modifiedClass.isAssignableFrom(c)) { assignableClasses.add(c); } } for (Class<?> assignableClass : assignableClasses) { ObjectType type = getTypeByClass(assignableClass); if (type != null) { List<Class<?>> modifications = typeModifications.get(type); if (modifications == null) { modifications = new ArrayList<Class<?>>(); typeModifications.put(type, modifications); } modifications.add(objectClass); } } } } // Apply global modifications. for (Class<?> modification : globalModifications) { ObjectType.modifyAll(database, modification); } // Initialize all types. List<Class<?>> rootTypeModifications = typeModifications.remove(rootType); initializeAndModify(temporaryTypes, rootType, rootTypeModifications); if (rootTypeModifications != null) { for (Class<?> modification : rootTypeModifications) { ObjectType t = getTypeByClass(modification); initializeAndModify(temporaryTypes, t, typeModifications.remove(t)); } } ObjectType fieldType = getTypeByClass(ObjectField.class); List<Class<?>> fieldModifications = typeModifications.remove(fieldType); initializeAndModify(temporaryTypes, fieldType, fieldModifications); if (fieldModifications != null) { for (Class<?> modification : fieldModifications) { ObjectType t = getTypeByClass(modification); initializeAndModify(temporaryTypes, t, typeModifications.remove(t)); } } for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) { initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue()); } database.commitWrites(); } finally { database.endWrites(); } } // Merge temporary types into new permanent types. TypesCache newPermanentTypes = new TypesCache(); for (ObjectType type : permanentTypes.byId.values()) { newPermanentTypes.add(type); } for (ObjectType type : temporaryTypes.byId.values()) { newPermanentTypes.add(type); } newPermanentTypes.changed.addAll(temporaryTypes.changed); newPermanentTypes.changed.addAll(permanentTypes.changed); permanentTypes = newPermanentTypes; lastTypesUpdate = new Date(); } finally { temporaryTypesLocal.remove(); } ObjectType singletonType = getTypeByClass(Singleton.class); if (singletonType != null) { for (ObjectType type : singletonType.findConcreteTypes()) { if (!Query. fromType(type). master(). noCache(). hasMoreThan(0)) { try { State.getInstance(type.createObject(null)).save(); } catch (Exception error) { LOGGER.warn(String.format("Can't save [%s] singleton!", type.getLabel()), error); } } } } }
public synchronized void refreshTypes() { bootstrapOnce.ensure(); Database database = getDatabase(); try { TypesCache temporaryTypes = temporaryTypesLocal.get(); if (temporaryTypes == null) { temporaryTypes = new TypesCache(); temporaryTypesLocal.set(temporaryTypes); } List<ObjectType> types = Query. from(ObjectType.class). using(database). selectAll(); int typesSize = types.size(); LOGGER.info("Loading [{}] types from [{}]", typesSize, database.getName()); // Load all types from the database first. for (ObjectType type : types) { type.getFields().size(); // Pre-fetch. temporaryTypes.add(type); } if (initializeClasses) { // Make sure that the root type exists. ObjectType rootType = getRootType(); State rootTypeState; if (rootType != null) { rootTypeState = rootType.getState(); } else { rootType = new ObjectType(); rootTypeState = rootType.getState(); rootTypeState.setDatabase(database); } Map<String, Object> rootTypeOriginals = rootTypeState.getSimpleValues(); UUID rootTypeId = rootTypeState.getId(); rootTypeState.setTypeId(rootTypeId); rootTypeState.clear(); rootType.setObjectClassName(ObjectType.class.getName()); rootType.initialize(); temporaryTypes.add(rootType); try { database.beginWrites(); // Make the new root type available to other types. temporaryTypes.add(rootType); if (rootTypeState.isNew()) { State globals = getGlobals(); globals.put(ROOT_TYPE_FIELD, rootType); globals.save(); } else if (!rootTypeState.getSimpleValues().equals(rootTypeOriginals)) { temporaryTypes.changed.add(rootTypeId); } Set<Class<? extends Recordable>> objectClasses = ClassFinder.Static.findClasses(Recordable.class); for (Iterator<Class<? extends Recordable>> i = objectClasses.iterator(); i.hasNext(); ) { Class<? extends Recordable> objectClass = i.next(); if (objectClass.isAnonymousClass()) { i.remove(); } } Set<Class<?>> globalModifications = new HashSet<Class<?>>(); Map<ObjectType, List<Class<?>>> typeModifications = new HashMap<ObjectType, List<Class<?>>>(); // Make sure all types are accessible to the rest of the // system as soon as possible, so that references can be // resolved properly later. for (Class<?> objectClass : objectClasses) { ObjectType type = getTypeByClass(objectClass); if (type == null) { type = new ObjectType(); type.getState().setDatabase(database); } else { type.getState().clear(); } type.setObjectClassName(objectClass.getName()); typeModifications.put(type, new ArrayList<Class<?>>()); temporaryTypes.add(type); } // Separate out all modifications from regular types. for (Class<?> objectClass : objectClasses) { if (!Modification.class.isAssignableFrom(objectClass)) { continue; } @SuppressWarnings("unchecked") Set<Class<?>> modifiedClasses = Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) objectClass); if (modifiedClasses.contains(Object.class)) { globalModifications.add(objectClass); continue; } for (Class<?> modifiedClass : modifiedClasses) { List<Class<?>> assignableClasses = new ArrayList<Class<?>>(); for (Class<?> c : objectClasses) { if (modifiedClass.isAssignableFrom(c)) { assignableClasses.add(c); } } for (Class<?> assignableClass : assignableClasses) { ObjectType type = getTypeByClass(assignableClass); if (type != null) { List<Class<?>> modifications = typeModifications.get(type); if (modifications == null) { modifications = new ArrayList<Class<?>>(); typeModifications.put(type, modifications); } modifications.add(objectClass); } } } } // Apply global modifications. for (Class<?> modification : globalModifications) { ObjectType.modifyAll(database, modification); } // Initialize all types. List<Class<?>> rootTypeModifications = typeModifications.remove(rootType); initializeAndModify(temporaryTypes, rootType, rootTypeModifications); if (rootTypeModifications != null) { for (Class<?> modification : rootTypeModifications) { ObjectType t = getTypeByClass(modification); initializeAndModify(temporaryTypes, t, typeModifications.remove(t)); } } ObjectType fieldType = getTypeByClass(ObjectField.class); List<Class<?>> fieldModifications = typeModifications.remove(fieldType); initializeAndModify(temporaryTypes, fieldType, fieldModifications); if (fieldModifications != null) { for (Class<?> modification : fieldModifications) { ObjectType t = getTypeByClass(modification); initializeAndModify(temporaryTypes, t, typeModifications.remove(t)); } } for (Map.Entry<ObjectType, List<Class<?>>> entry : typeModifications.entrySet()) { initializeAndModify(temporaryTypes, entry.getKey(), entry.getValue()); } database.commitWrites(); } finally { database.endWrites(); } } // Merge temporary types into new permanent types. TypesCache newPermanentTypes = new TypesCache(); for (ObjectType type : permanentTypes.byId.values()) { newPermanentTypes.add(type); } for (ObjectType type : temporaryTypes.byId.values()) { newPermanentTypes.add(type); } newPermanentTypes.changed.addAll(temporaryTypes.changed); newPermanentTypes.changed.addAll(permanentTypes.changed); permanentTypes = newPermanentTypes; lastTypesUpdate = new Date(); } finally { temporaryTypesLocal.remove(); } ObjectType singletonType = getTypeByClass(Singleton.class); if (singletonType != null) { for (ObjectType type : singletonType.findConcreteTypes()) { if (!Query. fromType(type). where("_type = ?", type). master(). noCache(). hasMoreThan(0)) { try { State.getInstance(type.createObject(null)).save(); } catch (Exception error) { LOGGER.warn(String.format("Can't save [%s] singleton!", type.getLabel()), error); } } } } }
diff --git a/src/com/android/settings/deviceinfo/Status.java b/src/com/android/settings/deviceinfo/Status.java index ea3ca9764..99a8975e0 100644 --- a/src/com/android/settings/deviceinfo/Status.java +++ b/src/com/android/settings/deviceinfo/Status.java @@ -1,420 +1,426 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.deviceinfo; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.BatteryManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.os.SystemProperties; import android.preference.Preference; import android.preference.PreferenceActivity; import android.telephony.PhoneNumberUtils; import android.telephony.PhoneStateListener; import android.telephony.ServiceState; import android.telephony.TelephonyManager; import android.text.TextUtils; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; import com.android.internal.telephony.PhoneStateIntentReceiver; import com.android.internal.telephony.TelephonyProperties; import com.android.settings.R; import java.lang.ref.WeakReference; /** * Display the following information * # Phone Number * # Network * # Roaming * # Device Id (IMEI in GSM and MEID in CDMA) * # Network type * # Signal Strength * # Battery Strength : TODO * # Uptime * # Awake Time * # XMPP/buzz/tickle status : TODO * */ public class Status extends PreferenceActivity { private static final String KEY_WIFI_MAC_ADDRESS = "wifi_mac_address"; private static final String KEY_BT_ADDRESS = "bt_address"; private static final int EVENT_SIGNAL_STRENGTH_CHANGED = 200; private static final int EVENT_SERVICE_STATE_CHANGED = 300; private static final int EVENT_UPDATE_STATS = 500; private TelephonyManager mTelephonyManager; private Phone mPhone = null; private PhoneStateIntentReceiver mPhoneStateReceiver; private Resources mRes; private Preference mSignalStrength; private Preference mUptime; private static String sUnknown; private Preference mBatteryStatus; private Preference mBatteryLevel; private Handler mHandler; private static class MyHandler extends Handler { private WeakReference<Status> mStatus; public MyHandler(Status activity) { mStatus = new WeakReference<Status>(activity); } @Override public void handleMessage(Message msg) { Status status = mStatus.get(); if (status == null) { return; } switch (msg.what) { case EVENT_SIGNAL_STRENGTH_CHANGED: status.updateSignalStrength(); break; case EVENT_SERVICE_STATE_CHANGED: ServiceState serviceState = status.mPhoneStateReceiver.getServiceState(); status.updateServiceState(serviceState); break; case EVENT_UPDATE_STATS: status.updateTimes(); sendEmptyMessageDelayed(EVENT_UPDATE_STATS, 1000); break; } } } private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_BATTERY_CHANGED.equals(action)) { int level = intent.getIntExtra("level", 0); int scale = intent.getIntExtra("scale", 100); mBatteryLevel.setSummary(String.valueOf(level * 100 / scale) + "%"); int plugType = intent.getIntExtra("plugged", 0); int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN); String statusString; if (status == BatteryManager.BATTERY_STATUS_CHARGING) { statusString = getString(R.string.battery_info_status_charging); if (plugType > 0) { statusString = statusString + " " + getString( (plugType == BatteryManager.BATTERY_PLUGGED_AC) ? R.string.battery_info_status_charging_ac : R.string.battery_info_status_charging_usb); } } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) { statusString = getString(R.string.battery_info_status_discharging); } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) { statusString = getString(R.string.battery_info_status_not_charging); } else if (status == BatteryManager.BATTERY_STATUS_FULL) { statusString = getString(R.string.battery_info_status_full); } else { statusString = getString(R.string.battery_info_status_unknown); } mBatteryStatus.setSummary(statusString); } } }; private PhoneStateListener mPhoneStateListener = new PhoneStateListener() { @Override public void onDataConnectionStateChanged(int state) { updateDataState(); updateNetworkType(); } }; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); Preference removablePref; mHandler = new MyHandler(this); mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); addPreferencesFromResource(R.xml.device_info_status); mBatteryLevel = findPreference("battery_level"); mBatteryStatus = findPreference("battery_status"); mRes = getResources(); if (sUnknown == null) { sUnknown = mRes.getString(R.string.device_info_default); } mPhone = PhoneFactory.getDefaultPhone(); // Note - missing in zaku build, be careful later... mSignalStrength = findPreference("signal_strength"); mUptime = findPreference("up_time"); //NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA if (mPhone.getPhoneName().equals("CDMA")) { setSummaryText("meid_number", mPhone.getMeid()); setSummaryText("min_number", mPhone.getCdmaMin()); setSummaryText("prl_version", mPhone.getCdmaPrlVersion()); // device is not GSM/UMTS, do not display GSM/UMTS features // check Null in case no specified preference in overlay xml removablePref = findPreference("imei"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("imei_sv"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } else { setSummaryText("imei", mPhone.getDeviceId()); setSummaryText("imei_sv", ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)) .getDeviceSoftwareVersion()); // device is not CDMA, do not display CDMA features // check Null in case no specified preference in overlay xml removablePref = findPreference("prl_version"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("meid_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("min_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } - setSummaryText("number", PhoneNumberUtils.formatNumber(mPhone.getLine1Number())); + String rawNumber = mPhone.getLine1Number(); // may be null or empty + String formattedNumber = null; + if (!TextUtils.isEmpty(rawNumber)) { + formattedNumber = PhoneNumberUtils.formatNumber(rawNumber); + } + // If formattedNumber is null or empty, it'll display as "Unknown". + setSummaryText("number", formattedNumber); mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler); mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED); mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED); setWifiStatus(); setBtStatus(); } @Override protected void onResume() { super.onResume(); mPhoneStateReceiver.registerIntent(); registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); updateSignalStrength(); updateServiceState(mPhone.getServiceState()); updateDataState(); mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); mHandler.sendEmptyMessage(EVENT_UPDATE_STATS); } @Override public void onPause() { super.onPause(); mPhoneStateReceiver.unregisterIntent(); mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE); unregisterReceiver(mBatteryInfoReceiver); mHandler.removeMessages(EVENT_UPDATE_STATS); } /** * @param preference The key for the Preference item * @param property The system property to fetch * @param alt The default value, if the property doesn't exist */ private void setSummary(String preference, String property, String alt) { try { findPreference(preference).setSummary( SystemProperties.get(property, alt)); } catch (RuntimeException e) { } } private void setSummaryText(String preference, String text) { if (TextUtils.isEmpty(text)) { text = sUnknown; } // some preferences may be missing if (findPreference(preference) != null) { findPreference(preference).setSummary(text); } } private void updateNetworkType() { // Whether EDGE, UMTS, etc... setSummary("network_type", TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE, sUnknown); } private void updateDataState() { int state = mTelephonyManager.getDataState(); String display = mRes.getString(R.string.radioInfo_unknown); switch (state) { case TelephonyManager.DATA_CONNECTED: display = mRes.getString(R.string.radioInfo_data_connected); break; case TelephonyManager.DATA_SUSPENDED: display = mRes.getString(R.string.radioInfo_data_suspended); break; case TelephonyManager.DATA_CONNECTING: display = mRes.getString(R.string.radioInfo_data_connecting); break; case TelephonyManager.DATA_DISCONNECTED: display = mRes.getString(R.string.radioInfo_data_disconnected); break; } setSummaryText("data_state", display); } private void updateServiceState(ServiceState serviceState) { int state = serviceState.getState(); String display = mRes.getString(R.string.radioInfo_unknown); switch (state) { case ServiceState.STATE_IN_SERVICE: display = mRes.getString(R.string.radioInfo_service_in); break; case ServiceState.STATE_OUT_OF_SERVICE: case ServiceState.STATE_EMERGENCY_ONLY: display = mRes.getString(R.string.radioInfo_service_out); break; case ServiceState.STATE_POWER_OFF: display = mRes.getString(R.string.radioInfo_service_off); break; } setSummaryText("service_state", display); if (serviceState.getRoaming()) { setSummaryText("roaming_state", mRes.getString(R.string.radioInfo_roaming_in)); } else { setSummaryText("roaming_state", mRes.getString(R.string.radioInfo_roaming_not)); } setSummaryText("operator_name", serviceState.getOperatorAlphaLong()); } void updateSignalStrength() { // TODO PhoneStateIntentReceiver is deprecated and PhoneStateListener // should probably used instead. // not loaded in some versions of the code (e.g., zaku) if (mSignalStrength != null) { int state = mPhoneStateReceiver.getServiceState().getState(); Resources r = getResources(); if ((ServiceState.STATE_OUT_OF_SERVICE == state) || (ServiceState.STATE_POWER_OFF == state)) { mSignalStrength.setSummary("0"); } int signalDbm = mPhoneStateReceiver.getSignalStrengthDbm(); if (-1 == signalDbm) signalDbm = 0; int signalAsu = mPhoneStateReceiver.getSignalStrength(); if (-1 == signalAsu) signalAsu = 0; mSignalStrength.setSummary(String.valueOf(signalDbm) + " " + r.getString(R.string.radioInfo_display_dbm) + " " + String.valueOf(signalAsu) + " " + r.getString(R.string.radioInfo_display_asu)); } } private void setWifiStatus() { WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); Preference wifiMacAddressPref = findPreference(KEY_WIFI_MAC_ADDRESS); String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress(); wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress : getString(R.string.status_unavailable)); } private void setBtStatus() { BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); Preference btAddressPref = findPreference(KEY_BT_ADDRESS); if (bluetooth == null) { // device not BT capable getPreferenceScreen().removePreference(btAddressPref); } else { String address = bluetooth.isEnabled() ? bluetooth.getAddress() : null; btAddressPref.setSummary(!TextUtils.isEmpty(address) ? address : getString(R.string.status_unavailable)); } } void updateTimes() { long at = SystemClock.uptimeMillis() / 1000; long ut = SystemClock.elapsedRealtime() / 1000; if (ut == 0) { ut = 1; } mUptime.setSummary(convert(ut)); } private String pad(int n) { if (n >= 10) { return String.valueOf(n); } else { return "0" + String.valueOf(n); } } private String convert(long t) { int s = (int)(t % 60); int m = (int)((t / 60) % 60); int h = (int)((t / 3600)); return h + ":" + pad(m) + ":" + pad(s); } }
true
true
protected void onCreate(Bundle icicle) { super.onCreate(icicle); Preference removablePref; mHandler = new MyHandler(this); mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); addPreferencesFromResource(R.xml.device_info_status); mBatteryLevel = findPreference("battery_level"); mBatteryStatus = findPreference("battery_status"); mRes = getResources(); if (sUnknown == null) { sUnknown = mRes.getString(R.string.device_info_default); } mPhone = PhoneFactory.getDefaultPhone(); // Note - missing in zaku build, be careful later... mSignalStrength = findPreference("signal_strength"); mUptime = findPreference("up_time"); //NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA if (mPhone.getPhoneName().equals("CDMA")) { setSummaryText("meid_number", mPhone.getMeid()); setSummaryText("min_number", mPhone.getCdmaMin()); setSummaryText("prl_version", mPhone.getCdmaPrlVersion()); // device is not GSM/UMTS, do not display GSM/UMTS features // check Null in case no specified preference in overlay xml removablePref = findPreference("imei"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("imei_sv"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } else { setSummaryText("imei", mPhone.getDeviceId()); setSummaryText("imei_sv", ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)) .getDeviceSoftwareVersion()); // device is not CDMA, do not display CDMA features // check Null in case no specified preference in overlay xml removablePref = findPreference("prl_version"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("meid_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("min_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } setSummaryText("number", PhoneNumberUtils.formatNumber(mPhone.getLine1Number())); mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler); mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED); mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED); setWifiStatus(); setBtStatus(); }
protected void onCreate(Bundle icicle) { super.onCreate(icicle); Preference removablePref; mHandler = new MyHandler(this); mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); addPreferencesFromResource(R.xml.device_info_status); mBatteryLevel = findPreference("battery_level"); mBatteryStatus = findPreference("battery_status"); mRes = getResources(); if (sUnknown == null) { sUnknown = mRes.getString(R.string.device_info_default); } mPhone = PhoneFactory.getDefaultPhone(); // Note - missing in zaku build, be careful later... mSignalStrength = findPreference("signal_strength"); mUptime = findPreference("up_time"); //NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA if (mPhone.getPhoneName().equals("CDMA")) { setSummaryText("meid_number", mPhone.getMeid()); setSummaryText("min_number", mPhone.getCdmaMin()); setSummaryText("prl_version", mPhone.getCdmaPrlVersion()); // device is not GSM/UMTS, do not display GSM/UMTS features // check Null in case no specified preference in overlay xml removablePref = findPreference("imei"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("imei_sv"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } else { setSummaryText("imei", mPhone.getDeviceId()); setSummaryText("imei_sv", ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)) .getDeviceSoftwareVersion()); // device is not CDMA, do not display CDMA features // check Null in case no specified preference in overlay xml removablePref = findPreference("prl_version"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("meid_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } removablePref = findPreference("min_number"); if (removablePref != null) { getPreferenceScreen().removePreference(removablePref); } } String rawNumber = mPhone.getLine1Number(); // may be null or empty String formattedNumber = null; if (!TextUtils.isEmpty(rawNumber)) { formattedNumber = PhoneNumberUtils.formatNumber(rawNumber); } // If formattedNumber is null or empty, it'll display as "Unknown". setSummaryText("number", formattedNumber); mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler); mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED); mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED); setWifiStatus(); setBtStatus(); }
diff --git a/loci/formats/in/FlexReader.java b/loci/formats/in/FlexReader.java index 78b27e2ed..31316d2b6 100644 --- a/loci/formats/in/FlexReader.java +++ b/loci/formats/in/FlexReader.java @@ -1,233 +1,233 @@ // // FlexReader.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan, Eric Kjellman and Brian Loranger. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Arrays; import java.util.Vector; import javax.xml.parsers.*; import loci.formats.*; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * FlexReader is a file format reader for Evotec Flex files. * To use it, the LuraWave decoder library, lwf_jsdk2.6.jar, must be available, * and a LuraWave license key must be specified in the lurawave.license system * property (e.g., <code>-Dlurawave.license=XXXX</code> on the command line). * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/in/FlexReader.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/in/FlexReader.java">SVN</a></dd></dl> */ public class FlexReader extends BaseTiffReader { // -- Constants -- /** Custom IFD entry for Flex XML. */ protected static final int FLEX = 65200; /** Factory for generating SAX parsers. */ public static final SAXParserFactory SAX_FACTORY = SAXParserFactory.newInstance(); // -- Fields -- /** Scale factor for each image. */ protected double[] factors; // -- Constructor -- /** Constructs a new Flex reader. */ public FlexReader() { super("Evotec Flex", "flex"); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(byte[]) */ public boolean isThisType(byte[] block) { return false; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); // expand pixel values with multiplication by factor[no] byte[] bytes = super.openBytes(no, buf, x, y, w, h); if (core.pixelType[0] == FormatTools.UINT8) { int num = bytes.length; for (int i=num-1; i>=0; i--) { int q = (int) ((bytes[i] & 0xff) * factors[no]); bytes[i] = (byte) (q & 0xff); } } if (core.pixelType[0] == FormatTools.UINT16) { int num = bytes.length / 2; for (int i=num-1; i>=0; i--) { int q = (int) ((bytes[i] & 0xff) * factors[no]); byte b0 = (byte) (q & 0xff); byte b1 = (byte) ((q >> 8) & 0xff); int ndx = 2 * i; if (core.littleEndian[0]) { bytes[ndx] = b0; bytes[ndx + 1] = b1; } else { bytes[ndx] = b1; bytes[ndx + 1] = b0; } } } else if (core.pixelType[0] == FormatTools.UINT32) { int num = bytes.length / 4; for (int i=num-1; i>=0; i--) { int q = (int) ((bytes[i] & 0xff) * factors[no]); byte b0 = (byte) (q & 0xff); byte b1 = (byte) ((q >> 8) & 0xff); byte b2 = (byte) ((q >> 16) & 0xff); byte b3 = (byte) ((q >> 24) & 0xff); int ndx = 4 * i; if (core.littleEndian[0]) { bytes[ndx] = b0; bytes[ndx + 1] = b1; bytes[ndx + 2] = b2; bytes[ndx + 3] = b3; } else { bytes[ndx] = b3; bytes[ndx + 1] = b2; bytes[ndx + 2] = b1; bytes[ndx + 3] = b0; } } } return bytes; } // -- IFormatHandler API methods -- /* @see loci.formats.IFormatHandler#close() */ public void close() throws IOException { super.close(); factors = null; } // -- Internal BaseTiffReader API methods -- /* @see loci.formats.BaseTiffReader#initStandardMetadata() */ protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); core.orderCertain[0] = false; // parse factors from XML String xml = (String) TiffTools.getIFDValue(ifds[0], FLEX, true, String.class); // HACK - workaround for Windows and Mac OS X bug where // SAX parser fails due to improperly handled mu (181) characters. char[] c = xml.toCharArray(); for (int i=0; i<c.length; i++) { - if (c[i] < ' ' || c[i] > '~') c[i] = '?'; + if (c[i] > '~' || (c[i] != '\t' && c[i] < ' ')) c[i] = ' '; } xml = new String(c); Vector n = new Vector(); Vector f = new Vector(); FlexHandler handler = new FlexHandler(n, f); try { SAXParser saxParser = SAX_FACTORY.newSAXParser(); saxParser.parse(new ByteArrayInputStream(xml.getBytes()), handler); } catch (ParserConfigurationException exc) { throw new FormatException(exc); } catch (SAXException exc) { throw new FormatException(exc); } // verify factor count int nsize = n.size(); int fsize = f.size(); if (debug && (nsize != fsize || nsize != core.imageCount[0])) { LogTools.println("Warning: mismatch between image count, " + "names and factors (count=" + core.imageCount[0] + ", names=" + nsize + ", factors=" + fsize + ")"); } for (int i=0; i<nsize; i++) addMeta("Name " + i, n.get(i)); for (int i=0; i<fsize; i++) addMeta("Factor " + i, f.get(i)); // parse factor values factors = new double[core.imageCount[0]]; int max = 0; for (int i=0; i<fsize; i++) { String factor = (String) f.get(i); double q = 1; try { q = Double.parseDouble(factor); } catch (NumberFormatException exc) { if (debug) { LogTools.println("Warning: invalid factor #" + i + ": " + factor); } } factors[i] = q; if (q > factors[max]) max = i; } Arrays.fill(factors, fsize, factors.length, 1); // determine pixel type if (factors[max] > 256) core.pixelType[0] = FormatTools.UINT32; else if (factors[max] > 1) core.pixelType[0] = FormatTools.UINT16; else core.pixelType[0] = FormatTools.UINT8; } // -- Helper classes -- /** SAX handler for parsing XML. */ public class FlexHandler extends DefaultHandler { private Vector names, factors; public FlexHandler(Vector names, Vector factors) { this.names = names; this.factors = factors; } public void startElement(String uri, String localName, String qName, Attributes attributes) { if (!qName.equals("Array")) return; int len = attributes.getLength(); for (int i=0; i<len; i++) { String name = attributes.getQName(i); if (name.equals("Name")) names.add(attributes.getValue(i)); else if (name.equals("Factor")) factors.add(attributes.getValue(i)); } } } }
true
true
protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); core.orderCertain[0] = false; // parse factors from XML String xml = (String) TiffTools.getIFDValue(ifds[0], FLEX, true, String.class); // HACK - workaround for Windows and Mac OS X bug where // SAX parser fails due to improperly handled mu (181) characters. char[] c = xml.toCharArray(); for (int i=0; i<c.length; i++) { if (c[i] < ' ' || c[i] > '~') c[i] = '?'; } xml = new String(c); Vector n = new Vector(); Vector f = new Vector(); FlexHandler handler = new FlexHandler(n, f); try { SAXParser saxParser = SAX_FACTORY.newSAXParser(); saxParser.parse(new ByteArrayInputStream(xml.getBytes()), handler); } catch (ParserConfigurationException exc) { throw new FormatException(exc); } catch (SAXException exc) { throw new FormatException(exc); } // verify factor count int nsize = n.size(); int fsize = f.size(); if (debug && (nsize != fsize || nsize != core.imageCount[0])) { LogTools.println("Warning: mismatch between image count, " + "names and factors (count=" + core.imageCount[0] + ", names=" + nsize + ", factors=" + fsize + ")"); } for (int i=0; i<nsize; i++) addMeta("Name " + i, n.get(i)); for (int i=0; i<fsize; i++) addMeta("Factor " + i, f.get(i)); // parse factor values factors = new double[core.imageCount[0]]; int max = 0; for (int i=0; i<fsize; i++) { String factor = (String) f.get(i); double q = 1; try { q = Double.parseDouble(factor); } catch (NumberFormatException exc) { if (debug) { LogTools.println("Warning: invalid factor #" + i + ": " + factor); } } factors[i] = q; if (q > factors[max]) max = i; } Arrays.fill(factors, fsize, factors.length, 1); // determine pixel type if (factors[max] > 256) core.pixelType[0] = FormatTools.UINT32; else if (factors[max] > 1) core.pixelType[0] = FormatTools.UINT16; else core.pixelType[0] = FormatTools.UINT8; }
protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); core.orderCertain[0] = false; // parse factors from XML String xml = (String) TiffTools.getIFDValue(ifds[0], FLEX, true, String.class); // HACK - workaround for Windows and Mac OS X bug where // SAX parser fails due to improperly handled mu (181) characters. char[] c = xml.toCharArray(); for (int i=0; i<c.length; i++) { if (c[i] > '~' || (c[i] != '\t' && c[i] < ' ')) c[i] = ' '; } xml = new String(c); Vector n = new Vector(); Vector f = new Vector(); FlexHandler handler = new FlexHandler(n, f); try { SAXParser saxParser = SAX_FACTORY.newSAXParser(); saxParser.parse(new ByteArrayInputStream(xml.getBytes()), handler); } catch (ParserConfigurationException exc) { throw new FormatException(exc); } catch (SAXException exc) { throw new FormatException(exc); } // verify factor count int nsize = n.size(); int fsize = f.size(); if (debug && (nsize != fsize || nsize != core.imageCount[0])) { LogTools.println("Warning: mismatch between image count, " + "names and factors (count=" + core.imageCount[0] + ", names=" + nsize + ", factors=" + fsize + ")"); } for (int i=0; i<nsize; i++) addMeta("Name " + i, n.get(i)); for (int i=0; i<fsize; i++) addMeta("Factor " + i, f.get(i)); // parse factor values factors = new double[core.imageCount[0]]; int max = 0; for (int i=0; i<fsize; i++) { String factor = (String) f.get(i); double q = 1; try { q = Double.parseDouble(factor); } catch (NumberFormatException exc) { if (debug) { LogTools.println("Warning: invalid factor #" + i + ": " + factor); } } factors[i] = q; if (q > factors[max]) max = i; } Arrays.fill(factors, fsize, factors.length, 1); // determine pixel type if (factors[max] > 256) core.pixelType[0] = FormatTools.UINT32; else if (factors[max] > 1) core.pixelType[0] = FormatTools.UINT16; else core.pixelType[0] = FormatTools.UINT8; }
diff --git a/library/src/main/java/com/wuman/android/auth/FragmentManagerCompat.java b/library/src/main/java/com/wuman/android/auth/FragmentManagerCompat.java index 0641c06..2d5c9ab 100644 --- a/library/src/main/java/com/wuman/android/auth/FragmentManagerCompat.java +++ b/library/src/main/java/com/wuman/android/auth/FragmentManagerCompat.java @@ -1,68 +1,70 @@ package com.wuman.android.auth; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.FragmentManager; import android.os.Build; import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import java.util.logging.Logger; @TargetApi(Build.VERSION_CODES.HONEYCOMB) class FragmentManagerCompat { static final Logger LOGGER = Logger.getLogger(OAuthConstants.TAG); private android.support.v4.app.FragmentManager supportFragmentManager; private android.app.FragmentManager nativeFragmentManager; FragmentManagerCompat(FragmentManager nativeFragmentManager) { super(); this.nativeFragmentManager = nativeFragmentManager; } FragmentManagerCompat(android.support.v4.app.FragmentManager supportFragmentManager) { super(); this.supportFragmentManager = supportFragmentManager; } Object getFragmentManager() { return supportFragmentManager != null ? supportFragmentManager : nativeFragmentManager; } @SuppressLint("CommitTransaction") FragmentTransactionCompat beginTransaction() { if (supportFragmentManager != null) { return new FragmentTransactionCompat(supportFragmentManager.beginTransaction()); } else { return new FragmentTransactionCompat(nativeFragmentManager.beginTransaction()); } } @SuppressWarnings("unchecked") <T extends FragmentCompat> T findFragmentByTag(Class<T> fragmentClass, String tag) { try { Object fragment = null; if (supportFragmentManager != null) { fragment = supportFragmentManager.findFragmentByTag(tag); + } else { + fragment = nativeFragmentManager.findFragmentByTag(tag); } if (fragment == null) { return null; } return (T) fragmentClass .getDeclaredMethod("newInstance", Object.class) .invoke(null, fragment); } catch (IllegalArgumentException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } catch (IllegalAccessException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } catch (InvocationTargetException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } catch (NoSuchMethodException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } return null; } }
true
true
<T extends FragmentCompat> T findFragmentByTag(Class<T> fragmentClass, String tag) { try { Object fragment = null; if (supportFragmentManager != null) { fragment = supportFragmentManager.findFragmentByTag(tag); } if (fragment == null) { return null; } return (T) fragmentClass .getDeclaredMethod("newInstance", Object.class) .invoke(null, fragment); } catch (IllegalArgumentException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } catch (IllegalAccessException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } catch (InvocationTargetException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } catch (NoSuchMethodException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } return null; }
<T extends FragmentCompat> T findFragmentByTag(Class<T> fragmentClass, String tag) { try { Object fragment = null; if (supportFragmentManager != null) { fragment = supportFragmentManager.findFragmentByTag(tag); } else { fragment = nativeFragmentManager.findFragmentByTag(tag); } if (fragment == null) { return null; } return (T) fragmentClass .getDeclaredMethod("newInstance", Object.class) .invoke(null, fragment); } catch (IllegalArgumentException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } catch (IllegalAccessException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } catch (InvocationTargetException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } catch (NoSuchMethodException e) { LOGGER.log(Level.WARNING, "Unable to perform findFragmentByTag()", e); } return null; }
diff --git a/src/com/sun/jini/start/SharedActivationPolicyPermission.java b/src/com/sun/jini/start/SharedActivationPolicyPermission.java index 7cddf732..4654c6a1 100644 --- a/src/com/sun/jini/start/SharedActivationPolicyPermission.java +++ b/src/com/sun/jini/start/SharedActivationPolicyPermission.java @@ -1,273 +1,275 @@ /* * 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 com.sun.jini.start; import java.io.File; import java.io.FilePermission; import java.io.Serializable; import java.net.URISyntaxException; import java.net.URL; import java.net.MalformedURLException; import java.net.URI; import java.security.Permission; import java.security.PermissionCollection; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.river.impl.net.UriString; /** * {@link Permission} class used by the * {@linkplain com.sun.jini.start service starter} * package. This class takes a policy string argument that follows the * matching semantics defined by {@link FilePermission}. The * {@link ActivateWrapper} class explicitly checks to see if the service's * import codebase has been granted access to service's associated policy * file in the shared VM's policy. *<P> * An example grant is: * <blockquote><pre> * grant codebase "file:<VAR><B>install_dir</B></VAR>/lib/fiddler.jar" { * permission com.sun.jini.start.SharedActivationPolicyPermission * "<VAR><B>policy_dir</B></VAR>${/}policy.fiddler"; * }; * </pre></blockquote> * This grant allows services using * <code><VAR><B>install_dir</B></VAR>/lib/fiddler.jar</code> for their * import codebase to use * <code><VAR><B>policy_dir</B></VAR>${/}policy.fiddler</code> for their * policy file, where <VAR><B>install_dir</B></VAR> is the installation * directory of the Apache River release and <VAR><B>policy_dir</B></VAR> is the * pathname to the directory containing the policy file. * * @author Sun Microsystems, Inc. * */ public final class SharedActivationPolicyPermission extends Permission implements Serializable { private static final long serialVersionUID = 1L; /* * Debug flag. */ private static final boolean DEBUG = false; /** * <code>FilePermission</code> object that is the delegation * target of the <code>implies()</code> checks. * @serial */ private final Permission policyPermission; /** * Constructor that creates a * <code>SharedActivationPolicyPermission</code> with the specified name. * Delegates <code>policy</code> to supertype. */ public SharedActivationPolicyPermission(String policy) { //TBD - check for null args super(policy); policyPermission = init(policy); } /** * Constructor that creates a * <code>SharedActivationPolicyPermission</code> with the specified name. * This constructor exists for use by the <code>Policy</code> object * to instantiate new Permission objects. The <code>action</code> * argument is currently ignored. */ public SharedActivationPolicyPermission(String policy, String action) { //TBD - check for null args super(policy); policyPermission = init(policy); } // /** // * Contains common code to all constructors. // */ // private Permission init(final String policy) { // /* // * In order to leverage the <code>FilePermission</code> logic // * we need to make sure that forward slashes ("/"), in // * <code>URLs</code>, are converted to // * the appropriate system dependent <code>File.separatorChar</code>. // * For example, // * http://host:port/* matches http://host:port/bogus.jar under // * UNIX, but not under Windows since "\*" is the wildcard there. // */ // if (policy == null) throw new NullPointerException("Null policy string not allowed"); // String uncanonicalPath = null; // try { // URL url = new URL(policy); // uncanonicalPath = url.toExternalForm(); // uncanonicalPath = uncanonicalPath.replace('/', File.separatorChar); // if (DEBUG) { // System.out.println("SharedActivationPolicyPermission::init() - " // + policy + " => " + uncanonicalPath); // } // } catch (MalformedURLException me) { // uncanonicalPath = policy; // } // // return new FilePermission(uncanonicalPath, "read"); // } /** * Contains common code to all constructors. */ private Permission init(final String policy) { /* * In order to leverage the <code>FilePermission</code> logic * we need to make sure that forward slashes ("/"), in * <code>URLs</code>, are converted to * the appropriate system dependent <code>File.separatorChar</code>. * For example, * http://host:port/* matches http://host:port/bogus.jar under * UNIX, but not under Windows since "\*" is the wildcard there. */ if (policy == null) throw new NullPointerException("Null policy string not allowed"); String uncanonicalPath = null; try { URL url = new URL(policy); uncanonicalPath = url.toExternalForm(); if (policy.startsWith("file:") || policy.startsWith("FILE:")){ String path = null; try { path = UriString.escapeIllegalCharacters(uncanonicalPath); path = new File(new URI(path)).getPath(); } catch (URISyntaxException ex) { path = uncanonicalPath.replace('/', File.separatorChar); + } catch (IllegalArgumentException ex){ + path = uncanonicalPath.replace('/', File.separatorChar); } uncanonicalPath = path; } else { uncanonicalPath = uncanonicalPath.replace('/', File.separatorChar); } if (DEBUG) { System.out.println("SharedActivationPolicyPermission::init() - " + policy + " => " + uncanonicalPath); } } catch (MalformedURLException me) { uncanonicalPath = policy; } return new FilePermission(uncanonicalPath, "read"); } // javadoc inherited from superclass public boolean implies(Permission p) { // Quick reject tests if (p == null) return false; if (!(p instanceof SharedActivationPolicyPermission)) return false; SharedActivationPolicyPermission other = (SharedActivationPolicyPermission)p; // Delegate to FilePermission logic boolean answer = policyPermission.implies(other.policyPermission); if (DEBUG) { System.out.println("SharedActivationPolicyPermission::implies() - " + "checking " + policyPermission + " vs. " + other.policyPermission + ": " + answer); } return answer; } /** Two instances are equal if they have the same name. */ public boolean equals(Object obj) { // Quick reject tests if (obj == null) return false; if (this == obj) return true; if (!(obj instanceof SharedActivationPolicyPermission)) return false; SharedActivationPolicyPermission other = (SharedActivationPolicyPermission)obj; boolean answer = policyPermission.equals(other.policyPermission); if (DEBUG) { System.out.println("SharedActivationPolicyPermission::equals() - " + "checking " + policyPermission + " vs. " + other.policyPermission + ": " + answer); } return answer; } // javadoc inherited from superclass public int hashCode() { return getName().hashCode(); } // javadoc inherited from superclass public String getActions() { return ""; } // javadoc inherited from superclass public PermissionCollection newPermissionCollection() { /* bug 4158302 fix */ return new Collection(); } /** Simple permission collection. See Bug 4158302 */ private static class Collection extends PermissionCollection { private static final long serialVersionUID = 1L; /** * Permissions * * @serial **/ private final ArrayList perms = new ArrayList(3); // javadoc inherited from superclass public synchronized void add(Permission p) { if (isReadOnly()) throw new SecurityException("Collection cannot be modified."); if (perms.indexOf(p) < 0) perms.add(p); } // javadoc inherited from superclass public synchronized boolean implies(Permission p) { for (int i = perms.size(); --i >= 0; ) { if (((Permission)perms.get(i)).implies(p)) return true; } return false; } // javadoc inherited from superclass public Enumeration elements() { return Collections.enumeration(perms); } } }
true
true
private Permission init(final String policy) { /* * In order to leverage the <code>FilePermission</code> logic * we need to make sure that forward slashes ("/"), in * <code>URLs</code>, are converted to * the appropriate system dependent <code>File.separatorChar</code>. * For example, * http://host:port/* matches http://host:port/bogus.jar under * UNIX, but not under Windows since "\*" is the wildcard there. */ if (policy == null) throw new NullPointerException("Null policy string not allowed"); String uncanonicalPath = null; try { URL url = new URL(policy); uncanonicalPath = url.toExternalForm(); if (policy.startsWith("file:") || policy.startsWith("FILE:")){ String path = null; try { path = UriString.escapeIllegalCharacters(uncanonicalPath); path = new File(new URI(path)).getPath(); } catch (URISyntaxException ex) { path = uncanonicalPath.replace('/', File.separatorChar); } uncanonicalPath = path; } else { uncanonicalPath = uncanonicalPath.replace('/', File.separatorChar); } if (DEBUG) { System.out.println("SharedActivationPolicyPermission::init() - " + policy + " => " + uncanonicalPath); } } catch (MalformedURLException me) { uncanonicalPath = policy; } return new FilePermission(uncanonicalPath, "read"); }
private Permission init(final String policy) { /* * In order to leverage the <code>FilePermission</code> logic * we need to make sure that forward slashes ("/"), in * <code>URLs</code>, are converted to * the appropriate system dependent <code>File.separatorChar</code>. * For example, * http://host:port/* matches http://host:port/bogus.jar under * UNIX, but not under Windows since "\*" is the wildcard there. */ if (policy == null) throw new NullPointerException("Null policy string not allowed"); String uncanonicalPath = null; try { URL url = new URL(policy); uncanonicalPath = url.toExternalForm(); if (policy.startsWith("file:") || policy.startsWith("FILE:")){ String path = null; try { path = UriString.escapeIllegalCharacters(uncanonicalPath); path = new File(new URI(path)).getPath(); } catch (URISyntaxException ex) { path = uncanonicalPath.replace('/', File.separatorChar); } catch (IllegalArgumentException ex){ path = uncanonicalPath.replace('/', File.separatorChar); } uncanonicalPath = path; } else { uncanonicalPath = uncanonicalPath.replace('/', File.separatorChar); } if (DEBUG) { System.out.println("SharedActivationPolicyPermission::init() - " + policy + " => " + uncanonicalPath); } } catch (MalformedURLException me) { uncanonicalPath = policy; } return new FilePermission(uncanonicalPath, "read"); }
diff --git a/src/java/com/opensymphony/sitemesh/compatability/DecoratorMapper2DecoratorSelector.java b/src/java/com/opensymphony/sitemesh/compatability/DecoratorMapper2DecoratorSelector.java index 0338a24..35b6a0c 100644 --- a/src/java/com/opensymphony/sitemesh/compatability/DecoratorMapper2DecoratorSelector.java +++ b/src/java/com/opensymphony/sitemesh/compatability/DecoratorMapper2DecoratorSelector.java @@ -1,35 +1,35 @@ package com.opensymphony.sitemesh.compatability; import com.opensymphony.module.sitemesh.DecoratorMapper; import com.opensymphony.sitemesh.Content; import com.opensymphony.sitemesh.Decorator; import com.opensymphony.sitemesh.DecoratorSelector; import com.opensymphony.sitemesh.SiteMeshContext; import com.opensymphony.sitemesh.webapp.SiteMeshWebAppContext; import com.opensymphony.sitemesh.webapp.decorator.NoDecorator; /** * Adapts a SiteMesh 2 {@link DecoratorMapper} to a SiteMesh 2 {@link DecoratorSelector}. * * @author Joe Walnes * @since SiteMesh 3 */ public class DecoratorMapper2DecoratorSelector implements DecoratorSelector { private final DecoratorMapper decoratorMapper; public DecoratorMapper2DecoratorSelector(DecoratorMapper decoratorMapper) { this.decoratorMapper = decoratorMapper; } public Decorator selectDecorator(Content content, SiteMeshContext context) { SiteMeshWebAppContext webAppContext = (SiteMeshWebAppContext) context; com.opensymphony.module.sitemesh.Decorator decorator = decoratorMapper.getDecorator(webAppContext.getRequest(), new Content2HTMLPage(content)); - if (decorator == null) { + if (decorator == null || decorator.getPage() == null) { return new NoDecorator(); } else { return new OldDecorator2NewDecorator(decorator); } } }
true
true
public Decorator selectDecorator(Content content, SiteMeshContext context) { SiteMeshWebAppContext webAppContext = (SiteMeshWebAppContext) context; com.opensymphony.module.sitemesh.Decorator decorator = decoratorMapper.getDecorator(webAppContext.getRequest(), new Content2HTMLPage(content)); if (decorator == null) { return new NoDecorator(); } else { return new OldDecorator2NewDecorator(decorator); } }
public Decorator selectDecorator(Content content, SiteMeshContext context) { SiteMeshWebAppContext webAppContext = (SiteMeshWebAppContext) context; com.opensymphony.module.sitemesh.Decorator decorator = decoratorMapper.getDecorator(webAppContext.getRequest(), new Content2HTMLPage(content)); if (decorator == null || decorator.getPage() == null) { return new NoDecorator(); } else { return new OldDecorator2NewDecorator(decorator); } }
diff --git a/assets/src/org/ruboto/test/InstrumentationTestRunner.java b/assets/src/org/ruboto/test/InstrumentationTestRunner.java index 8118546..3c4104c 100644 --- a/assets/src/org/ruboto/test/InstrumentationTestRunner.java +++ b/assets/src/org/ruboto/test/InstrumentationTestRunner.java @@ -1,117 +1,117 @@ package org.ruboto.test; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.jar.JarFile; import java.util.jar.JarEntry; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.ruboto.Script; public class InstrumentationTestRunner extends android.test.InstrumentationTestRunner { private Class activityClass; private Object setup; private TestSuite suite; public TestSuite getAllTests() { Log.i(getClass().getName(), "Finding test scripts"); suite = new TestSuite("Sweet"); try { if (Script.setUpJRuby(getTargetContext())) { - Script.defineGlobalVariable("$runner", this); - Script.defineGlobalVariable("$test", this); - Script.defineGlobalVariable("$suite", suite); + Script.defineGlobalVariable("$runner", this); + Script.defineGlobalVariable("$test", this); + Script.defineGlobalVariable("$suite", suite); - // TODO(uwe): Why doesn't this work? - // Script.copyScriptsIfNeeded(getContext()); + // TODO(uwe): Why doesn't this work? + // Script.copyScriptsIfNeeded(getContext()); - loadScript("test_helper.rb"); + loadScript("test_helper.rb"); - // TODO(uwe): Why doesn't this work? - // String[] scripts = new File(Script.scriptsDirName(getContext())).list(); + // TODO(uwe): Why doesn't this work? + // String[] scripts = new File(Script.scriptsDirName(getContext())).list(); - String[] scripts = getContext().getResources().getAssets().list("scripts"); - for (String f : scripts) { - if (f.equals("test_helper.rb")) continue; - Log.i(getClass().getName(), "Found script: " + f); - loadScript(f); - } + String[] scripts = getContext().getResources().getAssets().list("scripts"); + for (String f : scripts) { + if (f.equals("test_helper.rb")) continue; + Log.i(getClass().getName(), "Found script: " + f); + loadScript(f); + } } else { addError(suite, new RuntimeException("Ruboto Core platform is missing")); } } catch (IOException e) { addError(suite, e); } catch (RuntimeException e) { addError(suite, e); } return suite; } public void activity(Class activityClass) { this.activityClass = activityClass; } public void setup(Object block) { this.setup = block; } public void test(String name, Object block) { if (android.os.Build.VERSION.SDK_INT <= 8) { name ="runTest"; } Test test = new ActivityTest(activityClass, Script.getScriptFilename(), setup, name, block); suite.addTest(test); Log.d(getClass().getName(), "Made test instance: " + test); } private void addError(TestSuite suite, final Throwable t) { Log.e(getClass().getName(), "Exception loading tests: " + t); suite.addTest(new TestCase(t.getMessage()) { public void runTest() throws java.lang.Throwable { throw t; } }); } private void loadScript(String f) throws IOException { // TODO(uwe): Why doesn't this work? // InputStream is = new FileInputStream(Script.scriptsDirName(getContext()) + "/" + f); InputStream is = getContext().getResources().getAssets().open("scripts/" + f); BufferedReader buffer = new BufferedReader(new InputStreamReader(is)); StringBuilder source = new StringBuilder(); while (true) { String line = buffer.readLine(); if (line == null) break; source.append(line).append("\n"); } buffer.close(); Log.d(getClass().getName(), "Loading test script: " + f); String oldFilename = Script.getScriptFilename(); Script.setScriptFilename(f); Script.put("$script_code", source.toString()); Script.setScriptFilename(f); Script.execute("$test.instance_eval($script_code)"); Script.setScriptFilename(oldFilename); Log.d(getClass().getName(), "Test script " + f + " loaded"); } }
false
true
public TestSuite getAllTests() { Log.i(getClass().getName(), "Finding test scripts"); suite = new TestSuite("Sweet"); try { if (Script.setUpJRuby(getTargetContext())) { Script.defineGlobalVariable("$runner", this); Script.defineGlobalVariable("$test", this); Script.defineGlobalVariable("$suite", suite); // TODO(uwe): Why doesn't this work? // Script.copyScriptsIfNeeded(getContext()); loadScript("test_helper.rb"); // TODO(uwe): Why doesn't this work? // String[] scripts = new File(Script.scriptsDirName(getContext())).list(); String[] scripts = getContext().getResources().getAssets().list("scripts"); for (String f : scripts) { if (f.equals("test_helper.rb")) continue; Log.i(getClass().getName(), "Found script: " + f); loadScript(f); } } else { addError(suite, new RuntimeException("Ruboto Core platform is missing")); } } catch (IOException e) { addError(suite, e); } catch (RuntimeException e) { addError(suite, e); } return suite; }
public TestSuite getAllTests() { Log.i(getClass().getName(), "Finding test scripts"); suite = new TestSuite("Sweet"); try { if (Script.setUpJRuby(getTargetContext())) { Script.defineGlobalVariable("$runner", this); Script.defineGlobalVariable("$test", this); Script.defineGlobalVariable("$suite", suite); // TODO(uwe): Why doesn't this work? // Script.copyScriptsIfNeeded(getContext()); loadScript("test_helper.rb"); // TODO(uwe): Why doesn't this work? // String[] scripts = new File(Script.scriptsDirName(getContext())).list(); String[] scripts = getContext().getResources().getAssets().list("scripts"); for (String f : scripts) { if (f.equals("test_helper.rb")) continue; Log.i(getClass().getName(), "Found script: " + f); loadScript(f); } } else { addError(suite, new RuntimeException("Ruboto Core platform is missing")); } } catch (IOException e) { addError(suite, e); } catch (RuntimeException e) { addError(suite, e); } return suite; }
diff --git a/features/command/src/main/java/org/apache/karaf/features/command/ListUrlCommand.java b/features/command/src/main/java/org/apache/karaf/features/command/ListUrlCommand.java index e0c661a76..63c16e208 100644 --- a/features/command/src/main/java/org/apache/karaf/features/command/ListUrlCommand.java +++ b/features/command/src/main/java/org/apache/karaf/features/command/ListUrlCommand.java @@ -1,79 +1,79 @@ /* * 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.karaf.features.command; import java.net.URI; import org.apache.felix.gogo.commands.Command; import org.apache.felix.gogo.commands.Option; import org.apache.karaf.features.FeaturesService; import org.apache.karaf.features.Repository; /** * Command which lists feature URLs. * */ @Command(scope = "features", name = "listUrl", description = "Displays a list of all defined repository URLs.") public class ListUrlCommand extends FeaturesCommandSupport { @Option(name = "-v", aliases = "-validate", description = "Validate current version of descriptors", required = false, multiValued = false) boolean validation = false; @Option(name = "-vo", aliases = "-verbose", description = "Shows validation output", required = false, multiValued = false) boolean verbose = false; protected void doExecute(FeaturesService admin) throws Exception { Repository[] repos = admin.listRepositories(); String header; if (validation) { header = " Loaded Now valid URI "; } else { header = " Loaded URI "; } System.out.println(header); String verboseOutput = ""; if ((repos != null) && (repos.length > 0)) { for (int i = 0; i < repos.length; i++) { URI uri = repos[i].getURI(); String line = ""; line += repos[i].isValid() ? " true " : " false"; try { admin.validateRepository(uri); // append valid flag if validation mode is tuned on line += !validation ? "" : " true "; } catch (Exception e) { line += !validation ? "" : " false "; verboseOutput += uri + ":" + e.getMessage() + "\n"; } - System.out.println(line + " " + uri); + System.out.println(line + " " + uri); } if (verbose) { System.out.println("Validation output:\n" + verboseOutput); } } else { System.out.println("No repository URLs are set."); } } }
true
true
protected void doExecute(FeaturesService admin) throws Exception { Repository[] repos = admin.listRepositories(); String header; if (validation) { header = " Loaded Now valid URI "; } else { header = " Loaded URI "; } System.out.println(header); String verboseOutput = ""; if ((repos != null) && (repos.length > 0)) { for (int i = 0; i < repos.length; i++) { URI uri = repos[i].getURI(); String line = ""; line += repos[i].isValid() ? " true " : " false"; try { admin.validateRepository(uri); // append valid flag if validation mode is tuned on line += !validation ? "" : " true "; } catch (Exception e) { line += !validation ? "" : " false "; verboseOutput += uri + ":" + e.getMessage() + "\n"; } System.out.println(line + " " + uri); } if (verbose) { System.out.println("Validation output:\n" + verboseOutput); } } else { System.out.println("No repository URLs are set."); } }
protected void doExecute(FeaturesService admin) throws Exception { Repository[] repos = admin.listRepositories(); String header; if (validation) { header = " Loaded Now valid URI "; } else { header = " Loaded URI "; } System.out.println(header); String verboseOutput = ""; if ((repos != null) && (repos.length > 0)) { for (int i = 0; i < repos.length; i++) { URI uri = repos[i].getURI(); String line = ""; line += repos[i].isValid() ? " true " : " false"; try { admin.validateRepository(uri); // append valid flag if validation mode is tuned on line += !validation ? "" : " true "; } catch (Exception e) { line += !validation ? "" : " false "; verboseOutput += uri + ":" + e.getMessage() + "\n"; } System.out.println(line + " " + uri); } if (verbose) { System.out.println("Validation output:\n" + verboseOutput); } } else { System.out.println("No repository URLs are set."); } }
diff --git a/src/edu/wpi/first/wpilibj/templates/Launcher.java b/src/edu/wpi/first/wpilibj/templates/Launcher.java index fccea40..f4c5d7d 100644 --- a/src/edu/wpi/first/wpilibj/templates/Launcher.java +++ b/src/edu/wpi/first/wpilibj/templates/Launcher.java @@ -1,52 +1,53 @@ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.Jaguar; import edu.wpi.first.wpilibj.Timer; /** * * @author Nick, Michael */ public class Launcher { Jaguar launchMotor; Jaguar loadMotor; Encoder encoder; /** * Default constructor for the launcher */ public Launcher() { this.launchMotor = new Jaguar(RoboMap.LAUNCH_MOTOR); this.loadMotor = new Jaguar(RoboMap.LOAD_MOTOR); this.encoder = new Encoder(RoboMap.LAUNCH_ENCODER1, RoboMap.LAUNCH_ENCODER2, false); this.encoder.setDistancePerPulse(1); } private double getRPM() { double encod1 = encoder.get(); double deltaTime = .01; Timer.delay(deltaTime); double encod2 = encoder.get(); double deltaEncod = encod2 - encod1; double RPM = deltaEncod / (deltaTime * 6); return RPM; } public void shoot(int pixel) { double speed = 0.0; int launchSpeed = pixel * /* this can change to tested values later */1000; encoder.start(); while (MathX.abs(getRPM() - launchSpeed) >= 100) { launchMotor.set(speed); speed += .025; Timer.delay(.025); } encoder.stop(); loadMotor.set(.25); Timer.delay(5); loadMotor.set(0); + launchMotor.set(0); } }
true
true
public void shoot(int pixel) { double speed = 0.0; int launchSpeed = pixel * /* this can change to tested values later */1000; encoder.start(); while (MathX.abs(getRPM() - launchSpeed) >= 100) { launchMotor.set(speed); speed += .025; Timer.delay(.025); } encoder.stop(); loadMotor.set(.25); Timer.delay(5); loadMotor.set(0); }
public void shoot(int pixel) { double speed = 0.0; int launchSpeed = pixel * /* this can change to tested values later */1000; encoder.start(); while (MathX.abs(getRPM() - launchSpeed) >= 100) { launchMotor.set(speed); speed += .025; Timer.delay(.025); } encoder.stop(); loadMotor.set(.25); Timer.delay(5); loadMotor.set(0); launchMotor.set(0); }
diff --git a/src/com/android/camera/Util.java b/src/com/android/camera/Util.java index d6ebb0a5..c7d85830 100644 --- a/src/com/android/camera/Util.java +++ b/src/com/android/camera/Util.java @@ -1,718 +1,718 @@ /* * Copyright (C) 2009 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 android.app.Activity; import android.app.AlertDialog; import android.app.admin.DevicePolicyManager; import android.content.ActivityNotFoundException; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.RectF; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.hardware.Camera.Parameters; import android.hardware.Camera.Size; import android.location.Location; import android.net.Uri; import android.os.Build; import android.os.ParcelFileDescriptor; import android.provider.Settings; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.OrientationEventListener; import android.view.Surface; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.StringTokenizer; /** * Collection of utility functions used in this package. */ public class Util { private static final String TAG = "Util"; private static final int DIRECTION_LEFT = 0; private static final int DIRECTION_RIGHT = 1; private static final int DIRECTION_UP = 2; private static final int DIRECTION_DOWN = 3; // The brightness setting used when it is set to automatic in the system. // The reason why it is set to 0.7 is just because 1.0 is too bright. // Use the same setting among the Camera, VideoCamera and Panorama modes. private static final float DEFAULT_CAMERA_BRIGHTNESS = 0.7f; // Orientation hysteresis amount used in rounding, in degrees public static final int ORIENTATION_HYSTERESIS = 5; public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW"; // Private intent extras. Test only. private static final String EXTRAS_CAMERA_FACING = "android.intent.extras.CAMERA_FACING"; private static boolean sIsTabletUI; private static float sPixelDensity = 1; private static ImageFileNamer sImageFileNamer; private Util() { } public static void initialize(Context context) { sIsTabletUI = (context.getResources().getConfiguration().smallestScreenWidthDp >= 600); DisplayMetrics metrics = new DisplayMetrics(); WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(metrics); sPixelDensity = metrics.density; sImageFileNamer = new ImageFileNamer( context.getString(R.string.image_file_name_format)); } public static boolean isTabletUI() { return sIsTabletUI; } public static int dpToPixel(int dp) { return Math.round(sPixelDensity * dp); } // Rotates the bitmap by the specified degree. // If a new bitmap is created, the original bitmap is recycled. public static Bitmap rotate(Bitmap b, int degrees) { return rotateAndMirror(b, degrees, false); } // Rotates and/or mirrors the bitmap. If a new bitmap is created, the // original bitmap is recycled. public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) { if ((degrees != 0 || mirror) && b != null) { Matrix m = new Matrix(); // Mirror first. // horizontal flip + rotation = -rotation + horizontal flip if (mirror) { m.postScale(-1, 1); degrees = (degrees + 360) % 360; if (degrees == 0 || degrees == 180) { m.postTranslate((float) b.getWidth(), 0); } else if (degrees == 90 || degrees == 270) { m.postTranslate((float) b.getHeight(), 0); } else { throw new IllegalArgumentException("Invalid degrees=" + degrees); } } if (degrees != 0) { // clockwise m.postRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2); } try { Bitmap b2 = Bitmap.createBitmap( b, 0, 0, b.getWidth(), b.getHeight(), m, true); if (b != b2) { b.recycle(); b = b2; } } catch (OutOfMemoryError ex) { // We have no memory to rotate. Return the original bitmap. } } return b; } /* * Compute the sample size as a function of minSideLength * and maxNumOfPixels. * minSideLength is used to specify that minimal width or height of a * bitmap. * maxNumOfPixels is used to specify the maximal size in pixels that is * tolerable in terms of memory usage. * * The function returns a sample size based on the constraints. * Both size and minSideLength can be passed in as -1 * which indicates no care of the corresponding constraint. * The functions prefers returning a sample size that * generates a smaller bitmap, unless minSideLength = -1. * * Also, the function rounds up the sample size to a power of 2 or multiple * of 8 because BitmapFactory only honors sample size this way. * For example, BitmapFactory downsamples an image by 2 even though the * request is 3. So we round up the sample size to avoid OOM. */ public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels); int roundedSize; if (initialSize <= 8) { roundedSize = 1; while (roundedSize < initialSize) { roundedSize <<= 1; } } else { roundedSize = (initialSize + 7) / 8 * 8; } return roundedSize; } private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) { double w = options.outWidth; double h = options.outHeight; int lowerBound = (maxNumOfPixels < 0) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels)); int upperBound = (minSideLength < 0) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength)); if (upperBound < lowerBound) { // return the larger one when there is no overlapping zone. return lowerBound; } if (maxNumOfPixels < 0 && minSideLength < 0) { return 1; } else if (minSideLength < 0) { return lowerBound; } else { return upperBound; } } public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, options); if (options.mCancel || options.outWidth == -1 || options.outHeight == -1) { return null; } options.inSampleSize = computeSampleSize( options, -1, maxNumOfPixels); options.inJustDecodeBounds = false; options.inDither = false; options.inPreferredConfig = Bitmap.Config.ARGB_8888; return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length, options); } catch (OutOfMemoryError ex) { Log.e(TAG, "Got oom exception ", ex); return null; } } public static void closeSilently(Closeable c) { if (c == null) return; try { c.close(); } catch (Throwable t) { // do nothing } } public static void Assert(boolean cond) { if (!cond) { throw new AssertionError(); } } public static android.hardware.Camera openCamera(Activity activity, int cameraId) throws CameraHardwareException, CameraDisabledException { // Check if device policy has disabled the camera. DevicePolicyManager dpm = (DevicePolicyManager) activity.getSystemService( Context.DEVICE_POLICY_SERVICE); if (dpm.getCameraDisabled(null)) { throw new CameraDisabledException(); } try { return CameraHolder.instance().open(cameraId); } catch (CameraHardwareException e) { // In eng build, we throw the exception so that test tool // can detect it and report it if ("eng".equals(Build.TYPE)) { throw new RuntimeException("openCamera failed", e); } else { throw e; } } } public static void showErrorAndFinish(final Activity activity, int msgId) { DialogInterface.OnClickListener buttonListener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { activity.finish(); } }; new AlertDialog.Builder(activity) .setCancelable(false) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle(R.string.camera_error_title) .setMessage(msgId) .setNeutralButton(R.string.dialog_ok, buttonListener) .show(); } public static <T> T checkNotNull(T object) { if (object == null) throw new NullPointerException(); return object; } public static boolean equals(Object a, Object b) { return (a == b) || (a == null ? false : a.equals(b)); } public static int nextPowerOf2(int n) { n -= 1; n |= n >>> 16; n |= n >>> 8; n |= n >>> 4; n |= n >>> 2; n |= n >>> 1; return n + 1; } public static float distance(float x, float y, float sx, float sy) { float dx = x - sx; float dy = y - sy; return (float) Math.sqrt(dx * dx + dy * dy); } public static int clamp(int x, int min, int max) { if (x > max) return max; if (x < min) return min; return x; } public static int getDisplayRotation(Activity activity) { int rotation = activity.getWindowManager().getDefaultDisplay() .getRotation(); switch (rotation) { case Surface.ROTATION_0: return 0; case Surface.ROTATION_90: return 90; case Surface.ROTATION_180: return 180; case Surface.ROTATION_270: return 270; } return 0; } public static int getDisplayOrientation(int degrees, int cameraId) { // See android.hardware.Camera.setDisplayOrientation for // documentation. Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(cameraId, info); int result; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; // compensate the mirror } else { // back-facing result = (info.orientation - degrees + 360) % 360; } return result; } public static int getCameraOrientation(int cameraId) { Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(cameraId, info); return info.orientation; } public static int roundOrientation(int orientation, int orientationHistory) { boolean changeOrientation = false; if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) { changeOrientation = true; } else { int dist = Math.abs(orientation - orientationHistory); dist = Math.min( dist, 360 - dist ); changeOrientation = ( dist >= 45 + ORIENTATION_HYSTERESIS ); } if (changeOrientation) { return ((orientation + 45) / 90 * 90) % 360; } return orientationHistory; } public static Size getOptimalPreviewSize(Activity currentActivity, List<Size> sizes, double targetRatio) { - // Use a very small tolerance because we want an exact match. - final double ASPECT_TOLERANCE = 0.001; + // Not too small tolerance, some camera use 848, 854 or 864 for 480p + final double ASPECT_TOLERANCE = 0.05; if (sizes == null) return null; Size optimalSize = null; double minDiff = Double.MAX_VALUE; // Because of bugs of overlay and layout, we sometimes will try to // layout the viewfinder in the portrait orientation and thus get the // wrong size of mSurfaceView. When we change the preview size, the // new overlay will be created before the old one closed, which causes // an exception. For now, just get the screen size Display display = currentActivity.getWindowManager().getDefaultDisplay(); int targetHeight = Math.min(display.getHeight(), display.getWidth()); if (targetHeight <= 0) { // We don't know the size of SurfaceView, use screen height targetHeight = display.getHeight(); } // Try to find an size match aspect ratio and size for (Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } // Cannot find the one match the aspect ratio. This should not happen. // Ignore the requirement. if (optimalSize == null) { Log.w(TAG, "No preview size match the aspect ratio"); minDiff = Double.MAX_VALUE; for (Size size : sizes) { if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } } return optimalSize; } // Returns the largest picture size which matches the given aspect ratio. public static Size getOptimalVideoSnapshotPictureSize( List<Size> sizes, double targetRatio) { // Use a very small tolerance because we want an exact match. final double ASPECT_TOLERANCE = 0.001; if (sizes == null) return null; Size optimalSize = null; // Try to find a size matches aspect ratio and has the largest width for (Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; if (optimalSize == null || size.width > optimalSize.width) { optimalSize = size; } } // Cannot find one that matches the aspect ratio. This should not happen. // Ignore the requirement. if (optimalSize == null) { Log.w(TAG, "No picture size match the aspect ratio"); for (Size size : sizes) { if (optimalSize == null || size.width > optimalSize.width) { optimalSize = size; } } } return optimalSize; } public static void dumpParameters(Parameters parameters) { String flattened = parameters.flatten(); StringTokenizer tokenizer = new StringTokenizer(flattened, ";"); Log.d(TAG, "Dump all camera parameters:"); while (tokenizer.hasMoreElements()) { Log.d(TAG, tokenizer.nextToken()); } } /** * Returns whether the device is voice-capable (meaning, it can do MMS). */ public static boolean isMmsCapable(Context context) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager == null) { return false; } try { Class partypes[] = new Class[0]; Method sIsVoiceCapable = TelephonyManager.class.getMethod( "isVoiceCapable", partypes); Object arglist[] = new Object[0]; Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist); return (Boolean) retobj; } catch (java.lang.reflect.InvocationTargetException ite) { // Failure, must be another device. // Assume that it is voice capable. } catch (IllegalAccessException iae) { // Failure, must be an other device. // Assume that it is voice capable. } catch (NoSuchMethodException nsme) { } return true; } // This is for test only. Allow the camera to launch the specific camera. public static int getCameraFacingIntentExtras(Activity currentActivity) { int cameraId = -1; int intentCameraId = currentActivity.getIntent().getIntExtra(Util.EXTRAS_CAMERA_FACING, -1); if (isFrontCameraIntent(intentCameraId)) { // Check if the front camera exist int frontCameraId = CameraHolder.instance().getFrontCameraId(); if (frontCameraId != -1) { cameraId = frontCameraId; } } else if (isBackCameraIntent(intentCameraId)) { // Check if the back camera exist int backCameraId = CameraHolder.instance().getBackCameraId(); if (backCameraId != -1) { cameraId = backCameraId; } } return cameraId; } private static boolean isFrontCameraIntent(int intentCameraId) { return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT); } private static boolean isBackCameraIntent(int intentCameraId) { return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK); } private static int mLocation[] = new int[2]; // This method is not thread-safe. public static boolean pointInView(float x, float y, View v) { v.getLocationInWindow(mLocation); return x >= mLocation[0] && x < (mLocation[0] + v.getWidth()) && y >= mLocation[1] && y < (mLocation[1] + v.getHeight()); } public static boolean isUriValid(Uri uri, ContentResolver resolver) { if (uri == null) return false; try { ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r"); if (pfd == null) { Log.e(TAG, "Fail to open URI. URI=" + uri); return false; } pfd.close(); } catch (IOException ex) { return false; } return true; } public static void viewUri(Uri uri, Context context) { if (!isUriValid(uri, context.getContentResolver())) { Log.e(TAG, "Uri invalid. uri=" + uri); return; } try { context.startActivity(new Intent(Util.REVIEW_ACTION, uri)); } catch (ActivityNotFoundException ex) { try { context.startActivity(new Intent(Intent.ACTION_VIEW, uri)); } catch (ActivityNotFoundException e) { Log.e(TAG, "review image fail. uri=" + uri, e); } } } public static void dumpRect(RectF rect, String msg) { Log.v(TAG, msg + "=(" + rect.left + "," + rect.top + "," + rect.right + "," + rect.bottom + ")"); } public static void rectFToRect(RectF rectF, Rect rect) { rect.left = Math.round(rectF.left); rect.top = Math.round(rectF.top); rect.right = Math.round(rectF.right); rect.bottom = Math.round(rectF.bottom); } public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation, int viewWidth, int viewHeight) { // Need mirror for front camera. matrix.setScale(mirror ? -1 : 1, 1); // This is the value for android.hardware.Camera.setDisplayOrientation. matrix.postRotate(displayOrientation); // Camera driver coordinates range from (-1000, -1000) to (1000, 1000). // UI coordinates range from (0, 0) to (width, height). matrix.postScale(viewWidth / 2000f, viewHeight / 2000f); matrix.postTranslate(viewWidth / 2f, viewHeight / 2f); } public static String createJpegName(long dateTaken) { synchronized (sImageFileNamer) { return sImageFileNamer.generateName(dateTaken); } } public static void broadcastNewPicture(Context context, Uri uri) { context.sendBroadcast(new Intent(android.hardware.Camera.ACTION_NEW_PICTURE, uri)); // Keep compatibility context.sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri)); } public static void fadeIn(View view) { if (view.getVisibility() == View.VISIBLE) return; view.setVisibility(View.VISIBLE); Animation animation = new AlphaAnimation(0F, 1F); animation.setDuration(400); view.startAnimation(animation); } public static void fadeOut(View view) { if (view.getVisibility() != View.VISIBLE) return; Animation animation = new AlphaAnimation(1F, 0F); animation.setDuration(400); view.startAnimation(animation); view.setVisibility(View.GONE); } public static void setRotationParameter(Parameters parameters, int cameraId, int orientation) { // See android.hardware.Camera.Parameters.setRotation for // documentation. int rotation = 0; if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) { CameraInfo info = CameraHolder.instance().getCameraInfo()[cameraId]; if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { rotation = (info.orientation - orientation + 360) % 360; } else { // back-facing camera rotation = (info.orientation + orientation) % 360; } } parameters.setRotation(rotation); } public static void setGpsParameters(Parameters parameters, Location loc) { // Clear previous GPS location from the parameters. parameters.removeGpsData(); // We always encode GpsTimeStamp parameters.setGpsTimestamp(System.currentTimeMillis() / 1000); // Set GPS location. if (loc != null) { double lat = loc.getLatitude(); double lon = loc.getLongitude(); boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d); if (hasLatLon) { Log.d(TAG, "Set gps location"); parameters.setGpsLatitude(lat); parameters.setGpsLongitude(lon); parameters.setGpsProcessingMethod(loc.getProvider().toUpperCase()); if (loc.hasAltitude()) { parameters.setGpsAltitude(loc.getAltitude()); } else { // for NETWORK_PROVIDER location provider, we may have // no altitude information, but the driver needs it, so // we fake one. parameters.setGpsAltitude(0); } if (loc.getTime() != 0) { // Location.getTime() is UTC in milliseconds. // gps-timestamp is UTC in seconds. long utcTimeSeconds = loc.getTime() / 1000; parameters.setGpsTimestamp(utcTimeSeconds); } } else { loc = null; } } } public static void enterLightsOutMode(Window window) { WindowManager.LayoutParams params = window.getAttributes(); params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE; window.setAttributes(params); } public static void initializeScreenBrightness(Window win, ContentResolver resolver) { // Overright the brightness settings if it is automatic int mode = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { WindowManager.LayoutParams winParams = win.getAttributes(); winParams.screenBrightness = DEFAULT_CAMERA_BRIGHTNESS; win.setAttributes(winParams); } } private static class ImageFileNamer { private SimpleDateFormat mFormat; // The date (in milliseconds) used to generate the last name. private long mLastDate; // Number of names generated for the same second. private int mSameSecondCount; public ImageFileNamer(String format) { mFormat = new SimpleDateFormat(format); } public String generateName(long dateTaken) { Date date = new Date(dateTaken); String result = mFormat.format(date); // If the last name was generated for the same second, // we append _1, _2, etc to the name. if (dateTaken / 1000 == mLastDate / 1000) { mSameSecondCount++; result += "_" + mSameSecondCount; } else { mLastDate = dateTaken; mSameSecondCount = 0; } return result; } } }
true
true
public static Size getOptimalPreviewSize(Activity currentActivity, List<Size> sizes, double targetRatio) { // Use a very small tolerance because we want an exact match. final double ASPECT_TOLERANCE = 0.001; if (sizes == null) return null; Size optimalSize = null; double minDiff = Double.MAX_VALUE; // Because of bugs of overlay and layout, we sometimes will try to // layout the viewfinder in the portrait orientation and thus get the // wrong size of mSurfaceView. When we change the preview size, the // new overlay will be created before the old one closed, which causes // an exception. For now, just get the screen size Display display = currentActivity.getWindowManager().getDefaultDisplay(); int targetHeight = Math.min(display.getHeight(), display.getWidth()); if (targetHeight <= 0) { // We don't know the size of SurfaceView, use screen height targetHeight = display.getHeight(); } // Try to find an size match aspect ratio and size for (Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } // Cannot find the one match the aspect ratio. This should not happen. // Ignore the requirement. if (optimalSize == null) { Log.w(TAG, "No preview size match the aspect ratio"); minDiff = Double.MAX_VALUE; for (Size size : sizes) { if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } } return optimalSize; }
public static Size getOptimalPreviewSize(Activity currentActivity, List<Size> sizes, double targetRatio) { // Not too small tolerance, some camera use 848, 854 or 864 for 480p final double ASPECT_TOLERANCE = 0.05; if (sizes == null) return null; Size optimalSize = null; double minDiff = Double.MAX_VALUE; // Because of bugs of overlay and layout, we sometimes will try to // layout the viewfinder in the portrait orientation and thus get the // wrong size of mSurfaceView. When we change the preview size, the // new overlay will be created before the old one closed, which causes // an exception. For now, just get the screen size Display display = currentActivity.getWindowManager().getDefaultDisplay(); int targetHeight = Math.min(display.getHeight(), display.getWidth()); if (targetHeight <= 0) { // We don't know the size of SurfaceView, use screen height targetHeight = display.getHeight(); } // Try to find an size match aspect ratio and size for (Size size : sizes) { double ratio = (double) size.width / size.height; if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue; if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } // Cannot find the one match the aspect ratio. This should not happen. // Ignore the requirement. if (optimalSize == null) { Log.w(TAG, "No preview size match the aspect ratio"); minDiff = Double.MAX_VALUE; for (Size size : sizes) { if (Math.abs(size.height - targetHeight) < minDiff) { optimalSize = size; minDiff = Math.abs(size.height - targetHeight); } } } return optimalSize; }
diff --git a/src/com/group5/android/fd/activity/dialog/QuantityRemoverDialog.java b/src/com/group5/android/fd/activity/dialog/QuantityRemoverDialog.java index abe2504..33f59a1 100644 --- a/src/com/group5/android/fd/activity/dialog/QuantityRemoverDialog.java +++ b/src/com/group5/android/fd/activity/dialog/QuantityRemoverDialog.java @@ -1,62 +1,63 @@ package com.group5.android.fd.activity.dialog; import android.content.Context; import android.view.View; import android.widget.Toast; import com.group5.android.fd.R; import com.group5.android.fd.entity.OrderItemEntity; public class QuantityRemoverDialog extends NumberPickerDialog { protected OrderItemEntity m_orderItem; public QuantityRemoverDialog(Context context) { super(context); m_vwQuantity.setText("1"); onQuantityChange(); } public void setOrderItem(OrderItemEntity orderItem) { m_orderItem = orderItem; // m_vwItemName.setText(item.itemName); m_vwQuantity.setText(String.valueOf(m_orderItem.quantity)); onQuantityChange(); } public OrderItemEntity getOrderItem() { return m_orderItem; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnSet: if (getQuantity() < 0) { - Toast - .makeText( - getContext(), - R.string.quantityselectordialog_please_enter_a_valid_quantity, - Toast.LENGTH_SHORT); + Toast.makeText( + getContext(), + R.string.quantityselectordialog_please_enter_a_valid_quantity, + Toast.LENGTH_SHORT); m_vwQuantity.requestFocus(); } else { dismiss(); } break; case R.id.btnPlus: quantity += 1; m_vwQuantity.setText(String.valueOf(quantity)); break; case R.id.btnSubtract: - quantity -= 1; - if (quantity >= 0) { - m_vwQuantity.setText(String.valueOf(quantity)); + if (quantity > 0) { + quantity -= 1; + } else { + quantity = 0; } + m_vwQuantity.setText(String.valueOf(quantity)); break; case R.id.btnCancel: quantity = oldQuantity; dismiss(); break; } } }
false
true
public void onClick(View v) { switch (v.getId()) { case R.id.btnSet: if (getQuantity() < 0) { Toast .makeText( getContext(), R.string.quantityselectordialog_please_enter_a_valid_quantity, Toast.LENGTH_SHORT); m_vwQuantity.requestFocus(); } else { dismiss(); } break; case R.id.btnPlus: quantity += 1; m_vwQuantity.setText(String.valueOf(quantity)); break; case R.id.btnSubtract: quantity -= 1; if (quantity >= 0) { m_vwQuantity.setText(String.valueOf(quantity)); } break; case R.id.btnCancel: quantity = oldQuantity; dismiss(); break; } }
public void onClick(View v) { switch (v.getId()) { case R.id.btnSet: if (getQuantity() < 0) { Toast.makeText( getContext(), R.string.quantityselectordialog_please_enter_a_valid_quantity, Toast.LENGTH_SHORT); m_vwQuantity.requestFocus(); } else { dismiss(); } break; case R.id.btnPlus: quantity += 1; m_vwQuantity.setText(String.valueOf(quantity)); break; case R.id.btnSubtract: if (quantity > 0) { quantity -= 1; } else { quantity = 0; } m_vwQuantity.setText(String.valueOf(quantity)); break; case R.id.btnCancel: quantity = oldQuantity; dismiss(); break; } }
diff --git a/src/de/quiz/Servlets/PlayerServlet.java b/src/de/quiz/Servlets/PlayerServlet.java index 1a27c23..15594a7 100644 --- a/src/de/quiz/Servlets/PlayerServlet.java +++ b/src/de/quiz/Servlets/PlayerServlet.java @@ -1,138 +1,138 @@ package de.quiz.Servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.AsyncContext; 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 javax.servlet.http.HttpSession; import org.json.JSONObject; import de.fhwgt.quiz.application.Quiz; import de.fhwgt.quiz.error.QuizError; import de.quiz.LoggingManager.ILoggingManager; import de.quiz.ServiceManager.ServiceManager; import de.quiz.User.IUser; import de.quiz.UserManager.IUserManager; /** * Servlet implementation class PlayerServlet */ @WebServlet(description = "handles everything which has to do with players", urlPatterns = { "/PlayerServlet" }) public class PlayerServlet extends HttpServlet { private static final long serialVersionUID = 1L; private AsyncContext asyncCo; /** * @see HttpServlet#HttpServlet() */ public PlayerServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServiceManager.getInstance().getService(ILoggingManager.class).log("GET is not supported by this Servlet"); response.getWriter().print("GET is not supported by this Servlet"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sc = ""; if (request.getParameter("rID") != null) { sc = request.getParameter("rID"); } // login request if (sc.equals("1")) { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); IUser tmpUser; try { // create user tmpUser = ServiceManager.getInstance() .getService(IUserManager.class) .loginUser(request.getParameter("name"), session); System.out.println("session: "+session); // send playerlist //response.setContentType("application/json"); //JSONObject json = ServiceManager.getInstance() // .getService(IUserManager.class).getPlayerList(); //out.print(json); -// out.print(2); + out.print(2); ServiceManager .getInstance() .getService(ILoggingManager.class) .log("Successfully logged in User with ID: " + tmpUser.getUserID() + " and name: "+tmpUser.getName()); // response.reset(); // response.resetBuffer(); // doGet(request,response); } catch (Exception e) { ServiceManager.getInstance().getService(ILoggingManager.class) .log("User login failed!"); response.setContentType("text/plain"); out.print(255); } } // playerlist if (sc.equals("6")) { PrintWriter out = response.getWriter(); try { response.setContentType("application/json"); JSONObject json = ServiceManager.getInstance() .getService(IUserManager.class).getPlayerList(); out.print(json); ServiceManager.getInstance().getService(ILoggingManager.class) .log("Send Playerlist!"); } catch (Exception e) { ServiceManager.getInstance().getService(ILoggingManager.class) .log("Failed sending Playerlist!"); response.setContentType("text/plain"); out.print(255); } } // start game // TODO: MUSS �BER SERVER SENT EVENTS LAUFEN!!! if (sc.equals("7") && request.getParameter("uID").equals("0")) { PrintWriter out = response.getWriter(); QuizError error = new QuizError(); Quiz.getInstance().startGame( ServiceManager.getInstance().getService(IUserManager.class) .getUserBySession(request.getSession()) .getPlayerObject(), error); if (error.isSet()) { ServiceManager.getInstance().getService(ILoggingManager.class) .log("Failed starting game!"); response.setContentType("text/plain"); out.print(255); } else { ServiceManager.getInstance().getService(ILoggingManager.class) .log("Started game!"); response.setContentType("text/plain"); out.print(200); } } } }
true
true
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sc = ""; if (request.getParameter("rID") != null) { sc = request.getParameter("rID"); } // login request if (sc.equals("1")) { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); IUser tmpUser; try { // create user tmpUser = ServiceManager.getInstance() .getService(IUserManager.class) .loginUser(request.getParameter("name"), session); System.out.println("session: "+session); // send playerlist //response.setContentType("application/json"); //JSONObject json = ServiceManager.getInstance() // .getService(IUserManager.class).getPlayerList(); //out.print(json); // out.print(2); ServiceManager .getInstance() .getService(ILoggingManager.class) .log("Successfully logged in User with ID: " + tmpUser.getUserID() + " and name: "+tmpUser.getName()); // response.reset(); // response.resetBuffer(); // doGet(request,response); } catch (Exception e) { ServiceManager.getInstance().getService(ILoggingManager.class) .log("User login failed!"); response.setContentType("text/plain"); out.print(255); } } // playerlist if (sc.equals("6")) { PrintWriter out = response.getWriter(); try { response.setContentType("application/json"); JSONObject json = ServiceManager.getInstance() .getService(IUserManager.class).getPlayerList(); out.print(json); ServiceManager.getInstance().getService(ILoggingManager.class) .log("Send Playerlist!"); } catch (Exception e) { ServiceManager.getInstance().getService(ILoggingManager.class) .log("Failed sending Playerlist!"); response.setContentType("text/plain"); out.print(255); } } // start game // TODO: MUSS �BER SERVER SENT EVENTS LAUFEN!!! if (sc.equals("7") && request.getParameter("uID").equals("0")) { PrintWriter out = response.getWriter(); QuizError error = new QuizError(); Quiz.getInstance().startGame( ServiceManager.getInstance().getService(IUserManager.class) .getUserBySession(request.getSession()) .getPlayerObject(), error); if (error.isSet()) { ServiceManager.getInstance().getService(ILoggingManager.class) .log("Failed starting game!"); response.setContentType("text/plain"); out.print(255); } else { ServiceManager.getInstance().getService(ILoggingManager.class) .log("Started game!"); response.setContentType("text/plain"); out.print(200); } } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sc = ""; if (request.getParameter("rID") != null) { sc = request.getParameter("rID"); } // login request if (sc.equals("1")) { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); IUser tmpUser; try { // create user tmpUser = ServiceManager.getInstance() .getService(IUserManager.class) .loginUser(request.getParameter("name"), session); System.out.println("session: "+session); // send playerlist //response.setContentType("application/json"); //JSONObject json = ServiceManager.getInstance() // .getService(IUserManager.class).getPlayerList(); //out.print(json); out.print(2); ServiceManager .getInstance() .getService(ILoggingManager.class) .log("Successfully logged in User with ID: " + tmpUser.getUserID() + " and name: "+tmpUser.getName()); // response.reset(); // response.resetBuffer(); // doGet(request,response); } catch (Exception e) { ServiceManager.getInstance().getService(ILoggingManager.class) .log("User login failed!"); response.setContentType("text/plain"); out.print(255); } } // playerlist if (sc.equals("6")) { PrintWriter out = response.getWriter(); try { response.setContentType("application/json"); JSONObject json = ServiceManager.getInstance() .getService(IUserManager.class).getPlayerList(); out.print(json); ServiceManager.getInstance().getService(ILoggingManager.class) .log("Send Playerlist!"); } catch (Exception e) { ServiceManager.getInstance().getService(ILoggingManager.class) .log("Failed sending Playerlist!"); response.setContentType("text/plain"); out.print(255); } } // start game // TODO: MUSS �BER SERVER SENT EVENTS LAUFEN!!! if (sc.equals("7") && request.getParameter("uID").equals("0")) { PrintWriter out = response.getWriter(); QuizError error = new QuizError(); Quiz.getInstance().startGame( ServiceManager.getInstance().getService(IUserManager.class) .getUserBySession(request.getSession()) .getPlayerObject(), error); if (error.isSet()) { ServiceManager.getInstance().getService(ILoggingManager.class) .log("Failed starting game!"); response.setContentType("text/plain"); out.print(255); } else { ServiceManager.getInstance().getService(ILoggingManager.class) .log("Started game!"); response.setContentType("text/plain"); out.print(200); } } }
diff --git a/src/contrib/fairscheduler/src/test/org/apache/hadoop/mapred/TestFairSchedulerSystem.java b/src/contrib/fairscheduler/src/test/org/apache/hadoop/mapred/TestFairSchedulerSystem.java index f33697dd71..bb6808dfa1 100644 --- a/src/contrib/fairscheduler/src/test/org/apache/hadoop/mapred/TestFairSchedulerSystem.java +++ b/src/contrib/fairscheduler/src/test/org/apache/hadoop/mapred/TestFairSchedulerSystem.java @@ -1,189 +1,198 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.mapred; import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig; import org.apache.hadoop.mapreduce.SleepJob; import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.conf.Configuration; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.HttpURLConnection; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeUnit; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.BeforeClass; import org.junit.AfterClass; import static org.junit.Assert.*; /** * System tests for the fair scheduler. These run slower than the * mock-based tests in TestFairScheduler but have a better chance * of catching synchronization bugs with the real JT. * * This test suite will often be run inside JCarder in order to catch * deadlock bugs which have plagued the scheduler in the past - hence * it is a bit of a "grab-bag" of system tests, since it's important * that they all run as part of the same JVM instantiation. */ public class TestFairSchedulerSystem { static final int NUM_THREADS=2; static MiniMRCluster mr; static JobConf conf; @BeforeClass public static void setUp() throws Exception { conf = new JobConf(); final int taskTrackers = 1; // Bump up the frequency of preemption updates to test against // deadlocks, etc. conf.set("mapred.jobtracker.taskScheduler", FairScheduler.class.getCanonicalName()); conf.set("mapred.fairscheduler.update.interval", "1"); conf.set("mapred.fairscheduler.preemption.interval", "1"); conf.set("mapred.fairscheduler.preemption", "true"); conf.set("mapred.fairscheduler.eventlog.enabled", "true"); conf.set(JTConfig.JT_PERSIST_JOBSTATUS, "false"); mr = new MiniMRCluster(taskTrackers, "file:///", 1, null, null, conf); } @AfterClass public static void tearDown() throws Exception { if (mr != null) { mr.shutdown(); } } private void runSleepJob(JobConf conf) throws Exception { String[] args = { "-m", "1", "-r", "1", "-mt", "1", "-rt", "1" }; ToolRunner.run(conf, new SleepJob(), args); } /** * Submit some concurrent sleep jobs, and visit the scheduler servlet * while they're running. */ @Test public void testFairSchedulerSystem() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); List<Future<Void>> futures = new ArrayList<Future<Void>>(NUM_THREADS); for (int i = 0; i < NUM_THREADS; i++) { futures.add(exec.submit(new Callable<Void>() { public Void call() throws Exception { JobConf jobConf = mr.createJobConf(); runSleepJob(jobConf); return null; } })); } JobClient jc = new JobClient(mr.createJobConf(null)); // Wait for the tasks to finish, and visit the scheduler servlet // every few seconds while waiting. for (Future<Void> future : futures) { while (true) { try { future.get(3, TimeUnit.SECONDS); break; } catch (TimeoutException te) { // It's OK } checkServlet(true); checkServlet(false); JobStatus jobs[] = jc.getAllJobs(); if (jobs == null) { System.err.println("No jobs running, not checking tasklog servlet"); continue; } for (JobStatus j : jobs) { - System.err.println("Checking task log for " + j.getJobID()); - checkTaskGraphServlet(j.getJobID()); + System.err.println("Checking task graph for " + j.getJobID()); + try { + checkTaskGraphServlet(j.getJobID()); + } catch (AssertionError err) { + // The task graph servlet will be empty if the job has retired. + // This is OK. + RunningJob rj = jc.getJob(j.getJobID()); + if (!rj.isRetired()) { + throw err; + } + } } } } } /** * Check the fair scheduler servlet for good status code and smoke test * for contents. */ private void checkServlet(boolean advanced) throws Exception { String jtURL = "http://localhost:" + mr.getJobTrackerRunner().getJobTrackerInfoPort(); URL url = new URL(jtURL + "/scheduler" + (advanced ? "?advanced" : "")); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); assertEquals(200, connection.getResponseCode()); // Just to be sure, slurp the content and make sure it looks like the scheduler BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } String contents = sb.toString(); assertTrue("Bad contents for fair scheduler servlet: " + contents, contents.contains("Fair Scheduler Administration")); } private void checkTaskGraphServlet(JobID job) throws Exception { String jtURL = "http://localhost:" + mr.getJobTrackerRunner().getJobTrackerInfoPort(); URL url = new URL(jtURL + "/taskgraph?jobid=" + job.toString() + "&type=map"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); assertEquals(200, connection.getResponseCode()); // Just to be sure, slurp the content and make sure it looks like the scheduler String contents = slurpContents(connection); assertTrue("Bad contents for job " + job + ":\n" + contents, contents.contains("</svg>")); } private String slurpContents(HttpURLConnection connection) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } return sb.toString(); } }
true
true
public void testFairSchedulerSystem() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); List<Future<Void>> futures = new ArrayList<Future<Void>>(NUM_THREADS); for (int i = 0; i < NUM_THREADS; i++) { futures.add(exec.submit(new Callable<Void>() { public Void call() throws Exception { JobConf jobConf = mr.createJobConf(); runSleepJob(jobConf); return null; } })); } JobClient jc = new JobClient(mr.createJobConf(null)); // Wait for the tasks to finish, and visit the scheduler servlet // every few seconds while waiting. for (Future<Void> future : futures) { while (true) { try { future.get(3, TimeUnit.SECONDS); break; } catch (TimeoutException te) { // It's OK } checkServlet(true); checkServlet(false); JobStatus jobs[] = jc.getAllJobs(); if (jobs == null) { System.err.println("No jobs running, not checking tasklog servlet"); continue; } for (JobStatus j : jobs) { System.err.println("Checking task log for " + j.getJobID()); checkTaskGraphServlet(j.getJobID()); } } } }
public void testFairSchedulerSystem() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); List<Future<Void>> futures = new ArrayList<Future<Void>>(NUM_THREADS); for (int i = 0; i < NUM_THREADS; i++) { futures.add(exec.submit(new Callable<Void>() { public Void call() throws Exception { JobConf jobConf = mr.createJobConf(); runSleepJob(jobConf); return null; } })); } JobClient jc = new JobClient(mr.createJobConf(null)); // Wait for the tasks to finish, and visit the scheduler servlet // every few seconds while waiting. for (Future<Void> future : futures) { while (true) { try { future.get(3, TimeUnit.SECONDS); break; } catch (TimeoutException te) { // It's OK } checkServlet(true); checkServlet(false); JobStatus jobs[] = jc.getAllJobs(); if (jobs == null) { System.err.println("No jobs running, not checking tasklog servlet"); continue; } for (JobStatus j : jobs) { System.err.println("Checking task graph for " + j.getJobID()); try { checkTaskGraphServlet(j.getJobID()); } catch (AssertionError err) { // The task graph servlet will be empty if the job has retired. // This is OK. RunningJob rj = jc.getJob(j.getJobID()); if (!rj.isRetired()) { throw err; } } } } } }
diff --git a/library/src/test/java/com/datatorrent/lib/io/LocalFsInputOperatorTest.java b/library/src/test/java/com/datatorrent/lib/io/LocalFsInputOperatorTest.java index e11b6e8e8..d57a39ee7 100644 --- a/library/src/test/java/com/datatorrent/lib/io/LocalFsInputOperatorTest.java +++ b/library/src/test/java/com/datatorrent/lib/io/LocalFsInputOperatorTest.java @@ -1,44 +1,47 @@ /* * Copyright (c) 2013 Malhar Inc. ALL Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datatorrent.lib.io; import com.datatorrent.lib.io.LocalFsInputOperator; import com.datatorrent.lib.testbench.CollectorTestSink; import junit.framework.Assert; import org.junit.Test; /** * Functional tests for {@link com.datatorrent.lib.io.LocalFsInputOperator} <p> */ public class LocalFsInputOperatorTest { // Sample text file path. protected String fileName = "../demos/src/main/resources/com/datatorrent/demos/wordcount/samplefile.txt"; @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testFileRead() { LocalFsInputOperator oper = new LocalFsInputOperator(); oper.setFilePath(fileName); oper.setup(null); + oper.activate(null); CollectorTestSink sink = new CollectorTestSink(); oper.outport.setSink(sink); for(int i=0; i < 1000; i++) oper.emitTuples(); Assert.assertTrue("tuple emmitted", sink.collectedTuples.size() > 0); Assert.assertEquals(sink.collectedTuples.size(), 92); + oper.deactivate(); + oper.teardown(); } }
false
true
public void testFileRead() { LocalFsInputOperator oper = new LocalFsInputOperator(); oper.setFilePath(fileName); oper.setup(null); CollectorTestSink sink = new CollectorTestSink(); oper.outport.setSink(sink); for(int i=0; i < 1000; i++) oper.emitTuples(); Assert.assertTrue("tuple emmitted", sink.collectedTuples.size() > 0); Assert.assertEquals(sink.collectedTuples.size(), 92); }
public void testFileRead() { LocalFsInputOperator oper = new LocalFsInputOperator(); oper.setFilePath(fileName); oper.setup(null); oper.activate(null); CollectorTestSink sink = new CollectorTestSink(); oper.outport.setSink(sink); for(int i=0; i < 1000; i++) oper.emitTuples(); Assert.assertTrue("tuple emmitted", sink.collectedTuples.size() > 0); Assert.assertEquals(sink.collectedTuples.size(), 92); oper.deactivate(); oper.teardown(); }
diff --git a/main/src/cgeo/geocaching/export/FieldnoteExport.java b/main/src/cgeo/geocaching/export/FieldnoteExport.java index 9d0310cca..38cd43e29 100644 --- a/main/src/cgeo/geocaching/export/FieldnoteExport.java +++ b/main/src/cgeo/geocaching/export/FieldnoteExport.java @@ -1,252 +1,252 @@ package cgeo.geocaching.export; import cgeo.geocaching.Geocache; import cgeo.geocaching.LogEntry; import cgeo.geocaching.R; import cgeo.geocaching.cgData; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.connector.gc.Login; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.network.Network; import cgeo.geocaching.network.Parameters; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.ui.Formatter; import cgeo.geocaching.utils.AsyncTaskWithProgress; import cgeo.geocaching.utils.IOUtils; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.StringUtils; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Environment; import android.view.ContextThemeWrapper; import android.view.View; import android.widget.CheckBox; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; /** * Exports offline-logs in the Groundspeak Field Note format.<br> * <br> * * Field Notes are simple plain text files, but poorly documented. Syntax:<br> * <code>GCxxxxx,yyyy-mm-ddThh:mm:ssZ,Found it,"logtext"</code> */ class FieldnoteExport extends AbstractExport { private static final File exportLocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/field-notes"); private static final SimpleDateFormat fieldNoteDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); static { fieldNoteDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } protected FieldnoteExport() { super(getString(R.string.export_fieldnotes)); } @Override public void export(final List<Geocache> cachesList, final Activity activity) { final Geocache[] caches = cachesList.toArray(new Geocache[cachesList.size()]); if (null == activity) { // No activity given, so no user interaction possible. // Start export with default parameters. new ExportTask(null, false, false).execute(caches); } else { // Show configuration dialog getExportOptionsDialog(caches, activity).show(); } } private Dialog getExportOptionsDialog(final Geocache[] caches, final Activity activity) { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); // AlertDialog has always dark style, so we have to apply it as well always final View layout = View.inflate(new ContextThemeWrapper(activity, R.style.dark), R.layout.fieldnote_export_dialog, null); builder.setView(layout); final CheckBox uploadOption = (CheckBox) layout.findViewById(R.id.upload); final CheckBox onlyNewOption = (CheckBox) layout.findViewById(R.id.onlynew); if (Settings.getFieldnoteExportDate() > 0) { onlyNewOption.setText(getString(R.string.export_fieldnotes_onlynew) + "\n(" + Formatter.formatShortDateTime(activity, Settings.getFieldnoteExportDate()) + ')'); } builder.setPositiveButton(R.string.export, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); new ExportTask( activity, uploadOption.isChecked(), onlyNewOption.isChecked()) .execute(caches); } }); return builder.create(); } private class ExportTask extends AsyncTaskWithProgress<Geocache, Boolean> { private final Activity activity; private final boolean upload; private final boolean onlyNew; private File exportFile; private static final int STATUS_UPLOAD = -1; /** * Instantiates and configures the task for exporting field notes. * * @param activity * optional: Show a progress bar and toasts * @param upload * Upload the Field Note to geocaching.com * @param onlyNew * Upload/export only new logs since last export */ public ExportTask(final Activity activity, final boolean upload, final boolean onlyNew) { super(activity, getProgressTitle(), getString(R.string.export_fieldnotes_creating)); this.activity = activity; this.upload = upload; this.onlyNew = onlyNew; } @Override protected Boolean doInBackgroundInternal(Geocache[] caches) { final StringBuilder fieldNoteBuffer = new StringBuilder(); try { int i = 0; for (final Geocache cache : caches) { if (cache.isLogOffline()) { final LogEntry log = cgData.loadLogOffline(cache.getGeocode()); if (!onlyNew || onlyNew && log.date > Settings.getFieldnoteExportDate()) { appendFieldNote(fieldNoteBuffer, cache, log); } - publishProgress(++i); } + publishProgress(++i); } } catch (final Exception e) { Log.e("FieldnoteExport.ExportTask generation", e); return false; } fieldNoteBuffer.append('\n'); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return false; } exportLocation.mkdirs(); final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US); exportFile = new File(exportLocation.toString() + '/' + fileNameDateFormat.format(new Date()) + ".txt"); Writer fileWriter = null; BufferedOutputStream buffer = null; try { final OutputStream os = new FileOutputStream(exportFile); buffer = new BufferedOutputStream(os); fileWriter = new OutputStreamWriter(buffer, CharEncoding.UTF_16); fileWriter.write(fieldNoteBuffer.toString()); } catch (final IOException e) { Log.e("FieldnoteExport.ExportTask export", e); return false; } finally { IOUtils.closeQuietly(fileWriter); IOUtils.closeQuietly(buffer); } if (upload) { publishProgress(STATUS_UPLOAD); if (!Login.isActualLoginStatus()) { // no need to upload (possibly large file) if we're not logged in final StatusCode loginState = Login.login(); if (loginState != StatusCode.NO_ERROR) { Log.e("FieldnoteExport.ExportTask upload: Login failed"); } } final String uri = "http://www.geocaching.com/my/uploadfieldnotes.aspx"; final String page = Login.getRequestLogged(uri, null); if (StringUtils.isBlank(page)) { Log.e("FieldnoteExport.ExportTask get page: No data from server"); return false; } final String[] viewstates = Login.getViewstates(page); final Parameters uploadParams = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "ctl00$ContentBody$btnUpload", "Upload Field Note"); Login.putViewstates(uploadParams, viewstates); Network.getResponseData(Network.postRequest(uri, uploadParams, "ctl00$ContentBody$FieldNoteLoader", "text/plain", exportFile)); if (StringUtils.isBlank(page)) { Log.e("FieldnoteExport.ExportTask upload: No data from server"); return false; } } return true; } @Override protected void onPostExecuteInternal(Boolean result) { if (null != activity) { if (result) { Settings.setFieldnoteExportDate(System.currentTimeMillis()); ActivityMixin.showToast(activity, getName() + ' ' + getString(R.string.export_exportedto) + ": " + exportFile.toString()); if (upload) { ActivityMixin.showToast(activity, getString(R.string.export_fieldnotes_upload_success)); } } else { ActivityMixin.showToast(activity, getString(R.string.export_failed)); } } } @Override protected void onProgressUpdateInternal(int status) { if (null != activity) { if (STATUS_UPLOAD == status) { setMessage(getString(R.string.export_fieldnotes_uploading)); } else { setMessage(getString(R.string.export_fieldnotes_creating) + " (" + status + ')'); } } } } static void appendFieldNote(final StringBuilder fieldNoteBuffer, final Geocache cache, final LogEntry log) { fieldNoteBuffer.append(cache.getGeocode()) .append(',') .append(fieldNoteDateFormat.format(new Date(log.date))) .append(',') .append(StringUtils.capitalize(log.type.type)) .append(",\"") .append(StringUtils.replaceChars(log.log, '"', '\'')) .append("\"\n"); } }
false
true
protected Boolean doInBackgroundInternal(Geocache[] caches) { final StringBuilder fieldNoteBuffer = new StringBuilder(); try { int i = 0; for (final Geocache cache : caches) { if (cache.isLogOffline()) { final LogEntry log = cgData.loadLogOffline(cache.getGeocode()); if (!onlyNew || onlyNew && log.date > Settings.getFieldnoteExportDate()) { appendFieldNote(fieldNoteBuffer, cache, log); } publishProgress(++i); } } } catch (final Exception e) { Log.e("FieldnoteExport.ExportTask generation", e); return false; } fieldNoteBuffer.append('\n'); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return false; } exportLocation.mkdirs(); final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US); exportFile = new File(exportLocation.toString() + '/' + fileNameDateFormat.format(new Date()) + ".txt"); Writer fileWriter = null; BufferedOutputStream buffer = null; try { final OutputStream os = new FileOutputStream(exportFile); buffer = new BufferedOutputStream(os); fileWriter = new OutputStreamWriter(buffer, CharEncoding.UTF_16); fileWriter.write(fieldNoteBuffer.toString()); } catch (final IOException e) { Log.e("FieldnoteExport.ExportTask export", e); return false; } finally { IOUtils.closeQuietly(fileWriter); IOUtils.closeQuietly(buffer); } if (upload) { publishProgress(STATUS_UPLOAD); if (!Login.isActualLoginStatus()) { // no need to upload (possibly large file) if we're not logged in final StatusCode loginState = Login.login(); if (loginState != StatusCode.NO_ERROR) { Log.e("FieldnoteExport.ExportTask upload: Login failed"); } } final String uri = "http://www.geocaching.com/my/uploadfieldnotes.aspx"; final String page = Login.getRequestLogged(uri, null); if (StringUtils.isBlank(page)) { Log.e("FieldnoteExport.ExportTask get page: No data from server"); return false; } final String[] viewstates = Login.getViewstates(page); final Parameters uploadParams = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "ctl00$ContentBody$btnUpload", "Upload Field Note"); Login.putViewstates(uploadParams, viewstates); Network.getResponseData(Network.postRequest(uri, uploadParams, "ctl00$ContentBody$FieldNoteLoader", "text/plain", exportFile)); if (StringUtils.isBlank(page)) { Log.e("FieldnoteExport.ExportTask upload: No data from server"); return false; } } return true; }
protected Boolean doInBackgroundInternal(Geocache[] caches) { final StringBuilder fieldNoteBuffer = new StringBuilder(); try { int i = 0; for (final Geocache cache : caches) { if (cache.isLogOffline()) { final LogEntry log = cgData.loadLogOffline(cache.getGeocode()); if (!onlyNew || onlyNew && log.date > Settings.getFieldnoteExportDate()) { appendFieldNote(fieldNoteBuffer, cache, log); } } publishProgress(++i); } } catch (final Exception e) { Log.e("FieldnoteExport.ExportTask generation", e); return false; } fieldNoteBuffer.append('\n'); if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return false; } exportLocation.mkdirs(); final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US); exportFile = new File(exportLocation.toString() + '/' + fileNameDateFormat.format(new Date()) + ".txt"); Writer fileWriter = null; BufferedOutputStream buffer = null; try { final OutputStream os = new FileOutputStream(exportFile); buffer = new BufferedOutputStream(os); fileWriter = new OutputStreamWriter(buffer, CharEncoding.UTF_16); fileWriter.write(fieldNoteBuffer.toString()); } catch (final IOException e) { Log.e("FieldnoteExport.ExportTask export", e); return false; } finally { IOUtils.closeQuietly(fileWriter); IOUtils.closeQuietly(buffer); } if (upload) { publishProgress(STATUS_UPLOAD); if (!Login.isActualLoginStatus()) { // no need to upload (possibly large file) if we're not logged in final StatusCode loginState = Login.login(); if (loginState != StatusCode.NO_ERROR) { Log.e("FieldnoteExport.ExportTask upload: Login failed"); } } final String uri = "http://www.geocaching.com/my/uploadfieldnotes.aspx"; final String page = Login.getRequestLogged(uri, null); if (StringUtils.isBlank(page)) { Log.e("FieldnoteExport.ExportTask get page: No data from server"); return false; } final String[] viewstates = Login.getViewstates(page); final Parameters uploadParams = new Parameters( "__EVENTTARGET", "", "__EVENTARGUMENT", "", "ctl00$ContentBody$btnUpload", "Upload Field Note"); Login.putViewstates(uploadParams, viewstates); Network.getResponseData(Network.postRequest(uri, uploadParams, "ctl00$ContentBody$FieldNoteLoader", "text/plain", exportFile)); if (StringUtils.isBlank(page)) { Log.e("FieldnoteExport.ExportTask upload: No data from server"); return false; } } return true; }
diff --git a/plugins/org.eclipse.emf.compare.ide.ui/src/org/eclipse/emf/compare/ide/ui/internal/contentmergeviewer/table/TableMergeViewer.java b/plugins/org.eclipse.emf.compare.ide.ui/src/org/eclipse/emf/compare/ide/ui/internal/contentmergeviewer/table/TableMergeViewer.java index 0525c3e25..75ccab664 100644 --- a/plugins/org.eclipse.emf.compare.ide.ui/src/org/eclipse/emf/compare/ide/ui/internal/contentmergeviewer/table/TableMergeViewer.java +++ b/plugins/org.eclipse.emf.compare.ide.ui/src/org/eclipse/emf/compare/ide/ui/internal/contentmergeviewer/table/TableMergeViewer.java @@ -1,294 +1,295 @@ /******************************************************************************* * Copyright (c) 2012 Obeo. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Obeo - initial API and implementation *******************************************************************************/ package org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.table; import org.eclipse.emf.compare.Diff; import org.eclipse.emf.compare.DifferenceState; import org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.AbstractMergeViewer; import org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.EMFCompareContentMergeViewer; import org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.IMergeViewerItem; import org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.InsertionPoint; import org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.MergeViewerInfoComposite; import org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.provider.IStructuralFeatureAccessor; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.Region; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Widget; /** * @author <a href="mailto:[email protected]">Mikael Barbero</a> */ class TableMergeViewer extends AbstractMergeViewer<Composite> { private IStructuralFeatureAccessor fInput; private final EMFCompareContentMergeViewer fContentMergeViewer; private Composite c; private MergeViewerInfoComposite mergeViewerInfoComposite; TableMergeViewer(Composite parent, EMFCompareContentMergeViewer contentMergeViewer, MergeViewerSide side) { super(parent, side); fContentMergeViewer = contentMergeViewer; getStructuredViewer().getTable().addListener(SWT.EraseItem, new Listener() { public void handleEvent(Event event) { TableMergeViewer.this.handleEraseItemEvent(event); } }); getStructuredViewer().getTable().addListener(SWT.MeasureItem, new Listener() { private Widget fLastWidget; private int fLastHeight; public void handleEvent(Event event) { // Windows bug: prevents StackOverflow if (event.item == fLastWidget && event.height == fLastHeight) { return; } fLastWidget = event.item; fLastHeight = event.height; int newHeight = (int)(event.gc.getFontMetrics().getHeight() * 1.33d); - if (newHeight % 2 == 1) { + // If odd, make even + if ((newHeight & 1) == 1) { newHeight += 1; } event.height = newHeight; } }); } /** * {@inheritDoc} * * @see org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.IMergeViewer#getControl() */ public Composite getControl() { return c; } /** * {@inheritDoc} * * @see org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.AbstractMergeViewer#createStructuredViewer() */ @Override protected final TableViewer createStructuredViewer(Composite parent) { c = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(1, false); layout.marginLeft = -1; layout.marginRight = -1; layout.marginTop = -1; layout.marginBottom = 0; layout.horizontalSpacing = 0; layout.verticalSpacing = 0; layout.marginWidth = 0; layout.marginHeight = 0; c.setLayout(layout); mergeViewerInfoComposite = new MergeViewerInfoComposite(c); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); mergeViewerInfoComposite.setLayoutData(layoutData); TableViewer tableViewer = new TableViewer(c, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); tableViewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); return tableViewer; } public int getVerticalOffset() { return mergeViewerInfoComposite.getSize().y - 2; } /** * {@inheritDoc} * * @see org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.AbstractMergeViewer#setLabelProvider(org.eclipse.jface.viewers.ILabelProvider) */ @Override public void setLabelProvider(ILabelProvider labelProvider) { super.setLabelProvider(labelProvider); mergeViewerInfoComposite.setLabelProvider(labelProvider); } /** * {@inheritDoc} * * @see org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.AbstractMergeViewer#getStructuredViewer() */ @Override protected TableViewer getStructuredViewer() { return (TableViewer)super.getStructuredViewer(); } /** * {@inheritDoc} * * @see org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.IMergeViewer#setInput(java.lang.Object) */ public void setInput(Object object) { if (object instanceof IStructuralFeatureAccessor) { fInput = (IStructuralFeatureAccessor)object; getStructuredViewer().setInput(fInput.getItems()); mergeViewerInfoComposite.setInput(fInput, getSide()); } else { fInput = null; getStructuredViewer().setInput(null); } } /** * {@inheritDoc} * * @see org.eclipse.jface.viewers.IInputProvider#getInput() */ public Object getInput() { return fInput; } private void handleEraseItemEvent(Event event) { TableItem tableItem = (TableItem)event.item; Object data = tableItem.getData(); if (data instanceof InsertionPoint) { InsertionPoint insertionPoint = (InsertionPoint)data; paintItemDiffBox(event, insertionPoint.getDiff(), getBoundsForInsertionPoint(event)); } else if (data instanceof IMergeViewerItem) { Diff diff = ((IMergeViewerItem)data).getDiff(); if (diff != null) { paintItemDiffBox(event, diff, getBounds(event)); } } } private void paintItemDiffBox(Event event, Diff diff, Rectangle bounds) { event.detail &= ~SWT.HOT; if (diff.getState() == DifferenceState.DISCARDED || diff.getState() == DifferenceState.MERGED) { return; } GC g = event.gc; Color oldBackground = g.getBackground(); Color oldForeground = g.getForeground(); setDiffColorsToGC(g, diff, isSelected(event)); g.fillRectangle(bounds); g.drawRectangle(bounds); if (getSide() == MergeViewerSide.LEFT) { drawLineFromBoxToCenter(event, bounds, g); } else { drawLineFromCenterToBox(event, bounds, g); } if (isSelected(event)) { g.setForeground(event.display.getSystemColor(SWT.COLOR_LIST_FOREGROUND)); g.setBackground(event.display.getSystemColor(SWT.COLOR_LIST_BACKGROUND)); event.detail &= ~SWT.SELECTED; } else { g.setBackground(oldBackground); g.setForeground(oldForeground); } } private void drawLineFromCenterToBox(Event event, Rectangle boxBounds, GC g) { TableItem tableItem = (TableItem)event.item; Rectangle itemBounds = tableItem.getBounds(); Point from = new Point(0, 0); from.y = itemBounds.y + (itemBounds.height / 2); Point to = new Point(boxBounds.x, from.y); g.drawLine(from.x, from.y, to.x, to.y); } private void drawLineFromBoxToCenter(Event event, Rectangle boxBounds, GC g) { TableItem tableItem = (TableItem)event.item; Rectangle itemBounds = tableItem.getBounds(); Rectangle clientArea = tableItem.getParent().getClientArea(); Point from = new Point(0, 0); from.x = boxBounds.x + boxBounds.width; from.y = itemBounds.y + (itemBounds.height / 2); Point to = new Point(0, from.y); to.x = clientArea.x + clientArea.width; g.drawLine(from.x, from.y, to.x, to.y); } static boolean isSelected(Event event) { return (event.detail & SWT.SELECTED) != 0; } private static Rectangle getBounds(Event event) { TableItem tableItem = (TableItem)event.item; Table table = tableItem.getParent(); Rectangle tableBounds = table.getClientArea(); Rectangle itemBounds = tableItem.getBounds(); Rectangle fill = new Rectangle(0, 0, 0, 0); fill.x = 2; fill.y = itemBounds.y + 2; // +x to add the icon and the expand "+" if we are in a tree fill.width = itemBounds.width + itemBounds.x; fill.height = itemBounds.height - 3; final GC g = event.gc; // If you wish to paint the selection beyond the end of last column, you must change the clipping // region. int columnCount = table.getColumnCount(); if (event.index == columnCount - 1 || columnCount == 0) { int width = tableBounds.x + tableBounds.width - event.x; if (width > 0) { Region region = new Region(); g.getClipping(region); region.add(event.x, event.y, width, event.height); g.setClipping(region); region.dispose(); } } g.setAdvanced(true); return fill; } private static Rectangle getBoundsForInsertionPoint(Event event) { Rectangle fill = getBounds(event); TableItem tableItem = (TableItem)event.item; Rectangle tableBounds = tableItem.getParent().getClientArea(); fill.y = fill.y + 6; fill.width = tableBounds.width / 4; fill.height = fill.height - 12; return fill; } private void setDiffColorsToGC(GC g, Diff diff, boolean selected) { g.setForeground(fContentMergeViewer.getColors().getStrokeColor(diff, fContentMergeViewer.isThreeWay(), false, selected)); g.setBackground(fContentMergeViewer.getColors().getFillColor(diff, fContentMergeViewer.isThreeWay(), false, selected)); } }
true
true
TableMergeViewer(Composite parent, EMFCompareContentMergeViewer contentMergeViewer, MergeViewerSide side) { super(parent, side); fContentMergeViewer = contentMergeViewer; getStructuredViewer().getTable().addListener(SWT.EraseItem, new Listener() { public void handleEvent(Event event) { TableMergeViewer.this.handleEraseItemEvent(event); } }); getStructuredViewer().getTable().addListener(SWT.MeasureItem, new Listener() { private Widget fLastWidget; private int fLastHeight; public void handleEvent(Event event) { // Windows bug: prevents StackOverflow if (event.item == fLastWidget && event.height == fLastHeight) { return; } fLastWidget = event.item; fLastHeight = event.height; int newHeight = (int)(event.gc.getFontMetrics().getHeight() * 1.33d); if (newHeight % 2 == 1) { newHeight += 1; } event.height = newHeight; } }); }
TableMergeViewer(Composite parent, EMFCompareContentMergeViewer contentMergeViewer, MergeViewerSide side) { super(parent, side); fContentMergeViewer = contentMergeViewer; getStructuredViewer().getTable().addListener(SWT.EraseItem, new Listener() { public void handleEvent(Event event) { TableMergeViewer.this.handleEraseItemEvent(event); } }); getStructuredViewer().getTable().addListener(SWT.MeasureItem, new Listener() { private Widget fLastWidget; private int fLastHeight; public void handleEvent(Event event) { // Windows bug: prevents StackOverflow if (event.item == fLastWidget && event.height == fLastHeight) { return; } fLastWidget = event.item; fLastHeight = event.height; int newHeight = (int)(event.gc.getFontMetrics().getHeight() * 1.33d); // If odd, make even if ((newHeight & 1) == 1) { newHeight += 1; } event.height = newHeight; } }); }
diff --git a/software/nosql/src/main/java/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java b/software/nosql/src/main/java/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java index babf5f95b..7e462c300 100644 --- a/software/nosql/src/main/java/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java +++ b/software/nosql/src/main/java/brooklyn/entity/nosql/redis/RedisStoreSshDriver.java @@ -1,92 +1,91 @@ package brooklyn.entity.nosql.redis; import static java.lang.String.format; import java.util.List; import brooklyn.entity.basic.AbstractSoftwareProcessSshDriver; import brooklyn.entity.basic.Entities; import brooklyn.entity.drivers.downloads.DownloadResolver; import brooklyn.location.Location; import brooklyn.location.basic.SshMachineLocation; import brooklyn.util.collections.MutableMap; import brooklyn.util.ssh.CommonCommands; import com.google.common.collect.ImmutableList; /** * Start a {@link RedisStore} in a {@link Location} accessible over ssh. */ public class RedisStoreSshDriver extends AbstractSoftwareProcessSshDriver implements RedisStoreDriver { private String expandedInstallDir; public RedisStoreSshDriver(RedisStoreImpl entity, SshMachineLocation machine) { super(entity, machine); } private String getExpandedInstallDir() { if (expandedInstallDir == null) throw new IllegalStateException("expandedInstallDir is null; most likely install was not called"); return expandedInstallDir; } @Override public void install() { DownloadResolver resolver = Entities.newDownloader(this); List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); expandedInstallDir = getInstallDir()+"/"+resolver.getUnpackedDirectoryName(format("redis-%s", getVersion())); List<String> commands = ImmutableList.<String>builder() .addAll(CommonCommands.downloadUrlAs(urls, saveAs)) .add(CommonCommands.INSTALL_TAR) .add("tar xzfv " + saveAs) .add(format("cd redis-%s", getVersion())) - .add("make distclean") - .add("make") + .add("make clean && make") .build(); newScript(INSTALLING) .failOnNonZeroResultCode() .body.append(commands).execute(); } @Override public void customize() { newScript(MutableMap.of("usePidFile", false), CUSTOMIZING) .failOnNonZeroResultCode() .body.append( format("cd %s", getExpandedInstallDir()), "make install PREFIX="+getRunDir()) .execute(); copyTemplate(getEntity().getConfig(RedisStore.REDIS_CONFIG_TEMPLATE_URL), "redis.conf"); } @Override public void launch() { // TODO Should we redirect stdout/stderr: format(" >> %s/console 2>&1 </dev/null &", getRunDir()) newScript(MutableMap.of("usePidFile", false), LAUNCHING) .failOnNonZeroResultCode() .body.append("./bin/redis-server redis.conf") .execute(); } @Override public boolean isRunning() { return newScript(MutableMap.of("usePidFile", false), CHECK_RUNNING) .body.append("./bin/redis-cli -p " + getEntity().getAttribute(RedisStore.REDIS_PORT) + " ping > /dev/null") .execute() == 0; } /** * Restarts redis with the current configuration. */ @Override public void stop() { newScript(MutableMap.of("usePidFile", false), STOPPING) .failOnNonZeroResultCode() .body.append("./bin/redis-cli -p " + getEntity().getAttribute(RedisStore.REDIS_PORT) + " shutdown") .execute(); } }
true
true
public void install() { DownloadResolver resolver = Entities.newDownloader(this); List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); expandedInstallDir = getInstallDir()+"/"+resolver.getUnpackedDirectoryName(format("redis-%s", getVersion())); List<String> commands = ImmutableList.<String>builder() .addAll(CommonCommands.downloadUrlAs(urls, saveAs)) .add(CommonCommands.INSTALL_TAR) .add("tar xzfv " + saveAs) .add(format("cd redis-%s", getVersion())) .add("make distclean") .add("make") .build(); newScript(INSTALLING) .failOnNonZeroResultCode() .body.append(commands).execute(); }
public void install() { DownloadResolver resolver = Entities.newDownloader(this); List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); expandedInstallDir = getInstallDir()+"/"+resolver.getUnpackedDirectoryName(format("redis-%s", getVersion())); List<String> commands = ImmutableList.<String>builder() .addAll(CommonCommands.downloadUrlAs(urls, saveAs)) .add(CommonCommands.INSTALL_TAR) .add("tar xzfv " + saveAs) .add(format("cd redis-%s", getVersion())) .add("make clean && make") .build(); newScript(INSTALLING) .failOnNonZeroResultCode() .body.append(commands).execute(); }
diff --git a/src/VASSAL/build/module/map/ForwardToKeyBuffer.java b/src/VASSAL/build/module/map/ForwardToKeyBuffer.java index 0ee361d8..9fac7fa3 100644 --- a/src/VASSAL/build/module/map/ForwardToKeyBuffer.java +++ b/src/VASSAL/build/module/map/ForwardToKeyBuffer.java @@ -1,91 +1,93 @@ /* * $Id$ * * Copyright (c) 2000-2003 by Rodney Kinney * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.build.module.map; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.KeyStroke; import VASSAL.build.Buildable; import VASSAL.build.GameModule; import VASSAL.build.module.Map; import VASSAL.command.Command; import VASSAL.counters.KeyBuffer; /** * This KeyListener forwards key event from a {@link Map} to the * {@link KeyBuffer}, where it is given to selected GamePieces to * interpret. The event is forwarded only if not consumed * * @see KeyBuffer * @see VASSAL.counters.GamePiece#keyEvent * @see InputEvent#isConsumed */ public class ForwardToKeyBuffer implements Buildable, KeyListener { private KeyEvent lastConsumedEvent; public void build(org.w3c.dom.Element e) { } public void addTo(Buildable parent) { Map map = (Map) parent; map.getView().addKeyListener(this); } public void add(Buildable b) { } public org.w3c.dom.Element getBuildElement(org.w3c.dom.Document doc) { return doc.createElement(getClass().getName()); } public void keyPressed(KeyEvent e) { process(e); } public void keyReleased(KeyEvent e) { process(e); } public void keyTyped(KeyEvent e) { process(e); } protected void process(KeyEvent e) { // If we've consumed a KeyPressed event, // then automatically consume any following KeyTyped event // resulting from the same keypress // This prevents echoing characters to the Chat area if they're keycommand for selected pieces if (lastConsumedEvent != null && lastConsumedEvent.getWhen() == e.getWhen()) { e.consume(); } else { lastConsumedEvent = null; } - if (!e.isConsumed()) { + final int c = e.getKeyCode(); + // Don't pass SHIFT or CONTROL only to counters + if (!e.isConsumed() && c != KeyEvent.VK_SHIFT && c != KeyEvent.VK_CONTROL) { Command comm = KeyBuffer.getBuffer().keyCommand (KeyStroke.getKeyStrokeForEvent(e)); if (comm != null && !comm.isNull()) { GameModule.getGameModule().sendAndLog(comm); e.consume(); lastConsumedEvent = e; } } } }
true
true
protected void process(KeyEvent e) { // If we've consumed a KeyPressed event, // then automatically consume any following KeyTyped event // resulting from the same keypress // This prevents echoing characters to the Chat area if they're keycommand for selected pieces if (lastConsumedEvent != null && lastConsumedEvent.getWhen() == e.getWhen()) { e.consume(); } else { lastConsumedEvent = null; } if (!e.isConsumed()) { Command comm = KeyBuffer.getBuffer().keyCommand (KeyStroke.getKeyStrokeForEvent(e)); if (comm != null && !comm.isNull()) { GameModule.getGameModule().sendAndLog(comm); e.consume(); lastConsumedEvent = e; } } }
protected void process(KeyEvent e) { // If we've consumed a KeyPressed event, // then automatically consume any following KeyTyped event // resulting from the same keypress // This prevents echoing characters to the Chat area if they're keycommand for selected pieces if (lastConsumedEvent != null && lastConsumedEvent.getWhen() == e.getWhen()) { e.consume(); } else { lastConsumedEvent = null; } final int c = e.getKeyCode(); // Don't pass SHIFT or CONTROL only to counters if (!e.isConsumed() && c != KeyEvent.VK_SHIFT && c != KeyEvent.VK_CONTROL) { Command comm = KeyBuffer.getBuffer().keyCommand (KeyStroke.getKeyStrokeForEvent(e)); if (comm != null && !comm.isNull()) { GameModule.getGameModule().sendAndLog(comm); e.consume(); lastConsumedEvent = e; } } }
diff --git a/src/com/gitblit/wicket/panels/RepositoriesPanel.java b/src/com/gitblit/wicket/panels/RepositoriesPanel.java index a92b083d..d3b8ddbe 100644 --- a/src/com/gitblit/wicket/panels/RepositoriesPanel.java +++ b/src/com/gitblit/wicket/panels/RepositoriesPanel.java @@ -1,541 +1,542 @@ /* * Copyright 2011 gitblit.com. * * 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.gitblit.wicket.panels; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.wicket.Component; import org.apache.wicket.PageParameters; import org.apache.wicket.extensions.markup.html.repeater.data.sort.OrderByBorder; import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.link.ExternalLink; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.panel.Fragment; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.markup.repeater.data.IDataProvider; import org.apache.wicket.markup.repeater.data.ListDataProvider; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import com.gitblit.Constants.AccessRestrictionType; import com.gitblit.GitBlit; import com.gitblit.Keys; import com.gitblit.SyndicationServlet; import com.gitblit.models.ProjectModel; import com.gitblit.models.RepositoryModel; import com.gitblit.models.UserModel; import com.gitblit.utils.StringUtils; import com.gitblit.wicket.GitBlitWebSession; import com.gitblit.wicket.WicketUtils; import com.gitblit.wicket.pages.BasePage; import com.gitblit.wicket.pages.EditRepositoryPage; import com.gitblit.wicket.pages.EmptyRepositoryPage; import com.gitblit.wicket.pages.ProjectPage; import com.gitblit.wicket.pages.RepositoriesPage; import com.gitblit.wicket.pages.SummaryPage; import com.gitblit.wicket.pages.UserPage; public class RepositoriesPanel extends BasePanel { private static final long serialVersionUID = 1L; public RepositoriesPanel(String wicketId, final boolean showAdmin, final boolean showManagement, List<RepositoryModel> models, boolean enableLinks, final Map<AccessRestrictionType, String> accessRestrictionTranslations) { super(wicketId); final boolean linksActive = enableLinks; final boolean showSize = GitBlit.getBoolean(Keys.web.showRepositorySizes, true); final UserModel user = GitBlitWebSession.get().getUser(); final IDataProvider<RepositoryModel> dp; Fragment managementLinks; if (showAdmin) { // user is admin managementLinks = new Fragment("managementPanel", "adminLinks", this); managementLinks.add(new Link<Void>("clearCache") { private static final long serialVersionUID = 1L; @Override public void onClick() { GitBlit.self().resetRepositoryListCache(); setResponsePage(RepositoriesPage.class); } }.setVisible(GitBlit.getBoolean(Keys.git.cacheRepositoryList, true))); managementLinks.add(new BookmarkablePageLink<Void>("newRepository", EditRepositoryPage.class)); add(managementLinks); } else if (showManagement && user != null && user.canCreate()) { // user can create personal repositories managementLinks = new Fragment("managementPanel", "personalLinks", this); managementLinks.add(new BookmarkablePageLink<Void>("newRepository", EditRepositoryPage.class)); add(managementLinks); } else { // user has no management permissions add (new Label("managementPanel").setVisible(false)); } if (GitBlit.getString(Keys.web.repositoryListType, "flat").equalsIgnoreCase("grouped")) { List<RepositoryModel> rootRepositories = new ArrayList<RepositoryModel>(); Map<String, List<RepositoryModel>> groups = new HashMap<String, List<RepositoryModel>>(); for (RepositoryModel model : models) { String rootPath = StringUtils.getRootPath(model.name); if (StringUtils.isEmpty(rootPath)) { // root repository rootRepositories.add(model); } else { // non-root, grouped repository if (!groups.containsKey(rootPath)) { groups.put(rootPath, new ArrayList<RepositoryModel>()); } groups.get(rootPath).add(model); } } List<String> roots = new ArrayList<String>(groups.keySet()); Collections.sort(roots); if (rootRepositories.size() > 0) { // inject the root repositories at the top of the page String rootPath = GitBlit.getString(Keys.web.repositoryRootGroupName, " "); roots.add(0, rootPath); groups.put(rootPath, rootRepositories); } Map<String, ProjectModel> projects = new HashMap<String, ProjectModel>(); for (ProjectModel project : GitBlit.self().getProjectModels(user, true)) { projects.put(project.name, project); } List<RepositoryModel> groupedModels = new ArrayList<RepositoryModel>(); for (String root : roots) { List<RepositoryModel> subModels = groups.get(root); GroupRepositoryModel group = new GroupRepositoryModel(root, subModels.size()); if (projects.containsKey(root)) { group.title = projects.get(root).title; group.description = projects.get(root).description; } groupedModels.add(group); Collections.sort(subModels); groupedModels.addAll(subModels); } dp = new RepositoriesProvider(groupedModels); } else { dp = new SortableRepositoriesProvider(models); } final String baseUrl = WicketUtils.getGitblitURL(getRequest()); final boolean showSwatch = GitBlit.getBoolean(Keys.web.repositoryListSwatches, true); DataView<RepositoryModel> dataView = new DataView<RepositoryModel>("row", dp) { private static final long serialVersionUID = 1L; int counter; String currGroupName; @Override protected void onBeforeRender() { super.onBeforeRender(); counter = 0; } public void populateItem(final Item<RepositoryModel> item) { final RepositoryModel entry = item.getModelObject(); if (entry instanceof GroupRepositoryModel) { + GroupRepositoryModel groupRow = (GroupRepositoryModel) entry; currGroupName = entry.name; Fragment row = new Fragment("rowContent", "groupRepositoryRow", this); item.add(row); - String name = entry.toString(); + String name = groupRow.name; if (name.charAt(0) == '~') { // user page String username = name.substring(1); UserModel user = GitBlit.self().getUserModel(username); - row.add(new LinkPanel("groupName", null, user == null ? username : user.getDisplayName(), UserPage.class, WicketUtils.newUsernameParameter(username))); + row.add(new LinkPanel("groupName", null, (user == null ? username : user.getDisplayName()) + " (" + groupRow.count + ")", UserPage.class, WicketUtils.newUsernameParameter(username))); row.add(new Label("groupDescription", getString("gb.personalRepositories"))); } else { // project page - row.add(new LinkPanel("groupName", null, name, ProjectPage.class, WicketUtils.newProjectParameter(entry.name))); + row.add(new LinkPanel("groupName", null, groupRow.toString(), ProjectPage.class, WicketUtils.newProjectParameter(entry.name))); row.add(new Label("groupDescription", entry.description == null ? "":entry.description)); } WicketUtils.setCssClass(item, "group"); // reset counter so that first row is light background counter = 0; return; } Fragment row = new Fragment("rowContent", "repositoryRow", this); item.add(row); // try to strip group name for less cluttered list String repoName = entry.toString(); if (!StringUtils.isEmpty(currGroupName) && (repoName.indexOf('/') > -1)) { repoName = repoName.substring(currGroupName.length() + 1); } // repository swatch Component swatch; if (entry.isBare){ swatch = new Label("repositorySwatch", "&nbsp;").setEscapeModelStrings(false); } else { swatch = new Label("repositorySwatch", "!"); WicketUtils.setHtmlTooltip(swatch, getString("gb.workingCopyWarning")); } WicketUtils.setCssBackground(swatch, entry.toString()); row.add(swatch); swatch.setVisible(showSwatch); if (linksActive) { Class<? extends BasePage> linkPage; if (entry.hasCommits) { // repository has content linkPage = SummaryPage.class; } else { // new/empty repository OR proposed repository linkPage = EmptyRepositoryPage.class; } PageParameters pp = WicketUtils.newRepositoryParameter(entry.name); row.add(new LinkPanel("repositoryName", "list", repoName, linkPage, pp)); row.add(new LinkPanel("repositoryDescription", "list", entry.description, linkPage, pp)); } else { // no links like on a federation page row.add(new Label("repositoryName", repoName)); row.add(new Label("repositoryDescription", entry.description)); } if (entry.hasCommits) { // Existing repository row.add(new Label("repositorySize", entry.size).setVisible(showSize)); } else { // New repository row.add(new Label("repositorySize", "<span class='empty'>(" + getString("gb.empty") + ")</span>") .setEscapeModelStrings(false)); } if (entry.isFork()) { row.add(WicketUtils.newImage("forkIcon", "commit_divide_16x16.png", getString("gb.isFork"))); } else { row.add(WicketUtils.newClearPixel("forkIcon").setVisible(false)); } if (entry.useTickets) { row.add(WicketUtils.newImage("ticketsIcon", "bug_16x16.png", getString("gb.tickets"))); } else { row.add(WicketUtils.newBlankImage("ticketsIcon")); } if (entry.useDocs) { row.add(WicketUtils .newImage("docsIcon", "book_16x16.png", getString("gb.docs"))); } else { row.add(WicketUtils.newBlankImage("docsIcon")); } if (entry.isFrozen) { row.add(WicketUtils.newImage("frozenIcon", "cold_16x16.png", getString("gb.isFrozen"))); } else { row.add(WicketUtils.newClearPixel("frozenIcon").setVisible(false)); } if (entry.isFederated) { row.add(WicketUtils.newImage("federatedIcon", "federated_16x16.png", getString("gb.isFederated"))); } else { row.add(WicketUtils.newClearPixel("federatedIcon").setVisible(false)); } switch (entry.accessRestriction) { case NONE: row.add(WicketUtils.newBlankImage("accessRestrictionIcon")); break; case PUSH: row.add(WicketUtils.newImage("accessRestrictionIcon", "lock_go_16x16.png", accessRestrictionTranslations.get(entry.accessRestriction))); break; case CLONE: row.add(WicketUtils.newImage("accessRestrictionIcon", "lock_pull_16x16.png", accessRestrictionTranslations.get(entry.accessRestriction))); break; case VIEW: row.add(WicketUtils.newImage("accessRestrictionIcon", "shield_16x16.png", accessRestrictionTranslations.get(entry.accessRestriction))); break; default: row.add(WicketUtils.newBlankImage("accessRestrictionIcon")); } String owner = entry.owner; if (!StringUtils.isEmpty(owner)) { UserModel ownerModel = GitBlit.self().getUserModel(owner); if (ownerModel != null) { owner = ownerModel.getDisplayName(); } } row.add(new Label("repositoryOwner", owner)); String lastChange; if (entry.lastChange.getTime() == 0) { lastChange = "--"; } else { lastChange = getTimeUtils().timeAgo(entry.lastChange); } Label lastChangeLabel = new Label("repositoryLastChange", lastChange); row.add(lastChangeLabel); WicketUtils.setCssClass(lastChangeLabel, getTimeUtils().timeAgoCss(entry.lastChange)); boolean showOwner = user != null && entry.isOwner(user.username); boolean myPersonalRepository = showOwner && entry.isUsersPersonalRepository(user.username); if (showAdmin || myPersonalRepository) { Fragment repositoryLinks = new Fragment("repositoryLinks", "repositoryAdminLinks", this); repositoryLinks.add(new BookmarkablePageLink<Void>("editRepository", EditRepositoryPage.class, WicketUtils .newRepositoryParameter(entry.name))); Link<Void> deleteLink = new Link<Void>("deleteRepository") { private static final long serialVersionUID = 1L; @Override public void onClick() { if (GitBlit.self().deleteRepositoryModel(entry)) { if (dp instanceof SortableRepositoriesProvider) { info(MessageFormat.format(getString("gb.repositoryDeleted"), entry)); ((SortableRepositoriesProvider) dp).remove(entry); } else { setResponsePage(getPage().getClass(), getPage().getPageParameters()); } } else { error(MessageFormat.format(getString("gb.repositoryDeleteFailed"), entry)); } } }; deleteLink.add(new JavascriptEventConfirmation("onclick", MessageFormat.format( getString("gb.deleteRepository"), entry))); repositoryLinks.add(deleteLink); row.add(repositoryLinks); } else if (showOwner) { Fragment repositoryLinks = new Fragment("repositoryLinks", "repositoryOwnerLinks", this); repositoryLinks.add(new BookmarkablePageLink<Void>("editRepository", EditRepositoryPage.class, WicketUtils .newRepositoryParameter(entry.name))); row.add(repositoryLinks); } else { row.add(new Label("repositoryLinks")); } row.add(new ExternalLink("syndication", SyndicationServlet.asLink(baseUrl, entry.name, null, 0)).setVisible(linksActive)); WicketUtils.setAlternatingBackground(item, counter); counter++; } }; add(dataView); if (dp instanceof SortableDataProvider<?>) { // add sortable header SortableDataProvider<?> sdp = (SortableDataProvider<?>) dp; Fragment fragment = new Fragment("headerContent", "flatRepositoryHeader", this); fragment.add(newSort("orderByRepository", SortBy.repository, sdp, dataView)); fragment.add(newSort("orderByDescription", SortBy.description, sdp, dataView)); fragment.add(newSort("orderByOwner", SortBy.owner, sdp, dataView)); fragment.add(newSort("orderByDate", SortBy.date, sdp, dataView)); add(fragment); } else { // not sortable Fragment fragment = new Fragment("headerContent", "groupRepositoryHeader", this); add(fragment); } } private static class GroupRepositoryModel extends RepositoryModel { private static final long serialVersionUID = 1L; int count; String title; GroupRepositoryModel(String name, int count) { super(name, "", "", new Date(0)); this.count = count; } @Override public String toString() { return (StringUtils.isEmpty(title) ? name : title) + " (" + count + ")"; } } protected enum SortBy { repository, description, owner, date; } protected OrderByBorder newSort(String wicketId, SortBy field, SortableDataProvider<?> dp, final DataView<?> dataView) { return new OrderByBorder(wicketId, field.name(), dp) { private static final long serialVersionUID = 1L; @Override protected void onSortChanged() { dataView.setCurrentPage(0); } }; } private static class RepositoriesProvider extends ListDataProvider<RepositoryModel> { private static final long serialVersionUID = 1L; public RepositoriesProvider(List<RepositoryModel> list) { super(list); } @Override public List<RepositoryModel> getData() { return super.getData(); } public void remove(RepositoryModel model) { int index = getData().indexOf(model); RepositoryModel groupModel = null; if (index == (getData().size() - 1)) { // last element if (index > 0) { // previous element is group header, then this is last // repository in group. remove group too. if (getData().get(index - 1) instanceof GroupRepositoryModel) { groupModel = getData().get(index - 1); } } } else if (index < (getData().size() - 1)) { // not last element. check next element for group match. if (getData().get(index - 1) instanceof GroupRepositoryModel && getData().get(index + 1) instanceof GroupRepositoryModel) { // repository is sandwiched by group headers so this // repository is the only element in the group. remove // group. groupModel = getData().get(index - 1); } } if (groupModel == null) { // Find the group and decrement the count for (int i = index; i >= 0; i--) { if (getData().get(i) instanceof GroupRepositoryModel) { ((GroupRepositoryModel) getData().get(i)).count--; break; } } } else { // Remove the group header getData().remove(groupModel); } getData().remove(model); } } private static class SortableRepositoriesProvider extends SortableDataProvider<RepositoryModel> { private static final long serialVersionUID = 1L; private List<RepositoryModel> list; protected SortableRepositoriesProvider(List<RepositoryModel> list) { this.list = list; setSort(SortBy.date.name(), false); } public void remove(RepositoryModel model) { list.remove(model); } @Override public int size() { if (list == null) { return 0; } return list.size(); } @Override public IModel<RepositoryModel> model(RepositoryModel header) { return new Model<RepositoryModel>(header); } @Override public Iterator<RepositoryModel> iterator(int first, int count) { SortParam sp = getSort(); String prop = sp.getProperty(); final boolean asc = sp.isAscending(); if (prop == null || prop.equals(SortBy.date.name())) { Collections.sort(list, new Comparator<RepositoryModel>() { @Override public int compare(RepositoryModel o1, RepositoryModel o2) { if (asc) { return o1.lastChange.compareTo(o2.lastChange); } return o2.lastChange.compareTo(o1.lastChange); } }); } else if (prop.equals(SortBy.repository.name())) { Collections.sort(list, new Comparator<RepositoryModel>() { @Override public int compare(RepositoryModel o1, RepositoryModel o2) { if (asc) { return o1.name.compareTo(o2.name); } return o2.name.compareTo(o1.name); } }); } else if (prop.equals(SortBy.owner.name())) { Collections.sort(list, new Comparator<RepositoryModel>() { @Override public int compare(RepositoryModel o1, RepositoryModel o2) { if (asc) { return o1.owner.compareTo(o2.owner); } return o2.owner.compareTo(o1.owner); } }); } else if (prop.equals(SortBy.description.name())) { Collections.sort(list, new Comparator<RepositoryModel>() { @Override public int compare(RepositoryModel o1, RepositoryModel o2) { if (asc) { return o1.description.compareTo(o2.description); } return o2.description.compareTo(o1.description); } }); } return list.subList(first, first + count).iterator(); } } }
false
true
public RepositoriesPanel(String wicketId, final boolean showAdmin, final boolean showManagement, List<RepositoryModel> models, boolean enableLinks, final Map<AccessRestrictionType, String> accessRestrictionTranslations) { super(wicketId); final boolean linksActive = enableLinks; final boolean showSize = GitBlit.getBoolean(Keys.web.showRepositorySizes, true); final UserModel user = GitBlitWebSession.get().getUser(); final IDataProvider<RepositoryModel> dp; Fragment managementLinks; if (showAdmin) { // user is admin managementLinks = new Fragment("managementPanel", "adminLinks", this); managementLinks.add(new Link<Void>("clearCache") { private static final long serialVersionUID = 1L; @Override public void onClick() { GitBlit.self().resetRepositoryListCache(); setResponsePage(RepositoriesPage.class); } }.setVisible(GitBlit.getBoolean(Keys.git.cacheRepositoryList, true))); managementLinks.add(new BookmarkablePageLink<Void>("newRepository", EditRepositoryPage.class)); add(managementLinks); } else if (showManagement && user != null && user.canCreate()) { // user can create personal repositories managementLinks = new Fragment("managementPanel", "personalLinks", this); managementLinks.add(new BookmarkablePageLink<Void>("newRepository", EditRepositoryPage.class)); add(managementLinks); } else { // user has no management permissions add (new Label("managementPanel").setVisible(false)); } if (GitBlit.getString(Keys.web.repositoryListType, "flat").equalsIgnoreCase("grouped")) { List<RepositoryModel> rootRepositories = new ArrayList<RepositoryModel>(); Map<String, List<RepositoryModel>> groups = new HashMap<String, List<RepositoryModel>>(); for (RepositoryModel model : models) { String rootPath = StringUtils.getRootPath(model.name); if (StringUtils.isEmpty(rootPath)) { // root repository rootRepositories.add(model); } else { // non-root, grouped repository if (!groups.containsKey(rootPath)) { groups.put(rootPath, new ArrayList<RepositoryModel>()); } groups.get(rootPath).add(model); } } List<String> roots = new ArrayList<String>(groups.keySet()); Collections.sort(roots); if (rootRepositories.size() > 0) { // inject the root repositories at the top of the page String rootPath = GitBlit.getString(Keys.web.repositoryRootGroupName, " "); roots.add(0, rootPath); groups.put(rootPath, rootRepositories); } Map<String, ProjectModel> projects = new HashMap<String, ProjectModel>(); for (ProjectModel project : GitBlit.self().getProjectModels(user, true)) { projects.put(project.name, project); } List<RepositoryModel> groupedModels = new ArrayList<RepositoryModel>(); for (String root : roots) { List<RepositoryModel> subModels = groups.get(root); GroupRepositoryModel group = new GroupRepositoryModel(root, subModels.size()); if (projects.containsKey(root)) { group.title = projects.get(root).title; group.description = projects.get(root).description; } groupedModels.add(group); Collections.sort(subModels); groupedModels.addAll(subModels); } dp = new RepositoriesProvider(groupedModels); } else { dp = new SortableRepositoriesProvider(models); } final String baseUrl = WicketUtils.getGitblitURL(getRequest()); final boolean showSwatch = GitBlit.getBoolean(Keys.web.repositoryListSwatches, true); DataView<RepositoryModel> dataView = new DataView<RepositoryModel>("row", dp) { private static final long serialVersionUID = 1L; int counter; String currGroupName; @Override protected void onBeforeRender() { super.onBeforeRender(); counter = 0; } public void populateItem(final Item<RepositoryModel> item) { final RepositoryModel entry = item.getModelObject(); if (entry instanceof GroupRepositoryModel) { currGroupName = entry.name; Fragment row = new Fragment("rowContent", "groupRepositoryRow", this); item.add(row); String name = entry.toString(); if (name.charAt(0) == '~') { // user page String username = name.substring(1); UserModel user = GitBlit.self().getUserModel(username); row.add(new LinkPanel("groupName", null, user == null ? username : user.getDisplayName(), UserPage.class, WicketUtils.newUsernameParameter(username))); row.add(new Label("groupDescription", getString("gb.personalRepositories"))); } else { // project page row.add(new LinkPanel("groupName", null, name, ProjectPage.class, WicketUtils.newProjectParameter(entry.name))); row.add(new Label("groupDescription", entry.description == null ? "":entry.description)); } WicketUtils.setCssClass(item, "group"); // reset counter so that first row is light background counter = 0; return; } Fragment row = new Fragment("rowContent", "repositoryRow", this); item.add(row); // try to strip group name for less cluttered list String repoName = entry.toString(); if (!StringUtils.isEmpty(currGroupName) && (repoName.indexOf('/') > -1)) { repoName = repoName.substring(currGroupName.length() + 1); } // repository swatch Component swatch; if (entry.isBare){ swatch = new Label("repositorySwatch", "&nbsp;").setEscapeModelStrings(false); } else { swatch = new Label("repositorySwatch", "!"); WicketUtils.setHtmlTooltip(swatch, getString("gb.workingCopyWarning")); } WicketUtils.setCssBackground(swatch, entry.toString()); row.add(swatch); swatch.setVisible(showSwatch); if (linksActive) { Class<? extends BasePage> linkPage; if (entry.hasCommits) { // repository has content linkPage = SummaryPage.class; } else { // new/empty repository OR proposed repository linkPage = EmptyRepositoryPage.class; } PageParameters pp = WicketUtils.newRepositoryParameter(entry.name); row.add(new LinkPanel("repositoryName", "list", repoName, linkPage, pp)); row.add(new LinkPanel("repositoryDescription", "list", entry.description, linkPage, pp)); } else { // no links like on a federation page row.add(new Label("repositoryName", repoName)); row.add(new Label("repositoryDescription", entry.description)); } if (entry.hasCommits) { // Existing repository row.add(new Label("repositorySize", entry.size).setVisible(showSize)); } else { // New repository row.add(new Label("repositorySize", "<span class='empty'>(" + getString("gb.empty") + ")</span>") .setEscapeModelStrings(false)); } if (entry.isFork()) { row.add(WicketUtils.newImage("forkIcon", "commit_divide_16x16.png", getString("gb.isFork"))); } else { row.add(WicketUtils.newClearPixel("forkIcon").setVisible(false)); } if (entry.useTickets) { row.add(WicketUtils.newImage("ticketsIcon", "bug_16x16.png", getString("gb.tickets"))); } else { row.add(WicketUtils.newBlankImage("ticketsIcon")); } if (entry.useDocs) { row.add(WicketUtils .newImage("docsIcon", "book_16x16.png", getString("gb.docs"))); } else { row.add(WicketUtils.newBlankImage("docsIcon")); } if (entry.isFrozen) { row.add(WicketUtils.newImage("frozenIcon", "cold_16x16.png", getString("gb.isFrozen"))); } else { row.add(WicketUtils.newClearPixel("frozenIcon").setVisible(false)); } if (entry.isFederated) { row.add(WicketUtils.newImage("federatedIcon", "federated_16x16.png", getString("gb.isFederated"))); } else { row.add(WicketUtils.newClearPixel("federatedIcon").setVisible(false)); } switch (entry.accessRestriction) { case NONE: row.add(WicketUtils.newBlankImage("accessRestrictionIcon")); break; case PUSH: row.add(WicketUtils.newImage("accessRestrictionIcon", "lock_go_16x16.png", accessRestrictionTranslations.get(entry.accessRestriction))); break; case CLONE: row.add(WicketUtils.newImage("accessRestrictionIcon", "lock_pull_16x16.png", accessRestrictionTranslations.get(entry.accessRestriction))); break; case VIEW: row.add(WicketUtils.newImage("accessRestrictionIcon", "shield_16x16.png", accessRestrictionTranslations.get(entry.accessRestriction))); break; default: row.add(WicketUtils.newBlankImage("accessRestrictionIcon")); } String owner = entry.owner; if (!StringUtils.isEmpty(owner)) { UserModel ownerModel = GitBlit.self().getUserModel(owner); if (ownerModel != null) { owner = ownerModel.getDisplayName(); } } row.add(new Label("repositoryOwner", owner)); String lastChange; if (entry.lastChange.getTime() == 0) { lastChange = "--"; } else { lastChange = getTimeUtils().timeAgo(entry.lastChange); } Label lastChangeLabel = new Label("repositoryLastChange", lastChange); row.add(lastChangeLabel); WicketUtils.setCssClass(lastChangeLabel, getTimeUtils().timeAgoCss(entry.lastChange)); boolean showOwner = user != null && entry.isOwner(user.username); boolean myPersonalRepository = showOwner && entry.isUsersPersonalRepository(user.username); if (showAdmin || myPersonalRepository) { Fragment repositoryLinks = new Fragment("repositoryLinks", "repositoryAdminLinks", this); repositoryLinks.add(new BookmarkablePageLink<Void>("editRepository", EditRepositoryPage.class, WicketUtils .newRepositoryParameter(entry.name))); Link<Void> deleteLink = new Link<Void>("deleteRepository") { private static final long serialVersionUID = 1L; @Override public void onClick() { if (GitBlit.self().deleteRepositoryModel(entry)) { if (dp instanceof SortableRepositoriesProvider) { info(MessageFormat.format(getString("gb.repositoryDeleted"), entry)); ((SortableRepositoriesProvider) dp).remove(entry); } else { setResponsePage(getPage().getClass(), getPage().getPageParameters()); } } else { error(MessageFormat.format(getString("gb.repositoryDeleteFailed"), entry)); } } }; deleteLink.add(new JavascriptEventConfirmation("onclick", MessageFormat.format( getString("gb.deleteRepository"), entry))); repositoryLinks.add(deleteLink); row.add(repositoryLinks); } else if (showOwner) { Fragment repositoryLinks = new Fragment("repositoryLinks", "repositoryOwnerLinks", this); repositoryLinks.add(new BookmarkablePageLink<Void>("editRepository", EditRepositoryPage.class, WicketUtils .newRepositoryParameter(entry.name))); row.add(repositoryLinks); } else { row.add(new Label("repositoryLinks")); } row.add(new ExternalLink("syndication", SyndicationServlet.asLink(baseUrl, entry.name, null, 0)).setVisible(linksActive)); WicketUtils.setAlternatingBackground(item, counter); counter++; } }; add(dataView); if (dp instanceof SortableDataProvider<?>) { // add sortable header SortableDataProvider<?> sdp = (SortableDataProvider<?>) dp; Fragment fragment = new Fragment("headerContent", "flatRepositoryHeader", this); fragment.add(newSort("orderByRepository", SortBy.repository, sdp, dataView)); fragment.add(newSort("orderByDescription", SortBy.description, sdp, dataView)); fragment.add(newSort("orderByOwner", SortBy.owner, sdp, dataView)); fragment.add(newSort("orderByDate", SortBy.date, sdp, dataView)); add(fragment); } else { // not sortable Fragment fragment = new Fragment("headerContent", "groupRepositoryHeader", this); add(fragment); } }
public RepositoriesPanel(String wicketId, final boolean showAdmin, final boolean showManagement, List<RepositoryModel> models, boolean enableLinks, final Map<AccessRestrictionType, String> accessRestrictionTranslations) { super(wicketId); final boolean linksActive = enableLinks; final boolean showSize = GitBlit.getBoolean(Keys.web.showRepositorySizes, true); final UserModel user = GitBlitWebSession.get().getUser(); final IDataProvider<RepositoryModel> dp; Fragment managementLinks; if (showAdmin) { // user is admin managementLinks = new Fragment("managementPanel", "adminLinks", this); managementLinks.add(new Link<Void>("clearCache") { private static final long serialVersionUID = 1L; @Override public void onClick() { GitBlit.self().resetRepositoryListCache(); setResponsePage(RepositoriesPage.class); } }.setVisible(GitBlit.getBoolean(Keys.git.cacheRepositoryList, true))); managementLinks.add(new BookmarkablePageLink<Void>("newRepository", EditRepositoryPage.class)); add(managementLinks); } else if (showManagement && user != null && user.canCreate()) { // user can create personal repositories managementLinks = new Fragment("managementPanel", "personalLinks", this); managementLinks.add(new BookmarkablePageLink<Void>("newRepository", EditRepositoryPage.class)); add(managementLinks); } else { // user has no management permissions add (new Label("managementPanel").setVisible(false)); } if (GitBlit.getString(Keys.web.repositoryListType, "flat").equalsIgnoreCase("grouped")) { List<RepositoryModel> rootRepositories = new ArrayList<RepositoryModel>(); Map<String, List<RepositoryModel>> groups = new HashMap<String, List<RepositoryModel>>(); for (RepositoryModel model : models) { String rootPath = StringUtils.getRootPath(model.name); if (StringUtils.isEmpty(rootPath)) { // root repository rootRepositories.add(model); } else { // non-root, grouped repository if (!groups.containsKey(rootPath)) { groups.put(rootPath, new ArrayList<RepositoryModel>()); } groups.get(rootPath).add(model); } } List<String> roots = new ArrayList<String>(groups.keySet()); Collections.sort(roots); if (rootRepositories.size() > 0) { // inject the root repositories at the top of the page String rootPath = GitBlit.getString(Keys.web.repositoryRootGroupName, " "); roots.add(0, rootPath); groups.put(rootPath, rootRepositories); } Map<String, ProjectModel> projects = new HashMap<String, ProjectModel>(); for (ProjectModel project : GitBlit.self().getProjectModels(user, true)) { projects.put(project.name, project); } List<RepositoryModel> groupedModels = new ArrayList<RepositoryModel>(); for (String root : roots) { List<RepositoryModel> subModels = groups.get(root); GroupRepositoryModel group = new GroupRepositoryModel(root, subModels.size()); if (projects.containsKey(root)) { group.title = projects.get(root).title; group.description = projects.get(root).description; } groupedModels.add(group); Collections.sort(subModels); groupedModels.addAll(subModels); } dp = new RepositoriesProvider(groupedModels); } else { dp = new SortableRepositoriesProvider(models); } final String baseUrl = WicketUtils.getGitblitURL(getRequest()); final boolean showSwatch = GitBlit.getBoolean(Keys.web.repositoryListSwatches, true); DataView<RepositoryModel> dataView = new DataView<RepositoryModel>("row", dp) { private static final long serialVersionUID = 1L; int counter; String currGroupName; @Override protected void onBeforeRender() { super.onBeforeRender(); counter = 0; } public void populateItem(final Item<RepositoryModel> item) { final RepositoryModel entry = item.getModelObject(); if (entry instanceof GroupRepositoryModel) { GroupRepositoryModel groupRow = (GroupRepositoryModel) entry; currGroupName = entry.name; Fragment row = new Fragment("rowContent", "groupRepositoryRow", this); item.add(row); String name = groupRow.name; if (name.charAt(0) == '~') { // user page String username = name.substring(1); UserModel user = GitBlit.self().getUserModel(username); row.add(new LinkPanel("groupName", null, (user == null ? username : user.getDisplayName()) + " (" + groupRow.count + ")", UserPage.class, WicketUtils.newUsernameParameter(username))); row.add(new Label("groupDescription", getString("gb.personalRepositories"))); } else { // project page row.add(new LinkPanel("groupName", null, groupRow.toString(), ProjectPage.class, WicketUtils.newProjectParameter(entry.name))); row.add(new Label("groupDescription", entry.description == null ? "":entry.description)); } WicketUtils.setCssClass(item, "group"); // reset counter so that first row is light background counter = 0; return; } Fragment row = new Fragment("rowContent", "repositoryRow", this); item.add(row); // try to strip group name for less cluttered list String repoName = entry.toString(); if (!StringUtils.isEmpty(currGroupName) && (repoName.indexOf('/') > -1)) { repoName = repoName.substring(currGroupName.length() + 1); } // repository swatch Component swatch; if (entry.isBare){ swatch = new Label("repositorySwatch", "&nbsp;").setEscapeModelStrings(false); } else { swatch = new Label("repositorySwatch", "!"); WicketUtils.setHtmlTooltip(swatch, getString("gb.workingCopyWarning")); } WicketUtils.setCssBackground(swatch, entry.toString()); row.add(swatch); swatch.setVisible(showSwatch); if (linksActive) { Class<? extends BasePage> linkPage; if (entry.hasCommits) { // repository has content linkPage = SummaryPage.class; } else { // new/empty repository OR proposed repository linkPage = EmptyRepositoryPage.class; } PageParameters pp = WicketUtils.newRepositoryParameter(entry.name); row.add(new LinkPanel("repositoryName", "list", repoName, linkPage, pp)); row.add(new LinkPanel("repositoryDescription", "list", entry.description, linkPage, pp)); } else { // no links like on a federation page row.add(new Label("repositoryName", repoName)); row.add(new Label("repositoryDescription", entry.description)); } if (entry.hasCommits) { // Existing repository row.add(new Label("repositorySize", entry.size).setVisible(showSize)); } else { // New repository row.add(new Label("repositorySize", "<span class='empty'>(" + getString("gb.empty") + ")</span>") .setEscapeModelStrings(false)); } if (entry.isFork()) { row.add(WicketUtils.newImage("forkIcon", "commit_divide_16x16.png", getString("gb.isFork"))); } else { row.add(WicketUtils.newClearPixel("forkIcon").setVisible(false)); } if (entry.useTickets) { row.add(WicketUtils.newImage("ticketsIcon", "bug_16x16.png", getString("gb.tickets"))); } else { row.add(WicketUtils.newBlankImage("ticketsIcon")); } if (entry.useDocs) { row.add(WicketUtils .newImage("docsIcon", "book_16x16.png", getString("gb.docs"))); } else { row.add(WicketUtils.newBlankImage("docsIcon")); } if (entry.isFrozen) { row.add(WicketUtils.newImage("frozenIcon", "cold_16x16.png", getString("gb.isFrozen"))); } else { row.add(WicketUtils.newClearPixel("frozenIcon").setVisible(false)); } if (entry.isFederated) { row.add(WicketUtils.newImage("federatedIcon", "federated_16x16.png", getString("gb.isFederated"))); } else { row.add(WicketUtils.newClearPixel("federatedIcon").setVisible(false)); } switch (entry.accessRestriction) { case NONE: row.add(WicketUtils.newBlankImage("accessRestrictionIcon")); break; case PUSH: row.add(WicketUtils.newImage("accessRestrictionIcon", "lock_go_16x16.png", accessRestrictionTranslations.get(entry.accessRestriction))); break; case CLONE: row.add(WicketUtils.newImage("accessRestrictionIcon", "lock_pull_16x16.png", accessRestrictionTranslations.get(entry.accessRestriction))); break; case VIEW: row.add(WicketUtils.newImage("accessRestrictionIcon", "shield_16x16.png", accessRestrictionTranslations.get(entry.accessRestriction))); break; default: row.add(WicketUtils.newBlankImage("accessRestrictionIcon")); } String owner = entry.owner; if (!StringUtils.isEmpty(owner)) { UserModel ownerModel = GitBlit.self().getUserModel(owner); if (ownerModel != null) { owner = ownerModel.getDisplayName(); } } row.add(new Label("repositoryOwner", owner)); String lastChange; if (entry.lastChange.getTime() == 0) { lastChange = "--"; } else { lastChange = getTimeUtils().timeAgo(entry.lastChange); } Label lastChangeLabel = new Label("repositoryLastChange", lastChange); row.add(lastChangeLabel); WicketUtils.setCssClass(lastChangeLabel, getTimeUtils().timeAgoCss(entry.lastChange)); boolean showOwner = user != null && entry.isOwner(user.username); boolean myPersonalRepository = showOwner && entry.isUsersPersonalRepository(user.username); if (showAdmin || myPersonalRepository) { Fragment repositoryLinks = new Fragment("repositoryLinks", "repositoryAdminLinks", this); repositoryLinks.add(new BookmarkablePageLink<Void>("editRepository", EditRepositoryPage.class, WicketUtils .newRepositoryParameter(entry.name))); Link<Void> deleteLink = new Link<Void>("deleteRepository") { private static final long serialVersionUID = 1L; @Override public void onClick() { if (GitBlit.self().deleteRepositoryModel(entry)) { if (dp instanceof SortableRepositoriesProvider) { info(MessageFormat.format(getString("gb.repositoryDeleted"), entry)); ((SortableRepositoriesProvider) dp).remove(entry); } else { setResponsePage(getPage().getClass(), getPage().getPageParameters()); } } else { error(MessageFormat.format(getString("gb.repositoryDeleteFailed"), entry)); } } }; deleteLink.add(new JavascriptEventConfirmation("onclick", MessageFormat.format( getString("gb.deleteRepository"), entry))); repositoryLinks.add(deleteLink); row.add(repositoryLinks); } else if (showOwner) { Fragment repositoryLinks = new Fragment("repositoryLinks", "repositoryOwnerLinks", this); repositoryLinks.add(new BookmarkablePageLink<Void>("editRepository", EditRepositoryPage.class, WicketUtils .newRepositoryParameter(entry.name))); row.add(repositoryLinks); } else { row.add(new Label("repositoryLinks")); } row.add(new ExternalLink("syndication", SyndicationServlet.asLink(baseUrl, entry.name, null, 0)).setVisible(linksActive)); WicketUtils.setAlternatingBackground(item, counter); counter++; } }; add(dataView); if (dp instanceof SortableDataProvider<?>) { // add sortable header SortableDataProvider<?> sdp = (SortableDataProvider<?>) dp; Fragment fragment = new Fragment("headerContent", "flatRepositoryHeader", this); fragment.add(newSort("orderByRepository", SortBy.repository, sdp, dataView)); fragment.add(newSort("orderByDescription", SortBy.description, sdp, dataView)); fragment.add(newSort("orderByOwner", SortBy.owner, sdp, dataView)); fragment.add(newSort("orderByDate", SortBy.date, sdp, dataView)); add(fragment); } else { // not sortable Fragment fragment = new Fragment("headerContent", "groupRepositoryHeader", this); add(fragment); } }
diff --git a/src/me/krotn/ServerWarp/utils/history/PlayerTeleportHistoryManager.java b/src/me/krotn/ServerWarp/utils/history/PlayerTeleportHistoryManager.java index 8a2bdb9..21b7439 100644 --- a/src/me/krotn/ServerWarp/utils/history/PlayerTeleportHistoryManager.java +++ b/src/me/krotn/ServerWarp/utils/history/PlayerTeleportHistoryManager.java @@ -1,79 +1,84 @@ package me.krotn.ServerWarp.utils.history; import java.util.ArrayList; import org.bukkit.Location; import org.bukkit.entity.Player; public class PlayerTeleportHistoryManager { private Player player; private ArrayList<Location> history; private int locationPointer = 0; private int size; public PlayerTeleportHistoryManager(Player player,int size){ this.player = player; history = new ArrayList<Location>(); history.add(player.getLocation()); this.size = size; } protected void ensureSize(){ if(history.size()>size){ int toSubtract = history.size()-size; while(history.size()>size){ history.remove(history.size()-1); } locationPointer -= toSubtract; } } public Location back(){ if(locationPointer <= 0){ ensureSize(); return history.get(0); } else{ locationPointer--; ensureSize(); return history.get(locationPointer); } } public Location forward(){ if(locationPointer >= history.size()){ ensureSize(); return history.get(history.size()-1); } else{ locationPointer++; ensureSize(); return history.get(locationPointer); } } public void addToHistory(Location location){ + System.out.println(location); + if(history.get(history.size()-1).distance(location)<=1){ + System.out.println("Location already in history"); + return; + } if(locationPointer<history.size()){ while(history.size()>locationPointer){ history.remove(locationPointer); } history.add(location); locationPointer++; } else{ locationPointer++; history.add(location); } ensureSize(); System.out.println(history.size()); } public Player getPlayer(){ return player; } public void clear(){ this.history.clear(); locationPointer = 0; ensureSize(); } }
true
true
public void addToHistory(Location location){ if(locationPointer<history.size()){ while(history.size()>locationPointer){ history.remove(locationPointer); } history.add(location); locationPointer++; } else{ locationPointer++; history.add(location); } ensureSize(); System.out.println(history.size()); }
public void addToHistory(Location location){ System.out.println(location); if(history.get(history.size()-1).distance(location)<=1){ System.out.println("Location already in history"); return; } if(locationPointer<history.size()){ while(history.size()>locationPointer){ history.remove(locationPointer); } history.add(location); locationPointer++; } else{ locationPointer++; history.add(location); } ensureSize(); System.out.println(history.size()); }
diff --git a/cvs/trunk/src/version1/src/com/rohanclan/cfml/editors/cfscript/CFScriptScanner.java b/cvs/trunk/src/version1/src/com/rohanclan/cfml/editors/cfscript/CFScriptScanner.java index da36ccd6..523b76f2 100644 --- a/cvs/trunk/src/version1/src/com/rohanclan/cfml/editors/cfscript/CFScriptScanner.java +++ b/cvs/trunk/src/version1/src/com/rohanclan/cfml/editors/cfscript/CFScriptScanner.java @@ -1,151 +1,151 @@ /* * Created on Jan 31, 2004 * * The MIT License * Copyright (c) 2004 Rob Rohan * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.rohanclan.cfml.editors.cfscript; import org.eclipse.jface.text.rules.RuleBasedScanner; import org.eclipse.jface.text.rules.IToken; import org.eclipse.jface.text.rules.Token; import org.eclipse.jface.text.rules.SingleLineRule; import org.eclipse.jface.text.rules.MultiLineRule; import org.eclipse.jface.text.rules.EndOfLineRule; import org.eclipse.jface.text.rules.NumberRule; import org.eclipse.jface.text.rules.IRule; import org.eclipse.jface.text.TextAttribute; import com.rohanclan.cfml.editors.CFKeywordDetector; import com.rohanclan.cfml.editors.ColorManager; import com.rohanclan.cfml.editors.ICFColorConstants; import com.rohanclan.cfml.editors.PredicateWordRule; import com.rohanclan.cfml.editors.CFSyntaxDictionary; import com.rohanclan.cfml.dictionary.DictionaryManager; import java.util.Iterator; import java.util.Set; import java.util.ArrayList; import java.util.List; /** * @author Rob * * This is the scanner for cfscript partitions */ public class CFScriptScanner extends RuleBasedScanner { public CFScriptScanner(ColorManager manager) { super(); IToken cfnumber = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFNUMBER)) ); IToken cftag = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFTAG)) ); IToken cfcomment = new Token(new TextAttribute( - manager.getColor(ICFColorConstants.HTM_COMMENT)) + manager.getColor(ICFColorConstants.CF_COMMENT)) ); IToken string = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFSCRIPT_STRING)) ); IToken cfkeyword = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFSCRIPT_KEYWORD)) ); IToken cffunction = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFSCRIPT_FUNCTION)) ); IToken cfdefault = new Token(new TextAttribute( manager.getColor(ICFColorConstants.DEFAULT)) ); List rules = new ArrayList(); //so the script tags look correct rules.add(new SingleLineRule("<cfscript", ">", cftag)); rules.add(new SingleLineRule("</cfscript", ">", cftag)); rules.add(new SingleLineRule("<CFSCRIPT", ">", cftag)); rules.add(new SingleLineRule("</CFSCRIPT", ">", cftag)); //I think the reason this doesnt work as well as the <!-- type of comment //is that the <! type is defined on the partition scanner where this is //only here... javascript has the same problem //TODO: can the bad commment coloring be fixed? rules.add(new MultiLineRule("/*", "*/", cfcomment)); rules.add(new EndOfLineRule("//", cfcomment)); rules.add(new SingleLineRule("\"", "\"", string)); rules.add(new SingleLineRule("'", "'", string)); rules.add(new NumberRule(cfnumber)); CFSyntaxDictionary dic = (CFSyntaxDictionary)DictionaryManager.getDictionary(DictionaryManager.CFDIC); //do any keywords //get any needed operators (or, and et cetra) Set set = dic.getOperators(); //get any script specific keywords (if, case, while, et cetra) set.addAll(dic.getScriptKeywords()); String allkeys[] = new String[set.size()<<1]; int i=0; Iterator it = set.iterator(); while(it.hasNext()) { String opname = (String)it.next(); allkeys[i++] = opname; allkeys[i++] = opname.toUpperCase(); } //build the word highlighter CFKeywordDetector cfkd = new CFKeywordDetector(); PredicateWordRule words = new PredicateWordRule( cfkd, cfdefault, allkeys, cfkeyword ); //now do the cffuntions so they look pretty too :) set = dic.getFunctions(); it = set.iterator(); while(it.hasNext()) { String fun = (String)it.next(); words.addWord(fun, cffunction); words.addWord(fun.toUpperCase(), cffunction); } rules.add(words); IRule[] rulearry = new IRule[rules.size()]; rules.toArray(rulearry); setRules(rulearry); } }
true
true
public CFScriptScanner(ColorManager manager) { super(); IToken cfnumber = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFNUMBER)) ); IToken cftag = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFTAG)) ); IToken cfcomment = new Token(new TextAttribute( manager.getColor(ICFColorConstants.HTM_COMMENT)) ); IToken string = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFSCRIPT_STRING)) ); IToken cfkeyword = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFSCRIPT_KEYWORD)) ); IToken cffunction = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFSCRIPT_FUNCTION)) ); IToken cfdefault = new Token(new TextAttribute( manager.getColor(ICFColorConstants.DEFAULT)) ); List rules = new ArrayList(); //so the script tags look correct rules.add(new SingleLineRule("<cfscript", ">", cftag)); rules.add(new SingleLineRule("</cfscript", ">", cftag)); rules.add(new SingleLineRule("<CFSCRIPT", ">", cftag)); rules.add(new SingleLineRule("</CFSCRIPT", ">", cftag)); //I think the reason this doesnt work as well as the <!-- type of comment //is that the <! type is defined on the partition scanner where this is //only here... javascript has the same problem //TODO: can the bad commment coloring be fixed? rules.add(new MultiLineRule("/*", "*/", cfcomment)); rules.add(new EndOfLineRule("//", cfcomment)); rules.add(new SingleLineRule("\"", "\"", string)); rules.add(new SingleLineRule("'", "'", string)); rules.add(new NumberRule(cfnumber)); CFSyntaxDictionary dic = (CFSyntaxDictionary)DictionaryManager.getDictionary(DictionaryManager.CFDIC); //do any keywords //get any needed operators (or, and et cetra) Set set = dic.getOperators(); //get any script specific keywords (if, case, while, et cetra) set.addAll(dic.getScriptKeywords()); String allkeys[] = new String[set.size()<<1]; int i=0; Iterator it = set.iterator(); while(it.hasNext()) { String opname = (String)it.next(); allkeys[i++] = opname; allkeys[i++] = opname.toUpperCase(); } //build the word highlighter CFKeywordDetector cfkd = new CFKeywordDetector(); PredicateWordRule words = new PredicateWordRule( cfkd, cfdefault, allkeys, cfkeyword ); //now do the cffuntions so they look pretty too :) set = dic.getFunctions(); it = set.iterator(); while(it.hasNext()) { String fun = (String)it.next(); words.addWord(fun, cffunction); words.addWord(fun.toUpperCase(), cffunction); } rules.add(words); IRule[] rulearry = new IRule[rules.size()]; rules.toArray(rulearry); setRules(rulearry); }
public CFScriptScanner(ColorManager manager) { super(); IToken cfnumber = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFNUMBER)) ); IToken cftag = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFTAG)) ); IToken cfcomment = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CF_COMMENT)) ); IToken string = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFSCRIPT_STRING)) ); IToken cfkeyword = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFSCRIPT_KEYWORD)) ); IToken cffunction = new Token(new TextAttribute( manager.getColor(ICFColorConstants.CFSCRIPT_FUNCTION)) ); IToken cfdefault = new Token(new TextAttribute( manager.getColor(ICFColorConstants.DEFAULT)) ); List rules = new ArrayList(); //so the script tags look correct rules.add(new SingleLineRule("<cfscript", ">", cftag)); rules.add(new SingleLineRule("</cfscript", ">", cftag)); rules.add(new SingleLineRule("<CFSCRIPT", ">", cftag)); rules.add(new SingleLineRule("</CFSCRIPT", ">", cftag)); //I think the reason this doesnt work as well as the <!-- type of comment //is that the <! type is defined on the partition scanner where this is //only here... javascript has the same problem //TODO: can the bad commment coloring be fixed? rules.add(new MultiLineRule("/*", "*/", cfcomment)); rules.add(new EndOfLineRule("//", cfcomment)); rules.add(new SingleLineRule("\"", "\"", string)); rules.add(new SingleLineRule("'", "'", string)); rules.add(new NumberRule(cfnumber)); CFSyntaxDictionary dic = (CFSyntaxDictionary)DictionaryManager.getDictionary(DictionaryManager.CFDIC); //do any keywords //get any needed operators (or, and et cetra) Set set = dic.getOperators(); //get any script specific keywords (if, case, while, et cetra) set.addAll(dic.getScriptKeywords()); String allkeys[] = new String[set.size()<<1]; int i=0; Iterator it = set.iterator(); while(it.hasNext()) { String opname = (String)it.next(); allkeys[i++] = opname; allkeys[i++] = opname.toUpperCase(); } //build the word highlighter CFKeywordDetector cfkd = new CFKeywordDetector(); PredicateWordRule words = new PredicateWordRule( cfkd, cfdefault, allkeys, cfkeyword ); //now do the cffuntions so they look pretty too :) set = dic.getFunctions(); it = set.iterator(); while(it.hasNext()) { String fun = (String)it.next(); words.addWord(fun, cffunction); words.addWord(fun.toUpperCase(), cffunction); } rules.add(words); IRule[] rulearry = new IRule[rules.size()]; rules.toArray(rulearry); setRules(rulearry); }
diff --git a/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/server/servlets/PreferencesServlet.java b/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/server/servlets/PreferencesServlet.java index d6bc503b..1d344648 100644 --- a/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/server/servlets/PreferencesServlet.java +++ b/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/server/servlets/PreferencesServlet.java @@ -1,222 +1,226 @@ /******************************************************************************* * Copyright (c) 2010, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.orion.server.servlets; import java.io.IOException; import java.util.Iterator; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.preferences.IEclipsePreferences; import org.eclipse.orion.internal.server.servlets.Activator; import org.eclipse.orion.server.core.users.OrionScope; import org.eclipse.osgi.util.NLS; import org.json.*; import org.osgi.service.prefs.BackingStoreException; /** * A servlet for accessing and modifying preferences. * GET /prefs/ to return the preferences and children of the preference root node as a JSON object (the children of the root are the scopes) * GET /prefs/[path] returns the preferences and children of the given preference node as a JSON object * GET /prefs/[path]?key=[key] returns the value of the preference in the node at the given path, with the given key, as a JSON string * PUT /prefs/[path] sets all the preferences at the given path to the provided JSON object * PUT /prefs/[path]?key=[key]&value=[value] sets the value of the preference at the given path with the given key to the provided value * DELETE /prefs/[path] to delete an entire preference node * DELETE /prefs/[path]?key=[key] to delete a single preference at the given path with the given key */ public class PreferencesServlet extends OrionServlet { private static final long serialVersionUID = 1L; private IEclipsePreferences prefRoot; public PreferencesServlet() { super(); } @Override public void init() throws ServletException { super.init(); prefRoot = new OrionScope().getNode(""); //$NON-NLS-1$ } @Override public void destroy() { super.destroy(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { traceRequest(req); IEclipsePreferences node = getNode(req, resp, false); if (node == null) return; String key = req.getParameter("key"); try { //if a key is specified write that single value, otherwise write the entire node JSONObject result = null; if (key != null) { String value = node.get(key, null); if (value == null) { handleNotFound(req, resp, HttpServletResponse.SC_NOT_FOUND); return; } result = new JSONObject().put(key, value); } else result = toJSON(req, node); writeJSONResponse(req, resp, result); } catch (Exception e) { handleException(resp, NLS.bind("Failed to retrieve preferences for path {0}", req.getPathInfo()), e); return; } } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { IEclipsePreferences node = getNode(req, resp, false); if (node == null) { //should not fail on delete when resource doesn't exist resp.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } String key = req.getParameter("key"); try { //if a key is specified write that single value, otherwise write the entire node if (key != null) node.remove(key); else node.removeNode(); prefRoot.flush(); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } catch (Exception e) { handleException(resp, NLS.bind("Failed to retrieve preferences for path {0}", req.getPathInfo()), e); return; } } /** * Returns the preference node associated with this request. This method controls * exactly what preference nodes are exposed via this service. If there is no matching * preference node for the request, this method handles the appropriate response * and returns <code>null</code>. * @param req * @param resp * @param create If <code>true</code>, the node will be created if it does not already exist. If * <code>false</code>, this method sets the response status to 404 and returns null. */ private IEclipsePreferences getNode(HttpServletRequest req, HttpServletResponse resp, boolean create) throws ServletException { if (prefRoot == null) { handleException(resp, "Unable to obtain preference service", null); return null; } String pathString = req.getPathInfo(); if (pathString == null) pathString = ""; //$NON-NLS-1$ IPath path = new Path(pathString); int segmentCount = path.segmentCount(); String scope = path.segment(0); //note that the preference service API scope names don't match those used in our persistence layer. IPath nodePath = null; if ("user".equalsIgnoreCase(scope)) { //$NON-NLS-1$ String username = req.getRemoteUser(); if (username == null) { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } - nodePath = new Path("Users").append(username); //$NON-NLS-1$ + if (segmentCount > 1 && "operations".equalsIgnoreCase(path.segment(1))) { + nodePath = new Path("Operations").append(username); //$NON-NLS-1$ + } else { + nodePath = new Path("Users").append(username); //$NON-NLS-1$ + } } else if ("workspace".equalsIgnoreCase(scope) && segmentCount > 1) { //$NON-NLS-1$ nodePath = new Path("Workspaces"); //$NON-NLS-1$ } else if ("project".equalsIgnoreCase(scope) && segmentCount > 1) { //$NON-NLS-1$ nodePath = new Path("Projects"); //$NON-NLS-1$ } else { //invalid prefix handleNotFound(req, resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED); return null; } //we allow arbitrary subtrees beneath our three supported roots if (nodePath != null) { String childPath = nodePath.append(path.removeFirstSegments(1)).toString(); try { if (create || prefRoot.nodeExists(childPath)) return (IEclipsePreferences) prefRoot.node(childPath); } catch (BackingStoreException e) { String msg = NLS.bind("Error retrieving preferences for path {0}", pathString); handleException(resp, new Status(IStatus.ERROR, Activator.PI_SERVER_SERVLETS, msg), HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } } handleNotFound(req, resp, HttpServletResponse.SC_NOT_FOUND); return null; } private void handleNotFound(HttpServletRequest req, HttpServletResponse resp, int code) throws ServletException { String path = req.getPathInfo() == null ? "/" : req.getPathInfo(); String msg = code == HttpServletResponse.SC_NOT_FOUND ? "No preferences found for path {0}" : "Invalid preference path {0}"; handleException(resp, new Status(IStatus.ERROR, Activator.PI_SERVER_SERVLETS, NLS.bind(msg, path)), code); } @SuppressWarnings("unchecked") @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { traceRequest(req); IEclipsePreferences node = getNode(req, resp, true); if (node == null) return; String key = req.getParameter("key"); try { if (key != null) { node.put(key, req.getParameter("value")); } else { JSONObject newNode = new JSONObject(new JSONTokener(req.getReader())); node.clear(); for (Iterator<String> it = newNode.keys(); it.hasNext();) { key = it.next(); node.put(key, newNode.getString(key)); } } prefRoot.flush(); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } catch (Exception e) { handleException(resp, NLS.bind("Failed to store preferences for {0}", req.getRequestURL()), e); return; } } /** * Serializes a preference node as a JSON object. */ private JSONObject toJSON(HttpServletRequest req, IEclipsePreferences node) throws JSONException, BackingStoreException { JSONObject result = new JSONObject(); //TODO Do we need this extra information? // String nodePath = node.absolutePath(); // result.put("path", nodePath); // JSONObject children = new JSONObject(); // for (String child : node.childrenNames()) // children.put(child, createQuery(req, "/prefs" + nodePath + '/' + child)); // result.put("children", children); // JSONObject values = new JSONObject(); for (String key : node.keys()) { String valueString = node.get(key, null); Object value = null; if (valueString != null) { try { //value might be serialized JSON value = new JSONObject(valueString); } catch (JSONException e) { //value must be a string value = valueString; } } result.put(key, value); } return result; } }
true
true
private IEclipsePreferences getNode(HttpServletRequest req, HttpServletResponse resp, boolean create) throws ServletException { if (prefRoot == null) { handleException(resp, "Unable to obtain preference service", null); return null; } String pathString = req.getPathInfo(); if (pathString == null) pathString = ""; //$NON-NLS-1$ IPath path = new Path(pathString); int segmentCount = path.segmentCount(); String scope = path.segment(0); //note that the preference service API scope names don't match those used in our persistence layer. IPath nodePath = null; if ("user".equalsIgnoreCase(scope)) { //$NON-NLS-1$ String username = req.getRemoteUser(); if (username == null) { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } nodePath = new Path("Users").append(username); //$NON-NLS-1$ } else if ("workspace".equalsIgnoreCase(scope) && segmentCount > 1) { //$NON-NLS-1$ nodePath = new Path("Workspaces"); //$NON-NLS-1$ } else if ("project".equalsIgnoreCase(scope) && segmentCount > 1) { //$NON-NLS-1$ nodePath = new Path("Projects"); //$NON-NLS-1$ } else { //invalid prefix handleNotFound(req, resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED); return null; } //we allow arbitrary subtrees beneath our three supported roots if (nodePath != null) { String childPath = nodePath.append(path.removeFirstSegments(1)).toString(); try { if (create || prefRoot.nodeExists(childPath)) return (IEclipsePreferences) prefRoot.node(childPath); } catch (BackingStoreException e) { String msg = NLS.bind("Error retrieving preferences for path {0}", pathString); handleException(resp, new Status(IStatus.ERROR, Activator.PI_SERVER_SERVLETS, msg), HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } } handleNotFound(req, resp, HttpServletResponse.SC_NOT_FOUND); return null; }
private IEclipsePreferences getNode(HttpServletRequest req, HttpServletResponse resp, boolean create) throws ServletException { if (prefRoot == null) { handleException(resp, "Unable to obtain preference service", null); return null; } String pathString = req.getPathInfo(); if (pathString == null) pathString = ""; //$NON-NLS-1$ IPath path = new Path(pathString); int segmentCount = path.segmentCount(); String scope = path.segment(0); //note that the preference service API scope names don't match those used in our persistence layer. IPath nodePath = null; if ("user".equalsIgnoreCase(scope)) { //$NON-NLS-1$ String username = req.getRemoteUser(); if (username == null) { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } if (segmentCount > 1 && "operations".equalsIgnoreCase(path.segment(1))) { nodePath = new Path("Operations").append(username); //$NON-NLS-1$ } else { nodePath = new Path("Users").append(username); //$NON-NLS-1$ } } else if ("workspace".equalsIgnoreCase(scope) && segmentCount > 1) { //$NON-NLS-1$ nodePath = new Path("Workspaces"); //$NON-NLS-1$ } else if ("project".equalsIgnoreCase(scope) && segmentCount > 1) { //$NON-NLS-1$ nodePath = new Path("Projects"); //$NON-NLS-1$ } else { //invalid prefix handleNotFound(req, resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED); return null; } //we allow arbitrary subtrees beneath our three supported roots if (nodePath != null) { String childPath = nodePath.append(path.removeFirstSegments(1)).toString(); try { if (create || prefRoot.nodeExists(childPath)) return (IEclipsePreferences) prefRoot.node(childPath); } catch (BackingStoreException e) { String msg = NLS.bind("Error retrieving preferences for path {0}", pathString); handleException(resp, new Status(IStatus.ERROR, Activator.PI_SERVER_SERVLETS, msg), HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } } handleNotFound(req, resp, HttpServletResponse.SC_NOT_FOUND); return null; }
diff --git a/enough-polish-j2me/source/src/de/enough/polish/ui/TextEffect.java b/enough-polish-j2me/source/src/de/enough/polish/ui/TextEffect.java index 24e4a01..3c24579 100644 --- a/enough-polish-j2me/source/src/de/enough/polish/ui/TextEffect.java +++ b/enough-polish-j2me/source/src/de/enough/polish/ui/TextEffect.java @@ -1,542 +1,546 @@ //#condition polish.usePolishGui /* * Created on 16-Nov-2005 at 11:59:50. * * Copyright (c) 2010 Robert Virkus / Enough Software * * This file is part of J2ME Polish. * * J2ME Polish 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. * * J2ME Polish 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 J2ME Polish; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Commercial licenses are also available, please * refer to the accompanying LICENSE.txt or visit * http://www.j2mepolish.org for details. */ package de.enough.polish.ui; import javax.microedition.lcdui.Font; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; //import de.enough.polish.io.Serializable; import de.enough.polish.io.Serializable; import de.enough.polish.util.DrawUtil; import de.enough.polish.util.TextUtil; import de.enough.polish.util.WrappedText; /** * <p>Allows text effects for StringItems, IconItems and ChoiceItems.</p> * * <p>Copyright (c) Enough Software 2005 - 2009</p> * <pre> * history * 16-Nov-2005 - rob creation * </pre> * @author Robert Virkus, [email protected] */ public abstract class TextEffect implements Serializable { protected transient Style style; /** * Specifies if this effect needs a lot of texte dependent resources or processing power. * When this is the case, StringItems will create a StringItem specific copy of this effect instead of * using the effect from the Style (which may be used several times). */ protected boolean isTextSensitive; /** * Creates a new effect */ public TextEffect() { super(); } /** * Sets the style of this item. * The implementation sets the style field and then calls setStyle( style, false ). * Subclasses can override this method for getting specific settings. * * @param style the new style for this item. * @throws NullPointerException when style is null * @see #setStyle(Style, boolean) */ public void setStyle( Style style ) { this.style = style; setStyle( style, false ); } /** * Notifies the text effect that it has been attached to the specified item. * Subclasses can override this method to get access to the parent item. * @param parent the parent item */ public void onAttach(Item parent){ // subclasses may choose to override this. } /** * Notifies the text effect that it has been detached to the specified item * Subclasses can override this method to get access to the parent item. * @param parent the parent item */ public void onDetach(Item parent){ // subclasses may choose to override this. } /** * Sets the style of this item without assuming defaults for non-set style elements. * Subclasses can override this method for getting specific settings. * * @param style the new style for this item. * @param resetStyle true when all style elements should be reset to their default when no CSS attributes are defined. * @throws NullPointerException when style is null */ public void setStyle( Style style, boolean resetStyle ) { // subclasses may choose to override this. } /** * Animates this effect. * Subclasses can override this method to create animations. * * @return true when this effect has been animated. */ public boolean animate() { return false; } /** * Animates this effect. * Subclasses can override this method to create animations. * The default implementation calls the animate() method and adds the full content area to the repaint region. * * @param parent the parent item * @param currentTime the current time in milliseconds * @param repaintRegion the repaint area that needs to be updated when this item is animated * @see Item#addRelativeToContentRegion(ClippingRegion, int, int, int, int) */ public void animate(Item parent, long currentTime, ClippingRegion repaintRegion) { if (animate()) { parent.addRelativeToContentRegion( repaintRegion, 0, 0, parent.contentWidth, parent.contentHeight ); } } //#if polish.LibraryBuild /** * Paints the text and applies the text effect. * The default implementation calls drawText( String, int, int, int, int, int, Graphics) * * @param parent the parent item * @param textLines the text * @param textColor the color of the text * @param x horizontal start coordinate * @param y vertical start coordinate * @param leftBorder the left border, nothing must be painted left of this position * @param rightBorder the right border, nothing must be painted right of this position * @param lineHeight the height of a single text line * @param maxWidth the width of the longest line * @param layout the anchor or the text, e.g. Item.LAYOUT_CENTER or Item.LAYOUT_RIGHT * @param g the graphics context * @see #drawString( String,int,int,int,int,Graphics) */ public void drawStrings( FakeCustomItem parent, WrappedText textLines, int textColor, int x, int y, int leftBorder, int rightBorder, int lineHeight, int maxWidth, int layout, Graphics g ) { drawStrings(textLines, textColor, x, y, leftBorder, rightBorder, lineHeight, maxWidth, layout, g); } //#endif /** * Paints the text and applies the text effect. * The default implementation calls drawStrings(String[], int, int, int, int, int, int, int, int, Graphics) * * @param parent the parent item * @param textLines the text * @param textColor the color of the text * @param x horizontal start coordinate * @param y vertical start coordinate * @param leftBorder the left border, nothing must be painted left of this position * @param rightBorder the right border, nothing must be painted right of this position * @param lineHeight the height of a single text line * @param maxWidth the width of the longest line * @param layout the anchor or the text, e.g. Item.LAYOUT_CENTER or Item.LAYOUT_RIGHT * @param g the graphics context * @see #drawStrings(WrappedText, int, int, int, int, int, int, int, int, Graphics) */ public void drawStrings( Item parent, WrappedText textLines, int textColor, int x, int y, int leftBorder, int rightBorder, int lineHeight, int maxWidth, int layout, Graphics g ) { drawStrings(textLines, textColor, x, y, leftBorder, rightBorder, lineHeight, maxWidth, layout, g); } /** * Paints the text and applies the text effect. * The default implementation calls drawText( String, int, int, int, int, int, Graphics) * * @param textLines the text * @param textColor the color of the text * @param x horizontal start coordinate * @param y vertical start coordinate * @param leftBorder the left border, nothing must be painted left of this position * @param rightBorder the right border, nothing must be painted right of this position * @param lineHeight the height of a single text line * @param maxWidth the width of the longest line * @param layout the anchor or the text, e.g. Item.LAYOUT_CENTER or Item.LAYOUT_RIGHT * @param g the graphics context * @see #drawString( String,int,int,int,int,Graphics) */ public void drawStrings( WrappedText textLines, int textColor, int x, int y, int leftBorder, int rightBorder, int lineHeight, int maxWidth, int layout, Graphics g ) { boolean isLayoutRight = false; boolean isLayoutCenter = false; int centerX = 0; if ( ( layout & Item.LAYOUT_CENTER ) == Item.LAYOUT_CENTER ) { isLayoutCenter = true; centerX = leftBorder + (rightBorder - leftBorder) / 2; } else if ( ( layout & Item.LAYOUT_RIGHT ) == Item.LAYOUT_RIGHT ) { isLayoutRight = true; } Object[] lineObjects = textLines.getLinesInternalArray(); int size = textLines.size(); for (int i = 0; i < size; i++) { String line = (String) lineObjects[i]; + if (line == null) + { + break; + } int lineX = x; int lineY = y; int anchor = 0; // adjust the painting according to the layout: if (isLayoutRight) { lineX = rightBorder; //#if polish.Bugs.needsBottomOrientiationForStringDrawing anchor = Graphics.BOTTOM | Graphics.RIGHT; //#else anchor = Graphics.TOP | Graphics.RIGHT; //#endif } else if (isLayoutCenter) { lineX = centerX; //#if polish.Bugs.needsBottomOrientiationForStringDrawing anchor = Graphics.BOTTOM | Graphics.HCENTER; //#else anchor = Graphics.TOP | Graphics.HCENTER; //#endif } else { //#if polish.Bugs.needsBottomOrientiationForStringDrawing anchor = Graphics.BOTTOM | Graphics.LEFT; //#else anchor = Graphics.TOP | Graphics.LEFT; //#endif } drawString( line, textColor, lineX, lineY, anchor, g ); x = leftBorder; y += lineHeight; } } /** * Paints the text and applies the text effect. * * @param text the text * @param textColor the color of the text * @param x x coordinate * @param y y coordinate * @param anchor the orientation, e.g. Graphics.TOP | Graphics.LEFT or Graphics.TOP | Graphics.HCENTER * @param g the graphics context */ public abstract void drawString( String text, int textColor, int x, int y, int anchor, Graphics g ); /** * Retrieves the left start position for a text. * * @param x the x position given in drawString() * @param anchor the orientation given in drawString() * @param textWidth the width of the text given in drawString() * @return the left x position */ public int getLeftX( int x, int anchor, int textWidth ) { if ( (anchor & Graphics.LEFT) == Graphics.LEFT) { return x; } else if ( (anchor & Graphics.RIGHT) == Graphics.RIGHT) { return x - textWidth; } else { return x - textWidth / 2; } } /** * Retrieves the top y position for a text. * * @param y the y position given in drawString() * @param anchor the orientation given in drawString() * @param font the used font, usually g.getFont() * @return the top y position. */ public int getTopY( int y, int anchor, Font font ) { return getTopY(y, anchor, font.getHeight(), font.getBaselinePosition() ); } /** * Retrieves the top y position for a text. * * @param y the y position given in drawString() * @param anchor the orientation given in drawString() * @param height the height of the used font * @param baseLine the base line of the used font * @return the top y position. */ public int getTopY( int y, int anchor, int height, int baseLine ) { if ( (anchor & Graphics.TOP) == Graphics.TOP) { return y; } else if ( (anchor & Graphics.BOTTOM) == Graphics.BOTTOM) { return y - height; } else { return y - (height - baseLine); } } //#if polish.midp2 /** * Retrieves an RGB integer array in which the text is written on MIDP 2.0 devices. * NOTE: this method is not available on MIDP 1.0 devices! * You can determine the height and width of the produced RGB data with this code: * <pre> * int[] rgbData = getRgbData(text, textColor, font); * int height = font.getHeight(); * int width = rgbData.length / height; * </pre> * * @param text the text * @param textColor the color of the text * @param font the font of the text * @return the RGB data that contains the given text */ public static int[] getRgbData( String text, int textColor, Font font ) { int transparentColor = DrawUtil.getComplementaryColor( textColor ); if (transparentColor == textColor ) { transparentColor = 0; } int width = font.stringWidth( text ); int height = font.getHeight(); return getRgbData( text, textColor, font, 0, 0, width, height, transparentColor ); } //#endif //#if polish.midp2 /** * Retrieves an RGB integer array in which the text is written on MIDP 2.0 devices. * NOTE: this method is not available on MIDP 1.0 devices! * * @param text the text * @param textColor the color of the text * @param font the font of the text * @param x the left corner of the text in the created rgb data * @param y the top corner of the text in the created rgb data * @param width the desired width of the data array array, e.g. font.stringWidth(text) * @param height the desired height of the data array, e.g. font.getHeight() * @return the RGB data that contains the given text * @see DrawUtil#getComplementaryColor(int) */ public static int[] getRgbData(String text, int textColor, Font font, int x, int y, int width, int height ) { int transparentColor = DrawUtil.getComplementaryColor( textColor ); if (transparentColor == textColor ) { transparentColor = 0; } return getRgbData( text, textColor, font, x, y, width, height, transparentColor ); } //#endif //#if polish.midp2 /** * Retrieves an RGB integer array in which the text is written on MIDP 2.0 devices. * NOTE: this method is not available on MIDP 1.0 devices! * * @param text the text * @param textColor the color of the text * @param font the font of the text * @param x the left corner of the text in the created rgb data * @param y the top corner of the text in the created rgb data * @param width the desired width of the data array array, e.g. font.stringWidth(text) * @param height the desired height of the data array, e.g. font.getHeight() * @param transparentColor the color that should be used to flag transparent parts, using DrawUtil.getComplementaryColor( textColor ) might be a good idea * @return the RGB data that contains the given text * @see DrawUtil#getComplementaryColor(int) */ public static int[] getRgbData(String text, int textColor, Font font, int x, int y, int width, int height, int transparentColor) { // create Image, Graphics, ARGB-buffer Graphics bufferG; Image midp2ImageBuffer = Image.createImage( width, height); bufferG = midp2ImageBuffer.getGraphics(); // draw pseudo transparent Background bufferG.setColor( transparentColor ); bufferG.fillRect(0,0,width, height); // draw String on Graphics bufferG.setFont(font); bufferG.setColor( textColor ); bufferG.drawString(text, x, y, Graphics.LEFT | Graphics.TOP); // get RGB-Data from Image int[] rgbData = new int[ width * height ]; midp2ImageBuffer.getRGB( rgbData,0,width, 0, 0, width, height); // check clearColor int[] clearColorArray = new int[1]; midp2ImageBuffer.getRGB(clearColorArray, 0, 1, 0, 0, 1, 1 ); transparentColor = clearColorArray[0]; // transform RGB-Data for (int i=0; i<rgbData.length;i++){ // perform Transparency if (rgbData[i] == transparentColor){ rgbData[i] = 0x00000000; } } return rgbData; } //#endif /** * Notifies this effect that the corresponding item is to be shown. * The default implementation is empty. */ public void showNotify() { // default implementation is empty } /** * Notifies this effect that the corresponding item is to be hidden. * The default implementation is empty. */ public void hideNotify() { // default implementation is empty } /** * Releases any resources this effect might contain. * For staying future proof subclasses should call super.releaseResources() first, when overriding this method. */ public void releaseResources() { // do nothing } /** * Calculates the width of the given text. * By default getFont().stringWidth(text) is returned. * * @param str the text of which the width should be determined * @return the width of the text */ public int stringWidth(String str) { return getFont().stringWidth(str); } /** * Retrieves the width of the given char * @param c the char * @return the width of that char */ public int charWidth( char c) { return getFont().charWidth(c); } /** * Retrieves the font height by default. * @return the height of the font */ public int getFontHeight() { return getFont().getHeight(); } /** * Retrieves the font that should be used. * * @return the font */ protected Font getFont() { if (this.style != null && this.style.getFont() != null) { return this.style.getFont(); } return Font.getDefaultFont(); } /** * Wraps the text into several lines and adds the result to the specified wrappedText. * The default implementation just calls TextUtil.wrap(text, font, firstLineWidth, lineWidth, maxLines, maxLinesAppendix). * * @param parent the parent of this effect * @param text the text * @param textColor color of the text * @param font used font * @param firstLineWidth width of the first line * @param lineWidth width of following lines * @param maxLines the maximum number of lines * @param maxLinesAppendix the appendix that should be added to the last line when the line number is greater than maxLines * @param maxLinesAppendixPosition either TextUtil.MAXLINES_APPENDIX_POSITION_AFTER or TextUtil.MAXLINES_APPENDIX_POSITION_BEFORE * @param wrappedText the wrapped text object to which the single text lines should be added * @see TextUtil#wrap(String, Font, int, int, int, String, int) */ public void wrap(StringItem parent, String text, int textColor, Font font, int firstLineWidth, int lineWidth, int maxLines, String maxLinesAppendix, int maxLinesAppendixPosition, WrappedText wrappedText) { TextUtil.wrap(text, font, firstLineWidth, lineWidth, maxLines, maxLinesAppendix, maxLinesAppendixPosition, wrappedText); } //#if polish.libraryBuild /** * Wraps the text into several lines and adds the result to the specified wrappedText. * The default implementation just calls TextUtil.wrap(text, font, firstLineWidth, lineWidth, maxLines, maxLinesAppendix). * * @param parent the parent of this effect * @param text the text * @param textColor color of the text * @param font used font * @param firstLineWidth width of the first line * @param lineWidth width of following lines * @param maxLines the maximum number of lines * @param maxLinesAppendix the appendix that should be added to the last line when the line number is greater than maxLines * @param maxLinesAppendixPosition either TextUtil.MAXLINES_APPENDIX_POSITION_AFTER or TextUtil.MAXLINES_APPENDIX_POSITION_BEFORE * @param wrappedText the wrapped text object to which the single text lines should be added * @see TextUtil#wrap(String, Font, int, int, int, String, int) */ public void wrap(FakeStringCustomItem parent, String text, int textColor, Font font, int firstLineWidth, int lineWidth, int maxLines, String maxLinesAppendix, int maxLinesAppendixPosition, WrappedText wrappedText) { TextUtil.wrap(text, font, firstLineWidth, lineWidth, maxLines, maxLinesAppendix, maxLinesAppendixPosition, wrappedText); } //#endif /** * Draws the specified character using this effect. * Subclasses may override this - by default the character is just painted. * * @param c the character * @param x horizontal position * @param y vertical position * @param anchor anchor, e.g. Graphics.TOP | Graphics.LEFT * @param g the graphics context */ public void drawChar(char c, int x, int y, int anchor, Graphics g) { g.drawChar(c, x, y, anchor); } /** * Calculates the content height with the lines, the lineheight and the vertical padding * @param lines the lines * @param lineHeight the lineheight * @param paddingVertical the vertical padding * @return the height in pixels, normally (lines.size() * lineHeight) - paddingVertical; */ public int calculateLinesHeight(WrappedText lines, int lineHeight, int paddingVertical) { return (lines.size() * lineHeight) - paddingVertical; } }
true
true
public void drawStrings( WrappedText textLines, int textColor, int x, int y, int leftBorder, int rightBorder, int lineHeight, int maxWidth, int layout, Graphics g ) { boolean isLayoutRight = false; boolean isLayoutCenter = false; int centerX = 0; if ( ( layout & Item.LAYOUT_CENTER ) == Item.LAYOUT_CENTER ) { isLayoutCenter = true; centerX = leftBorder + (rightBorder - leftBorder) / 2; } else if ( ( layout & Item.LAYOUT_RIGHT ) == Item.LAYOUT_RIGHT ) { isLayoutRight = true; } Object[] lineObjects = textLines.getLinesInternalArray(); int size = textLines.size(); for (int i = 0; i < size; i++) { String line = (String) lineObjects[i]; int lineX = x; int lineY = y; int anchor = 0; // adjust the painting according to the layout: if (isLayoutRight) { lineX = rightBorder; //#if polish.Bugs.needsBottomOrientiationForStringDrawing anchor = Graphics.BOTTOM | Graphics.RIGHT; //#else anchor = Graphics.TOP | Graphics.RIGHT; //#endif } else if (isLayoutCenter) { lineX = centerX; //#if polish.Bugs.needsBottomOrientiationForStringDrawing anchor = Graphics.BOTTOM | Graphics.HCENTER; //#else anchor = Graphics.TOP | Graphics.HCENTER; //#endif } else { //#if polish.Bugs.needsBottomOrientiationForStringDrawing anchor = Graphics.BOTTOM | Graphics.LEFT; //#else anchor = Graphics.TOP | Graphics.LEFT; //#endif } drawString( line, textColor, lineX, lineY, anchor, g ); x = leftBorder; y += lineHeight; } }
public void drawStrings( WrappedText textLines, int textColor, int x, int y, int leftBorder, int rightBorder, int lineHeight, int maxWidth, int layout, Graphics g ) { boolean isLayoutRight = false; boolean isLayoutCenter = false; int centerX = 0; if ( ( layout & Item.LAYOUT_CENTER ) == Item.LAYOUT_CENTER ) { isLayoutCenter = true; centerX = leftBorder + (rightBorder - leftBorder) / 2; } else if ( ( layout & Item.LAYOUT_RIGHT ) == Item.LAYOUT_RIGHT ) { isLayoutRight = true; } Object[] lineObjects = textLines.getLinesInternalArray(); int size = textLines.size(); for (int i = 0; i < size; i++) { String line = (String) lineObjects[i]; if (line == null) { break; } int lineX = x; int lineY = y; int anchor = 0; // adjust the painting according to the layout: if (isLayoutRight) { lineX = rightBorder; //#if polish.Bugs.needsBottomOrientiationForStringDrawing anchor = Graphics.BOTTOM | Graphics.RIGHT; //#else anchor = Graphics.TOP | Graphics.RIGHT; //#endif } else if (isLayoutCenter) { lineX = centerX; //#if polish.Bugs.needsBottomOrientiationForStringDrawing anchor = Graphics.BOTTOM | Graphics.HCENTER; //#else anchor = Graphics.TOP | Graphics.HCENTER; //#endif } else { //#if polish.Bugs.needsBottomOrientiationForStringDrawing anchor = Graphics.BOTTOM | Graphics.LEFT; //#else anchor = Graphics.TOP | Graphics.LEFT; //#endif } drawString( line, textColor, lineX, lineY, anchor, g ); x = leftBorder; y += lineHeight; } }
diff --git a/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/bundle/api/BuildResource.java b/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/bundle/api/BuildResource.java index 7f020f727..0b0cd4370 100644 --- a/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/bundle/api/BuildResource.java +++ b/onebusaway-nyc-admin-webapp/src/main/java/org/onebusaway/nyc/admin/service/bundle/api/BuildResource.java @@ -1,107 +1,108 @@ package org.onebusaway.nyc.admin.service.bundle.api; import org.onebusaway.nyc.admin.model.BundleBuildRequest; import org.onebusaway.nyc.admin.model.BundleBuildResponse; import org.onebusaway.nyc.admin.service.BundleRequestService; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.MappingJsonFactory; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.io.StringWriter; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; @Path("/build/") @Component @Scope("singleton") public class BuildResource extends AuthenticatedResource { @Autowired private BundleRequestService _bundleService; private final ObjectMapper _mapper = new ObjectMapper(); private static Logger _log = LoggerFactory.getLogger(BuildResource.class); @Path("/{bundleDirectory}/{bundleName}/{email}/create") @GET @Produces("application/json") public Response build(@PathParam("bundleDirectory") String bundleDirectory, @PathParam("bundleName") String bundleName, @PathParam("email") String email) { Response response = null; if (!isAuthorized()) { return Response.noContent().build(); } BundleBuildRequest buildRequest = new BundleBuildRequest(); buildRequest.setBundleDirectory(bundleDirectory); buildRequest.setBundleName(bundleName); buildRequest.setEmailAddress(email); BundleBuildResponse buildResponse = null; try { buildResponse =_bundleService.build(buildRequest); + buildResponse = _bundleService.buildBundleResultURL(buildResponse.getId()); final StringWriter sw = new StringWriter(); final MappingJsonFactory jsonFactory = new MappingJsonFactory(); final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(sw); _mapper.writeValue(jsonGenerator, buildResponse); response = Response.ok(sw.toString()).build(); } catch (Exception any) { _log.error("exception in build:", any); response = Response.serverError().build(); } return response; } @Path("/{id}/list") @GET @Produces("application/json") public Response list(@PathParam("id") String id) { Response response = null; if (!isAuthorized()) { return Response.noContent().build(); } BundleBuildResponse buildResponse = _bundleService.lookupBuildRequest(id); try { final StringWriter sw = new StringWriter(); final MappingJsonFactory jsonFactory = new MappingJsonFactory(); final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(sw); _mapper.writeValue(jsonGenerator, buildResponse); _log.info("received response=" + buildResponse); response = Response.ok(sw.toString()).build(); } catch (Exception any){ _log.error("exception looking up build:", any); response = Response.serverError().build(); } return response; } @Path("/{id}/url") @GET @Produces("application/json") public Response url(@PathParam("id") String id) { Response response = null; if (!isAuthorized()) { return Response.noContent().build(); } BundleBuildResponse buildResponse = _bundleService.lookupBuildRequest(id); try { final StringWriter sw = new StringWriter(); final MappingJsonFactory jsonFactory = new MappingJsonFactory(); final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(sw); _mapper.writeValue(jsonGenerator, buildResponse); response = Response.ok(sw.toString()).build(); } catch (Exception any){ _log.error("exception looking up build:", any); response = Response.serverError().build(); } return response; } }
true
true
public Response build(@PathParam("bundleDirectory") String bundleDirectory, @PathParam("bundleName") String bundleName, @PathParam("email") String email) { Response response = null; if (!isAuthorized()) { return Response.noContent().build(); } BundleBuildRequest buildRequest = new BundleBuildRequest(); buildRequest.setBundleDirectory(bundleDirectory); buildRequest.setBundleName(bundleName); buildRequest.setEmailAddress(email); BundleBuildResponse buildResponse = null; try { buildResponse =_bundleService.build(buildRequest); final StringWriter sw = new StringWriter(); final MappingJsonFactory jsonFactory = new MappingJsonFactory(); final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(sw); _mapper.writeValue(jsonGenerator, buildResponse); response = Response.ok(sw.toString()).build(); } catch (Exception any) { _log.error("exception in build:", any); response = Response.serverError().build(); } return response; }
public Response build(@PathParam("bundleDirectory") String bundleDirectory, @PathParam("bundleName") String bundleName, @PathParam("email") String email) { Response response = null; if (!isAuthorized()) { return Response.noContent().build(); } BundleBuildRequest buildRequest = new BundleBuildRequest(); buildRequest.setBundleDirectory(bundleDirectory); buildRequest.setBundleName(bundleName); buildRequest.setEmailAddress(email); BundleBuildResponse buildResponse = null; try { buildResponse =_bundleService.build(buildRequest); buildResponse = _bundleService.buildBundleResultURL(buildResponse.getId()); final StringWriter sw = new StringWriter(); final MappingJsonFactory jsonFactory = new MappingJsonFactory(); final JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(sw); _mapper.writeValue(jsonGenerator, buildResponse); response = Response.ok(sw.toString()).build(); } catch (Exception any) { _log.error("exception in build:", any); response = Response.serverError().build(); } return response; }
diff --git a/framework/src/play/mvc/Mailer.java b/framework/src/play/mvc/Mailer.java index bb92fa66..819472e0 100644 --- a/framework/src/play/mvc/Mailer.java +++ b/framework/src/play/mvc/Mailer.java @@ -1,256 +1,256 @@ package play.mvc; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import play.Logger; import play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer; import play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesSupport; import play.exceptions.TemplateNotFoundException; import play.exceptions.UnexpectedException; import play.libs.Mail; import play.templates.Template; import play.templates.TemplateLoader; /** * Application mailer support */ public class Mailer implements LocalVariablesSupport { protected static ThreadLocal<HashMap<String, Object>> infos = new ThreadLocal<HashMap<String, Object>>(); public static void setSubject(String subject, Object... args) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } map.put("subject", String.format(subject, args)); infos.set(map); } public static void addRecipient(Object... recipients) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } List recipientsList = (List<String>) map.get("recipients"); if (recipientsList == null) { recipientsList = new ArrayList<String>(); map.put("recipients", recipientsList); } recipientsList.addAll(Arrays.asList(recipients)); infos.set(map); } public static void addAttachment(Object... attachments) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } List attachmentsList = (List) map.get("attachments"); if (attachmentsList == null) { attachmentsList = new ArrayList<Object>(); map.put("attachments", attachmentsList); } attachmentsList.addAll(Arrays.asList(attachments)); infos.set(map); } public static void setContentType(String contentType) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } map.put("contentType", contentType); infos.set(map); } /** * Can be of the form xxx <[email protected]> * @param from */ public static void setFrom(Object from) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } map.put("from", from); infos.set(map); } /** * Can be of the form xxx <[email protected]> * @param replyTo */ public static void setReplyTo(Object replyTo) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } map.put("replyTo", replyTo); infos.set(map); } /** * @deprecated * @param personal */ public static void setPersonal(String personal) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } map.put("personal", personal); infos.set(map); } public static void setCharset(String bodyCharset) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } map.put("charset", bodyCharset); infos.set(map); } public static void addHeader(String key, String value) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } HashMap<String, String> headers = (HashMap<String, String>) map.get("headers"); if (headers == null) { headers = new HashMap<String, String>(); } headers.put(key, value); map.put("headers", headers); infos.set(map); } public static Future<Boolean> send(Object... args) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } // Body character set String charset = (String) infos.get().get("charset"); // Headers Map<String, String> headers = (Map<String,String>) infos.get().get("headers"); // Subject String subject = (String) infos.get().get("subject"); String templateName = (String) infos.get().get("method"); if (templateName.startsWith("notifiers.")) { templateName = templateName.substring("notifiers.".length()); } if (templateName.startsWith("controllers.")) { templateName = templateName.substring("controllers.".length()); } templateName = templateName.substring(0, templateName.indexOf("(")); templateName = templateName.replace(".", "/"); // overrides Template name if (args.length > 0 && args[0] instanceof String && LocalVariablesNamesTracer.getAllLocalVariableNames(args[0]).isEmpty()) { templateName = args[0].toString(); } Map<String, Object> templateHtmlBinding = new HashMap(); Map<String, Object> templateTextBinding = new HashMap(); for (Object o : args) { List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o); for (String name : names) { templateHtmlBinding.put(name, o); templateTextBinding.put(name, o); } } // The rule is as follow: If we ask for text/plain, we don't care about the HTML // If we ask for HTML and there is a text/plain we add it as an alternative. // If contentType is not specified look at the template available: // - .txt only -> text/plain // else // - -> text/html String contentType = (String) infos.get().get("contentType"); String bodyHtml = null; String bodyText = ""; try { Template templateHtml = TemplateLoader.load(templateName + ".html"); bodyHtml = templateHtml.render(templateHtmlBinding); } catch (TemplateNotFoundException e) { - if (contentType != null && !"text/plain".equals(contentType)) { + if (contentType != null && !contentType.startsWith("text/plain")) { throw e; } } try { Template templateText = TemplateLoader.load(templateName + ".txt"); bodyText = templateText.render(templateTextBinding); } catch (TemplateNotFoundException e) { - if ("text/plain".equals(contentType)) { + if (bodyHtml == null && (contentType == null || (contentType != null && contentType.startsWith("text/plain")))) { throw e; } } // Content type if (contentType == null) { if (bodyHtml != null) { contentType = "text/html"; } else { contentType = "text/plain"; } } // Recipients List<Object> recipientList = (List<Object>) infos.get().get("recipients"); Object[] recipients = new Object[recipientList.size()]; int i = 0; for (Object recipient : recipientList) { recipients[i] = recipient; i++; } // From Object from = infos.get().get("from"); Object replyTo = infos.get().get("replyTo"); // Attachment Object[] attachements = new Object[0]; if (infos.get().get("attachments") != null) { List<Object> objectList = (List<Object>) infos.get().get("attachments"); attachements = new Object[objectList.size()]; i = 0; for (Object object : objectList) { attachements[i] = object; i++; } } // Send final String body = (bodyHtml != null ? bodyHtml : bodyText); final String alternate = (bodyHtml != null ? bodyText : null); return Mail.send(from, replyTo, recipients, subject, body, alternate, contentType, charset, headers, attachements); } public static boolean sendAndWait(Object... args) { try { Future<Boolean> result = send(args); return result.get(); } catch (InterruptedException e) { Logger.error(e, "Error while waiting Mail.send result"); } catch (ExecutionException e) { Logger.error(e, "Error while waiting Mail.send result"); } return false; } }
false
true
public static Future<Boolean> send(Object... args) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } // Body character set String charset = (String) infos.get().get("charset"); // Headers Map<String, String> headers = (Map<String,String>) infos.get().get("headers"); // Subject String subject = (String) infos.get().get("subject"); String templateName = (String) infos.get().get("method"); if (templateName.startsWith("notifiers.")) { templateName = templateName.substring("notifiers.".length()); } if (templateName.startsWith("controllers.")) { templateName = templateName.substring("controllers.".length()); } templateName = templateName.substring(0, templateName.indexOf("(")); templateName = templateName.replace(".", "/"); // overrides Template name if (args.length > 0 && args[0] instanceof String && LocalVariablesNamesTracer.getAllLocalVariableNames(args[0]).isEmpty()) { templateName = args[0].toString(); } Map<String, Object> templateHtmlBinding = new HashMap(); Map<String, Object> templateTextBinding = new HashMap(); for (Object o : args) { List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o); for (String name : names) { templateHtmlBinding.put(name, o); templateTextBinding.put(name, o); } } // The rule is as follow: If we ask for text/plain, we don't care about the HTML // If we ask for HTML and there is a text/plain we add it as an alternative. // If contentType is not specified look at the template available: // - .txt only -> text/plain // else // - -> text/html String contentType = (String) infos.get().get("contentType"); String bodyHtml = null; String bodyText = ""; try { Template templateHtml = TemplateLoader.load(templateName + ".html"); bodyHtml = templateHtml.render(templateHtmlBinding); } catch (TemplateNotFoundException e) { if (contentType != null && !"text/plain".equals(contentType)) { throw e; } } try { Template templateText = TemplateLoader.load(templateName + ".txt"); bodyText = templateText.render(templateTextBinding); } catch (TemplateNotFoundException e) { if ("text/plain".equals(contentType)) { throw e; } } // Content type if (contentType == null) { if (bodyHtml != null) { contentType = "text/html"; } else { contentType = "text/plain"; } } // Recipients List<Object> recipientList = (List<Object>) infos.get().get("recipients"); Object[] recipients = new Object[recipientList.size()]; int i = 0; for (Object recipient : recipientList) { recipients[i] = recipient; i++; } // From Object from = infos.get().get("from"); Object replyTo = infos.get().get("replyTo"); // Attachment Object[] attachements = new Object[0]; if (infos.get().get("attachments") != null) { List<Object> objectList = (List<Object>) infos.get().get("attachments"); attachements = new Object[objectList.size()]; i = 0; for (Object object : objectList) { attachements[i] = object; i++; } } // Send final String body = (bodyHtml != null ? bodyHtml : bodyText); final String alternate = (bodyHtml != null ? bodyText : null); return Mail.send(from, replyTo, recipients, subject, body, alternate, contentType, charset, headers, attachements); }
public static Future<Boolean> send(Object... args) { HashMap map = infos.get(); if (map == null) { throw new UnexpectedException("Mailer not instrumented ?"); } // Body character set String charset = (String) infos.get().get("charset"); // Headers Map<String, String> headers = (Map<String,String>) infos.get().get("headers"); // Subject String subject = (String) infos.get().get("subject"); String templateName = (String) infos.get().get("method"); if (templateName.startsWith("notifiers.")) { templateName = templateName.substring("notifiers.".length()); } if (templateName.startsWith("controllers.")) { templateName = templateName.substring("controllers.".length()); } templateName = templateName.substring(0, templateName.indexOf("(")); templateName = templateName.replace(".", "/"); // overrides Template name if (args.length > 0 && args[0] instanceof String && LocalVariablesNamesTracer.getAllLocalVariableNames(args[0]).isEmpty()) { templateName = args[0].toString(); } Map<String, Object> templateHtmlBinding = new HashMap(); Map<String, Object> templateTextBinding = new HashMap(); for (Object o : args) { List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o); for (String name : names) { templateHtmlBinding.put(name, o); templateTextBinding.put(name, o); } } // The rule is as follow: If we ask for text/plain, we don't care about the HTML // If we ask for HTML and there is a text/plain we add it as an alternative. // If contentType is not specified look at the template available: // - .txt only -> text/plain // else // - -> text/html String contentType = (String) infos.get().get("contentType"); String bodyHtml = null; String bodyText = ""; try { Template templateHtml = TemplateLoader.load(templateName + ".html"); bodyHtml = templateHtml.render(templateHtmlBinding); } catch (TemplateNotFoundException e) { if (contentType != null && !contentType.startsWith("text/plain")) { throw e; } } try { Template templateText = TemplateLoader.load(templateName + ".txt"); bodyText = templateText.render(templateTextBinding); } catch (TemplateNotFoundException e) { if (bodyHtml == null && (contentType == null || (contentType != null && contentType.startsWith("text/plain")))) { throw e; } } // Content type if (contentType == null) { if (bodyHtml != null) { contentType = "text/html"; } else { contentType = "text/plain"; } } // Recipients List<Object> recipientList = (List<Object>) infos.get().get("recipients"); Object[] recipients = new Object[recipientList.size()]; int i = 0; for (Object recipient : recipientList) { recipients[i] = recipient; i++; } // From Object from = infos.get().get("from"); Object replyTo = infos.get().get("replyTo"); // Attachment Object[] attachements = new Object[0]; if (infos.get().get("attachments") != null) { List<Object> objectList = (List<Object>) infos.get().get("attachments"); attachements = new Object[objectList.size()]; i = 0; for (Object object : objectList) { attachements[i] = object; i++; } } // Send final String body = (bodyHtml != null ? bodyHtml : bodyText); final String alternate = (bodyHtml != null ? bodyText : null); return Mail.send(from, replyTo, recipients, subject, body, alternate, contentType, charset, headers, attachements); }
diff --git a/weaver5/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java b/weaver5/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java index 1a66bf066..629a0f441 100644 --- a/weaver5/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java +++ b/weaver5/java5-src/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java @@ -1,354 +1,353 @@ /* ******************************************************************* * Copyright (c) 2005 Contributors. * 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://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.reflect; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.Iterator; import java.util.Set; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.AjType; import org.aspectj.lang.reflect.AjTypeSystem; import org.aspectj.lang.reflect.Pointcut; import org.aspectj.weaver.AnnotationX; import org.aspectj.weaver.ReferenceType; import org.aspectj.weaver.ResolvedMember; import org.aspectj.weaver.ResolvedPointcutDefinition; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariable; import org.aspectj.weaver.TypeVariableReferenceType; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.World; import org.aspectj.weaver.tools.PointcutDesignatorHandler; import org.aspectj.weaver.tools.PointcutParameter; /** * @author colyer * Provides Java 5 behaviour in reflection based delegates (overriding * 1.4 behaviour from superclass where appropriate) */ public class Java15ReflectionBasedReferenceTypeDelegate extends ReflectionBasedReferenceTypeDelegate { private AjType<?> myType; private ResolvedType[] annotations; private ResolvedMember[] pointcuts; private ResolvedMember[] methods; private ResolvedMember[] fields; private TypeVariable[] typeVariables; private ResolvedType superclass; private ResolvedType[] superInterfaces; private String genericSignature = null; private JavaLangTypeToResolvedTypeConverter typeConverter; private Java15AnnotationFinder annotationFinder = null; private ArgNameFinder argNameFinder = null; public Java15ReflectionBasedReferenceTypeDelegate() {} @Override public void initialize(ReferenceType aType, Class aClass, ClassLoader classLoader, World aWorld) { super.initialize(aType, aClass, classLoader, aWorld); myType = AjTypeSystem.getAjType(aClass); annotationFinder = new Java15AnnotationFinder(); argNameFinder = annotationFinder; annotationFinder.setClassLoader(this.classLoader); annotationFinder.setWorld(aWorld); this.typeConverter = new JavaLangTypeToResolvedTypeConverter(aWorld); } public ReferenceType buildGenericType() { return (ReferenceType) UnresolvedType.forGenericTypeVariables( getResolvedTypeX().getSignature(), getTypeVariables()).resolve(getWorld()); } public AnnotationX[] getAnnotations() { // AMC - we seem not to need to implement this method... //throw new UnsupportedOperationException("getAnnotations on Java15ReflectionBasedReferenceTypeDelegate is not implemented yet"); // FIXME is this the right implementation in the reflective case? return super.getAnnotations(); } public ResolvedType[] getAnnotationTypes() { if (annotations == null) { annotations = annotationFinder.getAnnotations(getBaseClass(), getWorld()); } return annotations; } public boolean hasAnnotation(UnresolvedType ofType) { ResolvedType[] myAnns = getAnnotationTypes(); ResolvedType toLookFor = ofType.resolve(getWorld()); for (int i = 0; i < myAnns.length; i++) { if (myAnns[i] == toLookFor) return true; } return false; } // use the MAP to ensure that any aj-synthetic fields are filtered out public ResolvedMember[] getDeclaredFields() { if (fields == null) { Field[] reflectFields = this.myType.getDeclaredFields(); ResolvedMember[] rFields = new ResolvedMember[reflectFields.length]; for (int i = 0; i < reflectFields.length; i++) { rFields[i] = createGenericFieldMember(reflectFields[i]); } this.fields = rFields; } return fields; } public String getDeclaredGenericSignature() { if (this.genericSignature == null && isGeneric()) { } return genericSignature; } public ResolvedType[] getDeclaredInterfaces() { if (superInterfaces == null) { Type[] genericInterfaces = getBaseClass().getGenericInterfaces(); this.superInterfaces = typeConverter.fromTypes(genericInterfaces); } return superInterfaces; } // If the superclass is null, return Object - same as bcel does public ResolvedType getSuperclass() { if (superclass == null && getBaseClass()!=Object.class) {// superclass of Object is null Type t = this.getBaseClass().getGenericSuperclass(); if (t!=null) superclass = typeConverter.fromType(t); if (t==null) superclass = getWorld().resolve(UnresolvedType.OBJECT); } return superclass; } public TypeVariable[] getTypeVariables() { TypeVariable[] workInProgressSetOfVariables = (TypeVariable[])getResolvedTypeX().getWorld().getTypeVariablesCurrentlyBeingProcessed(getBaseClass()); if (workInProgressSetOfVariables!=null) { return workInProgressSetOfVariables; } if (this.typeVariables == null) { java.lang.reflect.TypeVariable[] tVars = this.getBaseClass().getTypeParameters(); TypeVariable[] rTypeVariables = new TypeVariable[tVars.length]; // basic initialization for (int i = 0; i < tVars.length; i++) { rTypeVariables[i] = new TypeVariable(tVars[i].getName()); } // stash it this.getResolvedTypeX().getWorld().recordTypeVariablesCurrentlyBeingProcessed(getBaseClass(), rTypeVariables); // now fill in the details... for (int i = 0; i < tVars.length; i++) { TypeVariableReferenceType tvrt = ((TypeVariableReferenceType) typeConverter.fromType(tVars[i])); TypeVariable tv = tvrt.getTypeVariable(); rTypeVariables[i].setUpperBound(tv.getUpperBound()); rTypeVariables[i].setAdditionalInterfaceBounds(tv.getAdditionalInterfaceBounds()); rTypeVariables[i].setDeclaringElement(tv.getDeclaringElement()); rTypeVariables[i].setDeclaringElementKind(tv.getDeclaringElementKind()); rTypeVariables[i].setRank(tv.getRank()); rTypeVariables[i].setLowerBound(tv.getLowerBound()); } this.typeVariables = rTypeVariables; this.getResolvedTypeX().getWorld().forgetTypeVariablesCurrentlyBeingProcessed(getBaseClass()); } return this.typeVariables; } // overrides super method since by using the MAP we can filter out advice // methods that really shouldn't be seen in this list public ResolvedMember[] getDeclaredMethods() { if (methods == null) { Method[] reflectMethods = this.myType.getDeclaredMethods(); Constructor[] reflectCons = this.myType.getDeclaredConstructors(); ResolvedMember[] rMethods = new ResolvedMember[reflectMethods.length + reflectCons.length]; for (int i = 0; i < reflectMethods.length; i++) { rMethods[i] = createGenericMethodMember(reflectMethods[i]); } for (int i = 0; i < reflectCons.length; i++) { rMethods[i + reflectMethods.length] = createGenericConstructorMember(reflectCons[i]); } this.methods = rMethods; } return methods; } /** * Returns the generic type, regardless of the resolvedType we 'know about' */ public ResolvedType getGenericResolvedType() { ResolvedType rt = getResolvedTypeX(); if (rt.isParameterizedType() || rt.isRawType()) return rt.getGenericType(); return rt; } private ResolvedMember createGenericMethodMember(Method forMethod) { ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD, getGenericResolvedType(), forMethod.getModifiers(), typeConverter.fromType(forMethod.getReturnType()), forMethod.getName(), typeConverter.fromTypes(forMethod.getParameterTypes()), typeConverter.fromTypes(forMethod.getExceptionTypes()), forMethod ); ret.setAnnotationFinder(this.annotationFinder); ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld())); return ret; } private ResolvedMember createGenericConstructorMember(Constructor forConstructor) { ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl(org.aspectj.weaver.Member.METHOD, getGenericResolvedType(), forConstructor.getModifiers(), // to return what BCEL returns the return type is void ResolvedType.VOID,//getGenericResolvedType(), "<init>", typeConverter.fromTypes(forConstructor.getParameterTypes()), typeConverter.fromTypes(forConstructor.getExceptionTypes()), forConstructor ); ret.setAnnotationFinder(this.annotationFinder); ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld())); return ret; } private ResolvedMember createGenericFieldMember(Field forField) { ReflectionBasedResolvedMemberImpl ret = new ReflectionBasedResolvedMemberImpl( org.aspectj.weaver.Member.FIELD, getGenericResolvedType(), forField.getModifiers(), typeConverter.fromType(forField.getType()), forField.getName(), new UnresolvedType[0], forField); ret.setAnnotationFinder(this.annotationFinder); ret.setGenericSignatureInformationProvider(new Java15GenericSignatureInformationProvider(this.getWorld())); return ret; } public ResolvedMember[] getDeclaredPointcuts() { if (pointcuts == null) { Pointcut[] pcs = this.myType.getDeclaredPointcuts(); - ResolvedMember[] rPointcuts = new ResolvedMember[pcs.length]; + pointcuts = new ResolvedMember[pcs.length]; InternalUseOnlyPointcutParser parser = null; World world = getWorld(); if (world instanceof ReflectionWorld) { parser = new InternalUseOnlyPointcutParser(classLoader,(ReflectionWorld)getWorld()); } else { parser = new InternalUseOnlyPointcutParser(classLoader); } Set additionalPointcutHandlers = world.getRegisteredPointcutHandlers(); for (Iterator handlerIterator = additionalPointcutHandlers.iterator(); handlerIterator.hasNext();) { PointcutDesignatorHandler handler = (PointcutDesignatorHandler) handlerIterator.next(); parser.registerPointcutDesignatorHandler(handler); } // phase 1, create legitimate entries in pointcuts[] before we attempt to resolve *any* of the pointcuts // resolution can sometimes cause us to recurse, and this two stage process allows us to cope with that for (int i = 0; i < pcs.length; i++) { AjType<?>[] ptypes = pcs[i].getParameterTypes(); UnresolvedType[] weaverPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < weaverPTypes.length; j++) { weaverPTypes[j] = this.typeConverter.fromType(ptypes[j].getJavaClass()) ; } - rPointcuts[i] = new DeferredResolvedPointcutDefinition(getResolvedTypeX(), pcs[i].getModifiers(), pcs[i].getName(), weaverPTypes); + pointcuts[i] = new DeferredResolvedPointcutDefinition(getResolvedTypeX(),pcs[i].getModifiers(),pcs[i].getName(),weaverPTypes); } // phase 2, now go back round and resolve in-place all of the pointcuts PointcutParameter[][] parameters = new PointcutParameter[pcs.length][]; for (int i = 0; i < pcs.length; i++) { AjType<?>[] ptypes = pcs[i].getParameterTypes(); String[] pnames = pcs[i].getParameterNames(); if (pnames.length != ptypes.length) { pnames = tryToDiscoverParameterNames(pcs[i]); if (pnames == null || (pnames.length != ptypes.length)) { throw new IllegalStateException("Required parameter names not available when parsing pointcut " + pcs[i].getName() + " in type " + getResolvedTypeX().getName()); } } parameters[i] = new PointcutParameter[ptypes.length]; for (int j = 0; j < parameters[i].length; j++) { parameters[i][j] = parser.createPointcutParameter(pnames[j],ptypes[j].getJavaClass()); } String pcExpr = pcs[i].getPointcutExpression().toString(); org.aspectj.weaver.patterns.Pointcut pc = parser.resolvePointcutExpression(pcExpr,getBaseClass(),parameters[i]); - ((ResolvedPointcutDefinition) rPointcuts[i]).setParameterNames(pnames); - ((ResolvedPointcutDefinition) rPointcuts[i]).setPointcut(pc); + ((ResolvedPointcutDefinition)pointcuts[i]).setParameterNames(pnames); + ((ResolvedPointcutDefinition)pointcuts[i]).setPointcut(pc); } // phase 3, now concretize them all - for (int i = 0; i < rPointcuts.length; i++) { - ResolvedPointcutDefinition rpd = (ResolvedPointcutDefinition) rPointcuts[i]; + for (int i = 0; i < pointcuts.length; i++) { + ResolvedPointcutDefinition rpd = (ResolvedPointcutDefinition) pointcuts[i]; rpd.setPointcut(parser.concretizePointcutExpression(rpd.getPointcut(), getBaseClass(), parameters[i])); } - this.pointcuts = rPointcuts; } return pointcuts; } // for @AspectJ pointcuts compiled by javac only... private String[] tryToDiscoverParameterNames(Pointcut pcut) { Method[] ms = pcut.getDeclaringType().getJavaClass().getDeclaredMethods(); for(Method m : ms) { if (m.getName().equals(pcut.getName())) { return argNameFinder.getParameterNames(m); } } return null; } public boolean isAnnotation() { return getBaseClass().isAnnotation(); } public boolean isAnnotationStyleAspect() { return getBaseClass().isAnnotationPresent(Aspect.class); } public boolean isAnnotationWithRuntimeRetention() { if (!isAnnotation()) return false; if (getBaseClass().isAnnotationPresent(Retention.class)) { Retention retention = (Retention) getBaseClass().getAnnotation(Retention.class); RetentionPolicy policy = retention.value(); return policy == RetentionPolicy.RUNTIME; } else { return false; } } public boolean isAspect() { return this.myType.isAspect(); } public boolean isEnum() { return getBaseClass().isEnum(); } public boolean isGeneric() { //return false; // for now return getBaseClass().getTypeParameters().length > 0; } @Override public boolean isAnonymous() { return this.myClass.isAnonymousClass(); } }
false
true
public ResolvedMember[] getDeclaredPointcuts() { if (pointcuts == null) { Pointcut[] pcs = this.myType.getDeclaredPointcuts(); ResolvedMember[] rPointcuts = new ResolvedMember[pcs.length]; InternalUseOnlyPointcutParser parser = null; World world = getWorld(); if (world instanceof ReflectionWorld) { parser = new InternalUseOnlyPointcutParser(classLoader,(ReflectionWorld)getWorld()); } else { parser = new InternalUseOnlyPointcutParser(classLoader); } Set additionalPointcutHandlers = world.getRegisteredPointcutHandlers(); for (Iterator handlerIterator = additionalPointcutHandlers.iterator(); handlerIterator.hasNext();) { PointcutDesignatorHandler handler = (PointcutDesignatorHandler) handlerIterator.next(); parser.registerPointcutDesignatorHandler(handler); } // phase 1, create legitimate entries in pointcuts[] before we attempt to resolve *any* of the pointcuts // resolution can sometimes cause us to recurse, and this two stage process allows us to cope with that for (int i = 0; i < pcs.length; i++) { AjType<?>[] ptypes = pcs[i].getParameterTypes(); UnresolvedType[] weaverPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < weaverPTypes.length; j++) { weaverPTypes[j] = this.typeConverter.fromType(ptypes[j].getJavaClass()) ; } rPointcuts[i] = new DeferredResolvedPointcutDefinition(getResolvedTypeX(), pcs[i].getModifiers(), pcs[i].getName(), weaverPTypes); } // phase 2, now go back round and resolve in-place all of the pointcuts PointcutParameter[][] parameters = new PointcutParameter[pcs.length][]; for (int i = 0; i < pcs.length; i++) { AjType<?>[] ptypes = pcs[i].getParameterTypes(); String[] pnames = pcs[i].getParameterNames(); if (pnames.length != ptypes.length) { pnames = tryToDiscoverParameterNames(pcs[i]); if (pnames == null || (pnames.length != ptypes.length)) { throw new IllegalStateException("Required parameter names not available when parsing pointcut " + pcs[i].getName() + " in type " + getResolvedTypeX().getName()); } } parameters[i] = new PointcutParameter[ptypes.length]; for (int j = 0; j < parameters[i].length; j++) { parameters[i][j] = parser.createPointcutParameter(pnames[j],ptypes[j].getJavaClass()); } String pcExpr = pcs[i].getPointcutExpression().toString(); org.aspectj.weaver.patterns.Pointcut pc = parser.resolvePointcutExpression(pcExpr,getBaseClass(),parameters[i]); ((ResolvedPointcutDefinition) rPointcuts[i]).setParameterNames(pnames); ((ResolvedPointcutDefinition) rPointcuts[i]).setPointcut(pc); } // phase 3, now concretize them all for (int i = 0; i < rPointcuts.length; i++) { ResolvedPointcutDefinition rpd = (ResolvedPointcutDefinition) rPointcuts[i]; rpd.setPointcut(parser.concretizePointcutExpression(rpd.getPointcut(), getBaseClass(), parameters[i])); } this.pointcuts = rPointcuts; } return pointcuts; }
public ResolvedMember[] getDeclaredPointcuts() { if (pointcuts == null) { Pointcut[] pcs = this.myType.getDeclaredPointcuts(); pointcuts = new ResolvedMember[pcs.length]; InternalUseOnlyPointcutParser parser = null; World world = getWorld(); if (world instanceof ReflectionWorld) { parser = new InternalUseOnlyPointcutParser(classLoader,(ReflectionWorld)getWorld()); } else { parser = new InternalUseOnlyPointcutParser(classLoader); } Set additionalPointcutHandlers = world.getRegisteredPointcutHandlers(); for (Iterator handlerIterator = additionalPointcutHandlers.iterator(); handlerIterator.hasNext();) { PointcutDesignatorHandler handler = (PointcutDesignatorHandler) handlerIterator.next(); parser.registerPointcutDesignatorHandler(handler); } // phase 1, create legitimate entries in pointcuts[] before we attempt to resolve *any* of the pointcuts // resolution can sometimes cause us to recurse, and this two stage process allows us to cope with that for (int i = 0; i < pcs.length; i++) { AjType<?>[] ptypes = pcs[i].getParameterTypes(); UnresolvedType[] weaverPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < weaverPTypes.length; j++) { weaverPTypes[j] = this.typeConverter.fromType(ptypes[j].getJavaClass()) ; } pointcuts[i] = new DeferredResolvedPointcutDefinition(getResolvedTypeX(),pcs[i].getModifiers(),pcs[i].getName(),weaverPTypes); } // phase 2, now go back round and resolve in-place all of the pointcuts PointcutParameter[][] parameters = new PointcutParameter[pcs.length][]; for (int i = 0; i < pcs.length; i++) { AjType<?>[] ptypes = pcs[i].getParameterTypes(); String[] pnames = pcs[i].getParameterNames(); if (pnames.length != ptypes.length) { pnames = tryToDiscoverParameterNames(pcs[i]); if (pnames == null || (pnames.length != ptypes.length)) { throw new IllegalStateException("Required parameter names not available when parsing pointcut " + pcs[i].getName() + " in type " + getResolvedTypeX().getName()); } } parameters[i] = new PointcutParameter[ptypes.length]; for (int j = 0; j < parameters[i].length; j++) { parameters[i][j] = parser.createPointcutParameter(pnames[j],ptypes[j].getJavaClass()); } String pcExpr = pcs[i].getPointcutExpression().toString(); org.aspectj.weaver.patterns.Pointcut pc = parser.resolvePointcutExpression(pcExpr,getBaseClass(),parameters[i]); ((ResolvedPointcutDefinition)pointcuts[i]).setParameterNames(pnames); ((ResolvedPointcutDefinition)pointcuts[i]).setPointcut(pc); } // phase 3, now concretize them all for (int i = 0; i < pointcuts.length; i++) { ResolvedPointcutDefinition rpd = (ResolvedPointcutDefinition) pointcuts[i]; rpd.setPointcut(parser.concretizePointcutExpression(rpd.getPointcut(), getBaseClass(), parameters[i])); } } return pointcuts; }
diff --git a/src/main/java/nl/tudelft/commons/IOUtils.java b/src/main/java/nl/tudelft/commons/IOUtils.java index 12ce511..604e4f1 100644 --- a/src/main/java/nl/tudelft/commons/IOUtils.java +++ b/src/main/java/nl/tudelft/commons/IOUtils.java @@ -1,48 +1,49 @@ package nl.tudelft.commons; import static com.google.common.base.Preconditions.checkNotNull; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IOUtils { private static final Logger LOG = LoggerFactory.getLogger(IOUtils.class); /** * Read a resource from the classpath and return the contents as * {@link String}. * * @param name The name of the resource, for example, * <code>/nl/tudelft/commons/IOUtils.java</code>. * * @return The contents of the resource. * * @throws IOException An I/O error occurred while reading the resource. */ public static String readResource(final String name) throws IOException { LOG.info("Reading resource: {}", name); checkNotNull(name, "name must not be null"); final InputStream is = IOUtils.class.getResourceAsStream(name); final InputStreamReader isr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(isr); final StringBuilder sb = new StringBuilder(); while (br.ready()) { final String line = br.readLine(); sb.append(line); } + br.close(); return sb.toString(); } }
true
true
public static String readResource(final String name) throws IOException { LOG.info("Reading resource: {}", name); checkNotNull(name, "name must not be null"); final InputStream is = IOUtils.class.getResourceAsStream(name); final InputStreamReader isr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(isr); final StringBuilder sb = new StringBuilder(); while (br.ready()) { final String line = br.readLine(); sb.append(line); } return sb.toString(); }
public static String readResource(final String name) throws IOException { LOG.info("Reading resource: {}", name); checkNotNull(name, "name must not be null"); final InputStream is = IOUtils.class.getResourceAsStream(name); final InputStreamReader isr = new InputStreamReader(is); final BufferedReader br = new BufferedReader(isr); final StringBuilder sb = new StringBuilder(); while (br.ready()) { final String line = br.readLine(); sb.append(line); } br.close(); return sb.toString(); }
diff --git a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/test/utils/FileTestingUtils.java b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/test/utils/FileTestingUtils.java index a1c642087..83ab882b3 100644 --- a/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/test/utils/FileTestingUtils.java +++ b/nexus/nexus-test-harness/nexus-test-harness-launcher/src/test/java/org/sonatype/nexus/test/utils/FileTestingUtils.java @@ -1,299 +1,299 @@ /** * Sonatype Nexus (TM) Open Source Version. * Copyright (c) 2008 Sonatype, Inc. All rights reserved. * Includes the third-party code listed at http://nexus.sonatype.org/dev/attributions.html * This program is licensed to you under Version 3 only of the GNU General Public License as published by the Free Software Foundation. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License Version 3 for more details. * You should have received a copy of the GNU General Public License Version 3 along with this program. * If not, see http://www.gnu.org/licenses/. * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. * "Sonatype" and "Sonatype Nexus" are trademarks of Sonatype, Inc. */ package org.sonatype.nexus.test.utils; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Map; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.InterpolationFilterReader; /** * Simple File testing utilities. */ public class FileTestingUtils { private static final Logger LOG = Logger.getLogger( FileTestingUtils.class ); private static final int BUFFER_SIZE = 0x1000; private static final String SHA1 = "SHA1"; /** * Creates a SHA1 hash from a file. * * @param file The file to be digested. * @return An SHA1 hash based on the contents of the file. * @throws IOException */ public static String createSHA1FromFile( File file ) throws IOException { FileInputStream fis = null; try { fis = new FileInputStream( file ); return createSHA1FromStream( fis ); } finally { if ( fis != null ) fis.close(); } } /** * Creates a SHA1 hash from a url. * * @param url The URL to opened and digested. * @return An SHA1 hash based on the contents of the URL. * @throws IOException */ public static String createSHA1FromURL( URL url ) throws IOException { InputStream is = url.openStream(); try { return createSHA1FromStream( is ); } finally { if ( is != null ) { is.close(); } } } /** * Creates a SHA1 hash from the contents of a String. * * @param data the String to be digested. * @return An SHA1 hash based on the contents of the String. * @throws IOException */ public static String createSHA1FromString( String data ) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream( data.getBytes() ); return createSHA1FromStream( bais ); } /** * Creates a SHA1 hash from an InputStream. * * @param in Inputstream to be digested. * @returnn SHA1 hash based on the contents of the stream. * @throws IOException */ public static String createSHA1FromStream( InputStream in ) throws IOException { byte[] bytes = new byte[BUFFER_SIZE]; try { MessageDigest digest = MessageDigest.getInstance( SHA1 ); for ( int n; ( n = in.read( bytes ) ) >= 0; ) { if ( n > 0 ) { digest.update( bytes, 0, n ); } } bytes = digest.digest(); StringBuffer sb = new StringBuffer( bytes.length * 2 ); for ( int i = 0; i < bytes.length; i++ ) { int n = bytes[i] & 0xFF; if ( n < 0x10 ) { sb.append( '0' ); } sb.append( Integer.toHexString( n ) ); } return sb.toString(); } catch ( NoSuchAlgorithmException noSuchAlgorithmException ) { throw new IllegalStateException( noSuchAlgorithmException.getMessage(), noSuchAlgorithmException ); } } public static boolean compareFileSHA1s( File file1, File file2 ) throws IOException { if ( file1 != null && file1.exists() && file2 != null && file2.exists() ) { String file1SHA1 = createSHA1FromFile( file1 ); String file2SHA1 = createSHA1FromFile( file2 ); return file1SHA1.equals( file2SHA1 ); } return false; } @SuppressWarnings( "unchecked" ) public static File getTestFile( Class clazz, String filename ) { String resource = clazz.getName().replace( '.', '/' ) + "Resources/" + filename; LOG.debug( "Looking for resource: " + resource ); URL classURL = Thread.currentThread().getContextClassLoader().getResource( resource ); LOG.debug( "found: " + classURL ); return new File( classURL.getFile() ); } public static void main( String[] args ) { String usage = "Usage: java " + FileTestingUtils.class + " <url>"; if ( args == null || args.length != 1 ) { System.out.println( usage ); return; } try { URL url = new URL( args[0] ); System.out.println( createSHA1FromURL( url ) ); } catch ( Exception e ) { System.out.println( usage ); e.printStackTrace( System.out ); } } public static void fileCopy( File from, File dest ) throws IOException { // we may also need to create any parent directories if ( dest.getParentFile() != null && !dest.getParentFile().exists() ) { dest.getParentFile().mkdirs(); } FileReader fileReader = new FileReader( from ); FileWriter fos = new FileWriter( dest ); int readChar = -1; while ( ( readChar = fileReader.read() ) != -1 ) { fos.write( readChar ); } // close everything fileReader.close(); fos.close(); } public static void interpolationFileCopy( File from, File dest, Map<String, String> variables ) throws IOException { // we may also need to create any parent directories if ( dest.getParentFile() != null && !dest.getParentFile().exists() ) { dest.getParentFile().mkdirs(); } FileReader fileReader = new FileReader( from ); InterpolationFilterReader filterReader = new InterpolationFilterReader( fileReader, variables ); FileWriter fos = new FileWriter( dest ); int readChar = -1; while ( ( readChar = filterReader.read() ) != -1 ) { fos.write( readChar ); } // close everything fileReader.close(); fos.close(); } public static void interpolationDirectoryCopy( File from, File dest, Map<String, String> variables ) throws IOException { dest.mkdirs(); DirectoryScanner scan = new DirectoryScanner(); scan.addDefaultExcludes(); scan.setBasedir( from ); scan.scan(); String[] files = scan.getIncludedFiles(); for ( String fileName : files ) { String extension = FilenameUtils.getExtension( fileName ); File sourceFile = new File( from, fileName ); File destFile = new File( dest, fileName ); destFile.getParentFile().mkdirs(); - if ( Arrays.asList( "zip", "jar", "tar.gz" ).contains( extension ) ) + if ( Arrays.asList( "zip", "jar", "tar.gz", "jpg", "png" ).contains( extension ) ) { //just copy know binaries FileUtils.copyFile( sourceFile, destFile ); } else { FileReader reader = null; FileWriter writer = null; try { reader = new FileReader( sourceFile ); InterpolationFilterReader filterReader = new InterpolationFilterReader( reader, variables ); writer = new FileWriter( destFile ); IOUtil.copy( filterReader, writer ); } finally { IOUtil.close( reader ); IOUtil.close( writer ); } } } } }
true
true
public static void interpolationDirectoryCopy( File from, File dest, Map<String, String> variables ) throws IOException { dest.mkdirs(); DirectoryScanner scan = new DirectoryScanner(); scan.addDefaultExcludes(); scan.setBasedir( from ); scan.scan(); String[] files = scan.getIncludedFiles(); for ( String fileName : files ) { String extension = FilenameUtils.getExtension( fileName ); File sourceFile = new File( from, fileName ); File destFile = new File( dest, fileName ); destFile.getParentFile().mkdirs(); if ( Arrays.asList( "zip", "jar", "tar.gz" ).contains( extension ) ) { //just copy know binaries FileUtils.copyFile( sourceFile, destFile ); } else { FileReader reader = null; FileWriter writer = null; try { reader = new FileReader( sourceFile ); InterpolationFilterReader filterReader = new InterpolationFilterReader( reader, variables ); writer = new FileWriter( destFile ); IOUtil.copy( filterReader, writer ); } finally { IOUtil.close( reader ); IOUtil.close( writer ); } } } }
public static void interpolationDirectoryCopy( File from, File dest, Map<String, String> variables ) throws IOException { dest.mkdirs(); DirectoryScanner scan = new DirectoryScanner(); scan.addDefaultExcludes(); scan.setBasedir( from ); scan.scan(); String[] files = scan.getIncludedFiles(); for ( String fileName : files ) { String extension = FilenameUtils.getExtension( fileName ); File sourceFile = new File( from, fileName ); File destFile = new File( dest, fileName ); destFile.getParentFile().mkdirs(); if ( Arrays.asList( "zip", "jar", "tar.gz", "jpg", "png" ).contains( extension ) ) { //just copy know binaries FileUtils.copyFile( sourceFile, destFile ); } else { FileReader reader = null; FileWriter writer = null; try { reader = new FileReader( sourceFile ); InterpolationFilterReader filterReader = new InterpolationFilterReader( reader, variables ); writer = new FileWriter( destFile ); IOUtil.copy( filterReader, writer ); } finally { IOUtil.close( reader ); IOUtil.close( writer ); } } } }
diff --git a/filemgr/src/main/java/org/apache/oodt/cas/filemgr/catalog/LuceneCatalogFactory.java b/filemgr/src/main/java/org/apache/oodt/cas/filemgr/catalog/LuceneCatalogFactory.java index e70d87022..e31600527 100644 --- a/filemgr/src/main/java/org/apache/oodt/cas/filemgr/catalog/LuceneCatalogFactory.java +++ b/filemgr/src/main/java/org/apache/oodt/cas/filemgr/catalog/LuceneCatalogFactory.java @@ -1,101 +1,101 @@ /* * 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.oodt.cas.filemgr.catalog; //OODT imports import org.apache.oodt.cas.filemgr.util.GenericFileManagerObjectFactory; import org.apache.oodt.cas.metadata.util.PathUtils; import org.apache.oodt.cas.filemgr.validation.ValidationLayer; /** * @author mattmann * @version $Revision$ * * <p> * A Factory for creating {@link Lucene}-based {@link Catalog}s. * </p> * */ public class LuceneCatalogFactory implements CatalogFactory { /* path to the index directory for lucene catalogs */ private String indexFilePath = null; /* our validation layer */ private ValidationLayer validationLayer = null; /* the page size for pagination */ private int pageSize = -1; /* the write lock timeout */ private long writeLockTimeOut = -1L; /* the commit lock timeout */ private long commitLockTimeOut = -1L; /* the merge factor */ private int mergeFactor = -1; /** * */ public LuceneCatalogFactory() throws IllegalArgumentException { indexFilePath = System .getProperty("org.apache.oodt.cas.filemgr.catalog.lucene.idxPath"); if (indexFilePath == null) { throw new IllegalArgumentException( "error initializing lucene catalog: " + "[org.apache.oodt.cas.filemgr.catalog.lucene.idxPath=" + indexFilePath); } //do env var replacement indexFilePath = PathUtils.replaceEnvVariables(indexFilePath); String validationLayerFactoryClass = System .getProperty("filemgr.validationLayer.factory", - "org.apache.oodt.cas.validation.DataSourceValidationLayerFactory"); + "org.apache.oodt.cas.filemgr.validation.XMLValidationLayerFactory"); validationLayer = GenericFileManagerObjectFactory .getValidationLayerFromFactory(validationLayerFactoryClass); pageSize = Integer.getInteger("org.apache.oodt.cas.filemgr.catalog.lucene.pageSize", 20).intValue(); commitLockTimeOut = Long .getLong( "org.apache.oodt.cas.filemgr.catalog.lucene.commitLockTimeout.seconds", 60).longValue(); writeLockTimeOut = Long .getLong( "org.apache.oodt.cas.filemgr.catalog.lucene.writeLockTimeout.seconds", 60).longValue(); mergeFactor = Integer.getInteger( "org.apache.oodt.cas.filemgr.catalog.lucene.mergeFactor", 20) .intValue(); } /* * (non-Javadoc) * * @see org.apache.oodt.cas.filemgr.catalog.CatalogFactory#createCatalog() */ public Catalog createCatalog() { return new LuceneCatalog(indexFilePath, validationLayer, pageSize, commitLockTimeOut, writeLockTimeOut, mergeFactor); } }
true
true
public LuceneCatalogFactory() throws IllegalArgumentException { indexFilePath = System .getProperty("org.apache.oodt.cas.filemgr.catalog.lucene.idxPath"); if (indexFilePath == null) { throw new IllegalArgumentException( "error initializing lucene catalog: " + "[org.apache.oodt.cas.filemgr.catalog.lucene.idxPath=" + indexFilePath); } //do env var replacement indexFilePath = PathUtils.replaceEnvVariables(indexFilePath); String validationLayerFactoryClass = System .getProperty("filemgr.validationLayer.factory", "org.apache.oodt.cas.validation.DataSourceValidationLayerFactory"); validationLayer = GenericFileManagerObjectFactory .getValidationLayerFromFactory(validationLayerFactoryClass); pageSize = Integer.getInteger("org.apache.oodt.cas.filemgr.catalog.lucene.pageSize", 20).intValue(); commitLockTimeOut = Long .getLong( "org.apache.oodt.cas.filemgr.catalog.lucene.commitLockTimeout.seconds", 60).longValue(); writeLockTimeOut = Long .getLong( "org.apache.oodt.cas.filemgr.catalog.lucene.writeLockTimeout.seconds", 60).longValue(); mergeFactor = Integer.getInteger( "org.apache.oodt.cas.filemgr.catalog.lucene.mergeFactor", 20) .intValue(); }
public LuceneCatalogFactory() throws IllegalArgumentException { indexFilePath = System .getProperty("org.apache.oodt.cas.filemgr.catalog.lucene.idxPath"); if (indexFilePath == null) { throw new IllegalArgumentException( "error initializing lucene catalog: " + "[org.apache.oodt.cas.filemgr.catalog.lucene.idxPath=" + indexFilePath); } //do env var replacement indexFilePath = PathUtils.replaceEnvVariables(indexFilePath); String validationLayerFactoryClass = System .getProperty("filemgr.validationLayer.factory", "org.apache.oodt.cas.filemgr.validation.XMLValidationLayerFactory"); validationLayer = GenericFileManagerObjectFactory .getValidationLayerFromFactory(validationLayerFactoryClass); pageSize = Integer.getInteger("org.apache.oodt.cas.filemgr.catalog.lucene.pageSize", 20).intValue(); commitLockTimeOut = Long .getLong( "org.apache.oodt.cas.filemgr.catalog.lucene.commitLockTimeout.seconds", 60).longValue(); writeLockTimeOut = Long .getLong( "org.apache.oodt.cas.filemgr.catalog.lucene.writeLockTimeout.seconds", 60).longValue(); mergeFactor = Integer.getInteger( "org.apache.oodt.cas.filemgr.catalog.lucene.mergeFactor", 20) .intValue(); }
diff --git a/Tarsus/src/java/GameInstance.java b/Tarsus/src/java/GameInstance.java index 3ca3037..9b24005 100644 --- a/Tarsus/src/java/GameInstance.java +++ b/Tarsus/src/java/GameInstance.java @@ -1,2639 +1,2641 @@ /******************************************************* * Class for game instances, will be associated with * sessions through being the session data. *******************************************************/ import database.DBConnections; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.sql.*; import java.util.ArrayList; //Pulled from inclass exmple import database.*; import java.util.logging.Level; import java.util.logging.Logger; public class GameInstance { PlayerCharacter playerChar; AresCharacter aresChar; stateEnum currentState, startingState; String accountName; DBConnections dataSource = null; Connection conn = null; Statement stat = null; final int STORE_SIZE = 20; int gold; String error; int storeLevel; Item[] storeItems; String item_type_string[] = {"Error", "Weapon", "Armor", "Item"}; int constantPtsPerLevel = 5; int constantWeaponPtsPerLevel = 3; int constantArmorPtsPerLevel = 5; int constantGoldPerLevel = 20; int constantHealthPerLevel = 15; int constantStrengthPerLevel = 10; int constantAgilityPerLevel = 10; int constantMagicPerLevel = 10; int constantHealthBase = 200; int constantItemNameMaxLength = 20; GameInstance() { playerChar = null; aresChar = null; currentState = stateEnum.INIT; accountName = "Unregistered User"; gold = 0; error = null; int storeLevel = 0; Item[] storeItems = new Item[STORE_SIZE]; } /**************************************************** * Connect to the database using class variables * SQL Commands ***************************************************/ void connectDB(){ dataSource = DBConnections.getInstance(); conn = dataSource.getConnection(); } /**************************************************** * Disconnect from the database using class variables * SQL Commands ***************************************************/ void disconnectDB(){ DBUtilities.closeStatement(stat); dataSource.freeConnection(conn); } /**************************************************** * Returns the result set result of your query * @param query the SQL query you want to execute * @param out the printwriter ***************************************************/ ResultSet sqlQuery(String query, PrintWriter out){ ResultSet result = null; try{ stat = conn.createStatement(); result = stat.executeQuery(query); }catch(Exception ex){ out.println("Query error:"); out.println(ex); }finally{ return result; } } /**************************************************** * Returns true if your SQL command succeeded, * returns false if it does not * @param command the SQL command you want to execute * @param out the printwriter ***************************************************/ Boolean sqlCommand(String command, PrintWriter out){ Boolean result = false; try{ stat = conn.createStatement(); stat.execute(command); result = true; }catch(Exception ex){ out.println("sqlCommand Exception: "); out.println(ex); }finally{ return result; } } /**************************************************** * state machine case switch function, called from * the servlet. * @param out output PrintWriter * @param request the servlet request ***************************************************/ void advanceGame(PrintWriter out, HttpServletRequest request) { stateEnum nextState = currentState; startingState = currentState; do { currentState = nextState; switch(currentState) { case INIT: //first connection nextState = initState(out, request); break; case BATTLE: //battle function nextState = battleState(out, request); break; case STORE: //store function nextState = storeState(out, request); break; case REGISTERED_CHARACTER_CREATION: //character creation nextState = registeredCharacterCreationState(out, request); break; case UNREGISTERED_CHARACTER_CREATION: //character creation nextState = unregisteredCharacterCreationState(out, request); break; case DECISION: //this state is for asking what to do next nextState = decisionState(out, request); break; case BLACKSMITH: //upgrade items nextState = blackSmithState(out, request); break; case LOGIN: //login nextState = loginState(out, request); break; case ACCOUNT_CREATION: //account creation try{ nextState = accountCreation(out, request);} catch(SQLException ex) { out.println("What the "); out.println(ex); } break; case LEVEL_UP: nextState = levelUpState(out, request); break; case PROFILE: //profile try{ nextState = profileState(out, request);} catch(SQLException ex) { out.println("What the "); out.println(ex); } break; case PAST_CHARACTERS: //Look at Past Characters nextState = pastCharactersState(out, request); break; case LOGOUT: //Log Out nextState = LogoutState(out, request); break; default: //this should go to a specified state nextState = stateEnum.INIT; initState(out, request); break; } }while((currentState != nextState)|(error!=null)); } /**************************************************** * Generates an inventory for the store based on the * player character's level * @param level the level of the player character * @return an array of new items for the store ***************************************************/ Item[] getStoreInventory(int level, int size) { final int STORE_LEVEL = level; final int STORE_SIZE = size; Item[] storeItems = new Item[STORE_SIZE]; for(int i = 0; i < STORE_SIZE; i++) { //general type index that decides one of the three // item types. // not including error int gi = (int)(Math.round(Math.random() * (2)) + 1); storeItems[i] = generateItem(gi, STORE_LEVEL); } return storeItems; } Item generateItem(int type, int Level) { final String[] armor_name_type = {"Plate Armor", "Leather Armor", "Robe", "Mail Armor", "Magic Strength armor", "Magic Agility armor", "Armor"}; final String[] weapon_name_type = {"Sword", "Axe", "Mace", "Bow", "Crossbow", "Throwing Knives", "Staff", "Wand", "Orb"}; // Could have room for permutations final String[] item_name_type = {"Potion"}; final String[] error_name_type = {"Error"}; final String[] item_name_quality_description = {"Broken", "Inferior", "Common", "Slightly Better", "Ancient", "Legendary", "Actually Broken"}; final String[][] general_item_type = {error_name_type, weapon_name_type, armor_name_type, item_name_type}; //final String[] item_name_Modifier_description = ["Warrior", "Hunter", "Wizard", "Bandit", "BattleMage", "Magic-Range Thing whatever", "Balance"] // permutation for each thing double base_stats[] = {0, 0, 0, 0}; //general type index int gi = type; //System.out.println(gi); // special type index int si = (int)(Math.round(Math.random() * (general_item_type[gi].length - 1))); //System.out.println(si); // armor case if(gi == 2) { switch (si) { case 0: base_stats[0] = 1; base_stats[1] = 0; base_stats[2] = 0; break; case 1: base_stats[0] = 0; base_stats[1] = 1; base_stats[2] = 0; break; case 2: base_stats[0] = 0; base_stats[1] = 0; base_stats[2] = 1; break; case 3: base_stats[0] = .5; base_stats[1] = .5; base_stats[2] = 0; break; case 4: base_stats[0] = .5; base_stats[1] = 0; base_stats[2] = .5; break; case 5: base_stats[0] = 0; base_stats[1] = .5; base_stats[2] = .5; break; case 6: base_stats[0] = 0.3333; base_stats[1] = 0.3333; base_stats[2] = 0.3333; break; } } // weapon case else if(gi == 1) { if((si % 9) < 3) { base_stats[0] = 1; } else if((si % 9) < 6) { base_stats[1] = 1; } else if((si % 9) < 9) { base_stats[2] = 1; } } // item case else if(gi == 3) { switch(si) { // potions have an abitrary larger base value thing case 0: base_stats[3] = 2; break; } } // Higher levels will have a more balance distribution of items // e.g. Cannot possibly find a legendary item until at least level 9 double quality = getQuality(Level); int index = (int) Math.round(quality * ((item_name_quality_description.length) - 1)); String item_quality = item_name_quality_description[index]; String item_type = general_item_type[gi][si]; // Get the base damage of each stat // will only affect one stat at the moment //int value_sum = 0; for(int j = 0; j < 4; j++) { // multiples the base stat for cases where the base stat is split up in proportions base_stats[j] *=(((quality) * 100) + 20); base_stats[j] = Math.round(base_stats[j]); //value_sum += base_stats[j]; } String item_name = item_quality + " " + item_type; Item item = new Item(item_name, 0, gi, 0, (int)base_stats[0], (int)base_stats[1],(int)base_stats[2], (int)base_stats[3]); return item; } /**************************************************** * Generates an armor item based on the player * character's level * @param level the level of the player character * @return an item with a type of armor ***************************************************/ Item generateArmor(int level) { return generateItem(2, level); } /**************************************************** * Generates a weapon item based on the player * character's level * @param level the level of the player character * @return an item with a type of weapon ***************************************************/ Item generateWeapon(int level) { return generateItem(1,level); } /**************************************************** * Loads a new enemy from the database * @param level the players level ***************************************************/ void getNextEnemy(Integer Level, PrintWriter out) throws SQLException { String search1 = "SELECT * FROM Characters WHERE level='"+Level.toString() + "' AND isDead=b'1';"; connectDB(); String maxCount = "SELECT COUNT(*) AS rows FROM Characters WHERE level='1' AND isDead=b'1';"; ResultSet resultMax = sqlQuery(maxCount, out); resultMax.next(); int max = resultMax.getInt("rows"); disconnectDB(); connectDB(); ResultSet result = sqlQuery(search1, out); int number = (int) (Math.random()*max) +1; if(result.isBeforeFirst()) { for(int i=0;i<number;i++) { result.next(); } //result.next(); String name = result.getString("name"); String bio = result.getString("bio"); int level = result.getInt("level"); int health = result.getInt("health"); int strength = result.getInt("strength"); int agility = result.getInt("agility"); int magic = result.getInt("magic"); int timesAttacked = result.getInt("timesAttacked"); int timesSwitchedToStrength = result.getInt("timesSwitchedToStrength"); int timesSwitchedToAgility = result.getInt("timesSwitchedToAgility"); int timesSwitchedToMagic = result.getInt("timesSwitchedToMagic"); int equipWeaponId = result.getInt("equippedWeapon"); int equipArmorId = result.getInt("equippedArmor"); disconnectDB(); //getting the length for itemsHeld connectDB(); String search2 = "SELECT COUNT(I.itemId) AS rows FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + name + "';"; result = sqlQuery(search2, out); result.next(); int rows = result.getInt("rows"); disconnectDB(); Item[] itemsHeld = new Item[rows]; Item weapon = null; Item armor = null; String search3 = "SELECT * FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + name + "';"; connectDB(); result = sqlQuery(search3, out); //temp varible int i = 0; while (result.next()) { String iName = result.getString("name"); int itemId = result.getInt("itemId"); int type = result.getInt("type"); int upgradeCount = result.getInt("upgradeCount"); int strengthVal= result.getInt("strengthVal"); int agilityVal = result.getInt("agilityVal"); int magicVal = result.getInt("magicVal"); Item item = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0); itemsHeld[i] = item; if (equipWeaponId == itemId) { weapon = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0); } if (equipArmorId == itemId) { armor = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0); } i++; } disconnectDB(); aresChar = new AresCharacter(name, bio, level, health, strength, agility, magic, itemsHeld, weapon, armor, timesAttacked, timesSwitchedToStrength, timesSwitchedToAgility, timesSwitchedToMagic); } else { Item[] itemsHeld = {generateWeapon(Level +1), generateArmor(Level+1)}; int aresHealth = constantHealthBase+(Level+1)*constantPtsPerLevel*constantHealthPerLevel; int aresStrength = (Level+1)*constantPtsPerLevel*constantStrengthPerLevel; int aresAgility = (Level+1)*constantPtsPerLevel*constantAgilityPerLevel; int aresMagic = (Level+1)*constantPtsPerLevel*constantMagicPerLevel; aresChar = new AresCharacter("Ares", "", Level, aresHealth, aresStrength, aresAgility, aresMagic, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0); } } /**************************************************** * Loads the players current character from the * database ***************************************************/ void getCurrentCharacter() { } /**************************************************** * Adds a newly created character to the database * @param chrct character object to add to the database * @param isDead Boolean, whether or not the character is dead * @param out PrintWriter for the page * @return did it work ***************************************************/ Boolean newCharacter(Character chrct, Boolean isDead, PrintWriter out) { Integer dead=0; if(isDead) dead=1; connectDB(); String query = "INSERT into Characters (name, level, bio, creator, strength, health, isDead, magic, agility, timesAttacked, timesSwitchedToStrength, timesSwitchedToAgility, timesSwitchedToMagic, equippedWeapon, equippedArmor) VALUES ('"+chrct.getName()+"', '"+(((Integer)chrct.getLevel()).toString())+"', '"+chrct.getBio()+"', '"+accountName+"', '"+((Integer)(chrct.getStrength())).toString()+"', '"+((Integer)chrct.getMaxHealth()).toString()+"', b'"+dead.toString()+"', '"+((Integer)chrct.getMagic()).toString()+"', '"+((Integer)chrct.getAgility()).toString()+"', '"+((Integer)chrct.timesAttacked).toString()+"', '"+((Integer)chrct.timesSwitchedToStrength).toString()+"', '"+((Integer)chrct.timesSwitchedToAgility).toString()+"', '"+((Integer)chrct.timesSwitchedToMagic).toString()+"', '"+((Integer)chrct.weapon.getItemId()).toString()+"', '"+((Integer)chrct.armor.getItemId()).toString()+"');"; return sqlCommand(query,out); } /**************************************************** * update created character to the database * @param chrct character object to update in the database * @param isDead Boolean, whether or not the character is dead * @param out PrintWriter for the page * @return did it work ***************************************************/ Boolean updateCharacter(Character chrct, Boolean isDead, PrintWriter out) { Integer dead=0; if(isDead) dead=1; connectDB(); String query = "UPDATE Characters SET level='"+(((Integer)chrct.getLevel()).toString())+"', bio='"+chrct.getBio()+"', strength='"+((Integer)(chrct.getStrength())).toString()+"', health='"+((Integer)chrct.getMaxHealth()).toString()+"', isDead=b'"+(dead.toString())+"', magic='"+((Integer)chrct.getMagic()).toString()+"', agility='"+((Integer)chrct.getAgility()).toString()+"', timesAttacked='"+((Integer)chrct.timesAttacked).toString()+"', timesSwitchedToStrength='"+((Integer)chrct.timesSwitchedToStrength).toString()+"', timesSwitchedToAgility='"+((Integer)chrct.timesSwitchedToAgility).toString()+"', timesSwitchedToMagic='"+((Integer)chrct.timesSwitchedToMagic).toString()+"', equippedWeapon='"+((Integer)chrct.weapon.getItemId()).toString()+"', equippedArmor='"+((Integer)chrct.armor.getItemId()).toString()+"' WHERE name='"+chrct.getName()+"';"; return sqlCommand(query,out); } /**************************************************** * Adds new item to the database * @param item item object to add to the database * @param out PrintWriter for the page * @return did it work ***************************************************/ Boolean newItem(Item item, PrintWriter out) throws SQLException { if(item.getItemId()==0) item.itemId=nextItemId(out); connectDB(); String query = "Insert into Items (itemId, name, type, strengthVal, healthVal, upgradeCount, magicVal, agilityVal) VALUES ('"+((Integer)item.getItemId()).toString()+"', '"+item.getName()+"', '"+((Integer)item.getType()).toString()+"', '"+((Integer)item.getStrength()).toString()+"', '"+((Integer)item.getHeal()).toString()+"', '"+((Integer)item.getUpgradeCount()).toString()+"', '"+((Integer)item.getMagic()).toString()+"', '"+((Integer)item.getAgility()).toString()+"');"; return sqlCommand(query,out); } Boolean deleteCharacterHasItem(Item item, PrintWriter out) throws SQLException { //String query = "DELETE FROM CharacterHasItem WHERE itemID="; String query = "DELETE FROM CharacterHasItem WHERE itemId="; query += "" + item.getItemId() + ""; query += ";"; return sqlCommand(query, out); } Boolean deleteItem(Item item, PrintWriter out) throws SQLException { deleteCharacterHasItem(item, out); String query = "DELETE FROM Items WHERE itemId="; query += "" + item.getItemId() + ""; query += ";"; return sqlCommand(query, out); } int nextItemId(PrintWriter out) throws SQLException { String query="SELECT * FROM Items;"; int max = 0; connectDB(); ResultSet result = sqlQuery(query, out); while(result.next()){ if(result.getInt("itemId")>max) max=result.getInt("itemId"); } disconnectDB(); return max+1; } Boolean characterHasItem(Item item, Character character,PrintWriter out) { String query = "INSERT into CharacterHasItem (itemId, charName) VALUES ('"+item.getItemId()+"','"+character.getName()+"');"; return sqlCommand(query, out); } /**************************************************** * The initial state * @param out the print writer * @param request the servlet request * @return the next state ***************************************************/ stateEnum initState(PrintWriter out, HttpServletRequest request) { //can log in or unregistered user creation if(startingState != stateEnum.INIT) { //print the page out.println("<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <body>\n" + " <form action=\"Tarsus\" method=\"post\">\n" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + " <input href=\"index.html\" id=\"tarsusTitle\" /> \n" + " <input class=\"button\" type=\"submit\" value=\"Log In\" name=\"Log In\" /> </div>\n" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <h1 id=\"title\" class=\"centered\">Welcome</h1>\n" + " <p align=\"justify\"> \n" + " Tarsus is a web based Role Playing Game that allows you to create your own character and use it to fight progressively more difficult enemies as you try to make your way to the top. If you already have an account, click the Log In button above. If not, you can make a character using our character maker or your can sign up and start your own adventure.\n" + " </p>\n" + " <div align=\"center\">\n" + " <input type=\"submit\" value=\"Create a Character\" name=\"Create a Character\" class=frontPageButton />\n" + " <input type=\"submit\" value=\"Sign Up\" name=\"Sign Up\" class=frontPageButton />\n" + " </div>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " </form>\n" + " </body>\n" + " \n" + "</html>"); return stateEnum.INIT; } else { String value1 = request.getParameter("Sign Up"); String value2 = request.getParameter("Log In"); String value3 = request.getParameter("Create a Character"); String value = ""; if(value1 != null) value = value1; if(value2!=null) value = value2; if(value3!=null) value = value3; if(value.equals("Log In")) return stateEnum.LOGIN; if(value.equals("Create a Character")) return stateEnum.UNREGISTERED_CHARACTER_CREATION; if(value.equals("Sign Up")) return stateEnum.ACCOUNT_CREATION; } return stateEnum.INIT; } /**************************************************** * The initial state * @param out the print writer * @param request the servlet request * @return the next state ***************************************************/ private stateEnum storeState(PrintWriter out, HttpServletRequest request) { // have store level as well as the items be static so that it is the same each time the player comes back to the // store unless the player has increased in level // if level has changed create a new item inventory for the store // based on some hash function of the character's level if(playerChar.getLevel() != storeLevel) { storeLevel = playerChar.getLevel(); storeItems = getStoreInventory(storeLevel, STORE_SIZE); } if(startingState != stateEnum.STORE) { printStoreState(out); return stateEnum.STORE; } else{ String value1 = request.getParameter(accountName); String value2 = request.getParameter("Log Out"); if(value1 != null) { //out.println("going to Decision state"); return stateEnum.DECISION; } else if(value2 != null) { return stateEnum.LOGOUT; } else { //out.print("I think you pressed a button"); //out.print(" Currency: " + gold + " "); if(request.getParameter(accountName) != null) return stateEnum.DECISION; // for buying items from the store for (int i = 0; i < storeItems.length; i++) { //out.println("going through buy item: " + i); String buyValue = request.getParameter("Buy " + i); //out.println(buyValue); if(buyValue != null) { //out.println("You chose index: " + i + " /n"); gold -= storeItems[i].getValue(); // could also just move the last index to this index try{ connectDB(); newItem(storeItems[i], out); characterHasItem(storeItems[i], playerChar, out); disconnectDB(); storeItems[i] = null; getItems(out); } catch(Exception e) { error = "An error occured while trying to buy the item."; } //printStoreState(out); break; } } // for selling items player's inventory for (int i = 0; i < playerChar.itemsHeld.length; i++){ //out.println("going through sell item: " + i); String sellValue = request.getParameter("Sell " + i); if(sellValue != null) { gold += Math.round((.6) * playerChar.itemsHeld[i].getValue()); // need to drop the item from the table try{ connectDB(); deleteItem(playerChar.itemsHeld[i], out); disconnectDB(); getItems(out); } catch(Exception e) { error = "failed to delete item from player's inventory."; } break; //printStoreState(out); } } printStoreState(out); return stateEnum.STORE; } } } /**************************************************** * The initial state * @param out the print writer * @param request the servlet request * @return the next state ***************************************************/ private stateEnum battleState(PrintWriter out, HttpServletRequest request) { if(startingState != stateEnum.BATTLE) { try { //Item[] itemsHeld = {generateWeapon(1), generateArmor(1), generateWeapon(1), generateArmor(1)}; //playerChar = new PlayerCharacter("player", "", 1, 1000, 1, 2, 3, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0); //aresChar = new AresCharacter("enemy", "", 1, 100, 1, 2, 3, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0); getNextEnemy(playerChar.getLevel(), out); } catch (SQLException ex) { Logger.getLogger(GameInstance.class.getName()).log(Level.SEVERE, null, ex); } } String startPage = "<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + -" <link rel=\"stylesheet\" href=\"../css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + +" <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <body>\n" + -" <div id=\"header\" class=\"grid10\" align=\"right\">\n" + +" <div id=\"header\" class=\"grid10\" align=\"center\">\n" + " %s \n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <br />\n" + " <p align=\"center\">\n" + " </p>\n" + " <div class=\"gridHalf\"> \n"; String statsTable = " <h2 align=\"center\"> %s </h2>\n" + " \n" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <th> Health </th>\n" + " <th> Strength </th>\n" + " <th> Magic </th>\n" + " <th> Agility </th>\n" + " </tr>\n" + " <tr>\n" + " <th> %d </th>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " </tr>\n" + " </table>\n"; String equippedTable1 = " \n" + " <h3 align=\"center\"> Equipped </h3>\n" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <td> </td>\n" + " <th> Name </th>\n" + " <th> Strength </th>\n" + " <th> Magic </th>\n" + " <th> Agility </th>\n" + " </tr>\n" + " <tr>\n" + " <th> Weapon: </th>\n" + " <td> %s </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " </tr>\n"; String equippedTable2 = " <tr>\n" + " <th> Armor: </th>\n" + " <td> %s </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " </tr>\n" + " </table>\n"; String betweenCharacters = " </div>\n" + " <div class=\"gridHalf\"> \n"; String afterTable = " \n" + " </div>\n" + -" <form action=\"Tarsus\" method = \"post\">"; +" <div class=\"grid10\">\n" + +" <div align=\"center\">\n" + + " <form action=\"Tarsus\" method = \"post\">"; String attackButton = -" <input type = \"submit\" class=\"profileButton\" name = \"attack\" value = \"Attack\" /> \n" + +" <input type = \"submit\" class=\"profileButton\" name = \"attack\" value = \"Attack\" /> <br /> \n" + " <select name = \"itemSelected\"> \n"; String useButton = " </select>" + " <input type = \"submit\" class=\"profileButton\" name=\"use\" value = \"Use item\" /> \n"; String lastPart = " </form>" + -" <div class=\"grid1\"> </div>\n" + +" <div class=\"grid1\"> </div> </div>\n" + " </body>\n" + " \n" + "</html>"; int aresDamage = 0, playerDamage = 0; if(startingState == stateEnum.BATTLE) { String value = null, valueAttack=request.getParameter("attack"), valueUse=request.getParameter("use"), valueOK=request.getParameter("OK"), itemName; if(valueAttack!=null) value = valueAttack; if(valueUse!=null) { value=valueUse; itemName = request.getParameter("itemSelected"); } if(valueOK!=null) value=valueOK; if(!value.equals("OK")) { actionEnum playerAction = playerChar.requestAction(request); actionEnum aresAction = aresChar.requestAction(request); if(playerAction == actionEnum.ATTACK) { if(playerChar.weapon.getStrength()!=0) { aresDamage = (int) ((playerChar.getStrength()+playerChar.weapon.getStrength())*(Math.random()*.4+.8)-(aresChar.getStrength()*aresChar.armor.getStrength()/100)); } if(playerChar.weapon.getAgility()!=0) { aresDamage = (int) ((playerChar.getAgility()+playerChar.weapon.getAgility())*(Math.random()*.4+.8)-(aresChar.getAgility()*aresChar.armor.getAgility()/100)); } if(playerChar.weapon.getMagic()!=0) { aresDamage = (int) ((playerChar.getMagic()+playerChar.weapon.getMagic())*(Math.random()*.4+.8)-(aresChar.getMagic()*aresChar.armor.getMagic()/100)); } } if(aresAction == actionEnum.ATTACK) { if(aresChar.weapon.getStrength()!=0) { playerDamage = (int) ((aresChar.getStrength()+aresChar.weapon.getStrength())*(Math.random()*.4+.8)-(playerChar.getStrength()*playerChar.armor.getStrength()/100)); } if(aresChar.weapon.getMagic()!=0) { playerDamage = (int) ((aresChar.getMagic()+aresChar.weapon.getMagic())*(Math.random()*.4+.8)-(playerChar.getMagic()*playerChar.armor.getMagic()/100)); } if(aresChar.weapon.getAgility()!=0) { playerDamage = (int) ((aresChar.getAgility()+aresChar.weapon.getAgility())*(Math.random()*.4+.8)-(playerChar.getAgility()*playerChar.armor.getAgility()/100)); } } playerChar.setHealth(playerChar.getHealth() - playerDamage); aresChar.setHealth(aresChar.getHealth() - aresDamage); } else if(playerChar.getHealth()<1) { //mark the character as dead in the database updateCharacter(playerChar, true, out); return stateEnum.PROFILE; } else if(aresChar.getHealth()<1) return stateEnum.LEVEL_UP; } out.printf(startPage,accountName); out.printf(statsTable, playerChar.name, playerChar.getHealth(), playerChar.getStrength(), playerChar.getMagic(), playerChar.getAgility()); out.printf(equippedTable1, playerChar.weapon.getName(), playerChar.weapon.getStrength(), playerChar.weapon.getMagic(), playerChar.weapon.getAgility()); out.printf(equippedTable2, playerChar.armor.getName(), playerChar.armor.getStrength(), playerChar.armor.getMagic(), playerChar.armor.getAgility()); out.printf(betweenCharacters); out.printf(statsTable, aresChar.name, aresChar.getHealth(), aresChar.getStrength(), aresChar.getMagic(), aresChar.getAgility()); out.printf(equippedTable1, aresChar.weapon.getName(),aresChar.weapon.getStrength(), aresChar.weapon.getMagic(), aresChar.weapon.getAgility()); out.printf(equippedTable2, aresChar.armor.getName(), aresChar.armor.getStrength(), aresChar.armor.getMagic(), aresChar.armor.getAgility()); out.printf(afterTable); out.printf("<div>You have done %d damage to your opponent.\n Your opponent has done %d damage to you.</div>", aresDamage, playerDamage); if((playerChar.getHealth()>0) && (aresChar.getHealth()>0)) { out.printf(attackButton); for(int i=0; i < playerChar.itemsHeld.length;i++) { //change first string, the value parameter, to itemId out.printf("<option value = \"%s\"> %s </option> \n", playerChar.itemsHeld[i].getName(),playerChar.itemsHeld[i].getName()); } out.printf(useButton); } else if(playerChar.getHealth()<1) { - out.printf("The valiant hero has been killed.\n"); + out.printf("The valiant hero has been killed. <br />\n"); out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n"); } else if(aresChar.getHealth()<1) { int newGold = (int) (constantGoldPerLevel*playerChar.getLevel()*(Math.random()*.4+.8)); gold+=newGold; updateGold(out); playerChar.setHealth(playerChar.getMaxHealth()); out.printf("Congradulations you beat your enemy.\n You get %d gold.\n", newGold); out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n"); } out.printf(lastPart); return stateEnum.BATTLE; } /**************************************************** * Create a registered user character * @param out the print writer * @param request the servlet request * @return the next state ***************************************************/ stateEnum registeredCharacterCreationState(PrintWriter out, HttpServletRequest request) { if((startingState != stateEnum.REGISTERED_CHARACTER_CREATION)|(error!=null)) { //create new page for it Integer level = 1; printRegCharacterCreation(level, out); error = null; return stateEnum.REGISTERED_CHARACTER_CREATION; } else { String value1 = request.getParameter(accountName); String value2 = request.getParameter("Log Out"); String value = ""; if(value1 != null) value = value1; if(value2 != null) value = value2; if(value.equals(accountName)) return stateEnum.PROFILE; if(value.equals("Log Out")) return stateEnum.LOGOUT; } return stateEnum.PROFILE; } /**************************************************** * Create an unregistered user character * @param out the print writer * @param request the servlet request * @return the next state ***************************************************/ stateEnum unregisteredCharacterCreationState(PrintWriter out, HttpServletRequest request) { if((startingState != stateEnum.UNREGISTERED_CHARACTER_CREATION)|(error!=null)) { //create new page for it Integer level = (int)(Math.random()*49+1); printCharacterCreation(level, out); error = null; return stateEnum.UNREGISTERED_CHARACTER_CREATION; } else { /*String value = request.getParameter("Home"); if(value.equals("Home")) return stateEnum.INIT;*/ try { if(checkHome(request)) { return stateEnum.INIT; } } catch(Exception e) { return charCreationParameters(out, request, true); } return charCreationParameters(out, request, true); } } /**************************************************** * Asking what the player wants to do next * @param out the print writer * @param request the servlet request * @return the next state ***************************************************/ stateEnum decisionState(PrintWriter out, HttpServletRequest request) { if (startingState != stateEnum.DECISION) { out.println("<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <body>\n" + " <form action=\"Tarsus\" method=\"POST\">\n" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + " <input name=\"" + accountName + "\" value=\"" + accountName + "\" type=\"submit\" id=\"tarsusTitle\" /> \n" + " <input class=\"button\" name=\"Log Out\" value=\"Log Out\" type=\"submit\" /> </div>\n" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <h1 id=\"title\" class=\"centered\">" + playerChar.getName() + "</h1>\n" + " <h2 id=\"title\" class=\"GoldDisplay\"> Gold: " + gold + "</h2>" + " <p align=\"center\">\n" + " <input name=\"To Battle!\" value=\"To Battle!\" type=\"submit\" class=\"profileButton\" />\n" + " <input name=\"Store\" value=\"Store\" type=\"submit\" class=\"profileButton\" />\n" + " <input name=\"Blacksmith\" value=\"Blacksmith\" type=\"submit\" class=\"profileButton\" />\n" + " </p>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " </form>\n"); /*+ " </body>\n" + "</html>");*/ printInventory(out); out.println(" </body>\n" + "</html>"); return stateEnum.DECISION; } else { String value1 = request.getParameter(accountName); String value2 = request.getParameter("Log Out"); String value3 = request.getParameter("To Battle!"); String value4 = request.getParameter("Store"); String value5 = request.getParameter("Blacksmith"); String value = ""; if(value1 != null) value = value1; if(value2 != null) value = value2; if(value3 != null) value = value3; if(value4 != null) value = value4; if(value5 != null) value = value5; if(value.equals(accountName)) return stateEnum.PROFILE; if(value.equals("Log Out")) return stateEnum.LOGOUT; if(value.equals("To Battle!")) return stateEnum.BATTLE; if(value.equals("Store")) return stateEnum.STORE; if(value.equals("Blacksmith")) return stateEnum.BLACKSMITH; } return stateEnum.PROFILE; } /**************************************************** * At the blacksmith and can upgrade items * @param out the print writer * @param request the servlet request * @return the next state ***************************************************/ stateEnum blackSmithState(PrintWriter out, HttpServletRequest request) { if(startingState != stateEnum.BLACKSMITH) { printBlacksmithState(out); return stateEnum.BLACKSMITH; } else { String value1 = request.getParameter(accountName); String value2 = request.getParameter("Log Out"); if(value1 != null) return stateEnum.DECISION; else if(value2 != null) return stateEnum.LOGOUT; else { for (int i = 0; i < playerChar.itemsHeld.length; i++){ String tempValue = request.getParameter("Upgrade" + i); if(tempValue != null) { if(gold < playerChar.itemsHeld[i].CONSTANT_upgradeGold) { out.println("You do not have enought gold."); return stateEnum.BLACKSMITH; } playerChar.itemsHeld[i].upgradeItem(); String query = "UPDATE Items SET upgradeCount=upgradeCount+1, "; if(playerChar.itemsHeld[i].getType() == 1) { if(playerChar.itemsHeld[i].getStrength() > 0) { query = query + "strengthVal=strengthVal+'" + playerChar.itemsHeld[i].CONSTANT_weaponUpgrade; } if(playerChar.itemsHeld[i].getAgility() > 0) { query = query + "agilityVal=agilityVal+'" + playerChar.itemsHeld[i].CONSTANT_weaponUpgrade; } if(playerChar.itemsHeld[i].getMagic() > 0) { query = query + "magicVal=magicVal+'" + playerChar.itemsHeld[i].CONSTANT_weaponUpgrade; } } else //playerChar.itemsHeld[i].getType() == 2 { query = query + "strengthVal=strengthVal+'" + playerChar.itemsHeld[i].CONSTANT_armorUpgrade + "', agilityVal=agilityVal+'" + playerChar.itemsHeld[i].CONSTANT_armorUpgrade + "', magicVal=magicVal+'" + playerChar.itemsHeld[i].CONSTANT_armorUpgrade; } query = query + "' WHERE itemId='" + playerChar.itemsHeld[i].getItemId() + "';"; connectDB(); sqlCommand(query, out); disconnectDB(); printBlacksmithState(out); break; } } return stateEnum.BLACKSMITH; } } } /**************************************************** * Registered user login state * @param out the print writer * @param request the servlet request * @return the next state ***************************************************/ stateEnum loginState(PrintWriter out, HttpServletRequest request) { if(startingState != stateEnum.LOGIN){ out.println("<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <div id=\"header\" class=\"grid10\" align=\"right\"> \n" + " <form method=\"post\" action=\"Tarsus\"> \n" + " <input type=\"submit\" name=\"home\" value=\"TARSUS\" id=\"tarsusTitle\"> \n" + " </form> </div>" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <h1 id=\"title\" class=\"centered\"> Log In</h1>\n" + " <form method=\"post\" action=\"Tarsus\"> \n" + " <p align=\"center\"> \n" + " Username: <input name=\"username\" type=\"text\" /> \n" + " </p>\n" + " <p align=\"center\"> \n" + " Password: <input name=\"password\" type=\"password\" /> \n" + " </p>\n" + " <p align=\"center\"> \n" + " <input class=\"signUpButton\" value=\"Log In\" type=\"submit\"/>\n" + " </p>\n" + " </form>\n" + " </div>\n" + "</html>"); }else{ String value1 = request.getParameter("home"); String value = ""; if(value1 != null) value = value1; if(value.equals("TARSUS")) return stateEnum.INIT; String username = request.getParameter("username"); int password = request.getParameter("password").hashCode(); if(!isValidString(username)){ out.println("Error"); return stateEnum.LOGIN; } String search = "SELECT * FROM Login WHERE username='" + username + "' AND password= MD5('" + password+ "');"; connectDB(); ResultSet result = sqlQuery(search, out); try{ if(result.isBeforeFirst()){ result.next(); accountName = username; gold = result.getInt("gold"); return stateEnum.PROFILE; }else{ out.println("<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <div id=\"header\" class=\"grid10\" align=\"right\"> \n" + " <a href=\"index.jsp\" id=\"tarsusTitle\"> TARSUS </a> </div>\n" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <h1 id=\"title\" class=\"centered\"> Log In</h1>\n" + " <h3>Invalid Login </h3> \n " + " <form method=\"post\" action=\"Tarsus\"> \n " + " <p align=\"center\"> \n" + " Username: <input name=\"username\" type=\"text\" /> \n" + " </p>\n" + " <p align=\"center\"> \n" + " Password: <input name=\"password\" type=\"password\" /> \n" + " </p>\n" + " <p align=\"center\"> \n" + " <input class=\"signUpButton\" value=\"Log In\" type=\"submit\"/>\n" + " </p>\n" + " </form>\n" + " </div>\n" + "</html>"); return stateEnum.LOGIN; } }catch(Exception ex){ out.println("Login SQL Error: " + ex); } } return stateEnum.LOGIN; } /**************************************************** * Registered user creation state * @param out the print writer * @param request the servlet request * @return the next state ***************************************************/ stateEnum accountCreation(PrintWriter out, HttpServletRequest request) throws SQLException { String accountPageBegin = "<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <div id=\"header\" class=\"grid10\" align=\"right\"> \n" + " <form method=\"post\" action=\"Tarsus\"> \n" + " <input type=\"submit\" name=\"home\" value=\"TARSUS\" id=\"tarsusTitle\"> \n" + " <input type=\"submit\" name=\"login\" value=\"Log In\" class=\"button\" href=\"login.html\"> \n" + " </form> </div>" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <h1 id=\"title\" class=\"centered\"> Sign Up Below</h1>\n"; String accountPageEnd = " <form method=\"post\" action=\"Tarsus\"> \n" + " <p align=\"center\"> \n" + " Username: <input name=\"username\" type=\"text\" /> \n" + " </p>\n" + " <p align=\"center\"> \n" + " Password: <input name=\"password\" type=\"password\" /> \n" + " </p>\n" + " <p align=\"center\"> \n" + " Confirm Password: <input name=\"confirmpassword\" type=\"password\" /> \n" + " </p>\n" + " <p align=\"center\"> \n" + " <input class=\"signUpButton\" value=\"Sign Up\" type=\"submit\"/> \n" + " </p>\n" + " </form>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " \n" + "</html>"; if(startingState != stateEnum.ACCOUNT_CREATION) { out.println(accountPageBegin + accountPageEnd); return stateEnum.ACCOUNT_CREATION; } else{ String value1 = request.getParameter("home"); String value2 = request.getParameter("login"); String value = ""; if(value1 != null) value = value1; if(value2!=null) value = value2; if(value.equals("Log In")) return stateEnum.LOGIN; if(value.equals("TARSUS")) return stateEnum.INIT; String username = request.getParameter("username"); String findUsername = "SELECT username FROM Login " + "WHERE username = \"" + username + "\";"; Boolean alreadyExists = false; try{ connectDB(); ResultSet result = sqlQuery(findUsername, out); if(result.isBeforeFirst()){ alreadyExists= true; } }catch(Exception ex){ out.println("username check failure"); //Test Check out.println(ex); alreadyExists=true; } DBUtilities.closeStatement(stat); disconnectDB(); // Check to see if the username is valid if(!isValidString(username) || alreadyExists) { out.println(accountPageBegin + "<h3 id=\"title\" class=\"centered\"> Invalid Username " + "</h3 \n" + accountPageEnd); return stateEnum.ACCOUNT_CREATION; } int password = request.getParameter("password").hashCode(); int confirmPassword = request.getParameter("confirmpassword").hashCode(); if(password != confirmPassword){ out.println(accountPageBegin + "<h3 id=\"title\" class=\"centered\"> The Passwords Do " + "Not Match </h3 \n" + accountPageEnd); return stateEnum.ACCOUNT_CREATION; } String command = "INSERT INTO Login VALUES ('" + username + "', MD5('" + password +"'), gold=0);"; try{ connectDB(); if(sqlCommand(command, out)) { DBUtilities.closeStatement(stat); disconnectDB(); return stateEnum.LOGIN; } else{ out.println(accountPageBegin +"<h1> ERROR! </h1>"+ accountPageEnd); return stateEnum.ACCOUNT_CREATION; } }catch(Exception ex) { out.println("SQL Command Error:"); out.println(ex); return stateEnum.ACCOUNT_CREATION;} } } stateEnum profileState(PrintWriter out, HttpServletRequest request) throws SQLException { if(startingState != stateEnum.PROFILE) { printProfileState(out); } else { String value1 = request.getParameter(accountName); String value2 = request.getParameter("Log Out"); String value3 = request.getParameter("Create Character"); String value4 = request.getParameter("Load Character"); String value5 = request.getParameter("Look at Past Characters"); String value = ""; if(value1 != null) value = value1; if(value2 != null) value = value2; if(value3 != null) value = value3; if(value4 != null) value = value4; if(value5 != null) value = value5; if(value.equals(accountName)) printProfileState(out); if(value.equals("Log Out")) return stateEnum.LOGOUT; if(value.equals("Create Character")) return stateEnum.REGISTERED_CHARACTER_CREATION; if(value.equals("Load Character")) { String search1 = "SELECT * FROM Characters WHERE creator='" + accountName + "' AND isDead=0;"; connectDB(); ResultSet result = sqlQuery(search1, out); if(result.isBeforeFirst()) { result.next(); String name = result.getString("name"); String bio = result.getString("bio"); int level = result.getInt("level"); int health = result.getInt("health"); int strength = result.getInt("strength"); int agility = result.getInt("agility"); int magic = result.getInt("magic"); int timesAttacked = result.getInt("timesAttacked"); int timesSwitchedToStrength = result.getInt("timesSwitchedToStrength"); int timesSwitchedToAgility = result.getInt("timesSwitchedToAgility"); int timesSwitchedToMagic = result.getInt("timesSwitchedToMagic"); int equipWeaponId = result.getInt("equippedWeapon"); int equipArmorId = result.getInt("equippedArmor"); disconnectDB(); //getting the length for itemsHeld connectDB(); String search2 = "SELECT COUNT(I.itemId) AS rows FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + name + "';"; result = sqlQuery(search2, out); result.next(); int rows = result.getInt("rows"); disconnectDB(); Item[] itemsHeld = new Item[rows]; Item weapon = null; Item armor = null; String search3 = "SELECT * FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + name + "';"; connectDB(); result = sqlQuery(search3, out); //temp varible int i = 0; while (result.next()) { String iName = result.getString("name"); int itemId = result.getInt("itemId"); int type = result.getInt("type"); int upgradeCount = result.getInt("upgradeCount"); int strengthVal= result.getInt("strengthVal"); int agilityVal = result.getInt("agilityVal"); int magicVal = result.getInt("magicVal"); Item item = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0); itemsHeld[i] = item; if (equipWeaponId == itemId) { weapon = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0); } if (equipArmorId == itemId) { armor = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0); } i++; } disconnectDB(); playerChar = new PlayerCharacter(name, bio, level, health, strength, agility, magic, itemsHeld, weapon, armor, timesAttacked, timesSwitchedToStrength, timesSwitchedToAgility, timesSwitchedToMagic); return stateEnum.DECISION; } else { out.println("No Valid Character"); printProfileStateNewChar(out); return stateEnum.PROFILE; } } if(value.equals("Look at Past Characters")) return stateEnum.PAST_CHARACTERS; } return stateEnum.PROFILE; } stateEnum pastCharactersState(PrintWriter out, HttpServletRequest request) { if(startingState != stateEnum.PAST_CHARACTERS) { String startPart = "<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <body>\n" + " <form action=\"Tarsus\" method=\"get\">" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + " <input name=\"" + accountName + "\" value=\"" + accountName + "\" type=\"submit\" id=\"tarsusTitle\" /> \n" + " <input class=\"button\" name=\"Log Out\" value=\"Log Out\" type=\"submit\" /> </div>\n" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <h1 id=\"title\" class=\"centered\">Past Characters</h1>\n" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <th> Name </th>\n" + " <th> Level </th>\n" + " <th> Health </th>\n" + " <th> Strength </th>\n" + " <th> Agility </th>\n" + " <th> Magic </th>\n" + " <th> Bio </th>\n" + " </tr>\n"; String lastPart = " </tr>\n" + " </table>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " </form>" + " </body>\n" + " \n" + "</html>"; out.println(startPart); ResultSet result; int rows = 0; try { //getting the amount of dead characters String search1 = "SELECT COUNT(name) AS rows FROM Characters WHERE creator='" + accountName + "' AND isDead=1;"; connectDB(); result = sqlQuery(search1, out); result.next(); rows = result.getInt("rows"); disconnectDB(); } catch(Exception ex) { out.println("Error in getting rows: " + ex); } boolean noDead; if(rows > 0) { noDead = false; } else { noDead = true; } String search2 = "SELECT * FROM Characters WHERE creator='" + accountName + "' AND isDead=1;"; connectDB(); try { result = sqlQuery(search2, out); if(noDead) { out.println("<tr>"); out.println("<th></th>\n" + "<th></th>\n" + "<th></th>\n" + "<th></th>\n" + "<th></th>\n" + "<th></th>\n" + "<th></th>\n"); out.println("</tr>"); } else //there are one or more dead characters { while (result.next()) { out.println("<td>"); out.println(result.getString("name")); out.println("</td>"); out.println("<td>"); out.println(result.getInt("level")); out.println("</td>"); out.println("<td>"); out.println(result.getInt("health")); out.println("</td>"); out.println("<td>"); out.println(result.getInt("strength")); out.println("</td>"); out.println("<td>"); out.println(result.getInt("agility")); out.println("</td>"); out.println("<td>"); out.println(result.getInt("magic")); out.println("</td>"); out.println("<td>"); out.println(result.getString("bio")); out.println("</td>"); out.println("</tr>\n"); } } } catch(Exception ex) { out.println("Error grabbing dead characters: " + ex); } disconnectDB(); out.println(lastPart); return stateEnum.PAST_CHARACTERS; } else { String value1 = request.getParameter(accountName); String value2 = request.getParameter("Log Out"); String value = ""; if(value1 != null) value = value1; if(value2 != null) value = value2; if(value.equals(accountName)) return stateEnum.PROFILE; if(value.equals("Log Out")) return stateEnum.LOGOUT; } return stateEnum.PROFILE; } stateEnum LogoutState(PrintWriter out, HttpServletRequest request) { playerChar = null; aresChar = null; accountName = "Unregistered User"; gold = 0; error = null; //accountName = null; return stateEnum.INIT; //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } /**************************************************** * Checks the validity of a String for the database * @param string the string to check for validity * @return the validity ***************************************************/ Boolean isValidString(String string) { Boolean toBeReturned = true; if(string.contains("drop")) toBeReturned = false; if(string.contains("delete")) toBeReturned = false; if(string.contains(";")) toBeReturned = false; if(string.contains("'")) toBeReturned = false; return toBeReturned; } String maxValueScript(int value) { return ("<script> var maxValue=" + Integer.toString(value) +";</script>"); } double getQuality(int level) { double ratio = ((double)level) / ((double)level + 5.0); double quality = Math.random() * ratio; return quality; } void printBlacksmithState(PrintWriter out) { String startPart = "<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <body>\n" + " <form action=\"Tarsus\" method=\"post\">" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + " <input value=\"" + accountName + "\" name=\"" + accountName + "\" type=\"submit\" id=\"tarsusTitle\" />\n" + " <input class=\"button\" value=\"Log Out\" name=\"Log Out\" type=\"submit\" /> </div>\n" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <h1 id=\"title\" class=\"centered\">Blacksmith</h1>\n" + " <h2 id=\"title\" class=\"GoldDisplay\"> Gold: " + gold + "</h2>" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <td> </td>\n" + " <th> Name </th>\n" + " <th> Upgrade Cost </th>\n" + " <th> Strength </th>\n" + " <th> Agility </th>\n" + " <th> Magic </th>\n" + " <th> Type </th>\n" + " <th> Times Upgraded </th>\n" + " </tr>\n"; String endPart = "</table>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " </form>" + " </body>\n" + " \n" + "</html>"; out.println(startPart); boolean noItems; if(playerChar.itemsHeld.length > 0) { noItems = false; } else { noItems = true; } if(noItems) { out.println("<tr>"); out.println("<td> </td>\n" + "<th></th>\n" + "<th></th>\n" + "<th></th>\n" + "<th></th>\n" + "<th></th>\n" + "<th></th>\n" + "<th></th>\n"); out.println("</tr>"); } else //there are one or more items { for (int i = 0; i < playerChar.itemsHeld.length; i++){ if(playerChar.itemsHeld[i].getUpgradeCount() < 3) { out.println("<tr>\n"); out.println("<td> <input value=\"Upgrade\" name=\"Upgrade" + i + "\" type=\"submit\" class=\"tableButton\" /> </td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getName()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].CONSTANT_upgradeGold); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getStrength()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getAgility()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getMagic()); out.println("</td>"); out.println("<td>"); out.println(item_type_string[playerChar.itemsHeld[i].getType()]); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getUpgradeCount()); out.println("</td>"); out.println("</tr>\n"); } } } out.println(endPart); } void printProfileState(PrintWriter out) { try{ String search1 = "SELECT * FROM Characters WHERE creator='" + accountName + "' AND isDead=0;"; connectDB(); ResultSet result = sqlQuery(search1, out); if(result.isBeforeFirst()) { printProfileStateLoadChar(out); } else{ printProfileStateNewChar(out); } } catch(Exception ex){ out.println(ex); } } void printProfileStateNewChar(PrintWriter out) { out.println("<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <body>\n" + " <form action=\"Tarsus\" method=\"post\">" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + " <input name=\"" + accountName + "\" value=\"" + accountName + "\" id=\"tarsusTitle\" type=\"submit\" /> \n" + " <input class=\"button\" name=\"Log Out\" value=\"Log Out\" type=\"submit\" /> </div>\n" + " <div class=\"grid2\"> </div>\n" + " <div class=\"grid6 centered\">\n" + " <h1 id=\"title\" class=\"centered\">TARSUS</h1> <br />\n" + " <h2 id=\"title\" class=\"GoldDisplay\"> Gold: " + gold + "</h2>" + " <div align=\"center\"> \n" + " <input class=\"profileButton\" name=\"Create Character\" value=\"Create Character\" type=\"submit\" />\n" + " <input class=\"profileButton\" name=\"Look at Past Characters\" value=\"Look at Past Characters\" type=\"submit\" /> \n" + " </div>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " </form>" + " </body>\n" + " \n" + "</html>"); } void printProfileStateLoadChar(PrintWriter out) { out.println("<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <body>\n" + " <form action=\"Tarsus\" method=\"post\">" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + " <input name=\"" + accountName + "\" value=\"" + accountName + "\" id=\"tarsusTitle\" type=\"submit\" /> \n" + " <input class=\"button\" name=\"Log Out\" value=\"Log Out\" type=\"submit\" /> </div>\n" + " <div class=\"grid2\"> </div>\n" + " <div class=\"grid6 centered\">\n" + " <h1 id=\"title\" class=\"centered\">TARSUS</h1> <br />\n" + " <h2 id=\"title\" class=\"GoldDisplay\"> Gold: " + gold + "</h2>" + " <div align=\"center\"> \n" + " <input class=\"profileButton\" name=\"Load Character\" value=\"Load Character\" type=\"submit\" /> \n" + " <input class=\"profileButton\" name=\"Look at Past Characters\" value=\"Look at Past Characters\" type=\"submit\" /> \n" + " </div>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " </form>" + " </body>\n" + " \n" + "</html>"); } public void printStoreState(PrintWriter out) { //String item_type_string[] = {"Error", "Weapon", "Armor", "Item"}; String startPart = "<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <body>\n" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + " <form action=\"Tarsus\" method=\"post\">" + " <input value=\"" + accountName + "\" name=\"" + accountName + "\" type=\"submit\" id=\"tarsusTitle\" />\n" + " <input class=\"button\" type=\"submit\" value=\"Log Out\" name=\"Log Out\" /> </div>\n" + "</form>" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " </br><b>Your current amount of gold: " + gold + "</b></br>" + " <h1 id=\"title\" class=\"centered\">Store Inventory</h1>\n" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <td> </td>\n" + " <th> Name </th>\n" + " <th> Strength </th>\n" + " <th> Agility </th>\n" + " <th> Magic </th>\n" + " <th> Heal </th>\n" + " <th> Type </th>\n" + " <th> Price </th>\n" + " </tr>\n" + " <tr>"; String sellPart = " </table>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + "<div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <h1 id=\"title\" class=\"centered\">Your Items</h1>\n" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <td> </td>\n" + " <th> Name </th>\n" + " <th> Strength </th>\n" + " <th> Agility </th>\n" + " <th> Magic </th>\n" + " <th> Heal </th>\n" + " <th> Type </th>\n" + " <th> Sell Price </th>\n" + " </tr>\n" + " "; String buttonPart = (" </table>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid10\" align=\"center\">\n" + " <input id=\"Form\" type =\"submit\" value=\"This button does not do anything\" class=frontPageButton /> \n" + " </div>\n" + " </form>\n"); String endPart = /*"</table>\n" +"</div>\n" +*/ " </body>\n" + " \n" + "</html>"; String script = "<script> function getFormValues() {" + "for(var i = 0; i < 20; i++){" + " var item = document.getElementById('i');" + " alert(item.getAttribute('name'));" + "} return false;} </script>"; out.println(startPart); out.println("<form name=\"buyItems\" action=\"Tarsus\" onsubmit=\"return getFormValues()\" method=\"post\">\n"); for (int i = 0; i < storeItems.length; i++){ out.println("<tr>"); if(storeItems[i] == null) { out.println("<td> </td>"); out.println("<td> Item sold out</td>"); out.println("<td> n/a </td>"); out.println("<td> n/a </td>"); out.println("<td> n/a </td>"); out.println("<td> n/a </td>"); out.println("<td> n/a </td>"); out.println("<td> n/a </td>"); out.println("</tr>"); } else{ //out.println(storeItems[i]); out.println("<tr>"); out.println("<td> <input id =\"" + i + "\" type=\"submit\" value=\"Buy" + "\" name=\"Buy " + i + "\" class=\"tableButton\"> </td>"); out.println("<td>"); out.println(storeItems[i].getName()); out.println("</td>"); out.println("<td>"); out.println(storeItems[i].getStrength()); out.println("</td>"); out.println("<td>"); out.println(storeItems[i].getAgility()); out.println("</td>"); out.println("<td>"); out.println(storeItems[i].getMagic()); out.println("</td>"); out.println("<td>"); out.println(storeItems[i].getHeal()); out.println("</td>"); out.println("<td>"); out.println(item_type_string[storeItems[i].getType()]); out.println("</td>"); out.println("<td>"); out.println(storeItems[i].getValue()); out.println("</td>"); out.println("</tr>"); } } out.println(sellPart); //out.println("player items held length: " + playerChar.itemsHeld.length); for (int i = 0; i < playerChar.itemsHeld.length; i++){ if(playerChar.itemsHeld[i] == null) { continue; } out.println("<tr>"); //out.println(" loop level: " + i); out.println("<td>"); if((playerChar.itemsHeld[i] != playerChar.weapon) && (playerChar.itemsHeld[i] != playerChar.armor)) { out.println("<input type=\"submit\" value=\"Sell" + "\" name=\"Sell " + i + "\" class=\"tableButton\">"); } else { out.println("Equiped Item"); } out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getName()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getStrength()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getAgility()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getMagic()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getHeal()); out.println("</td>"); out.println("<td>"); out.println(item_type_string[playerChar.itemsHeld[i].getType()]); out.println("</td>"); out.println("<td>"); out.println((int)(0.60 * (double)(playerChar.itemsHeld[i].getValue()))); out.println("</td>"); out.println("</tr>"); } out.println(buttonPart); out.println(endPart); out.println(script); } private stateEnum levelUpState(PrintWriter out, HttpServletRequest request) { if(startingState != stateEnum.LEVEL_UP) { String page = "<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <script>\n" + " function validateForm()\n" + " {\n" + " \n" + " var maxValue = 5 \n" + " var strength = parseInt(document.forms[\"createCharacterForm\"][\"strength\"].value); \n" + " var agility = parseInt(document.forms[\"createCharacterForm\"][\"agility\"].value);\n" + " var magic = parseInt(document.forms[\"createCharacterForm\"][\"magic\"].value);\n" + " var health = parseInt(document.forms[\"createCharacterForm\"][\"health\"].value);\n" + " var total = strength + agility + magic + health;\n" + " alert(\"Total Experience points used: \" + total);\n" + " if(total > maxValue)\n" + " {\n" + " alert(\"Cannot use more than\" + maxValue + \" experience points.\");\n" + " return false;\n" + " }\n" + " \n" + " }\n" + " </script>" + " <body>\n" + "<form name=\"createCharacterForm\" action=\"Tarsus\" onsubmit=\"return validateForm()\" method=\"post\">\n" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + "<input type=\"Submit\" name=\"Home\" value=\"Home\" id=\"tarsusTitle\" />" + " <div class=\"grid1\"> </div></div>\n" + " <div class=\"grid1\"> </div>" + " <div class=\"grid8 centered\">\n" + " <h1 id=\"title\" class=\"centered\">Character Creation</h1>\n" + " \n" + " <div class=\"grid2\"> </div>\n" + " <div class=\"grid6\" align=\"center\">\n" + " <p> Experience Points to Allocate: 5\n" + " </p>\n" + " <p> \n" + " Strength is currently %d add: <input type=\"number\" name=\"strength\"min=\"0\" max=\"5\" value=\"0\"/>\n" + " </p> \n" + " <p> \n" + " Agility is currently %d add: <input type=\"number\" name=\"agility\"min=\"0\" max=\"5\" value=\"0\"/>\n" + " </p> \n" + " <p> \n" + " Magic is currently %d add: <input type=\"number\" name=\"magic\" min=\"0\" max=\"5\" value=\"0\"/>\n" + " </p> \n" + " <p> \n" + " Health is currently %d add: <input type=\"number\" name=\"health\" min=\"0\" max=\"5\" value=\"0\"/>\n" + " </p> \n" + " </div>\n"+ " <div class=\"grid10\" align=\"center\">\n" + " <input type =\"submit\" value=\"update level\" class=frontPageButton /> \n" + " </div>\n" + " </form>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " </body>\n" + " \n" + "</html>"; out.printf(page,playerChar.getStrength(),playerChar.getAgility(),playerChar.getMagic(),playerChar.getMaxHealth()/constantHealthPerLevel); return stateEnum.LEVEL_UP; } else { int health = Integer.parseInt(request.getParameter("health")); int strength = Integer.parseInt(request.getParameter("strength")); int agility = Integer.parseInt(request.getParameter("agility")); int magic = Integer.parseInt(request.getParameter("magic")); playerChar.setMaxHealth(playerChar.getMaxHealth()+health*constantHealthPerLevel); playerChar.setHealth(playerChar.getMaxHealth()); playerChar.setStrength(playerChar.getStrength()+strength*constantStrengthPerLevel); playerChar.setAgility(playerChar.getAgility()+agility*constantAgilityPerLevel); playerChar.setMagic(playerChar.getMagic()+magic*constantMagicPerLevel); playerChar.setLevel(playerChar.getLevel()+1); //update database updateCharacter(playerChar, false, out); return stateEnum.DECISION; } } private void printCharacterCreation(Integer level, PrintWriter out) { String StartPage = "<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <script>\n" + " function validateForm()\n" + " {\n" + " \n" + " var maxValue = "; String secondPart = "; \n" + " var strength = parseInt(document.forms[\"createCharacterForm\"][\"strength\"].value); \n" + " var agility = parseInt(document.forms[\"createCharacterForm\"][\"agility\"].value);\n" + " var magic = parseInt(document.forms[\"createCharacterForm\"][\"magic\"].value);\n" + " var health = parseInt(document.forms[\"createCharacterForm\"][\"health\"].value);\n" + " var total = strength + agility + magic + health;\n" + " alert(\"Total Experience points used: \" + total);\n" + " if(total > maxValue)\n" + " {\n" + " alert(\"Cannot use more than\" + maxValue + \" experience points.\");\n" + " return false;\n" + " }\n" + " \n" + " }\n" + " </script>" + " <body>\n" + " <form action=\"Tarsus\" method=\"post\">" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + "<input type=\"Submit\" name=\"Home\" value=\"Home\" id=\"tarsusTitle\" />" + " <div class=\"grid1\"> </div></div>\n" + " <div class=\"grid1\"> </div>"+ " <div class=\"grid8 centered\">\n" + "</form>" + "<form name=\"createCharacterForm\" action=\"Tarsus\" onsubmit=\"return validateForm()\" method=\"post\">\n" + " <h1 id=\"title\" class=\"centered\">Character Creation</h1>\n" + " \n" + " <div class=\"grid2\"> </div>\n" + " <input type = \"hidden\" name = \"level\" value=\""; String thirdPart = "\"/>\n"+ " <div class=\"grid6\" align=\"center\">\n" + " <h3> Level "; String fourthPart = " </h3>\n" + " <p> Experience Points to Allocate: "; String fifthPart = "\n" + " </p>\n" + " <p> \n" + " Name: <input type=\"text\" name=\"name\"/>\n" + " </p>\n" + " <p> \n" + " Strength: <input type=\"number\" name=\"strength\"min=\"0\" max=\"100\" value=\"0\"/>\n" + " </p> \n" + " <p> \n" + " Agility: <input type=\"number\" name=\"agility\"min=\"0\" max=\"100\" value=\"0\"/>\n" + " </p> \n" + " <p> \n" + " Magic: <input type=\"number\" name=\"magic\" min=\"0\" max=\"100\" value=\"0\"/>\n" + " </p> \n" + " <p> \n" + " Health: <input type=\"number\" name=\"health\" min=\"0\" max=\"100\" value=\"0\"/>\n" + " </p> \n" + " <p>\n" + " Biography:<textarea name=\"bio\" cols=\"35\" rows=\"3\" maxlength=\"300\"> </textarea> <br /> <a id=\"bioLimitID\"> (Max of 300 Chars)</a>\n" + " </p>\n"; String lastPart = " </div>\n"+ " <div class=\"grid10\" align=\"center\">\n" + " <input type =\"submit\" value=\"Create a Character\" class=frontPageButton /> \n" + " </div>\n" + " </form>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " </body>\n" + " \n" + "</html>"; int numItemChoices = 5; Item tempItem; String submitValue; out.printf(StartPage); out.println(((Integer)(level*constantPtsPerLevel)).toString()); out.printf(secondPart); out.printf(level.toString()); out.printf(thirdPart); out.printf(level.toString()); out.printf(fourthPart); out.printf(((Integer)(level*constantPtsPerLevel)).toString()); out.printf(fifthPart); out.printf("<input type=\"hidden\" name=\"level\" value=\"%d\" />\n",level); out.println("<table><tr><h2>Weapons</h2></tr><tr><th>Name</th><th>Strength</th><th>Agility</th><th>Magic</th><th>select</th><tr>"); for(int i=0; i<numItemChoices; i++) { tempItem = generateWeapon(level); submitValue = tempItem.getName()+"="+((Integer)tempItem.itemId).toString()+"+"+((Integer)tempItem.getStrength()).toString()+"-"+((Integer)tempItem.getAgility()).toString()+"*"+((Integer)tempItem.getMagic()).toString()+"_"+((Integer)tempItem.getType()).toString(); if(i==0) out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"weapon\" value=\"%s\" checked></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue); else out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"weapon\" value=\"%s\"></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue); } out.println("</table>"); out.println("<table><tr><h2>Armor</h2></tr><tr><th>Name</th><th>Strength</th><th>Agility</th><th>Magic</th><th>select</th><tr>"); for(int i=0; i<numItemChoices; i++) { tempItem = generateArmor(level); submitValue = tempItem.getName()+"="+((Integer)tempItem.itemId).toString()+"+"+((Integer)tempItem.getStrength()).toString()+"-"+((Integer)tempItem.getAgility()).toString()+"*"+((Integer)tempItem.getMagic()).toString()+"_"+((Integer)tempItem.getType()).toString(); if(i==0) out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"armor\" value=\"%s\" checked></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue); else out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"armor\" value=\"%s\"></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue); } out.println("</table>"); out.println(lastPart); if(error!=null) out.printf("<script>alert(\"%s\");</script>",error); error = null; } private void printRegCharacterCreation(Integer level, PrintWriter out) { String StartPage = "<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <script>\n" + " function validateForm()\n" + " {\n" + " \n" + " var maxValue = "; String secondPart = "; \n" + " var strength = parseInt(document.forms[\"createCharacterForm\"][\"strength\"].value); \n" + " var agility = parseInt(document.forms[\"createCharacterForm\"][\"agility\"].value);\n" + " var magic = parseInt(document.forms[\"createCharacterForm\"][\"magic\"].value);\n" + " var health = parseInt(document.forms[\"createCharacterForm\"][\"health\"].value);\n" + " var total = strength + agility + magic + health;\n" + " alert(\"Total Experience points used: \" + total);\n" + " if(total > maxValue)\n" + " {\n" + " alert(\"Cannot use more than\" + maxValue + \" experience points.\");\n" + " return false;\n" + " }\n" + " \n" + " }\n" + " </script>" + " <body>\n" + " <form action=\"Tarsus\" method=\"post\">" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + "<input type=\"Submit\" name=\"" + accountName + "\" value=\"" + accountName + "\" id=\"tarsusTitle\" />" + "<input class=\"button\" type=\"Submit\" name=\"Log Out\" value=\"Log Out\" />" + " <div class=\"grid1\"> </div></div>\n" + " <div class=\"grid1\"> </div>"+ " <div class=\"grid8 centered\">\n" + "</form>" + "<form name=\"createCharacterForm\" action=\"Tarsus\" onsubmit=\"return validateForm()\" method=\"post\">\n" + " <h1 id=\"title\" class=\"centered\">Character Creation</h1>\n" + " \n" + " <div class=\"grid2\"> </div>\n" + " <input type = \"hidden\" name = \"level\" value=\""; String thirdPart = "\"/>\n"+ " <div class=\"grid6\" align=\"center\">\n" + " <h3> Level "; String fourthPart = " </h3>\n" + " <p> Experience Points to Allocate: "; String fifthPart = "\n" + " </p>\n" + " <p> \n" + " Name: <input type=\"text\" name=\"name\"/>\n" + " </p>\n" + " <p> \n" + " Strength: <input type=\"number\" name=\"strength\"min=\"0\" max=\"100\" value=\"0\"/>\n" + " </p> \n" + " <p> \n" + " Agility: <input type=\"number\" name=\"agility\"min=\"0\" max=\"100\" value=\"0\"/>\n" + " </p> \n" + " <p> \n" + " Magic: <input type=\"number\" name=\"magic\" min=\"0\" max=\"100\" value=\"0\"/>\n" + " </p> \n" + " <p> \n" + " Health: <input type=\"number\" name=\"health\" min=\"0\" max=\"100\" value=\"0\"/>\n" + " </p> \n" + " <p>\n" + " Biography:<textarea name=\"bio\" cols=\"35\" rows=\"3\" maxlength=\"300\"> </textarea> <br /> <a id=\"bioLimitID\"> (Max of 300 Chars)</a>\n" + " </p>\n"; String lastPart = " </div>\n"+ " <div class=\"grid10\" align=\"center\">\n" + " <input type =\"submit\" value=\"Create a Character\" class=frontPageButton /> \n" + " </div>\n" + " </form>\n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " </body>\n" + " \n" + "</html>"; int numItemChoices = 5; Item tempItem; String submitValue; out.printf(StartPage); out.println(((Integer)(level*constantPtsPerLevel)).toString()); out.printf(secondPart); out.printf(level.toString()); out.printf(thirdPart); out.printf(level.toString()); out.printf(fourthPart); out.printf(((Integer)(level*constantPtsPerLevel)).toString()); out.printf(fifthPart); out.printf("<input type=\"hidden\" name=\"level\" value=\"%d\" />\n",level); out.println("<table><tr><h2>Weapons</h2></tr><tr><th>Name</th><th>Strength</th><th>Agility</th><th>Magic</th><th>select</th><tr>"); for(int i=0; i<numItemChoices; i++) { tempItem = generateWeapon(level); submitValue = tempItem.getName()+"="+((Integer)tempItem.itemId).toString()+"+"+((Integer)tempItem.getStrength()).toString()+"-"+((Integer)tempItem.getAgility()).toString()+"*"+((Integer)tempItem.getMagic()).toString()+"_"+((Integer)tempItem.getType()).toString(); if(i==0) out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"weapon\" value=\"%s\" checked></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue); else out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"weapon\" value=\"%s\"></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue); } out.println("</table>"); out.println("<table><tr><h2>Armor</h2></tr><tr><th>Name</th><th>Strength</th><th>Agility</th><th>Magic</th><th>select</th><tr>"); for(int i=0; i<numItemChoices; i++) { tempItem = generateArmor(level); submitValue = tempItem.getName()+"="+((Integer)tempItem.itemId).toString()+"+"+((Integer)tempItem.getStrength()).toString()+"-"+((Integer)tempItem.getAgility()).toString()+"*"+((Integer)tempItem.getMagic()).toString()+"_"+((Integer)tempItem.getType()).toString(); if(i==0) out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"armor\" value=\"%s\" checked></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue); else out.printf("<tr><td>%s </td><td>%d</td><td>%d</td><td>%d</td><td><input type=\"radio\" name=\"armor\" value=\"%s\"></td></tr>\n",tempItem.getName(),tempItem.getStrength(), tempItem.getAgility(), tempItem.getMagic(), submitValue); } out.println("</table>"); out.println(lastPart); if(error!=null) out.printf("<script>alert(\"%s\");</script>",error); error = null; } private boolean checkHome(HttpServletRequest request) { String value = request.getParameter("Home"); return value.equals("Home"); } private void printInventory(PrintWriter out) { String startPart = " <div class=\"grid1 centered\"> </div>\n" + "<div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <h1 id=\"title\" class=\"centered\">Your Inventory</h1>\n" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <td> </td>\n" + " <th> Name </th>\n" + " <th> Strength </th>\n" + " <th> Agility </th>\n" + " <th> Magic </th>\n" + " <th> Heal </th>\n" + " <th> Type </th>\n" + " <th> Upgrade Count </th>\n" + " </tr>\n" + " "; String endPart = "</table> </div>"; out.println(startPart); for (int i = 0; i < playerChar.itemsHeld.length; i++){ if(playerChar.itemsHeld[i] == null) { continue; } out.println("<tr>"); //out.println(" loop level: " + i); out.println("<td>"); if(playerChar.itemsHeld[i] == playerChar.armor) { out.println("<b>Equiped Armor</b>"); } else if(playerChar.itemsHeld[i] == playerChar.weapon) { out.println("<b>Equiped Weapon</b>"); } else { out.println(""); } out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getName()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getStrength()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getAgility()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getMagic()); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getHeal()); out.println("</td>"); out.println("<td>"); out.println(item_type_string[playerChar.itemsHeld[i].getType()]); out.println("</td>"); out.println("<td>"); out.println(playerChar.itemsHeld[i].getUpgradeCount()); out.println("</td>"); out.println("</tr>"); } out.println(endPart); } private stateEnum charCreationParameters(PrintWriter out, HttpServletRequest request, Boolean isUnReg) { String name = (String) request.getParameter("name"); String bio = request.getParameter("bio"); int level = Integer.parseInt(request.getParameter("level")); int health = (Integer.parseInt(request.getParameter("health"))*constantHealthPerLevel + constantHealthBase); int strength = (Integer.parseInt(request.getParameter("strength"))*constantStrengthPerLevel); int agility = (Integer.parseInt(request.getParameter("agility"))*constantAgilityPerLevel); int magic = (Integer.parseInt(request.getParameter("magic"))*constantMagicPerLevel); //Item[] items = {new Item(request.getParameter("weapon")), new Item(request.getParameter("armor"))}; String weap = request.getParameter("weapon"); Item weap2 = new Item(weap); String armor = request.getParameter("armor"); Item armor2 = new Item(armor); Item[] items = {weap2, armor2}; try{ String findCharName = "SELECT name FROM Characters " + "WHERE name = \"" + name + "\";"; Boolean alreadyExists = false; connectDB(); ResultSet result = sqlQuery(findCharName, out); if(result.isBeforeFirst()){ alreadyExists= true; } if(isValidString(name) & isValidString(bio) & !alreadyExists) { newItem(items[0], out); newItem(items[1], out); PlayerCharacter chrct = new PlayerCharacter(name,bio, level, health, strength, agility, magic, items,items[0],items[1],0,0,0,0); newCharacter(chrct,isUnReg, out); characterHasItem(items[0], chrct, out); characterHasItem(items[1], chrct, out); if(isUnReg) return stateEnum.INIT; playerChar = chrct; return stateEnum.DECISION; } else { error = "The character name or bio is invalid or there was a database error"; if(alreadyExists) error = "That name is already in use"; if(isUnReg) return stateEnum.UNREGISTERED_CHARACTER_CREATION; return stateEnum.REGISTERED_CHARACTER_CREATION; } } catch(Exception e) { error = "The character name or bio is invalid or there was a database error"; if(isUnReg) return stateEnum.UNREGISTERED_CHARACTER_CREATION; return stateEnum.REGISTERED_CHARACTER_CREATION; } } void getItems(PrintWriter out) { //getting the length for itemsHeld playerChar.itemsHeld = null; try { String search1 = "SELECT * FROM Characters WHERE creator='" + accountName + "' AND isDead=0;"; connectDB(); ResultSet result = sqlQuery(search1, out); if(result.isBeforeFirst()) { result.next(); int equipWeaponId = result.getInt("equippedWeapon"); int equipArmorId = result.getInt("equippedArmor"); disconnectDB(); connectDB(); String search2 = "SELECT COUNT(I.itemId) AS rows FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + playerChar.getName() + "';"; result = sqlQuery(search2, out); result.next(); int rows = result.getInt("rows"); disconnectDB(); playerChar.itemsHeld = new Item[rows]; Item weapon = null; Item armor = null; String search3 = "SELECT * FROM Items I, CharacterHasItem C WHERE I.itemId=C.itemId AND C.charName='" + playerChar.getName() + "';"; connectDB(); result = sqlQuery(search3, out); //temp varible int i = 0; while (result.next()) { String iName = result.getString("name"); int itemId = result.getInt("itemId"); int type = result.getInt("type"); int upgradeCount = result.getInt("upgradeCount"); int strengthVal= result.getInt("strengthVal"); int agilityVal = result.getInt("agilityVal"); int magicVal = result.getInt("magicVal"); Item item = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0); playerChar.itemsHeld[i] = item; if (equipWeaponId == itemId) { weapon = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0); } if (equipArmorId == itemId) { armor = new Item(iName, itemId, type, upgradeCount, strengthVal, agilityVal, magicVal, 0); } i++; } disconnectDB(); } } catch(Exception ex) { out.println("Error: " + ex); } } void updateGold(PrintWriter out) { connectDB(); String query = "UPDATE Login SET gold=\"" + gold + "\" WHERE username='" + accountName + "';"; boolean okay = sqlCommand(query, out); if(okay) { //do nothing } else { out.println("Error: You suck!"); } disconnectDB(); } }
false
true
private stateEnum battleState(PrintWriter out, HttpServletRequest request) { if(startingState != stateEnum.BATTLE) { try { //Item[] itemsHeld = {generateWeapon(1), generateArmor(1), generateWeapon(1), generateArmor(1)}; //playerChar = new PlayerCharacter("player", "", 1, 1000, 1, 2, 3, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0); //aresChar = new AresCharacter("enemy", "", 1, 100, 1, 2, 3, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0); getNextEnemy(playerChar.getLevel(), out); } catch (SQLException ex) { Logger.getLogger(GameInstance.class.getName()).log(Level.SEVERE, null, ex); } } String startPage = "<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"../css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <body>\n" + " <div id=\"header\" class=\"grid10\" align=\"right\">\n" + " %s \n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <br />\n" + " <p align=\"center\">\n" + " </p>\n" + " <div class=\"gridHalf\"> \n"; String statsTable = " <h2 align=\"center\"> %s </h2>\n" + " \n" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <th> Health </th>\n" + " <th> Strength </th>\n" + " <th> Magic </th>\n" + " <th> Agility </th>\n" + " </tr>\n" + " <tr>\n" + " <th> %d </th>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " </tr>\n" + " </table>\n"; String equippedTable1 = " \n" + " <h3 align=\"center\"> Equipped </h3>\n" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <td> </td>\n" + " <th> Name </th>\n" + " <th> Strength </th>\n" + " <th> Magic </th>\n" + " <th> Agility </th>\n" + " </tr>\n" + " <tr>\n" + " <th> Weapon: </th>\n" + " <td> %s </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " </tr>\n"; String equippedTable2 = " <tr>\n" + " <th> Armor: </th>\n" + " <td> %s </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " </tr>\n" + " </table>\n"; String betweenCharacters = " </div>\n" + " <div class=\"gridHalf\"> \n"; String afterTable = " \n" + " </div>\n" + " <form action=\"Tarsus\" method = \"post\">"; String attackButton = " <input type = \"submit\" class=\"profileButton\" name = \"attack\" value = \"Attack\" /> \n" + " <select name = \"itemSelected\"> \n"; String useButton = " </select>" + " <input type = \"submit\" class=\"profileButton\" name=\"use\" value = \"Use item\" /> \n"; String lastPart = " </form>" + " <div class=\"grid1\"> </div>\n" + " </body>\n" + " \n" + "</html>"; int aresDamage = 0, playerDamage = 0; if(startingState == stateEnum.BATTLE) { String value = null, valueAttack=request.getParameter("attack"), valueUse=request.getParameter("use"), valueOK=request.getParameter("OK"), itemName; if(valueAttack!=null) value = valueAttack; if(valueUse!=null) { value=valueUse; itemName = request.getParameter("itemSelected"); } if(valueOK!=null) value=valueOK; if(!value.equals("OK")) { actionEnum playerAction = playerChar.requestAction(request); actionEnum aresAction = aresChar.requestAction(request); if(playerAction == actionEnum.ATTACK) { if(playerChar.weapon.getStrength()!=0) { aresDamage = (int) ((playerChar.getStrength()+playerChar.weapon.getStrength())*(Math.random()*.4+.8)-(aresChar.getStrength()*aresChar.armor.getStrength()/100)); } if(playerChar.weapon.getAgility()!=0) { aresDamage = (int) ((playerChar.getAgility()+playerChar.weapon.getAgility())*(Math.random()*.4+.8)-(aresChar.getAgility()*aresChar.armor.getAgility()/100)); } if(playerChar.weapon.getMagic()!=0) { aresDamage = (int) ((playerChar.getMagic()+playerChar.weapon.getMagic())*(Math.random()*.4+.8)-(aresChar.getMagic()*aresChar.armor.getMagic()/100)); } } if(aresAction == actionEnum.ATTACK) { if(aresChar.weapon.getStrength()!=0) { playerDamage = (int) ((aresChar.getStrength()+aresChar.weapon.getStrength())*(Math.random()*.4+.8)-(playerChar.getStrength()*playerChar.armor.getStrength()/100)); } if(aresChar.weapon.getMagic()!=0) { playerDamage = (int) ((aresChar.getMagic()+aresChar.weapon.getMagic())*(Math.random()*.4+.8)-(playerChar.getMagic()*playerChar.armor.getMagic()/100)); } if(aresChar.weapon.getAgility()!=0) { playerDamage = (int) ((aresChar.getAgility()+aresChar.weapon.getAgility())*(Math.random()*.4+.8)-(playerChar.getAgility()*playerChar.armor.getAgility()/100)); } } playerChar.setHealth(playerChar.getHealth() - playerDamage); aresChar.setHealth(aresChar.getHealth() - aresDamage); } else if(playerChar.getHealth()<1) { //mark the character as dead in the database updateCharacter(playerChar, true, out); return stateEnum.PROFILE; } else if(aresChar.getHealth()<1) return stateEnum.LEVEL_UP; } out.printf(startPage,accountName); out.printf(statsTable, playerChar.name, playerChar.getHealth(), playerChar.getStrength(), playerChar.getMagic(), playerChar.getAgility()); out.printf(equippedTable1, playerChar.weapon.getName(), playerChar.weapon.getStrength(), playerChar.weapon.getMagic(), playerChar.weapon.getAgility()); out.printf(equippedTable2, playerChar.armor.getName(), playerChar.armor.getStrength(), playerChar.armor.getMagic(), playerChar.armor.getAgility()); out.printf(betweenCharacters); out.printf(statsTable, aresChar.name, aresChar.getHealth(), aresChar.getStrength(), aresChar.getMagic(), aresChar.getAgility()); out.printf(equippedTable1, aresChar.weapon.getName(),aresChar.weapon.getStrength(), aresChar.weapon.getMagic(), aresChar.weapon.getAgility()); out.printf(equippedTable2, aresChar.armor.getName(), aresChar.armor.getStrength(), aresChar.armor.getMagic(), aresChar.armor.getAgility()); out.printf(afterTable); out.printf("<div>You have done %d damage to your opponent.\n Your opponent has done %d damage to you.</div>", aresDamage, playerDamage); if((playerChar.getHealth()>0) && (aresChar.getHealth()>0)) { out.printf(attackButton); for(int i=0; i < playerChar.itemsHeld.length;i++) { //change first string, the value parameter, to itemId out.printf("<option value = \"%s\"> %s </option> \n", playerChar.itemsHeld[i].getName(),playerChar.itemsHeld[i].getName()); } out.printf(useButton); } else if(playerChar.getHealth()<1) { out.printf("The valiant hero has been killed.\n"); out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n"); } else if(aresChar.getHealth()<1) { int newGold = (int) (constantGoldPerLevel*playerChar.getLevel()*(Math.random()*.4+.8)); gold+=newGold; updateGold(out); playerChar.setHealth(playerChar.getMaxHealth()); out.printf("Congradulations you beat your enemy.\n You get %d gold.\n", newGold); out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n"); } out.printf(lastPart); return stateEnum.BATTLE; }
private stateEnum battleState(PrintWriter out, HttpServletRequest request) { if(startingState != stateEnum.BATTLE) { try { //Item[] itemsHeld = {generateWeapon(1), generateArmor(1), generateWeapon(1), generateArmor(1)}; //playerChar = new PlayerCharacter("player", "", 1, 1000, 1, 2, 3, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0); //aresChar = new AresCharacter("enemy", "", 1, 100, 1, 2, 3, itemsHeld, itemsHeld[0], itemsHeld[1], 0, 0, 0, 0); getNextEnemy(playerChar.getLevel(), out); } catch (SQLException ex) { Logger.getLogger(GameInstance.class.getName()).log(Level.SEVERE, null, ex); } } String startPage = "<html>\n" + " <head>\n" + " <!-- Call normalize.css -->\n" + " <link rel=\"stylesheet\" href=\"css/normalize.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Import Font to be used in titles and buttons -->\n" + " <link href='http://fonts.googleapis.com/css?family=Sanchez' rel='stylesheet' type='text/css'>\n" + " <link href='http://fonts.googleapis.com/css?family=Prosto+One' rel='stylesheet' type='text/css'>\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/grid.css\" type=\"text/css\" media=\"screen\">\n" + " <!-- Call style.css -->\n" + " <link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen\">\n" + " <title> Tarsus </title>\n" + " </head>\n" + " <body>\n" + " <div id=\"header\" class=\"grid10\" align=\"center\">\n" + " %s \n" + " </div>\n" + " <div class=\"grid1\"> </div>\n" + " <div class=\"grid8 centered\">\n" + " <br />\n" + " <p align=\"center\">\n" + " </p>\n" + " <div class=\"gridHalf\"> \n"; String statsTable = " <h2 align=\"center\"> %s </h2>\n" + " \n" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <th> Health </th>\n" + " <th> Strength </th>\n" + " <th> Magic </th>\n" + " <th> Agility </th>\n" + " </tr>\n" + " <tr>\n" + " <th> %d </th>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " </tr>\n" + " </table>\n"; String equippedTable1 = " \n" + " <h3 align=\"center\"> Equipped </h3>\n" + " <table id=\"table\" align=\"center\">\n" + " <tr>\n" + " <td> </td>\n" + " <th> Name </th>\n" + " <th> Strength </th>\n" + " <th> Magic </th>\n" + " <th> Agility </th>\n" + " </tr>\n" + " <tr>\n" + " <th> Weapon: </th>\n" + " <td> %s </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " </tr>\n"; String equippedTable2 = " <tr>\n" + " <th> Armor: </th>\n" + " <td> %s </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " <td> %d </td>\n" + " </tr>\n" + " </table>\n"; String betweenCharacters = " </div>\n" + " <div class=\"gridHalf\"> \n"; String afterTable = " \n" + " </div>\n" + " <div class=\"grid10\">\n" + " <div align=\"center\">\n" + " <form action=\"Tarsus\" method = \"post\">"; String attackButton = " <input type = \"submit\" class=\"profileButton\" name = \"attack\" value = \"Attack\" /> <br /> \n" + " <select name = \"itemSelected\"> \n"; String useButton = " </select>" + " <input type = \"submit\" class=\"profileButton\" name=\"use\" value = \"Use item\" /> \n"; String lastPart = " </form>" + " <div class=\"grid1\"> </div> </div>\n" + " </body>\n" + " \n" + "</html>"; int aresDamage = 0, playerDamage = 0; if(startingState == stateEnum.BATTLE) { String value = null, valueAttack=request.getParameter("attack"), valueUse=request.getParameter("use"), valueOK=request.getParameter("OK"), itemName; if(valueAttack!=null) value = valueAttack; if(valueUse!=null) { value=valueUse; itemName = request.getParameter("itemSelected"); } if(valueOK!=null) value=valueOK; if(!value.equals("OK")) { actionEnum playerAction = playerChar.requestAction(request); actionEnum aresAction = aresChar.requestAction(request); if(playerAction == actionEnum.ATTACK) { if(playerChar.weapon.getStrength()!=0) { aresDamage = (int) ((playerChar.getStrength()+playerChar.weapon.getStrength())*(Math.random()*.4+.8)-(aresChar.getStrength()*aresChar.armor.getStrength()/100)); } if(playerChar.weapon.getAgility()!=0) { aresDamage = (int) ((playerChar.getAgility()+playerChar.weapon.getAgility())*(Math.random()*.4+.8)-(aresChar.getAgility()*aresChar.armor.getAgility()/100)); } if(playerChar.weapon.getMagic()!=0) { aresDamage = (int) ((playerChar.getMagic()+playerChar.weapon.getMagic())*(Math.random()*.4+.8)-(aresChar.getMagic()*aresChar.armor.getMagic()/100)); } } if(aresAction == actionEnum.ATTACK) { if(aresChar.weapon.getStrength()!=0) { playerDamage = (int) ((aresChar.getStrength()+aresChar.weapon.getStrength())*(Math.random()*.4+.8)-(playerChar.getStrength()*playerChar.armor.getStrength()/100)); } if(aresChar.weapon.getMagic()!=0) { playerDamage = (int) ((aresChar.getMagic()+aresChar.weapon.getMagic())*(Math.random()*.4+.8)-(playerChar.getMagic()*playerChar.armor.getMagic()/100)); } if(aresChar.weapon.getAgility()!=0) { playerDamage = (int) ((aresChar.getAgility()+aresChar.weapon.getAgility())*(Math.random()*.4+.8)-(playerChar.getAgility()*playerChar.armor.getAgility()/100)); } } playerChar.setHealth(playerChar.getHealth() - playerDamage); aresChar.setHealth(aresChar.getHealth() - aresDamage); } else if(playerChar.getHealth()<1) { //mark the character as dead in the database updateCharacter(playerChar, true, out); return stateEnum.PROFILE; } else if(aresChar.getHealth()<1) return stateEnum.LEVEL_UP; } out.printf(startPage,accountName); out.printf(statsTable, playerChar.name, playerChar.getHealth(), playerChar.getStrength(), playerChar.getMagic(), playerChar.getAgility()); out.printf(equippedTable1, playerChar.weapon.getName(), playerChar.weapon.getStrength(), playerChar.weapon.getMagic(), playerChar.weapon.getAgility()); out.printf(equippedTable2, playerChar.armor.getName(), playerChar.armor.getStrength(), playerChar.armor.getMagic(), playerChar.armor.getAgility()); out.printf(betweenCharacters); out.printf(statsTable, aresChar.name, aresChar.getHealth(), aresChar.getStrength(), aresChar.getMagic(), aresChar.getAgility()); out.printf(equippedTable1, aresChar.weapon.getName(),aresChar.weapon.getStrength(), aresChar.weapon.getMagic(), aresChar.weapon.getAgility()); out.printf(equippedTable2, aresChar.armor.getName(), aresChar.armor.getStrength(), aresChar.armor.getMagic(), aresChar.armor.getAgility()); out.printf(afterTable); out.printf("<div>You have done %d damage to your opponent.\n Your opponent has done %d damage to you.</div>", aresDamage, playerDamage); if((playerChar.getHealth()>0) && (aresChar.getHealth()>0)) { out.printf(attackButton); for(int i=0; i < playerChar.itemsHeld.length;i++) { //change first string, the value parameter, to itemId out.printf("<option value = \"%s\"> %s </option> \n", playerChar.itemsHeld[i].getName(),playerChar.itemsHeld[i].getName()); } out.printf(useButton); } else if(playerChar.getHealth()<1) { out.printf("The valiant hero has been killed. <br />\n"); out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n"); } else if(aresChar.getHealth()<1) { int newGold = (int) (constantGoldPerLevel*playerChar.getLevel()*(Math.random()*.4+.8)); gold+=newGold; updateGold(out); playerChar.setHealth(playerChar.getMaxHealth()); out.printf("Congradulations you beat your enemy.\n You get %d gold.\n", newGold); out.printf("<input type=\"submit\" name=\"OK\" value=\"OK\" class=\"profileButton\" /> \n"); } out.printf(lastPart); return stateEnum.BATTLE; }
diff --git a/src/edu/unsw/comp9321/assign2/AuctionBuilder.java b/src/edu/unsw/comp9321/assign2/AuctionBuilder.java index db57f8f..7f7947e 100644 --- a/src/edu/unsw/comp9321/assign2/AuctionBuilder.java +++ b/src/edu/unsw/comp9321/assign2/AuctionBuilder.java @@ -1,110 +1,110 @@ package edu.unsw.comp9321.assign2; import java.sql.*; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AuctionBuilder { ConnectionManager cm; Connection c; PreparedStatement auction; // insert item String auctionString; public AuctionBuilder() { cm = new ConnectionManager(); c = cm.getConnection(); auctionString = "INSERT INTO auction (username, starttime, " + "auctionlength, status, title, category, " + "picture, description, postagedetails, " + "startingprice, reserveprice, bidincrement)" + "VALUES (?, ?, ?, 'new', ?, ?, ?, ?, ?, ?, ?, ?)"; // prepare statement try { auction = c.prepareStatement(auctionString); } catch (SQLException s) { System.out.println("An error occured initialising query"); s.printStackTrace(); } } /* * Adds auction to database and sends confirmation email * calls addToItem * calls addToAuction */ public void createAuction(HttpServletRequest request, HttpServletResponse response) { /*This version does not yet allow for pictures to be added*/ System.out.println("createAuction called"); try { auction.setString(1, "user1"); auction.setString(2, request.getParameter("start")); if (request.getParameter("biddingHours").equals("")) { - auction.setString(3, "10"); System.out.println("empty length default to 10"); + auction.setInt(3, 10); System.out.println("empty length default to 10"); } - if (Integer.parseInt(request.getParameter("biddingHours")) < 3 || - Integer.parseInt(request.getParameter("biddingHours")) > 60) { + else if (Integer.parseInt(request.getParameter("biddingHours")) < 3 || + Integer.parseInt(request.getParameter("biddingHours")) > 60) { System.out.println("auction length is invalid"); redirectFailedAttempt(request, response); } else { auction.setString(3, request.getParameter("length"));System.out.println("specified length"); } auction.setString(4, request.getParameter("title")); auction.setString(5, request.getParameter("category")); auction.setString(6, request.getParameter("picture")); auction.setString(7, request.getParameter("description")); auction.setString(8, request.getParameter("postage")); auction.setString(9, request.getParameter("startingPrice")); auction.setString(10, request.getParameter("reservePrice")); auction.setString(11, request.getParameter("biddingIncrements")); int result = auction.executeUpdate(); if (result > 0) { System.out.println("successfully added auction"); RequestDispatcher rd = request.getRequestDispatcher("Success.jsp"); try { rd.forward(request, response); } catch (Exception e) { } } else { redirectFailedAttempt(request, response); } } catch (SQLException s) { System.out.println("An error occured querying the database"); s.printStackTrace(); redirectFailedAttempt(request, response); } return; } /* * Initiates auction * sets start time * how to track auction not yet implemented - will need to initialize tracking */ public void confirm() { // rename to startAuction if needed } private void redirectFailedAttempt(HttpServletRequest request, HttpServletResponse response) { try { RequestDispatcher rdFailed = request.getRequestDispatcher("BidRegistration.jsp"); rdFailed.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } }
false
true
public void createAuction(HttpServletRequest request, HttpServletResponse response) { /*This version does not yet allow for pictures to be added*/ System.out.println("createAuction called"); try { auction.setString(1, "user1"); auction.setString(2, request.getParameter("start")); if (request.getParameter("biddingHours").equals("")) { auction.setString(3, "10"); System.out.println("empty length default to 10"); } if (Integer.parseInt(request.getParameter("biddingHours")) < 3 || Integer.parseInt(request.getParameter("biddingHours")) > 60) { System.out.println("auction length is invalid"); redirectFailedAttempt(request, response); } else { auction.setString(3, request.getParameter("length"));System.out.println("specified length"); } auction.setString(4, request.getParameter("title")); auction.setString(5, request.getParameter("category")); auction.setString(6, request.getParameter("picture")); auction.setString(7, request.getParameter("description")); auction.setString(8, request.getParameter("postage")); auction.setString(9, request.getParameter("startingPrice")); auction.setString(10, request.getParameter("reservePrice")); auction.setString(11, request.getParameter("biddingIncrements")); int result = auction.executeUpdate(); if (result > 0) { System.out.println("successfully added auction"); RequestDispatcher rd = request.getRequestDispatcher("Success.jsp"); try { rd.forward(request, response); } catch (Exception e) { } } else { redirectFailedAttempt(request, response); } } catch (SQLException s) { System.out.println("An error occured querying the database"); s.printStackTrace(); redirectFailedAttempt(request, response); } return; }
public void createAuction(HttpServletRequest request, HttpServletResponse response) { /*This version does not yet allow for pictures to be added*/ System.out.println("createAuction called"); try { auction.setString(1, "user1"); auction.setString(2, request.getParameter("start")); if (request.getParameter("biddingHours").equals("")) { auction.setInt(3, 10); System.out.println("empty length default to 10"); } else if (Integer.parseInt(request.getParameter("biddingHours")) < 3 || Integer.parseInt(request.getParameter("biddingHours")) > 60) { System.out.println("auction length is invalid"); redirectFailedAttempt(request, response); } else { auction.setString(3, request.getParameter("length"));System.out.println("specified length"); } auction.setString(4, request.getParameter("title")); auction.setString(5, request.getParameter("category")); auction.setString(6, request.getParameter("picture")); auction.setString(7, request.getParameter("description")); auction.setString(8, request.getParameter("postage")); auction.setString(9, request.getParameter("startingPrice")); auction.setString(10, request.getParameter("reservePrice")); auction.setString(11, request.getParameter("biddingIncrements")); int result = auction.executeUpdate(); if (result > 0) { System.out.println("successfully added auction"); RequestDispatcher rd = request.getRequestDispatcher("Success.jsp"); try { rd.forward(request, response); } catch (Exception e) { } } else { redirectFailedAttempt(request, response); } } catch (SQLException s) { System.out.println("An error occured querying the database"); s.printStackTrace(); redirectFailedAttempt(request, response); } return; }
diff --git a/src/java/davmail/smtp/SmtpConnection.java b/src/java/davmail/smtp/SmtpConnection.java index 2ebeef1..f368063 100644 --- a/src/java/davmail/smtp/SmtpConnection.java +++ b/src/java/davmail/smtp/SmtpConnection.java @@ -1,218 +1,218 @@ /* * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway * Copyright (C) 2009 Mickael Guessant * * 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 davmail.smtp; import davmail.AbstractConnection; import davmail.BundleMessage; import davmail.exception.DavMailException; import davmail.exchange.ExchangeSessionFactory; import davmail.ui.tray.DavGatewayTray; import javax.mail.internet.InternetAddress; import javax.mail.internet.AddressException; import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.util.Date; import java.util.StringTokenizer; import java.util.List; import java.util.ArrayList; /** * Dav Gateway smtp connection implementation */ public class SmtpConnection extends AbstractConnection { /** * Initialize the streams and start the thread. * * @param clientSocket SMTP client socket */ public SmtpConnection(Socket clientSocket) { super(SmtpConnection.class.getSimpleName(), clientSocket, null); } @Override public void run() { String line; StringTokenizer tokens; List<String> recipients = new ArrayList<String>(); try { ExchangeSessionFactory.checkConfig(); sendClient("220 DavMail SMTP ready at " + new Date()); for (; ;) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new StringTokenizer(line); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); if (state == State.LOGIN) { // AUTH LOGIN, read userName userName = base64Decode(line); sendClient("334 " + base64Encode("Password:")); state = State.PASSWORD; } else if (state == State.PASSWORD) { // AUTH LOGIN, read password password = base64Decode(line); authenticate(); } else if ("QUIT".equalsIgnoreCase(command)) { sendClient("221 Closing connection"); break; } else if ("EHLO".equalsIgnoreCase(command)) { sendClient("250-" + tokens.nextToken()); // inform server that AUTH is supported // actually it is mandatory (only way to get credentials) sendClient("250-AUTH LOGIN PLAIN"); sendClient("250 Hello"); } else if ("HELO".equalsIgnoreCase(command)) { sendClient("250 Hello"); } else if ("AUTH".equalsIgnoreCase(command)) { if (tokens.hasMoreElements()) { String authType = tokens.nextToken(); if ("PLAIN".equalsIgnoreCase(authType) && tokens.hasMoreElements()) { decodeCredentials(tokens.nextToken()); authenticate(); } else if ("LOGIN".equalsIgnoreCase(authType)) { sendClient("334 " + base64Encode("Username:")); state = State.LOGIN; } else { sendClient("451 Error : unknown authentication type"); } } else { sendClient("451 Error : authentication type not specified"); } } else if ("MAIL".equalsIgnoreCase(command)) { if (state == State.AUTHENTICATED) { state = State.STARTMAIL; recipients.clear(); sendClient("250 Sender OK"); } else { state = State.INITIAL; sendClient("503 Bad sequence of commands"); } } else if ("RCPT".equalsIgnoreCase(command)) { if (state == State.STARTMAIL || state == State.RECIPIENT) { - if (line.startsWith("RCPT TO:")) { + if (line.toUpperCase().startsWith("RCPT TO:")) { state = State.RECIPIENT; try { InternetAddress internetAddress = new InternetAddress(line.substring("RCPT TO:".length())); recipients.add(internetAddress.getAddress()); } catch (AddressException e) { throw new DavMailException("EXCEPTION_INVALID_RECIPIENT", line); } sendClient("250 Recipient OK"); } else { sendClient("500 Unrecognized command"); } } else { state = State.AUTHENTICATED; sendClient("503 Bad sequence of commands"); } } else if ("DATA".equalsIgnoreCase(command)) { if (state == State.RECIPIENT) { state = State.MAILDATA; sendClient("354 Start mail input; end with <CRLF>.<CRLF>"); try { session.sendMessage(recipients, in); state = State.AUTHENTICATED; sendClient("250 Queued mail for delivery"); } catch (Exception e) { DavGatewayTray.error(e); state = State.AUTHENTICATED; sendClient("451 Error : " + e + ' ' + e.getMessage()); } } else { state = State.AUTHENTICATED; sendClient("503 Bad sequence of commands"); } } } else { sendClient("500 Unrecognized command"); } os.flush(); } } catch (SocketException e) { DavGatewayTray.debug(new BundleMessage("LOG_CONNECTION_CLOSED")); } catch (Exception e) { DavGatewayTray.log(e); try { sendClient("500 " + ((e.getMessage()==null)?e:e.getMessage())); } catch (IOException e2) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); } /** * Create authenticated session with Exchange server * * @throws IOException on error */ protected void authenticate() throws IOException { try { session = ExchangeSessionFactory.getInstance(userName, password); sendClient("235 OK Authenticated"); state = State.AUTHENTICATED; } catch (Exception e) { DavGatewayTray.error(e); String message = e.getMessage(); if (message == null) { message = e.toString(); } message = message.replaceAll("\\n", " "); sendClient("554 Authenticated failed " + message); state = State.INITIAL; } } /** * Decode SMTP credentials * * @param encodedCredentials smtp encoded credentials * @throws IOException if invalid credentials */ protected void decodeCredentials(String encodedCredentials) throws IOException { String decodedCredentials = base64Decode(encodedCredentials); int index = decodedCredentials.indexOf((char) 0, 1); if (index > 0) { userName = decodedCredentials.substring(1, index); password = decodedCredentials.substring(index + 1); } else { throw new DavMailException("EXCEPTION_INVALID_CREDENTIALS"); } } }
true
true
public void run() { String line; StringTokenizer tokens; List<String> recipients = new ArrayList<String>(); try { ExchangeSessionFactory.checkConfig(); sendClient("220 DavMail SMTP ready at " + new Date()); for (; ;) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new StringTokenizer(line); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); if (state == State.LOGIN) { // AUTH LOGIN, read userName userName = base64Decode(line); sendClient("334 " + base64Encode("Password:")); state = State.PASSWORD; } else if (state == State.PASSWORD) { // AUTH LOGIN, read password password = base64Decode(line); authenticate(); } else if ("QUIT".equalsIgnoreCase(command)) { sendClient("221 Closing connection"); break; } else if ("EHLO".equalsIgnoreCase(command)) { sendClient("250-" + tokens.nextToken()); // inform server that AUTH is supported // actually it is mandatory (only way to get credentials) sendClient("250-AUTH LOGIN PLAIN"); sendClient("250 Hello"); } else if ("HELO".equalsIgnoreCase(command)) { sendClient("250 Hello"); } else if ("AUTH".equalsIgnoreCase(command)) { if (tokens.hasMoreElements()) { String authType = tokens.nextToken(); if ("PLAIN".equalsIgnoreCase(authType) && tokens.hasMoreElements()) { decodeCredentials(tokens.nextToken()); authenticate(); } else if ("LOGIN".equalsIgnoreCase(authType)) { sendClient("334 " + base64Encode("Username:")); state = State.LOGIN; } else { sendClient("451 Error : unknown authentication type"); } } else { sendClient("451 Error : authentication type not specified"); } } else if ("MAIL".equalsIgnoreCase(command)) { if (state == State.AUTHENTICATED) { state = State.STARTMAIL; recipients.clear(); sendClient("250 Sender OK"); } else { state = State.INITIAL; sendClient("503 Bad sequence of commands"); } } else if ("RCPT".equalsIgnoreCase(command)) { if (state == State.STARTMAIL || state == State.RECIPIENT) { if (line.startsWith("RCPT TO:")) { state = State.RECIPIENT; try { InternetAddress internetAddress = new InternetAddress(line.substring("RCPT TO:".length())); recipients.add(internetAddress.getAddress()); } catch (AddressException e) { throw new DavMailException("EXCEPTION_INVALID_RECIPIENT", line); } sendClient("250 Recipient OK"); } else { sendClient("500 Unrecognized command"); } } else { state = State.AUTHENTICATED; sendClient("503 Bad sequence of commands"); } } else if ("DATA".equalsIgnoreCase(command)) { if (state == State.RECIPIENT) { state = State.MAILDATA; sendClient("354 Start mail input; end with <CRLF>.<CRLF>"); try { session.sendMessage(recipients, in); state = State.AUTHENTICATED; sendClient("250 Queued mail for delivery"); } catch (Exception e) { DavGatewayTray.error(e); state = State.AUTHENTICATED; sendClient("451 Error : " + e + ' ' + e.getMessage()); } } else { state = State.AUTHENTICATED; sendClient("503 Bad sequence of commands"); } } } else { sendClient("500 Unrecognized command"); } os.flush(); } } catch (SocketException e) { DavGatewayTray.debug(new BundleMessage("LOG_CONNECTION_CLOSED")); } catch (Exception e) { DavGatewayTray.log(e); try { sendClient("500 " + ((e.getMessage()==null)?e:e.getMessage())); } catch (IOException e2) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); }
public void run() { String line; StringTokenizer tokens; List<String> recipients = new ArrayList<String>(); try { ExchangeSessionFactory.checkConfig(); sendClient("220 DavMail SMTP ready at " + new Date()); for (; ;) { line = readClient(); // unable to read line, connection closed ? if (line == null) { break; } tokens = new StringTokenizer(line); if (tokens.hasMoreTokens()) { String command = tokens.nextToken(); if (state == State.LOGIN) { // AUTH LOGIN, read userName userName = base64Decode(line); sendClient("334 " + base64Encode("Password:")); state = State.PASSWORD; } else if (state == State.PASSWORD) { // AUTH LOGIN, read password password = base64Decode(line); authenticate(); } else if ("QUIT".equalsIgnoreCase(command)) { sendClient("221 Closing connection"); break; } else if ("EHLO".equalsIgnoreCase(command)) { sendClient("250-" + tokens.nextToken()); // inform server that AUTH is supported // actually it is mandatory (only way to get credentials) sendClient("250-AUTH LOGIN PLAIN"); sendClient("250 Hello"); } else if ("HELO".equalsIgnoreCase(command)) { sendClient("250 Hello"); } else if ("AUTH".equalsIgnoreCase(command)) { if (tokens.hasMoreElements()) { String authType = tokens.nextToken(); if ("PLAIN".equalsIgnoreCase(authType) && tokens.hasMoreElements()) { decodeCredentials(tokens.nextToken()); authenticate(); } else if ("LOGIN".equalsIgnoreCase(authType)) { sendClient("334 " + base64Encode("Username:")); state = State.LOGIN; } else { sendClient("451 Error : unknown authentication type"); } } else { sendClient("451 Error : authentication type not specified"); } } else if ("MAIL".equalsIgnoreCase(command)) { if (state == State.AUTHENTICATED) { state = State.STARTMAIL; recipients.clear(); sendClient("250 Sender OK"); } else { state = State.INITIAL; sendClient("503 Bad sequence of commands"); } } else if ("RCPT".equalsIgnoreCase(command)) { if (state == State.STARTMAIL || state == State.RECIPIENT) { if (line.toUpperCase().startsWith("RCPT TO:")) { state = State.RECIPIENT; try { InternetAddress internetAddress = new InternetAddress(line.substring("RCPT TO:".length())); recipients.add(internetAddress.getAddress()); } catch (AddressException e) { throw new DavMailException("EXCEPTION_INVALID_RECIPIENT", line); } sendClient("250 Recipient OK"); } else { sendClient("500 Unrecognized command"); } } else { state = State.AUTHENTICATED; sendClient("503 Bad sequence of commands"); } } else if ("DATA".equalsIgnoreCase(command)) { if (state == State.RECIPIENT) { state = State.MAILDATA; sendClient("354 Start mail input; end with <CRLF>.<CRLF>"); try { session.sendMessage(recipients, in); state = State.AUTHENTICATED; sendClient("250 Queued mail for delivery"); } catch (Exception e) { DavGatewayTray.error(e); state = State.AUTHENTICATED; sendClient("451 Error : " + e + ' ' + e.getMessage()); } } else { state = State.AUTHENTICATED; sendClient("503 Bad sequence of commands"); } } } else { sendClient("500 Unrecognized command"); } os.flush(); } } catch (SocketException e) { DavGatewayTray.debug(new BundleMessage("LOG_CONNECTION_CLOSED")); } catch (Exception e) { DavGatewayTray.log(e); try { sendClient("500 " + ((e.getMessage()==null)?e:e.getMessage())); } catch (IOException e2) { DavGatewayTray.debug(new BundleMessage("LOG_EXCEPTION_SENDING_ERROR_TO_CLIENT"), e2); } } finally { close(); } DavGatewayTray.resetIcon(); }
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/editor/format/JFXReformatTask.java b/javafx.editor/src/org/netbeans/modules/javafx/editor/format/JFXReformatTask.java index c28c77b8..40e2489b 100644 --- a/javafx.editor/src/org/netbeans/modules/javafx/editor/format/JFXReformatTask.java +++ b/javafx.editor/src/org/netbeans/modules/javafx/editor/format/JFXReformatTask.java @@ -1,3828 +1,3834 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-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 * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. 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 * nbbuild/licenses/CDDL-GPL-2-CP. 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): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2008 Sun * Microsystems, Inc. All Rights Reserved. * * 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 do not 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.netbeans.modules.javafx.editor.format; import com.sun.javafx.api.JavafxBindStatus; import com.sun.javafx.api.tree.*; import com.sun.javafx.api.tree.Tree.JavaFXKind; import com.sun.javafx.api.tree.UnitTree; import com.sun.tools.javafx.tree.*; import java.io.*; import java.util.*; import javax.lang.model.element.Name; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import org.netbeans.api.javafx.editor.FXSourceUtils; import org.netbeans.api.javafx.lexer.JFXTokenId; import org.netbeans.api.javafx.source.*; import org.netbeans.api.lexer.*; import org.netbeans.modules.editor.indent.spi.Context; import org.netbeans.modules.editor.indent.spi.ExtraLock; import org.netbeans.modules.editor.indent.spi.ReformatTask; import org.netbeans.modules.javafx.editor.format.CodeStyle.WrapStyle; import org.openide.cookies.EditorCookie; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; /** * This code based on org.netbeans.modules.java.source.save.Reformatter written by Dusan Balek. * * @see org.netbeans.modules.java.source.save.Reformatter * @see http://openjfx.java.sun.com/job/openjfx-compiler-nightly/lastSuccessfulBuild/artifact/dist/doc/reference/JavaFXReference.html * @author Anton Chechel */ public class JFXReformatTask implements ReformatTask { private static final Object CT_HANDLER_DOC_PROPERTY = "code-template-insert-handler"; // NOI18N private static final String NEWLINE = "\n"; //NOI18N private static final String LCBRACE = "{"; //NOI18N private static final String RCBRACE = "}"; //NOI18N private static final String MAGIC_FUNCTION = "javafx$run$"; //NOI18N private final Context context; private CompilationController controller; private Document doc; private int shift; public JFXReformatTask(Context context) { this.context = context; this.doc = context.document(); } public void reformat() throws BadLocationException { if (controller == null) { try { final JavaFXSource source = JavaFXSource.forDocument(context.document()); source.runUserActionTask(new Task<CompilationController>() { public void run(CompilationController controller) throws Exception { JFXReformatTask.this.controller = controller; } }, true); if (controller == null) { return; } if (controller.toPhase(JavaFXSource.Phase.PARSED).lessThan(JavaFXSource.Phase.PARSED)) { return; } } catch (Exception ex) { controller = null; return; } } CodeStyle cs = CodeStyle.getDefault(doc); for (Context.Region region : context.indentRegions()) { reformatImpl(region, cs); } } // to be invoked from formatting settings // TODO optimize it and refactor public static String reformat(final String text, final CodeStyle style) { final StringBuilder sb = new StringBuilder(text); try { final File file = FileUtil.normalizeFile( File.createTempFile("format", "tmp")); // NOI18N FileOutputStream os = null; InputStream is = null; try { os = new FileOutputStream(file); is = new ByteArrayInputStream(text.getBytes("UTF-8")); // NOI18N FileUtil.copy(is, os); } finally { if (os != null) { os.close(); } if (is != null) { is.close(); } } FileObject fObj = FileUtil.toFileObject(file); DataObject dObj = DataObject.find(fObj); EditorCookie ec = (EditorCookie) dObj.getCookie(EditorCookie.class); Document doc = ec.openDocument(); doc.putProperty(Language.class, JFXTokenId.language()); doc.putProperty("mimeType", FXSourceUtils.MIME_TYPE); // NOI18N JavaFXSource src = JavaFXSource.forDocument(doc); src.runUserActionTask(new Task<CompilationController>() { public void run(CompilationController controller) throws Exception { if (controller != null && !controller.toPhase(JavaFXSource.Phase.PARSED).lessThan(JavaFXSource.Phase.PARSED)) { TokenSequence<JFXTokenId> tokens = TokenHierarchy.create(text, JFXTokenId.language()).tokenSequence(JFXTokenId.language()); UnitTree tree = controller.getCompilationUnit(); for (Diff diff : Pretty.reformat(controller, text, tokens, new JavaFXTreePath(tree), style)) { int start = diff.getStartOffset(); int end = diff.getEndOffset(); sb.delete(start, end); String t = diff.getText(); if (t != null && t.length() > 0) { sb.insert(start, t); } } } } }, true); } catch (Exception ex) { } return sb.toString(); } private void reformatImpl(Context.Region region, CodeStyle cs) throws BadLocationException { boolean templateEdit = doc.getProperty(CT_HANDLER_DOC_PROPERTY) != null; int startOffset = region.getStartOffset() - shift; int endOffset = region.getEndOffset() - shift; int originalEndOffset = endOffset; startOffset = controller.getSnapshot().getEmbeddedOffset(startOffset); if (startOffset < 0) { return; } endOffset = controller.getSnapshot().getEmbeddedOffset(endOffset); if (endOffset < 0) { return; } if (startOffset >= endOffset) { return; } JavaFXTreePath path = getCommonPath(startOffset); if (path == null) { return; } for (Diff diff : Pretty.reformat(controller, path, cs, startOffset, endOffset, templateEdit)) { int start = diff.getStartOffset(); int end = diff.getEndOffset(); String text = diff.getText(); if (startOffset > end) { continue; } if (endOffset < start) { continue; } if (endOffset == start && (text == null || !text.trim().equals(RCBRACE))) { continue; } if (startOffset >= start) { if (text != null && text.length() > 0) { TokenSequence<JFXTokenId> ts = controller.getTokenHierarchy().tokenSequence(JFXTokenId.language()); if (ts == null) { continue; } if (ts.move(startOffset) == 0) { if (!ts.movePrevious() && !ts.moveNext()) { continue; } } else { if (!ts.moveNext() && !ts.movePrevious()) { continue; } } if (ts.token().id() == JFXTokenId.WS) { // JavaFX diffenerce int tsOffset = ts.offset(); StringBuilder t1 = new StringBuilder(); do { t1.append(ts.token().text().toString()); } while (ts.moveNext() && ts.token().id() == JFXTokenId.WS); String t = t1.toString(); // String t = ts.token().text().toString(); t = t.substring(0, startOffset - tsOffset); if (templateEdit) { int idx = t.lastIndexOf(NEWLINE); if (idx >= 0) { t = t.substring(idx + 1); idx = text.lastIndexOf(NEWLINE); if (idx >= 0) { text = text.substring(idx + 1); } if (text.trim().length() > 0) { text = null; } else if (text.length() > t.length()) { text = text.substring(t.length()); } else { text = null; } } else { text = null; } } else { int idx1 = 0; int idx2 = 0; int lastIdx1 = 0; int lastIdx2 = 0; while ((idx1 = t.indexOf(NEWLINE, lastIdx1)) >= 0 && (idx2 = text.indexOf(NEWLINE, lastIdx2)) >= 0) { lastIdx1 = idx1 + 1; lastIdx2 = idx2 + 1; } if ((idx2 = text.lastIndexOf(NEWLINE)) >= 0 && idx2 >= lastIdx2) { if (lastIdx1 == 0) { t = null; } else { text = text.substring(idx2 + 1); t = t.substring(lastIdx1); } } else if ((idx1 = t.lastIndexOf(NEWLINE)) >= 0 && idx1 >= lastIdx1) { t = t.substring(idx1 + 1); text = text.substring(lastIdx2); } else { t = t.substring(lastIdx1); text = text.substring(lastIdx2); } if (text != null && t != null) { text = text.length() > t.length() ? text.substring(t.length()) : null; } } } else if (templateEdit) { text = null; } } start = startOffset; } if (endOffset < end) { if (text != null && text.length() > 0 && !templateEdit) { TokenSequence<JFXTokenId> ts = controller.getTokenHierarchy().tokenSequence(JFXTokenId.language()); if (ts != null) { ts.move(endOffset); if (ts.moveNext() && ts.token().id() == JFXTokenId.WS) { // JavaFX diffenerce int tsOffset = ts.offset(); StringBuilder t1 = new StringBuilder(); do { t1.append(ts.token().text().toString()); } while (ts.moveNext() && ts.token().id() == JFXTokenId.WS); String t = t1.toString(); // String t = ts.token().text().toString(); t = t.substring(endOffset - tsOffset); int idx1, idx2; while ((idx1 = t.lastIndexOf(NEWLINE)) >= 0 && (idx2 = text.lastIndexOf(NEWLINE)) >= 0) { t = t.substring(0, idx1); text = text.substring(0, idx2); } text = text.length() > t.length() ? text.substring(0, text.length() - t.length()) : null; } } } end = endOffset; } start = controller.getSnapshot().getOriginalOffset(start); end = controller.getSnapshot().getOriginalOffset(end); start += shift; end += shift; doc.remove(start, end - start); if (text != null && text.length() > 0) { doc.insertString(start, text, null); } } shift = region.getEndOffset() - originalEndOffset; return; } public ExtraLock reformatLock() { return JavaFXReformatExtraLock.getInstance(); } private JavaFXTreePath getCommonPath(final int offset) { JavaFXTreePath path = controller.getTreeUtilities().pathFor(offset); if (offset > 0) { if (path.getLeaf() instanceof FunctionValueTree) { path = path.getParentPath(); } } else { while (path.getParentPath() != null) { path = path.getParentPath(); } } return path; } private static class TreePosComparator implements Comparator<Tree> { private final SourcePositions sp; private final UnitTree ut; public TreePosComparator(SourcePositions sp, UnitTree ut) { this.sp = sp; this.ut = ut; } public int compare(Tree t1, Tree t2) { long t1p = sp.getStartPosition(ut, t1); long t2p = sp.getStartPosition(ut, t2); if (t1p == t2p) { t1p = sp.getEndPosition(ut, t1); t2p = sp.getEndPosition(ut, t2); } if (t1p == t2p) { t1p = t1.hashCode(); t2p = t2.hashCode(); } return (t1p < t2p ? -1 : (t1p == t2p ? 0 : 1)); // long diff = sp.getStartPosition(ut, t2) - sp.getStartPosition(ut, t1); // if (diff == 0) { // diff = sp.getEndPosition(ut, t1) - sp.getEndPosition(ut, t2); // } // return (int) diff; } } /* * This scanner places trees in correct order how they presented actually in the source code. * @see JFXC-3633 */ private static class FilterScanner<R,P> extends JavaFXTreePathScanner<R, P> { private CompilationInfo ci; private TreeSet<Tree> displaced; public FilterScanner(final CompilationInfo ci) { this.ci = ci; displaced = new TreeSet<Tree>(new TreePosComparator(ci.getTrees().getSourcePositions(), ci.getCompilationUnit())); ci.getCompilationUnit().accept(new JavaFXTreeScanner<Void, Void>() { int state = 0; public @Override Void scan(Tree node, Void p) { if (state == 4) {// FUNCTION_DEFINITION -> FUNCTION_VALUE -> BLOCK_EXPRESSION state = 0; addTree(node); super.scan(node, p); state = 4; return null; } else { // or CLASS_DECLARATION->VARIABLE(static) // or CLASS_DECLARATION->FUNCTION_DEFINITION(static) return super.scan(node, p); } } public @Override Void visitClassDeclaration(ClassDeclarationTree node, Void p) { int oldState = state; state = 1; super.visitClassDeclaration(node, p); state = oldState; return null; } // TODO get "static" via flags when they will work in compiler public @Override Void visitVariable(VariableTree node, Void p) { if (state == 1 && node.getModifiers().toString().contains("static")) { // NOI18N addTree(node); } return super.visitVariable(node, p); } // TODO get "static" via flags when they will work in compiler public @Override Void visitFunctionDefinition(FunctionDefinitionTree node, Void p) { JFXFunctionDefinition funcDef = (JFXFunctionDefinition) node; boolean magicFunc = MAGIC_FUNCTION.contentEquals(funcDef.getName()) && isSynthetic(funcDef); int oldState = state; if (state == 1) { if (magicFunc) { state = 2; } else if (node.getModifiers().toString().contains("static")) { // NOI18N addTree(node); } } super.visitFunctionDefinition(node, p); state = oldState; return null; } public @Override Void visitFunctionValue(FunctionValueTree node, Void p) { int oldState = state; if (state == 2) { state = 3; } super.visitFunctionValue(node, p); state = oldState; return null; } public @Override Void visitBlockExpression(BlockExpressionTree node, Void p) { int oldState = state; if (state == 3) { state = 4; } super.visitBlockExpression(node, p); state = oldState; return null; } private void addTree(Tree tree) { if (!isSynthetic(tree)) { displaced.add(tree); } } }, null); } // public @Override R scan(Tree tree, P p) { // if (displaced.contains(tree)) { // return null; // } else { // return super.scan(tree, p); // } // } // // public R myScan(Tree tree, P p) { // return super.scan(tree, p); // } // // private R myScan(Iterable<? extends Tree> nodes, P p) { // R r = null; // if (nodes != null) { // boolean first = true; // for (Tree node : nodes) { // r = (first ? super.scan(node, p) : reduce(super.scan(nodes, p), r)); // first = false; // } // } // return r; // } SortedSet<Tree> getCUTrees(UnitTree node) { TreeSet<Tree> cuTrees = (TreeSet<Tree>) displaced.clone(); // toNotify.add(node.getPackageName()); cuTrees.addAll(node.getImports()); final List<? extends Tree> typeDecls = node.getTypeDecls(); Tree topLevelClass = null; for (Tree tree : typeDecls) { // assume FXScript has only 1 top level class and it's named as a file (nice FX feature) if (tree.getJavaFXKind() == JavaFXKind.CLASS_DECLARATION) { topLevelClass = tree; if (!isSynthetic(tree)) { cuTrees.add(tree); } } } // other class declarations are children of top level (nice FX feature) if (topLevelClass != null) { List<Tree> members = ((ClassDeclarationTree) topLevelClass).getClassMembers(); for (Tree member : members) { if (member.getJavaFXKind() == JavaFXKind.CLASS_DECLARATION) { cuTrees.add(member); } } } return cuTrees; } private boolean isSynthetic(Tree node) { if (node instanceof BlockExpressionTree) { UnitTree cu = ci.getCompilationUnit(); final JavaFXTreePath path = ci.getTrees().getPath(cu, node); if (path == null) { return true; } JavaFXTreePath pp = path.getParentPath(); if (pp != null && pp instanceof FunctionValueTree) { pp = pp.getParentPath(); JFXTree tree = (JFXTree) pp.getLeaf(); if (tree instanceof FunctionDefinitionTree) { return synthetic(tree); } } } return synthetic((JFXTree) node); } private boolean synthetic(JFXTree node) { SourcePositions sp = ci.getTrees().getSourcePositions(); UnitTree cu = ci.getCompilationUnit(); long startPos = sp.getStartPosition(cu, node); long endPos = sp.getEndPosition(cu, node); return node.getGenType() == SyntheticTree.SynthType.SYNTHETIC || startPos == endPos; } // public @Override R visitCompilationUnit(UnitTree node, P p) { // SortedSet<Tree> toNotify = getCUTrees(node); // return myScan(toNotify, p); // } } private static class Pretty extends FilterScanner<Boolean, Void> { // private static class Pretty extends JavaFXTreePathScanner<Boolean, Void> { private static final String OPERATOR = "operator"; // NOI18N private static final String EMPTY = ""; // NOI18N private static final String SPACE = " "; // NOI18N private static final String ERROR = "<error>"; // NOI18N private static final String SEMI = ";"; // NOI18N private static final String WS_TEMPLATE = "\\s+"; // NOI18N private static final int ANY_COUNT = -1; // private final Document doc; private final String fText; private final CodeStyle cs; private final SourcePositions sp; private final UnitTree root; private final int rightMargin; private final int tabSize; private final int indentSize; private final int continuationIndentSize; private final boolean expandTabToSpaces; private TokenSequence<JFXTokenId> tokens; private int indent; private int col; private int endPos; private int wrapDepth; private int lastBlankLines; private int lastBlankLinesTokenIndex; private Diff lastBlankLinesDiff; private boolean templateEdit; private LinkedList<Diff> diffs = new LinkedList<Diff>(); private DanglingElseChecker danglingElseChecker = new DanglingElseChecker(); private int startOffset; private int endOffset; private SortedSet<Tree> cuTrees; private Pretty(CompilationInfo info, JavaFXTreePath path, CodeStyle cs, int startOffset, int endOffset, boolean templateEdit) { this(info, FXSourceUtils.getText(info), info.getTokenHierarchy().tokenSequence(JFXTokenId.language()), path, cs, startOffset, endOffset); this.templateEdit = templateEdit; } private Pretty(CompilationInfo info, String text, TokenSequence<JFXTokenId> tokens, JavaFXTreePath path, CodeStyle cs, int startOffset, int endOffset) { super(info); // this.doc = info.getDocument(); this.root = path.getCompilationUnit(); this.fText = text; this.sp = info.getTrees().getSourcePositions(); this.cs = cs; this.rightMargin = cs.getRightMargin(); this.tabSize = cs.getTabSize(); this.indentSize = cs.getIndentSize(); this.continuationIndentSize = cs.getContinuationIndentSize(); this.expandTabToSpaces = cs.expandTabToSpaces(); this.wrapDepth = 0; this.lastBlankLines = -1; this.lastBlankLinesTokenIndex = -1; this.lastBlankLinesDiff = null; Tree tree = path.getLeaf(); this.indent = tokens != null ? getIndentLevel(tokens, path) : 0; this.col = this.indent; this.tokens = tokens; if (tree.getJavaFXKind() == JavaFXKind.COMPILATION_UNIT) { tokens.moveEnd(); tokens.movePrevious(); } else { tokens.move((int) getEndPos(tree)); if (!tokens.moveNext()) { tokens.movePrevious(); } } this.endPos = tokens.offset(); if (tree.getJavaFXKind() == JavaFXKind.COMPILATION_UNIT) { tokens.moveStart(); } else { tokens.move((int) sp.getStartPosition(path.getCompilationUnit(), tree)); } tokens.moveNext(); this.startOffset = startOffset; this.endOffset = endOffset; } public static LinkedList<Diff> reformat(CompilationInfo info, JavaFXTreePath path, CodeStyle cs, int startOffset, int endOffset, boolean templateEdit) { Pretty pretty = new Pretty(info, path, cs, startOffset, endOffset, templateEdit); if (pretty.indent >= 0) { pretty.scan(path, null); } if (path.getLeaf().getJavaFXKind() == JavaFXKind.COMPILATION_UNIT) { pretty.tokens.moveEnd(); pretty.tokens.movePrevious(); if (pretty.tokens.token().id() != JFXTokenId.WS || pretty.tokens.token().text().toString().indexOf(NEWLINE) < 0) { String text = FXSourceUtils.getText(info); pretty.diffs.addFirst(new Diff(text.length(), text.length(), NEWLINE)); } } return pretty.diffs; } public static LinkedList<Diff> reformat(CompilationInfo info, String text, TokenSequence<JFXTokenId> tokens, JavaFXTreePath path, CodeStyle cs) { Pretty pretty = new Pretty(info, text, tokens, path, cs, 0, text.length()); pretty.scan(path, null); tokens.moveEnd(); tokens.movePrevious(); if (tokens.token().id() != JFXTokenId.WS || tokens.token().text().toString().indexOf(NEWLINE) < 0) { pretty.diffs.addFirst(new Diff(text.length(), text.length(), NEWLINE)); } return pretty.diffs; } /// === /// === START OF THE VISITOR IMPLEMENTATION /// === @Override public Boolean scan(Tree tree, Void p) { if (tree == null) { return false; } int lastEndPos = endPos; if (tree != null && tree.getJavaFXKind() != JavaFXKind.COMPILATION_UNIT) { if (tree instanceof FakeBlock) { endPos = Integer.MAX_VALUE; } else { endPos = (int) getEndPos(tree); // final int _startOffset = doc.getStartPosition().getOffset(); // final int _endOffset = doc.getEndPosition().getOffset(); // if (endPos > _startOffset && endPos < _endOffset + 1) { // try { // int i = 0; // String txt = null; // do { // txt = doc.getText(endPos + i, 1); // i++; // // TODO remove it after missing semi-colon and missing parenthesis fixes in parser // } while ((txt.matches(WS_TEMPLATE) || txt.matches("\\)")) && i < _endOffset - _startOffset); // NOI18N //// } while (txt.matches(WS_TEMPLATE) && i < _endOffset - _startOffset); // NOI18N // if (SEMI.equals(txt) || RCBRACE.equals(txt) || LCBRACE.equals(txt)) { //// endPos += i; // } // } catch (BadLocationException ex) { // } // } } } try { if (endPos < 0) { return false; } if (tokens.offset() <= endPos) { final Boolean scan = super.scan(tree, p); // final Boolean scan = super.myScan(tree, p); return scan != null ? scan : false; } return true; } finally { endPos = lastEndPos; } } @Override public Boolean visitCompilationUnit(UnitTree node, Void p) { ExpressionTree pkg = node.getPackageName(); if (pkg != null) { blankLines(cs.getBlankLinesBeforePackage()); accept(JFXTokenId.PACKAGE); int old = indent; indent += continuationIndentSize; space(); scan(pkg, p); accept(JFXTokenId.SEMI); indent = old; blankLines(cs.getBlankLinesAfterPackage()); } // imports in javafx could be where ever // TODO remove cs.getBlankLinesBeforeImports() from settings therefore cuTrees = getCUTrees(node); if (cuTrees != null && !cuTrees.isEmpty()) { // TODO process semicolon between members and expressions // boolean semiRead = false; final Tree[] treeArray = (Tree[]) cuTrees.toArray(new Tree[cuTrees.size()]); for (int i = 0; i < treeArray.length; i++) { Tree tree = treeArray[i]; boolean isLastInCU = i == treeArray.length - 1; JavaFXKind kind = tree.getJavaFXKind(); switch (kind) { case IMPORT: blankLines(); scan(tree, p); if (!isLastInCU && isLastMemberOfSuchKind(i, treeArray, kind)) { blankLines(cs.getBlankLinesAfterImports()); } break; case CLASS_DECLARATION: blankLines(cs.getBlankLinesBeforeClass()); scan(tree, p); if (!isLastInCU) { blankLines(cs.getBlankLinesAfterClass()); } break; case VARIABLE: if (isFirstMemberOfSuchKind(i, treeArray, kind)) { blankLines(cs.getBlankLinesBeforeFields()); } processClassMembers(Arrays.asList(new Tree[]{tree}), p, isLastInCU); if (!isLastInCU) { if (isLastMemberOfSuchKind(i, treeArray, kind)) { blankLines(cs.getBlankLinesAfterFields()); } blankLines(); } break; case INIT_DEFINITION: case POSTINIT_DEFINITION: case FUNCTION_DEFINITION: case FUNCTION_VALUE: case INSTANTIATE_OBJECT_LITERAL: blankLines(cs.getBlankLinesBeforeMethods()); processClassMembers(Arrays.asList(new Tree[]{tree}), p, isLastInCU); if (!isLastInCU) { blankLines(cs.getBlankLinesAfterMethods()); } break; default: if (isFirstMemberOfSuchKind(i, treeArray, kind)) { blankLines(1); } processClassMembers(Arrays.asList(new Tree[] {tree}), p, isLastInCU); if (!isLastInCU) { if (isLastMemberOfSuchKind(i, treeArray, kind)) { blankLines(1); } blankLines(); } } } } return true; } private static boolean isFirstMemberOfSuchKind(int i, final Tree[] treeArray, JavaFXKind kind) { return (i == 0) || (i > 0 && treeArray[i - 1].getJavaFXKind() != kind); } private static boolean isLastMemberOfSuchKind(int i, final Tree[] treeArray, JavaFXKind kind) { int l = treeArray.length; return (i == l - 1) || (i < l - 2 && treeArray[i + 1].getJavaFXKind() != kind); } @Override public Boolean visitInitDefinition(InitDefinitionTree node, Void p) { accept(JFXTokenId.INIT); space(); scan(node.getBody(), p); return true; } @Override public Boolean visitPostInitDefinition(InitDefinitionTree node, Void p) { accept(JFXTokenId.POSTINIT); space(); scan(node.getBody(), p); return true; } @Override public Boolean visitImport(ImportTree node, Void p) { accept(JFXTokenId.IMPORT); int old = indent; indent += continuationIndentSize; space(); scan(node.getQualifiedIdentifier(), p); accept(JFXTokenId.SEMI); indent = old; return true; } @Override public Boolean visitClassDeclaration(ClassDeclarationTree node, Void p) { // members without class belong to synthetic one boolean isClassSynthetic = isSynthetic((JFXTree) node); if (!isClassSynthetic) { int old = indent; ModifiersTree mods = node.getModifiers(); if (hasModifiers(mods)) { if (scan(mods, p)) { indent += continuationIndentSize; if (cs.placeNewLineAfterModifiers()) { newline(); } else { space(); } } } accept(JFXTokenId.CLASS, JFXTokenId.AT); if (indent == old) { indent += continuationIndentSize; } space(); if (!ERROR.contentEquals(node.getSimpleName())) { accept(JFXTokenId.IDENTIFIER); } List<ExpressionTree> exts = new ArrayList<ExpressionTree>(); exts.addAll(node.getExtends()); exts.addAll(node.getImplements()); exts.addAll(node.getMixins()); if (exts != null && !exts.isEmpty()) { wrapToken(cs.wrapExtendsImplementsKeyword(), -1, 1, JFXTokenId.EXTENDS); wrapExtendsList(cs.wrapExtendsImplementsList(), cs.alignMultilineImplements(), true, exts); // TODO cs.alignMultilineExtends() } indent = old; CodeStyle.BracePlacement bracePlacement = cs.getClassDeclBracePlacement(); boolean spaceBeforeLeftBrace = cs.spaceBeforeClassDeclLeftBrace(); old = indent; int halfIndent = indent; switch (bracePlacement) { case SAME_LINE: spaces(spaceBeforeLeftBrace ? 1 : 0); accept(JFXTokenId.LBRACE); indent += indentSize; break; case NEW_LINE: newline(); accept(JFXTokenId.LBRACE); indent += indentSize; break; case NEW_LINE_HALF_INDENTED: indent += (indentSize >> 1); halfIndent = indent; newline(); accept(JFXTokenId.LBRACE); indent = old + indentSize; break; case NEW_LINE_INDENTED: indent += indentSize; halfIndent = indent; newline(); accept(JFXTokenId.LBRACE); break; } boolean emptyClass = true; for (Tree member : node.getClassMembers()) { if (!isSynthetic((JFXTree) member)) { emptyClass = false; break; } } if (emptyClass) { newline(); } else { if (!cs.indentTopLevelClassMembers()) { indent = old; } blankLines(cs.getBlankLinesAfterClassHeader()); processClassMembers(node.getClassMembers(), p, false); if (lastBlankLinesTokenIndex < 0) { newline(); } } indent = halfIndent; processClassWS(); accept(JFXTokenId.RBRACE); indent = old; } else { processClassMembers(node.getClassMembers(), p, false); } return true; } private void processClassMembers(List<Tree> members, Void p, boolean isLastInCU) { boolean first = true; boolean semiRead = false; for (Tree member : members) { if (member.getJavaFXKind() == JavaFXKind.CLASS_DECLARATION && cuTrees != null && cuTrees.contains(member)) { // this class has been already processed in visitCompilationUnit() continue; } boolean magicFunc = false; if (member instanceof JFXFunctionDefinition) { String name = ((JFXFunctionDefinition) member).getName().toString(); magicFunc = MAGIC_FUNCTION.contentEquals(name) && isSynthetic((JFXTree) member); } if (magicFunc || !isSynthetic((JFXTree) member)) { switch (member.getJavaFXKind()) { case VARIABLE: boolean bool = tokens.moveNext(); if (bool) { tokens.movePrevious(); if (!first) { blankLines(cs.getBlankLinesBeforeFields()); } scan(member, p); if (!isLastInCU) { blankLines(cs.getBlankLinesAfterFields()); } } break; case FUNCTION_DEFINITION: case FUNCTION_VALUE: case INIT_DEFINITION: case POSTINIT_DEFINITION: if (!first) { blankLines(cs.getBlankLinesBeforeMethods()); } scan(member, p); int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) == JFXTokenId.SEMI) { semiRead = true; } else { rollback(index, c, d); semiRead = false; } if (!isLastInCU) { blankLines(cs.getBlankLinesAfterMethods()); } break; case BLOCK_EXPRESSION: final BlockExpressionTree blockExpTree = (BlockExpressionTree) member; boolean hasStatements = !(blockExpTree).getStatements().isEmpty(); boolean hasValue = (blockExpTree).getValue() != null; if (semiRead && !(blockExpTree).isStatic() && !hasStatements && !hasValue) { semiRead = false; continue; } if (!first) { blankLines(cs.getBlankLinesBeforeMethods()); } index = tokens.index(); c = col; d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) == JFXTokenId.SEMI) { continue; } else { rollback(index, c, d); } scan(member, p); if (!isLastInCU) { blankLines(cs.getBlankLinesAfterMethods()); } break; case INSTANTIATE_OBJECT_LITERAL: case CLASS_DECLARATION: if (!first) { blankLines(cs.getBlankLinesBeforeClass()); } scan(member, p); index = tokens.index(); c = col; d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) == JFXTokenId.SEMI) { semiRead = true; } else { rollback(index, c, d); semiRead = false; } if (!isLastInCU) { blankLines(cs.getBlankLinesAfterClass()); } break; default: scan(member, p); index = tokens.index(); c = col; d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) == JFXTokenId.SEMI) { semiRead = true; } else { rollback(index, c, d); semiRead = false; } } if (!magicFunc) { first = false; } } } } private void processClassWS() { Diff diff = diffs.isEmpty() ? null : diffs.getFirst(); if (diff != null && diff.end == tokens.offset()) { if (diff.text != null) { int idx = diff.text.lastIndexOf(NEWLINE); if (idx < 0) { diff.text = getIndent(); } else { diff.text = diff.text.substring(0, idx + 1) + getIndent(); } } String spaces = diff.text != null ? diff.text : getIndent(); if (spaces.equals(fText.substring(diff.start, diff.end))) { diffs.removeFirst(); } } else if (tokens.movePrevious()) { if (tokens.token().id() == JFXTokenId.WS) { String text = tokens.token().text().toString(); int idx = text.lastIndexOf(NEWLINE); if (idx >= 0) { text = text.substring(idx + 1); String ind = getIndent(); if (!ind.equals(text)) { addDiff(new Diff(tokens.offset() + idx + 1, tokens.offset() + tokens.token().length(), ind)); } } } tokens.moveNext(); } } @Override public Boolean visitVariable(VariableTree node, Void p) { if (isSynthetic((JFXTree) node)) { return false; } int old = indent; Tree parent = getCurrentPath().getParentPath().getLeaf(); boolean insideFor = parent.getJavaFXKind() == JavaFXKind.FOR_EXPRESSION_FOR; ModifiersTree mods = node.getModifiers(); if (hasModifiers(mods)) { if (scan(mods, p)) { if (!insideFor) { indent += continuationIndentSize; if (cs.placeNewLineAfterModifiers()) { newline(); } else { space(); } } else { space(); } } } if (indent == old && !insideFor) { indent += continuationIndentSize; } int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); JFXTokenId accepted = accept(JFXTokenId.DEF, JFXTokenId.VAR, JFXTokenId.ATTRIBUTE); // put space if this VAR is not parameter if (accepted != null) { space(); } else { rollback(index, c, d); } final Name name = node.getName(); if (name != null && !ERROR.contentEquals(name)) { accept(JFXTokenId.IDENTIFIER); } final Tree type = node.getType(); if (type != null && type.getJavaFXKind() != JavaFXKind.TYPE_UNKNOWN) { accept(JFXTokenId.COLON); spaces(cs.spaceAroundAssignOps() ? 1 : 0); // TODO space around colon in the type definition if (type instanceof TypeArrayTree) { index = tokens.index(); c = col; d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.NATIVEARRAY) == JFXTokenId.NATIVEARRAY) { space(); // accept(JFXTokenId.OF); accept(JFXTokenId.IDENTIFIER); // lexer bug? space(); } else { rollback(index, c, d); } } else if (type.getJavaFXKind() == JavaFXKind.TYPE_FUNCTIONAL) { accept(JFXTokenId.FUNCTION); spaces(cs.spaceBeforeMethodDeclParen() ? 1 : 0); } scan(type, p); } ExpressionTree initTree = node.getInitializer(); if (initTree != null) { int alignIndent = -1; if (cs.alignMultilineAssignment()) { alignIndent = col; if (!ERROR.contentEquals(name)) { alignIndent -= name.length(); } } spaces(cs.spaceAroundAssignOps() ? 1 : 0); accept(JFXTokenId.EQ); final JavafxBindStatus bindStatus = node.getBindStatus(); if (bindStatus.isUnidiBind() || bindStatus.isBidiBind()) { spaces(cs.spaceAroundAssignOps() ? 1 : 0); accept(JFXTokenId.BIND); } wrapTree(cs.wrapAssignOps(), alignIndent, cs.spaceAroundAssignOps() ? 1 : 0, initTree); if (bindStatus.isBidiBind()) { space(); accept(JFXTokenId.WITH); space(); accept(JFXTokenId.INVERSE); } } OnReplaceTree onReplaceTree = node.getOnReplaceTree(); if (onReplaceTree != null) { // TODO introduce cs.wrapOnReplace and invoke wrapTree spaces(1, true); scan(onReplaceTree, p); } index = tokens.index(); c = col; d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) != JFXTokenId.SEMI) { rollback(index, c, d); } indent = old; return true; } // TODO isInitialized Built-In Function @Override public Boolean visitFunctionDefinition(FunctionDefinitionTree node, Void p) { JFXFunctionDefinition funcDef = (JFXFunctionDefinition) node; boolean magicOverridenFunc = MAGIC_FUNCTION.contentEquals(funcDef.getName()); boolean magicFunc = magicOverridenFunc && isSynthetic(funcDef); // magic function processed in visitCompilationUnit() if (magicFunc) { return false; } int old = indent; // TODO work around for magic function modifiers compiler bug if (magicOverridenFunc) { // even more magic! // --- JFXTokenId id = null; while (tokens.offset() < endPos) { if (id != null) { space(); } int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); id = accept(JFXTokenId.PRIVATE, JFXTokenId.PACKAGE, JFXTokenId.PROTECTED, JFXTokenId.PUBLIC, JFXTokenId.PUBLIC_READ, JFXTokenId.PUBLIC_INIT, JFXTokenId.STATIC, JFXTokenId.ABSTRACT, JFXTokenId.NATIVEARRAY, JFXTokenId.AT, JFXTokenId.MIXIN, JFXTokenId.OVERRIDE); if (id == null) { rollback(index, c, d); break; } } // --- } else { ModifiersTree mods = funcDef.getModifiers(); if (hasModifiers(mods)) { if (scan(mods, p)) { indent += continuationIndentSize; if (cs.placeNewLineAfterModifiers()) { newline(); } else { space(); } } else { blankLines(); } } } accept(JFXTokenId.FUNCTION); space(); if (!ERROR.contentEquals(funcDef.getName())) { accept(JFXTokenId.IDENTIFIER); } if (indent == old) { indent += continuationIndentSize; } spaces(cs.spaceBeforeMethodDeclParen() ? 1 : 0); accept(JFXTokenId.LPAREN); List<? extends JFXVar> params = funcDef.getParams(); if (params != null && !params.isEmpty() && !magicOverridenFunc) { spaces(cs.spaceWithinMethodDeclParens() ? 1 : 0, true); wrapList(cs.wrapMethodParams(), cs.alignMultilineMethodParams(), false, params); spaces(cs.spaceWithinMethodDeclParens() ? 1 : 0); } accept(JFXTokenId.RPAREN); JFXType retType = funcDef.getJFXReturnType(); if (retType != null && retType.getJavaFXKind() != JavaFXKind.TYPE_UNKNOWN && !magicOverridenFunc) { accept(JFXTokenId.COLON); spaces(cs.spaceAroundAssignOps() ? 1 : 0); // TODO space around colon in the type definition scan(retType, p); } indent = old; JFXBlock body = funcDef.getBodyExpression(); if (body != null) { scan(body, p); // } else if (!magicFunc) { } else { int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) != JFXTokenId.SEMI) { rollback(index, c, d); } } return true; } @Override public Boolean visitFunctionValue(FunctionValueTree node, Void p) { accept(JFXTokenId.FUNCTION); space(); int old = indent; indent += continuationIndentSize; spaces(cs.spaceBeforeMethodDeclParen() ? 1 : 0); accept(JFXTokenId.LPAREN); List<? extends VariableTree> params = node.getParameters(); if (params != null && !params.isEmpty()) { spaces(cs.spaceWithinMethodDeclParens() ? 1 : 0, true); wrapList(cs.wrapMethodParams(), cs.alignMultilineMethodParams(), false, params); spaces(cs.spaceWithinMethodDeclParens() ? 1 : 0); } accept(JFXTokenId.RPAREN); TypeTree retType = node.getType(); if (retType != null && retType.getJavaFXKind() != JavaFXKind.TYPE_UNKNOWN) { accept(JFXTokenId.COLON); spaces(cs.spaceAroundAssignOps() ? 1 : 0); // TODO space around colon in the type definition scan(retType, p); } indent = old; BlockExpressionTree body = node.getBodyExpression(); if (body != null) { scan(body, p); } return true; } @Override public Boolean visitModifiers(ModifiersTree node, Void p) { boolean ret = true; JFXTokenId id = null; JavaFXTreePath path = getCurrentPath().getParentPath(); path = path.getParentPath(); while (tokens.offset() < endPos) { if (id != null) { space(); } int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); id = accept(JFXTokenId.PRIVATE, JFXTokenId.PACKAGE, JFXTokenId.PROTECTED, JFXTokenId.PUBLIC, JFXTokenId.PUBLIC_READ, JFXTokenId.PUBLIC_INIT, JFXTokenId.STATIC, JFXTokenId.ABSTRACT, JFXTokenId.NATIVEARRAY, JFXTokenId.AT, JFXTokenId.MIXIN, JFXTokenId.OVERRIDE); if (id == null) { rollback(index, c, d); break; } ret = id != JFXTokenId.AT; } return ret; } @Override public Boolean visitBlockExpression(BlockExpressionTree node, Void p) { if (node.isStatic()) { accept(JFXTokenId.STATIC); } CodeStyle.BracePlacement bracePlacement; boolean spaceBeforeLeftBrace = false; Tree parentTree = getCurrentPath().getParentPath().getLeaf(); boolean magicFunc = false; if (parentTree instanceof JFXFunctionDefinition) { String name = ((JFXFunctionDefinition) parentTree).getName().toString(); magicFunc = MAGIC_FUNCTION.contentEquals(name) && isSynthetic((JFXTree) parentTree); } int halfIndent = 0; int old = 0; if (!magicFunc) { switch (parentTree.getJavaFXKind()) { case CLASS_DECLARATION: case INSTANTIATE_NEW: case INSTANTIATE_OBJECT_LITERAL: case ON_REPLACE: bracePlacement = cs.getOtherBracePlacement(); if (node.isStatic()) { spaceBeforeLeftBrace = cs.spaceBeforeStaticInitLeftBrace(); } break; case FUNCTION_DEFINITION: case FUNCTION_VALUE: bracePlacement = cs.getMethodDeclBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeMethodDeclLeftBrace(); break; case TRY: bracePlacement = cs.getOtherBracePlacement(); if (((TryTree) parentTree).getBlock() == node) { spaceBeforeLeftBrace = cs.spaceBeforeTryLeftBrace(); } else { spaceBeforeLeftBrace = cs.spaceBeforeFinallyLeftBrace(); } break; case CATCH: bracePlacement = cs.getOtherBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeCatchLeftBrace(); break; case WHILE_LOOP: bracePlacement = cs.getOtherBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeWhileLeftBrace(); break; case FOR_EXPRESSION_FOR: bracePlacement = cs.getOtherBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeForLeftBrace(); break; case CONDITIONAL_EXPRESSION: bracePlacement = cs.getOtherBracePlacement(); if (((JFXIfExpression) parentTree).getTrueExpression() == node) { spaceBeforeLeftBrace = cs.spaceBeforeIfLeftBrace(); } else { spaceBeforeLeftBrace = cs.spaceBeforeElseLeftBrace(); } break; default: bracePlacement = cs.getOtherBracePlacement(); break; } old = indent; halfIndent = indent; switch (bracePlacement) { case SAME_LINE: spaces(spaceBeforeLeftBrace ? 1 : 0); if (node instanceof FakeBlock) { appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); } indent += indentSize; break; case NEW_LINE: newline(); if (node instanceof FakeBlock) { indent += indentSize; appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); indent += indentSize; } break; case NEW_LINE_HALF_INDENTED: indent += (indentSize >> 1); halfIndent = indent; newline(); if (node instanceof FakeBlock) { indent = old + indentSize; appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); indent = old + indentSize; } break; case NEW_LINE_INDENTED: indent += indentSize; halfIndent = indent; newline(); if (node instanceof FakeBlock) { appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); } break; } } // boolean isEmpty = true; final List<ExpressionTree> expressions = new ArrayList<ExpressionTree>(); expressions.addAll(node.getStatements()); // JFXC-3284 if (expressions.isEmpty()) { final ExpressionTree value = node.getValue(); if (value != null) { expressions.add(value); } } for (ExpressionTree stat : expressions) { if (magicFunc || !isSynthetic((JFXTree) node)) { // isEmpty = false; if (node instanceof FakeBlock) { appendToDiff(getNewlines(1) + getIndent()); col = indent; + } else if (parentTree.getJavaFXKind() == JavaFXKind.FUNCTION_DEFINITION || parentTree.getJavaFXKind() == JavaFXKind.INSTANTIATE_OBJECT_LITERAL) { + spaces(1, true); } else { blankLines(); } // Missing return statement, compliler bug http://javafx-jira.kenai.com/browse/JFXC-3528 int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.RETURN) != JFXTokenId.RETURN) { rollback(index, c, d); } else { space(); } processExpression(stat, p); } } // if (isEmpty || templateEdit) { if (templateEdit) { newline(); } if (node instanceof FakeBlock) { indent = halfIndent; int i = tokens.index(); boolean loop = true; while (loop) { switch (tokens.token().id()) { case WS: if (tokens.token().text().toString().indexOf(NEWLINE) < 0) { tokens.moveNext(); } else { loop = false; appendToDiff(NEWLINE); col = 0; } break; case LINE_COMMENT: loop = false; case COMMENT: tokens.moveNext(); break; default: if (tokens.index() != i) { tokens.moveIndex(i); tokens.moveNext(); } loop = false; appendToDiff(NEWLINE); col = 0; } } appendToDiff(getIndent() + RCBRACE); col = indent + 1; lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { if (!magicFunc) { - blankLines(); + if (parentTree.getJavaFXKind() == JavaFXKind.FUNCTION_DEFINITION || parentTree.getJavaFXKind() == JavaFXKind.INSTANTIATE_OBJECT_LITERAL) { + spaces(1, true); + } else { + blankLines(); + } indent = halfIndent; Diff diff = diffs.isEmpty() ? null : diffs.getFirst(); if (diff != null && diff.end == tokens.offset()) { if (diff.text != null) { int idx = diff.text.lastIndexOf(NEWLINE); if (idx < 0) { diff.text = getIndent(); } else { diff.text = diff.text.substring(0, idx + 1) + getIndent(); } } String spaces = diff.text != null ? diff.text : getIndent(); if (spaces.equals(fText.substring(diff.start, diff.end))) { diffs.removeFirst(); } } else if (tokens.movePrevious()) { if (tokens.token().id() == JFXTokenId.WS) { String text = tokens.token().text().toString(); int idx = text.lastIndexOf(NEWLINE); if (idx >= 0) { text = text.substring(idx + 1); String ind = getIndent(); if (!ind.equals(text)) { addDiff(new Diff(tokens.offset() + idx + 1, tokens.offset() + tokens.token().length(), ind)); } } } tokens.moveNext(); } JFXTokenId accept = accept(JFXTokenId.RBRACE); indent = old; } } return true; } // there is no visitExpression in javafx so far private void processExpression(ExpressionTree stat, Void p) { // int old = indent; // indent += continuationIndentSize; scan(stat, p); int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) != JFXTokenId.SEMI) { rollback(index, c, d); } // indent = old; } @Override public Boolean visitMemberSelect(MemberSelectTree node, Void p) { scan(node.getExpression(), p); accept(JFXTokenId.DOT); accept(JFXTokenId.IDENTIFIER, JFXTokenId.STAR, JFXTokenId.THIS, JFXTokenId.SUPER, JFXTokenId.CLASS); return true; } // Java MethodInvocationTree --> FunctionInvocationTree @Override public Boolean visitMethodInvocation(FunctionInvocationTree node, Void p) { ExpressionTree ms = node.getMethodSelect(); if (ms.getJavaFXKind() == JavaFXKind.MEMBER_SELECT) { ExpressionTree exp = ((MemberSelectTree) ms).getExpression(); scan(exp, p); accept(JFXTokenId.DOT); CodeStyle.WrapStyle wrapStyle = cs.wrapChainedMethodCalls(); if (exp.getJavaFXKind() == JavaFXKind.METHOD_INVOCATION) { wrapToken(wrapStyle, -1, 0, JFXTokenId.IDENTIFIER, JFXTokenId.THIS, JFXTokenId.SUPER); } else { int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); accept(JFXTokenId.IDENTIFIER, JFXTokenId.THIS, JFXTokenId.SUPER); if (wrapStyle != CodeStyle.WrapStyle.WRAP_NEVER && col > rightMargin && c > indent && (wrapDepth == 0 || c <= rightMargin)) { rollback(index, c, d); newline(); accept(JFXTokenId.IDENTIFIER, JFXTokenId.THIS, JFXTokenId.SUPER); } } } else { scan(node.getMethodSelect(), p); } spaces(cs.spaceBeforeMethodCallParen() ? 1 : 0); accept(JFXTokenId.LPAREN); List<? extends ExpressionTree> args = node.getArguments(); if (args != null && !args.isEmpty()) { spaces(cs.spaceWithinMethodCallParens() ? 1 : 0, true); wrapList(cs.wrapMethodCallArgs(), cs.alignMultilineCallArgs(), false, args); spaces(cs.spaceWithinMethodCallParens() ? 1 : 0); } accept(JFXTokenId.RPAREN); return true; } // Java NewClassTree --> InstantiateTree @Override public Boolean visitInstantiate(InstantiateTree node, Void p) { int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); // JFXC-3545 final boolean isNewKeyWordUsed = accept(JFXTokenId.NEW) == JFXTokenId.NEW; if (isNewKeyWordUsed) { space(); } else { rollback(index, c, d); } scan(node.getIdentifier(), p); spaces(!isNewKeyWordUsed || cs.spaceBeforeMethodCallParen() ? 1 : 0); if (isNewKeyWordUsed) { accept(JFXTokenId.LPAREN); List<? extends ExpressionTree> args = node.getArguments(); if (args != null && !args.isEmpty()) { spaces(cs.spaceWithinMethodCallParens() ? 1 : 0, true); wrapList(cs.wrapMethodCallArgs(), cs.alignMultilineCallArgs(), false, args); spaces(cs.spaceWithinMethodCallParens() ? 1 : 0); } accept(JFXTokenId.RPAREN); ClassDeclarationTree body = node.getClassBody(); if (body != null) { scan(body, p); } } else { accept(JFXTokenId.LBRACE); int old = indent; indent += indentSize; TreeSet<Tree> members = new TreeSet<Tree>(new TreePosComparator(sp, root)); members.addAll(node.getLiteralParts()); ClassDeclarationTree body = node.getClassBody(); if (body != null) { members.addAll(body.getClassMembers()); } if (!members.isEmpty()) { spaces(cs.spaceWithinMethodCallParens() ? 1 : 0, true); wrapLiteralList(cs.wrapMethodCallArgs(), cs.alignMultilineCallArgs(), members); } indent = old; spaces(0, true); accept(JFXTokenId.RBRACE); } return true; } @Override public Boolean visitReturn(ReturnTree node, Void p) { int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); // there is a compiler bug with dissappearing return keyword from the tree boolean accepted = accept(JFXTokenId.RETURN) == JFXTokenId.RETURN; if (!accepted) { rollback(index, c, d); } int old = indent; indent += continuationIndentSize; ExpressionTree exp = node.getExpression(); if (exp != null) { if (accepted) { space(); } scan(exp, p); } // should be accepted in processExpression() // accept(JFXTokenId.SEMI); indent = old; return true; } @Override public Boolean visitThrow(ThrowTree node, Void p) { accept(JFXTokenId.THROW); int old = indent; indent += continuationIndentSize; ExpressionTree exp = node.getExpression(); if (exp != null) { space(); scan(exp, p); } int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) != JFXTokenId.SEMI) { rollback(index, c, d); } indent = old; return true; } @Override public Boolean visitTry(TryTree node, Void p) { accept(JFXTokenId.TRY); scan(node.getBlock(), p); for (CatchTree catchTree : node.getCatches()) { if (cs.placeCatchOnNewLine()) { newline(); } else { spaces(cs.spaceBeforeCatch() ? 1 : 0); } scan(catchTree, p); } BlockExpressionTree finallyBlockTree = node.getFinallyBlock(); if (finallyBlockTree != null) { if (cs.placeFinallyOnNewLine()) { newline(); } else { spaces(cs.spaceBeforeFinally() ? 1 : 0); } accept(JFXTokenId.FINALLY); scan(finallyBlockTree, p); } return true; } @Override public Boolean visitCatch(CatchTree node, Void p) { accept(JFXTokenId.CATCH); int old = indent; indent += continuationIndentSize; spaces(cs.spaceBeforeCatchParen() ? 1 : 0); accept(JFXTokenId.LPAREN); spaces(cs.spaceWithinCatchParens() ? 1 : 0); scan(node.getParameter(), p); spaces(cs.spaceWithinCatchParens() ? 1 : 0); accept(JFXTokenId.RPAREN); indent = old; scan(node.getBlock(), p); return true; } @Override public Boolean visitWhileLoop(WhileLoopTree node, Void p) { accept(JFXTokenId.WHILE); int old = indent; indent += continuationIndentSize; spaces(cs.spaceBeforeWhileParen() ? 1 : 0); // missing parenthesized work around int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); boolean wrapped = accept(JFXTokenId.LPAREN) == JFXTokenId.LPAREN; if (!wrapped) { rollback(index, c, d); } scan(node.getCondition(), p); if (wrapped) { accept(JFXTokenId.RPAREN); } indent = old; CodeStyle.BracesGenerationStyle redundantWhileBraces = cs.redundantWhileBraces(); if (redundantWhileBraces == CodeStyle.BracesGenerationStyle.GENERATE && (startOffset > getStartPos(node) || endOffset < getEndPos(node))) { redundantWhileBraces = CodeStyle.BracesGenerationStyle.LEAVE_ALONE; } wrapStatement(cs.wrapWhileStatement(), redundantWhileBraces, cs.spaceBeforeWhileLeftBrace() ? 1 : 0, node.getStatement()); return true; } @Override public Boolean visitForExpression(ForExpressionTree node, Void p) { Tree parent = getCurrentPath().getParentPath().getLeaf(); JavaFXKind kind = parent.getJavaFXKind(); boolean insideVar = kind == JavaFXKind.VARIABLE || kind == JavaFXKind.SEQUENCE_EXPLICIT; int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.FOR) == JFXTokenId.FOR) { // FOR_EXPRESSION int old = indent; indent += continuationIndentSize; spaces(cs.spaceBeforeForParen() ? 1 : 0); accept(JFXTokenId.LPAREN); spaces(cs.spaceWithinForParens() ? 1 : 0); List<? extends ForExpressionInClauseTree> clauses = node.getInClauses(); if (clauses != null && !clauses.isEmpty()) { for (Iterator<? extends ForExpressionInClauseTree> it = clauses.iterator(); it.hasNext();) { ForExpressionInClauseTree feict = it.next(); scan(feict, p); if (it.hasNext()) { spaces(cs.spaceBeforeComma() ? 1 : 0); accept(JFXTokenId.COMMA); spaces(cs.spaceAfterComma() ? 1 : 0); } } } spaces(cs.spaceWithinForParens() ? 1 : 0); accept(JFXTokenId.RPAREN); indent = old; CodeStyle.BracesGenerationStyle redundantForBraces = cs.redundantForBraces(); if (insideVar || (redundantForBraces == CodeStyle.BracesGenerationStyle.GENERATE && (startOffset > getStartPos(node) || endOffset < getEndPos(node)))) { redundantForBraces = CodeStyle.BracesGenerationStyle.LEAVE_ALONE; } WrapStyle wrapStyle = insideVar ? WrapStyle.WRAP_NEVER : cs.wrapForStatement(); wrapStatement(wrapStyle, redundantForBraces, cs.spaceBeforeForLeftBrace() ? 1 : 0, node.getBodyExpression()); } else { // FOR_EXPRESSION_PREDICATE rollback(index, c, d); ForExpressionInClauseTree feict = node.getInClauses().get(0); scan(feict.getSequenceExpression(), p); spaces(cs.spaceBeforeArrayInitLeftBrace() ? 1 : 0, false); accept(JFXTokenId.LBRACKET); int old = indent; indent += indentSize; spaces(cs.spaceWithinArrayInitBrackets() ? 1 : 0, true); scan(feict.getVariable(), p); spaces(cs.spaceAroundBinaryOps() ? 1 : 0, false); accept(JFXTokenId.PIPE); spaces(cs.spaceAroundBinaryOps() ? 1 : 0, false); scan(feict.getWhereExpression(), p); spaces(cs.spaceWithinArrayInitBrackets() ? 1 : 0, true); indent = old; accept(JFXTokenId.RBRACKET); } return true; } @Override public Boolean visitForExpressionInClause(ForExpressionInClauseTree node, Void p) { scan(node.getVariable(), p); space(); accept(JFXTokenId.IN); space(); scan(node.getSequenceExpression(), p); ExpressionTree whereExpression = node.getWhereExpression(); if (whereExpression != null) { space(); accept(JFXTokenId.WHERE); space(); scan(whereExpression, p); } return true; } @Override public Boolean visitBreak(BreakTree node, Void p) { accept(JFXTokenId.BREAK); // TODO check, there should be no label in javafx Name label = node.getLabel(); if (label != null) { space(); accept(JFXTokenId.IDENTIFIER); } int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) != JFXTokenId.SEMI) { rollback(index, c, d); } return true; } @Override public Boolean visitContinue(ContinueTree node, Void p) { accept(JFXTokenId.CONTINUE); Name label = node.getLabel(); // TODO there is no label in javafx, check it if (label != null) { space(); accept(JFXTokenId.IDENTIFIER); } int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) != JFXTokenId.SEMI) { rollback(index, c, d); } return true; } // TODO sequence @Override public Boolean visitAssignment(AssignmentTree node, Void p) { int alignIndent = cs.alignMultilineAssignment() ? col : -1; boolean b = scan(node.getVariable(), p); if (b) { spaces(cs.spaceAroundAssignOps() ? 1 : 0); accept(JFXTokenId.EQ); ExpressionTree expr = node.getExpression(); // if (expr.getJavaFXKind() == JavaFXKind.NEW_ARRAY && ((NewArrayTree)expr).getType() == null) { // if (cs.getOtherBracePlacement() == CodeStyle.BracePlacement.SAME_LINE) // spaces(cs.spaceAroundAssignOps() ? 1 : 0); // scan(expr, p); // } else { wrapTree(cs.wrapAssignOps(), alignIndent, cs.spaceAroundAssignOps() ? 1 : 0, expr); // } } else { scan(node.getExpression(), p); } return true; } @Override public Boolean visitCompoundAssignment(CompoundAssignmentTree node, Void p) { int alignIndent = cs.alignMultilineAssignment() ? col : -1; scan(node.getVariable(), p); spaces(cs.spaceAroundAssignOps() ? 1 : 0); if (OPERATOR.equals(tokens.token().id().primaryCategory())) { col += tokens.token().length(); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; tokens.moveNext(); } wrapTree(cs.wrapAssignOps(), alignIndent, cs.spaceAroundAssignOps() ? 1 : 0, node.getExpression()); return true; } // TODO check it @Override public Boolean visitTypeAny(TypeAnyTree node, Void p) { return super.visitTypeAny(node, p); } // whether this been invoked at all? @Override public Boolean visitTypeArray(TypeArrayTree node, Void p) { boolean ret = scan(node.getElementType(), p); int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); JFXTokenId id = accept(JFXTokenId.LBRACKET, JFXTokenId.IDENTIFIER); if (id != JFXTokenId.IDENTIFIER) { accept(JFXTokenId.RBRACKET); return ret; } rollback(index, c, d); spaces(1, false); accept(JFXTokenId.IDENTIFIER); accept(JFXTokenId.LBRACKET); accept(JFXTokenId.RBRACKET); return false; } @Override public Boolean visitTypeClass(TypeClassTree node, Void p) { // issue #177106: TypeClass before MemberSelect boolean accepted = true; while (accepted) { accept(JFXTokenId.IDENTIFIER, JFXTokenId.STAR, JFXTokenId.THIS, JFXTokenId.SUPER, JFXTokenId.CLASS); int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); accepted = accept(JFXTokenId.DOT) == JFXTokenId.DOT; if (!accepted) { rollback(index, c, d); } } // sequence type int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.LBRACKET) == JFXTokenId.LBRACKET) { if (cs.spaceWithinArrayInitBrackets()) { space(); } accept(JFXTokenId.RBRACKET); } else { rollback(index, c, d); } return true; } @Override public Boolean visitTypeFunctional(TypeFunctionalTree node, Void p) { accept(JFXTokenId.LPAREN); List<? extends TypeTree> params = node.getParameters(); if (params != null && !params.isEmpty()) { // TODO introduce cs.spaceWithingFunctionalType // spaces(cs.spaceWithinMethodDeclParens() ? 1 : 0, true); wrapFunctionalParamList(cs.wrapMethodParams(), cs.alignMultilineMethodParams(), params); spaces(cs.spaceWithinMethodDeclParens() ? 1 : 0); } accept(JFXTokenId.RPAREN); TypeTree retType = node.getReturnType(); if (retType != null && retType.getJavaFXKind() != JavaFXKind.TYPE_UNKNOWN) { accept(JFXTokenId.COLON); spaces(cs.spaceAroundAssignOps() ? 1 : 0); // TODO space around colon in the type definition scan(retType, p); } return true; } @Override public Boolean visitTypeUnknown(TypeUnknownTree node, Void p) { // copied from java visitOther() do { col += tokens.token().length(); } while (tokens.moveNext() && tokens.offset() < endPos); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; return true; } @Override public Boolean visitIdentifier(IdentifierTree node, Void p) { accept(JFXTokenId.IDENTIFIER, JFXTokenId.THIS, JFXTokenId.SUPER); return true; } @Override public Boolean visitUnary(UnaryTree node, Void p) { final JFXTokenId id = tokens.token().id(); final JavaFXKind kind = node.getJavaFXKind(); if (kind == JavaFXKind.SIZEOF) { accept(JFXTokenId.SIZEOF); space(); scan(node.getExpression(), p); } else if (kind == JavaFXKind.INDEXOF) { accept(JFXTokenId.INDEXOF); space(); scan(node.getExpression(), p); } else if (kind == JavaFXKind.LOGICAL_COMPLEMENT) { accept(JFXTokenId.NOT); space(); scan(node.getExpression(), p); } else if (kind == JavaFXKind.REVERSE) { accept(JFXTokenId.REVERSE); space(); scan(node.getExpression(), p); } else if (OPERATOR.equals(id.primaryCategory())) { spaces(cs.spaceAroundUnaryOps() ? 1 : 0); col += tokens.token().length(); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; tokens.moveNext(); int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); spaces(cs.spaceAroundUnaryOps() ? 1 : 0); if (tokens.token().id() == id) { rollback(index, c, d); space(); } scan(node.getExpression(), p); } else { scan(node.getExpression(), p); spaces(cs.spaceAroundUnaryOps() ? 1 : 0); col += tokens.token().length(); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; tokens.moveNext(); spaces(cs.spaceAroundUnaryOps() ? 1 : 0); } return true; } @Override public Boolean visitBinary(BinaryTree node, Void p) { scan(node.getLeftOperand(), p); int alignIndent = cs.alignMultilineBinaryOp() ? col : -1; wrapOperatorAndTree(cs.wrapBinaryOps(), alignIndent, cs.spaceAroundBinaryOps() ? 1 : 0, node.getRightOperand()); return true; } // "if else" is here @Override public Boolean visitConditionalExpression(ConditionalExpressionTree node, Void p) { JFXIfExpression ifExpr = (JFXIfExpression) node; accept(JFXTokenId.IF); int old = indent; indent += continuationIndentSize; spaces(cs.spaceBeforeIfParen() ? 1 : 0); // missing parenthesized work around int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); boolean wrapped = accept(JFXTokenId.LPAREN) == JFXTokenId.LPAREN; if (!wrapped) { rollback(index, c, d); } scan(ifExpr.getCondition(), p); if (wrapped) { accept(JFXTokenId.RPAREN); } indent = old; index = tokens.index(); c = col; d = diffs.isEmpty() ? null : diffs.getFirst(); JFXTokenId accepted = accept(JFXTokenId.THEN); rollback(index, c, d); if (accepted == JFXTokenId.THEN) { space(); accept(JFXTokenId.THEN); } JFXExpression trueExpr = ifExpr.getTrueExpression(); JFXExpression falseExpr = ifExpr.getFalseExpression(); CodeStyle.BracesGenerationStyle redundantIfBraces = cs.redundantIfBraces(); if ((falseExpr != null && redundantIfBraces == CodeStyle.BracesGenerationStyle.ELIMINATE && danglingElseChecker.hasDanglingElse(trueExpr)) || (redundantIfBraces == CodeStyle.BracesGenerationStyle.GENERATE && (startOffset > getStartPos(ifExpr) || endOffset < getEndPos(node)))) { redundantIfBraces = CodeStyle.BracesGenerationStyle.LEAVE_ALONE; } boolean insideVar = false; JavaFXTreePath parentPath = getCurrentPath().getParentPath(); Tree leaf = parentPath.getLeaf(); while (leaf.getJavaFXKind() != JavaFXKind.COMPILATION_UNIT) { if (leaf.getJavaFXKind() == JavaFXKind.VARIABLE || leaf.getJavaFXKind() == JavaFXKind.SEQUENCE_EXPLICIT) { insideVar = true; break; } parentPath = parentPath.getParentPath(); leaf = parentPath.getLeaf(); } // TODO make cs.wrapIfExpression final WrapStyle wrapIfStatement = insideVar ? WrapStyle.WRAP_NEVER : cs.wrapIfStatement(); boolean prevblock = wrapStatement(wrapIfStatement, redundantIfBraces, cs.spaceBeforeIfLeftBrace() ? 1 : 0, trueExpr); if (falseExpr != null) { if (!insideVar && (cs.placeElseOnNewLine() || !prevblock)) { newline(); } else { spaces(cs.spaceBeforeElse() ? 1 : 0); } accept(JFXTokenId.ELSE); if (falseExpr.getJavaFXKind() == JavaFXKind.CONDITIONAL_EXPRESSION && cs.specialElseIf()) { space(); scan(falseExpr, p); } else { redundantIfBraces = cs.redundantIfBraces(); if (redundantIfBraces == CodeStyle.BracesGenerationStyle.GENERATE && (startOffset > getStartPos(ifExpr) || endOffset < getEndPos(ifExpr))) { redundantIfBraces = CodeStyle.BracesGenerationStyle.LEAVE_ALONE; } wrapStatement(wrapIfStatement, redundantIfBraces, cs.spaceBeforeElseLeftBrace() ? 1 : 0, falseExpr); } indent = old; } return true; } @Override public Boolean visitEmptyStatement(EmptyStatementTree node, Void p) { int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SEMI) == JFXTokenId.SEMI) { rollback(index, c, d); } return true; } @Override public Boolean visitInstanceOf(InstanceOfTree node, Void p) { scan(node.getExpression(), p); space(); accept(JFXTokenId.INSTANCEOF); space(); scan(node.getType(), p); return true; } @Override public Boolean visitIndexof(IndexofTree node, Void p) { accept(JFXTokenId.INDEXOF); space(); scan(node.getForVarIdentifier(), p); return true; } @Override public Boolean visitTypeCast(TypeCastTree node, Void p) { scan(node.getExpression(), p); space(); accept(JFXTokenId.AS); space(); scan(node.getType(), p); return true; } @Override public Boolean visitParenthesized(ParenthesizedTree node, Void p) { accept(JFXTokenId.LPAREN); boolean spaceWithinParens; switch (getCurrentPath().getParentPath().getLeaf().getJavaFXKind()) { case CONDITIONAL_EXPRESSION: spaceWithinParens = cs.spaceWithinIfParens(); break; case FOR_EXPRESSION_FOR: spaceWithinParens = cs.spaceWithinForParens(); break; // case DO_WHILE_LOOP: case WHILE_LOOP: spaceWithinParens = cs.spaceWithinWhileParens(); break; // case SWITCH: // spaceWithinParens = cs.spaceWithinSwitchParens(); // break; default: spaceWithinParens = cs.spaceWithinParens(); } spaces(spaceWithinParens ? 1 : 0); scan(node.getExpression(), p); spaces(spaceWithinParens ? 1 : 0); accept(JFXTokenId.RPAREN); return true; } @Override public Boolean visitInterpolateValue(InterpolateValueTree node, Void p) { scan(node.getAttribute(), p); space(); accept(JFXTokenId.SUCHTHAT); // nice token, LOL space(); scan(node.getValue(), p); ExpressionTree interpolation = node.getInterpolation(); if (interpolation != null) { space(); accept(JFXTokenId.TWEEN); space(); scan(interpolation, p); } return true; } // TODO @Override public Boolean visitKeyFrameLiteral(KeyFrameLiteralTree node, Void p) { do { col += tokens.token().length(); } while (tokens.moveNext() && tokens.offset() < endPos); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; return true; } @Override public Boolean visitMissingExpression(ExpressionTree node, Void p) { do { col += tokens.token().length(); } while (tokens.moveNext() && tokens.offset() < endPos); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; return true; } @Override public Boolean visitObjectLiteralPart(ObjectLiteralPartTree node, Void p) { accept(JFXTokenId.IDENTIFIER); accept(JFXTokenId.COLON); spaces(cs.spaceAroundAssignOps() ? 1 : 0); // TODO space around colon in the type definition final JavafxBindStatus bindStatus = node.getBindStatus(); if (bindStatus.isUnidiBind() || bindStatus.isBidiBind()) { accept(JFXTokenId.BIND); space(); } scan(node.getExpression(), p); if (bindStatus.isBidiBind()) { space(); accept(JFXTokenId.WITH); space(); accept(JFXTokenId.INVERSE); } return true; } @Override public Boolean visitOnReplace(OnReplaceTree node, Void p) { accept(JFXTokenId.ON); space(); accept(JFXTokenId.REPLACE); VariableTree oldValue = node.getOldValue(); if (oldValue != null) { space(); scan(oldValue, p); } int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); boolean hasInitializer = accept(JFXTokenId.EQ) == JFXTokenId.EQ; rollback(index, c, d); if (hasInitializer) { spaces(cs.spaceAroundAssignOps() ? 1 : 0); accept(JFXTokenId.EQ); spaces(cs.spaceAroundAssignOps() ? 1 : 0); index = tokens.index(); c = col; d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.IDENTIFIER) == JFXTokenId.IDENTIFIER) { space(); } else { rollback(index, c, d); } } else { space(); } scan(node.getBody(), p); return true; } @Override public Boolean visitTrigger(TriggerTree node, Void p) { do { col += tokens.token().length(); } while (tokens.moveNext() && tokens.offset() < endPos); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; return true; } // remove that workaround after JFXC-3494 fix @Override public Boolean visitStringExpression(StringExpressionTree node, Void p) { do { col += tokens.token().length(); } while (tokens.moveNext() && tokens.offset() < endPos); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; return true; } @Override public Boolean visitTimeLiteral(TimeLiteralTree node, Void p) { do { col += tokens.token().length(); } while (tokens.moveNext() && tokens.offset() < endPos); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; return true; } // TODO remove that workarounds for JFXC-3528 after switching to SoMa @Override public Boolean visitLiteral(LiteralTree node, Void p) { // Missing return statement, compliler bug http://javafx-jira.kenai.com/browse/JFXC-3528 // --- int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.RETURN) == JFXTokenId.RETURN) { space(); } else { rollback(index, c, d); } // --- // #176654: probably compiler bug // for literal "-10" AST literal tree only but lexer has SUB token and INT_LITERAL token // workaround // --- index = tokens.index(); c = col; d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.SUB) != JFXTokenId.SUB) { rollback(index, c, d); } // --- accept(JFXTokenId.TRUE, JFXTokenId.FALSE, JFXTokenId.NULL, JFXTokenId.DECIMAL_LITERAL, JFXTokenId.FLOATING_POINT_LITERAL, JFXTokenId.HEX_LITERAL, JFXTokenId.OCTAL_LITERAL, JFXTokenId.STRING_LITERAL, JFXTokenId.QUOTE_LBRACE_STRING_LITERAL, JFXTokenId.RBRACE_LBRACE_STRING_LITERAL, JFXTokenId.RBRACE_QUOTE_STRING_LITERAL); return true; } @Override public Boolean visitSequenceDelete(SequenceDeleteTree node, Void p) { accept(JFXTokenId.DELETE); space(); scan(node.getElement(), p); space(); int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.FROM) == JFXTokenId.FROM) { space(); } else { rollback(index, c, d); } scan(node.getSequence(), p); return true; } @Override public Boolean visitSequenceEmpty(SequenceEmptyTree node, Void p) { accept(JFXTokenId.LBRACKET); spaces(cs.spaceWithinArrayInitBrackets() ? 1 : 0); accept(JFXTokenId.RBRACKET); return true; } // TODO check cs.getOtherBracePlacement() @Override public Boolean visitSequenceExplicit(SequenceExplicitTree node, Void p) { List<ExpressionTree> itemList = node.getItemList(); accept(JFXTokenId.LBRACKET); int old = indent; indent += indentSize; spaces(cs.spaceWithinArrayInitBrackets() ? 1 : 0, true); if (itemList != null) { boolean first = true; for (Iterator<ExpressionTree> it = itemList.iterator(); it.hasNext();) { ExpressionTree expressionTree = it.next(); if (!first) { spaces(cs.spaceAfterComma() ? 1 : 0, true); } scan(expressionTree, p); int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.COMMA) != JFXTokenId.COMMA) { rollback(index, c, d); } first = false; } } indent = old; spaces(cs.spaceWithinArrayInitBrackets() ? 1 : 0, true); accept(JFXTokenId.RBRACKET); return true; } @Override public Boolean visitSequenceIndexed(SequenceIndexedTree node, Void p) { scan(node.getSequence(), p); accept(JFXTokenId.LBRACKET); scan(node.getIndex(), p); accept(JFXTokenId.RBRACKET); return true; } @Override public Boolean visitSequenceInsert(SequenceInsertTree node, Void p) { accept(JFXTokenId.INSERT); space(); scan(node.getElement(), p); space(); accept(JFXTokenId.INTO, JFXTokenId.BEFORE, JFXTokenId.AFTER); space(); scan(node.getSequence(), p); return true; } @Override public Boolean visitSequenceRange(SequenceRangeTree node, Void p) { accept(JFXTokenId.LBRACKET); spaces(cs.spaceWithinArrayInitBrackets() ? 1 : 0); scan(node.getLower(), p); accept(JFXTokenId.DOTDOT); if (node.isExclusive()) { accept(JFXTokenId.LT); } scan(node.getUpper(), p); ExpressionTree stepOrNull = node.getStepOrNull(); if (stepOrNull != null) { space(); accept(JFXTokenId.STEP); space(); scan(stepOrNull, p); } spaces(cs.spaceWithinArrayInitBrackets() ? 1 : 0); accept(JFXTokenId.RBRACKET); return true; } @Override public Boolean visitSequenceSlice(SequenceSliceTree node, Void p) { scan(node.getSequence(), p); accept(JFXTokenId.LBRACKET); spaces(cs.spaceWithinArrayInitBrackets() ? 1 : 0); scan(node.getFirstIndex(), p); spaces(cs.spaceAroundUnaryOps() ? 1 : 0); // scan(node.getEndKind(), p); accept(JFXTokenId.DOTDOT); int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.LT) != JFXTokenId.LT) { rollback(index, c, d); } spaces(cs.spaceAroundUnaryOps() ? 1 : 0); scan(node.getLastIndex(), p); accept(JFXTokenId.RBRACKET); return true; } @Override public Boolean visitErroneous(ErroneousTree node, Void p) { for (Tree tree : node.getErrorTrees()) { do { col += tokens.token().length(); } while (tokens.moveNext() && tokens.offset() < endPos); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; scan(tree, p); } do { col += tokens.token().length(); } while (tokens.moveNext() && tokens.offset() < endPos); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; return true; } /// === /// === END OF THE VISITOR IMPLEMENTATION /// === private JFXTokenId accept(JFXTokenId first, JFXTokenId... rest) { lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; EnumSet<JFXTokenId> tokenIds = EnumSet.of(first, rest); // javafx lexer generates one token for each WS // java - one for all // therefore StringBuilder is been used instead of Token StringBuilder lastWSToken = new StringBuilder(); // TODO do not use text var, use this builder.subSequence int after = 0; do { if (isTokenOutOfTree()) { if (lastWSToken.length() != 0) { lastBlankLines = 0; lastBlankLinesTokenIndex = tokens.index() - 1; lastBlankLinesDiff = diffs.isEmpty() ? null : diffs.getFirst(); } return null; } JFXTokenId id = tokens.token().id(); if (tokenIds.contains(id)) { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : null; if (lastWSToken.length() != 0) { if (spaces == null || !spaces.contentEquals(lastWSToken.toString())) { addDiff(new Diff(tokens.offset() - lastWSToken.length(), tokens.offset(), spaces)); } } else { if (spaces != null && spaces.length() > 0) { addDiff(new Diff(tokens.offset(), tokens.offset(), spaces)); } } if (after > 0) { col = indent; } col += tokens.token().length(); return tokens.moveNext() ? id : null; } switch (id) { case WS: lastWSToken.append(tokens.token().text()); break; case LINE_COMMENT: if (lastWSToken.length() != 0) { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : SPACE; if (!spaces.contentEquals(lastWSToken.toString())) { addDiff(new Diff(tokens.offset() - lastWSToken.length(), tokens.offset(), spaces)); } lastWSToken = new StringBuilder(); } else { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : null; if (spaces != null && spaces.length() > 0) { addDiff(new Diff(tokens.offset(), tokens.offset(), spaces)); } } col = 0; after = 1; //line comment break; case DOC_COMMENT: if (lastWSToken.length() != 0) { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : SPACE; if (!spaces.contentEquals(lastWSToken.toString())) { addDiff(new Diff(tokens.offset() - lastWSToken.length(), tokens.offset(), spaces)); } lastWSToken = new StringBuilder(); if (after > 0) { col = indent; } else { col++; } } else { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : null; if (spaces != null && spaces.length() > 0) { addDiff(new Diff(tokens.offset(), tokens.offset(), spaces)); } if (after > 0) { col = indent; } } String tokenText = tokens.token().text().toString(); int idx = tokenText.lastIndexOf(NEWLINE); if (idx >= 0) { tokenText = tokenText.substring(idx + 1); } col += getCol(tokenText); indentComment(); after = 2; //javadoc comment break; case COMMENT: if (lastWSToken.length() != 0) { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : SPACE; if (!spaces.contentEquals(lastWSToken.toString())) { addDiff(new Diff(tokens.offset() - lastWSToken.length(), tokens.offset(), spaces)); } lastWSToken = new StringBuilder(); if (after > 0) { col = indent; } else { col++; } } else { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : null; if (spaces != null && spaces.length() > 0) { addDiff(new Diff(tokens.offset(), tokens.offset(), spaces)); } if (after > 0) { col = indent; } } tokenText = tokens.token().text().toString(); idx = tokenText.lastIndexOf(NEWLINE); if (idx >= 0) { tokenText = tokenText.substring(idx + 1); } col += getCol(tokenText); indentComment(); after = 0; break; default: return null; } } while (tokens.moveNext()); return null; } // TODO uncomment it after switching to SoMa private boolean isTokenOutOfTree() { // return tokens.offset() >= endPos; return false; } private void space() { spaces(1); } private void spaces(int count) { spaces(count, false); } private void spaces(int count, boolean preserveNewline) { // javafx lexer generates one token for each WS // java - one for all // therefore StringBuilder is been used instead of Token StringBuilder lastWSToken = new StringBuilder(); // TODO do not use text var, use this builder.subSequence int after = 0; do { if (isTokenOutOfTree()) { return; } switch (tokens.token().id()) { case WS: lastWSToken.append(tokens.token().text()); break; case LINE_COMMENT: if (lastWSToken.length() != 0) { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : SPACE; if (preserveNewline) { String text = lastWSToken.toString(); int idx = text.lastIndexOf(NEWLINE); if (idx >= 0) { spaces = getNewlines(1) + getIndent(); lastBlankLines = 1; lastBlankLinesTokenIndex = tokens.index(); lastBlankLinesDiff = diffs.isEmpty() ? null : diffs.getFirst(); } } if (!spaces.contentEquals(lastWSToken.toString())) { addDiff(new Diff(tokens.offset() - lastWSToken.length(), tokens.offset(), spaces)); } lastWSToken = new StringBuilder(); } else { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : null; if (spaces != null && spaces.length() > 0) { addDiff(new Diff(tokens.offset(), tokens.offset(), spaces)); } } col = 0; after = 1; //line comment break; case DOC_COMMENT: if (lastWSToken.length() != 0) { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : SPACE; if (preserveNewline) { String text = lastWSToken.toString(); int idx = text.lastIndexOf(NEWLINE); if (idx >= 0) { spaces = getNewlines(1) + getIndent(); after = 3; lastBlankLines = 1; lastBlankLinesTokenIndex = tokens.index(); lastBlankLinesDiff = diffs.isEmpty() ? null : diffs.getFirst(); } } if (!spaces.contentEquals(lastWSToken.toString())) { addDiff(new Diff(tokens.offset() - lastWSToken.length(), tokens.offset(), spaces)); } lastWSToken = new StringBuilder(); if (after > 0) { col = indent; } else { col++; } } else { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : null; if (spaces != null && spaces.length() > 0) { addDiff(new Diff(tokens.offset(), tokens.offset(), spaces)); } if (after > 0) { col = indent; } } String tokenText = tokens.token().text().toString(); int idx = tokenText.lastIndexOf(NEWLINE); if (idx >= 0) { tokenText = tokenText.substring(idx + 1); } col += getCol(tokenText); indentComment(); after = 2; //javadoc comment break; case COMMENT: if (lastWSToken.length() != 0) { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : SPACE; if (preserveNewline) { String text = lastWSToken.toString(); idx = text.lastIndexOf(NEWLINE); if (idx >= 0) { spaces = getNewlines(1) + getIndent(); after = 3; lastBlankLines = 1; lastBlankLinesTokenIndex = tokens.index(); lastBlankLinesDiff = diffs.isEmpty() ? null : diffs.getFirst(); } } if (!spaces.contentEquals(lastWSToken.toString())) { addDiff(new Diff(tokens.offset() - lastWSToken.length(), tokens.offset(), spaces)); } lastWSToken = new StringBuilder(); if (after > 0) { col = indent; } else { col++; } } else { String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : null; if (spaces != null && spaces.length() > 0) { addDiff(new Diff(tokens.offset(), tokens.offset(), spaces)); } if (after > 0) { col = indent; } } tokenText = tokens.token().text().toString(); idx = tokenText.lastIndexOf(NEWLINE); if (idx >= 0) { tokenText = tokenText.substring(idx + 1); } col += getCol(tokenText); indentComment(); after = 0; break; default: String spaces = after == 1 //after line comment ? getIndent() : after == 2 //after javadoc comment ? getNewlines(1) + getIndent() : getSpaces(count); if (lastWSToken.length() != 0) { if (preserveNewline) { String text = lastWSToken.toString(); idx = text.lastIndexOf(NEWLINE); if (idx >= 0) { spaces = getNewlines(1) + getIndent(); after = 3; lastBlankLines = 1; lastBlankLinesTokenIndex = tokens.index(); lastBlankLinesDiff = diffs.isEmpty() ? null : diffs.getFirst(); } } if (!spaces.contentEquals(lastWSToken.toString())) { addDiff(new Diff(tokens.offset() - lastWSToken.length(), tokens.offset(), spaces)); } } else if (spaces.length() > 0) { addDiff(new Diff(tokens.offset(), tokens.offset(), spaces)); } if (after > 0) { col = indent; } else { col += count; } return; } } while (tokens.moveNext()); } private void newline() { blankLines(templateEdit ? ANY_COUNT : 0); } private void blankLines() { blankLines(ANY_COUNT); } private void blankLines(int count) { if (count >= 0) { if (lastBlankLinesTokenIndex < 0) { lastBlankLines = count; lastBlankLinesTokenIndex = tokens.index(); lastBlankLinesDiff = diffs.isEmpty() ? null : diffs.getFirst(); } else if (lastBlankLines < count) { lastBlankLines = count; rollback(lastBlankLinesTokenIndex, lastBlankLinesTokenIndex, lastBlankLinesDiff); } else { return; } } else { if (lastBlankLinesTokenIndex < 0) { lastBlankLinesTokenIndex = tokens.index(); lastBlankLinesDiff = diffs.isEmpty() ? null : diffs.getFirst(); } else { return; } } // javafx lexer generates one token for each WS // java - one for all // therefore StringBuilder is been used instead of Token StringBuilder lastToken = new StringBuilder(); // TODO do not use text var, use this builder.subSequence int after = 0; do { if (isTokenOutOfTree()) { return; } switch (tokens.token().id()) { case WS: lastToken.append(tokens.token().text()); break; case COMMENT: if (count >= 0 && tokens.index() > 1 && after != 1) { count++; } if (lastToken.length() != 0) { int offset = tokens.offset() - lastToken.length(); String text = lastToken.toString(); int idx = 0; int lastIdx = 0; while (count != 0 && (idx = text.indexOf(NEWLINE, lastIdx)) >= 0) { if (idx > lastIdx) { addDiff(new Diff(offset + lastIdx, offset + idx, null)); } lastIdx = idx + 1; count--; } if ((idx = text.lastIndexOf(NEWLINE)) >= 0) { if (idx > lastIdx) { addDiff(new Diff(offset + lastIdx, offset + idx + 1, null)); } lastIdx = idx + 1; } if (lastIdx > 0) { String _indent = getIndent(); if (!_indent.contentEquals(text.substring(lastIdx))) { addDiff(new Diff(offset + lastIdx, tokens.offset(), _indent)); } } lastToken = new StringBuilder(); } indentComment(); after = 3; break; case DOC_COMMENT: if (count >= 0 && tokens.index() > 1 && after != 1) { count++; } if (lastToken.length() != 0) { int offset = tokens.offset() - lastToken.length(); String text = lastToken.toString(); int idx = 0; int lastIdx = 0; while (count != 0 && (idx = text.indexOf(NEWLINE, lastIdx)) >= 0) { if (idx > lastIdx) { addDiff(new Diff(offset + lastIdx, offset + idx, null)); } lastIdx = idx + 1; count--; } if ((idx = text.lastIndexOf(NEWLINE)) >= 0) { after = 0; if (idx >= lastIdx) { addDiff(new Diff(offset + lastIdx, offset + idx + 1, null)); } lastIdx = idx + 1; } if (lastIdx == 0 && count < 0 && after != 1) { count = count == ANY_COUNT ? 1 : 0; } String _indent = after == 3 ? SPACE : getNewlines(count) + getIndent(); if (!_indent.contentEquals(text.substring(lastIdx))) { addDiff(new Diff(offset + lastIdx, tokens.offset(), _indent)); } lastToken = new StringBuilder(); } else { if (lastBlankLines < 0 && count == ANY_COUNT) { count = lastBlankLines = 1; } String text = getNewlines(count) + getIndent(); if (text.length() > 0) { addDiff(new Diff(tokens.offset(), tokens.offset(), text)); } } indentComment(); count = 0; after = 2; break; case LINE_COMMENT: if (lastToken.length() != 0) { int offset = tokens.offset() - lastToken.length(); String text = lastToken.toString(); if (count >= 0 && tokens.index() > 1 && after != 1 && text.indexOf(NEWLINE) >= 0) { count++; } int idx = 0; int lastIdx = 0; while (count != 0 && (idx = text.indexOf(NEWLINE, lastIdx)) >= 0) { if (idx > lastIdx) { addDiff(new Diff(offset + lastIdx, offset + idx, null)); } lastIdx = idx + 1; count--; } if ((idx = text.lastIndexOf(NEWLINE)) >= 0) { if (idx >= lastIdx) { addDiff(new Diff(offset + lastIdx, offset + idx + 1, null)); } lastIdx = idx + 1; } if (lastIdx == 0 && after == 1) { String _indent = getIndent(); if (!_indent.contentEquals(text)) { addDiff(new Diff(offset, tokens.offset(), _indent)); } } else if (lastIdx > 0 && lastIdx < lastToken.length()) { String _indent = getIndent(); if (!_indent.contentEquals(text.substring(lastIdx))) { addDiff(new Diff(offset + lastIdx, tokens.offset(), _indent)); } } lastToken = new StringBuilder(); } after = 1; break; default: if (count >= 0 && tokens.index() > 1 && after != 1) { count++; } if (lastToken.length() != 0) { int offset = tokens.offset() - lastToken.length(); String text = lastToken.toString(); int idx = 0; int lastIdx = 0; while (count != 0 && (idx = text.indexOf(NEWLINE, lastIdx)) >= 0) { if (idx > lastIdx) { addDiff(new Diff(offset + lastIdx, offset + idx, templateEdit ? getIndent() : null)); } lastIdx = idx + 1; count--; } if ((idx = text.lastIndexOf(NEWLINE)) >= 0) { after = 0; if (idx >= lastIdx) { addDiff(new Diff(offset + lastIdx, offset + idx + 1, null)); } lastIdx = idx + 1; } if (lastIdx == 0 && count < 0 && after != 1) { count = count == ANY_COUNT ? 1 : 0; } String _indent = after == 3 ? SPACE : getNewlines(count) + getIndent(); if (!_indent.contentEquals(text.substring(lastIdx))) { addDiff(new Diff(offset + lastIdx, tokens.offset(), _indent)); } } else { if (lastBlankLines < 0 && count == ANY_COUNT) { count = lastBlankLines = 1; } String text = after == 1 ? getIndent() : getNewlines(count) + getIndent(); if (text.length() > 0) { addDiff(new Diff(tokens.offset(), tokens.offset(), text)); } } col = indent; return; } } while (tokens.moveNext()); } private void rollback(int index, int col, Diff diff) { tokens.moveIndex(index); tokens.moveNext(); if (diff == null) { diffs.clear(); } else { while (!diffs.isEmpty() && diffs.getFirst() != diff) { diffs.removeFirst(); } } this.col = col; } private void appendToDiff(String s) { int offset = tokens.offset(); Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (d != null && d.getEndOffset() == offset) { d.text += s; } else { addDiff(new Diff(offset, offset, s)); } } private void addDiff(Diff diff) { Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (d == null || d.getStartOffset() <= diff.getStartOffset()) { diffs.addFirst(diff); } } private int wrapToken(CodeStyle.WrapStyle wrapStyle, int alignIndent, int spacesCnt, JFXTokenId first, JFXTokenId... rest) { int ret = -1; switch (wrapStyle) { case WRAP_ALWAYS: int old = indent; if (alignIndent >= 0) { indent = alignIndent; } newline(); indent = old; ret = col; accept(first, rest); break; case WRAP_IF_LONG: int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); old = indent; if (alignIndent >= 0) { indent = alignIndent; } spaces(spacesCnt, true); indent = old; ret = col; accept(first, rest); if (this.col > rightMargin) { rollback(index, c, d); old = indent; if (alignIndent >= 0) { indent = alignIndent; } newline(); indent = old; ret = col; accept(first, rest); } break; case WRAP_NEVER: old = indent; if (alignIndent >= 0) { indent = alignIndent; } spaces(spacesCnt, true); indent = old; ret = col; accept(first, rest); break; } return ret; } private int wrapTree(CodeStyle.WrapStyle wrapStyle, int alignIndent, int spacesCnt, Tree tree) { int ret = -1; switch (wrapStyle) { case WRAP_ALWAYS: int old = indent; if (alignIndent >= 0) { indent = alignIndent; } newline(); indent = old; ret = col; scan(tree, null); break; case WRAP_IF_LONG: int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); old = indent; if (alignIndent >= 0) { indent = alignIndent; } spaces(spacesCnt, true); indent = old; ret = col; wrapDepth++; scan(tree, null); wrapDepth--; if (col > rightMargin && (wrapDepth == 0 || c <= rightMargin)) { rollback(index, c, d); old = indent; if (alignIndent >= 0) { indent = alignIndent; } newline(); indent = old; ret = col; scan(tree, null); } break; case WRAP_NEVER: old = indent; if (alignIndent >= 0) { indent = alignIndent; } spaces(spacesCnt, true); indent = old; ret = col; scan(tree, null); break; } return ret; } private int wrapExtendsTree(CodeStyle.WrapStyle wrapStyle, int alignIndent, int spacesCnt, Tree tree) { int ret = -1; switch (wrapStyle) { case WRAP_ALWAYS: int old = indent; if (alignIndent >= 0) { indent = alignIndent; } newline(); indent = old; ret = col; accept(JFXTokenId.IDENTIFIER); break; case WRAP_IF_LONG: int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); old = indent; if (alignIndent >= 0) { indent = alignIndent; } spaces(spacesCnt, true); indent = old; ret = col; wrapDepth++; accept(JFXTokenId.IDENTIFIER); wrapDepth--; if (col > rightMargin && (wrapDepth == 0 || c <= rightMargin)) { rollback(index, c, d); old = indent; if (alignIndent >= 0) { indent = alignIndent; } newline(); indent = old; ret = col; accept(JFXTokenId.IDENTIFIER); } break; case WRAP_NEVER: old = indent; if (alignIndent >= 0) { indent = alignIndent; } spaces(spacesCnt, true); indent = old; ret = col; accept(JFXTokenId.IDENTIFIER); break; } return ret; } private int wrapOperatorAndTree(CodeStyle.WrapStyle wrapStyle, int alignIndent, int spacesCnt, Tree tree) { int ret = -1; switch (wrapStyle) { case WRAP_ALWAYS: int old = indent; if (alignIndent >= 0) { indent = alignIndent; } newline(); indent = old; ret = col; processOperator(spacesCnt); spaces(spacesCnt); scan(tree, null); break; case WRAP_IF_LONG: int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); old = indent; if (alignIndent >= 0) { indent = alignIndent; } spaces(spacesCnt, true); indent = old; ret = col; wrapDepth++; processOperator(spacesCnt); spaces(spacesCnt); scan(tree, null); wrapDepth--; if (col > rightMargin && (wrapDepth == 0 || c <= rightMargin)) { rollback(index, c, d); old = indent; if (alignIndent >= 0) { indent = alignIndent; } newline(); indent = old; ret = col; processOperator(spacesCnt); spaces(spacesCnt); scan(tree, null); } break; case WRAP_NEVER: old = indent; if (alignIndent >= 0) { indent = alignIndent; } spaces(spacesCnt, true); indent = old; ret = col; processOperator(spacesCnt); spaces(spacesCnt); scan(tree, null); break; } return ret; } private void processOperator(int spacesCnt) { if (OPERATOR.equals(tokens.token().id().primaryCategory())) { col += tokens.token().length(); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; tokens.moveNext(); } else { int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); final JFXTokenId accept = accept(JFXTokenId.AND, JFXTokenId.OR, JFXTokenId.MOD); if (accept != JFXTokenId.AND && accept != JFXTokenId.OR && accept != JFXTokenId.MOD) { rollback(index, c, d); } } } private boolean wrapStatement(CodeStyle.WrapStyle wrapStyle, CodeStyle.BracesGenerationStyle bracesGenerationStyle, int spacesCnt, ExpressionTree tree) { if (tree.getJavaFXKind() == JavaFXKind.EMPTY_STATEMENT) { scan(tree, null); return true; } if (tree.getJavaFXKind() == JavaFXKind.BLOCK_EXPRESSION) { // check this elimination if (bracesGenerationStyle == CodeStyle.BracesGenerationStyle.ELIMINATE) { Iterator<? extends ExpressionTree> stats = ((BlockExpressionTree) tree).getStatements().iterator(); if (stats.hasNext()) { ExpressionTree stat = stats.next(); if (!stats.hasNext() && stat.getJavaFXKind() != JavaFXKind.VARIABLE) { int start = tokens.offset(); accept(JFXTokenId.LBRACE); Diff d; while (!diffs.isEmpty() && (d = diffs.getFirst()) != null && d.getStartOffset() >= start) { diffs.removeFirst(); } addDiff(new Diff(start, tokens.offset(), null)); int old = indent; indent += indentSize; wrapTree(wrapStyle, -1, spacesCnt, stat); indent = old; start = tokens.offset(); accept(JFXTokenId.RBRACE); while (!diffs.isEmpty() && (d = diffs.getFirst()) != null && d.getStartOffset() >= start) { diffs.removeFirst(); } addDiff(new Diff(start, tokens.offset(), null)); return false; } } } scan(tree, null); return true; } // TODO generate braces if parent is function or class // if (bracesGenerationStyle == CodeStyle.BracesGenerationStyle.GENERATE) { // scan(new FakeBlock(tree), null); // return true; // } int old = indent; indent += indentSize; wrapTree(wrapStyle, -1, spacesCnt, tree); indent = old; return false; } private void wrapList(CodeStyle.WrapStyle wrapStyle, boolean align, boolean prependSpace, List<? extends Tree> trees) { boolean first = true; int alignIndent = -1; for (Iterator<? extends Tree> it = trees.iterator(); it.hasNext();) { Tree tree = it.next(); if (tree.getJavaFXKind() == JavaFXKind.ERRONEOUS) { scan(tree, null); } else if (first) { int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (prependSpace) { spaces(1, true); } if (align) { alignIndent = col; } scan(tree, null); if (wrapStyle != CodeStyle.WrapStyle.WRAP_NEVER && col > rightMargin && c > indent && (wrapDepth == 0 || c <= rightMargin)) { rollback(index, c, d); newline(); scan(tree, null); } } else { wrapTree(wrapStyle, alignIndent, cs.spaceAfterComma() ? 1 : 0, tree); } first = false; int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); JFXTokenId accepted = accept(JFXTokenId.COMMA); rollback(index, c, d); if (accepted == JFXTokenId.COMMA) { spaces(cs.spaceBeforeComma() ? 1 : 0); accept(JFXTokenId.COMMA); } } } private void wrapExtendsList(CodeStyle.WrapStyle wrapStyle, boolean align, boolean prependSpace, List<? extends Tree> trees) { boolean first = true; int alignIndent = -1; for (Iterator<? extends Tree> it = trees.iterator(); it.hasNext();) { Tree tree = it.next(); if (tree.getJavaFXKind() == JavaFXKind.ERRONEOUS) { scan(tree, null); } else if (first) { int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (prependSpace) { spaces(1, true); } if (align) { alignIndent = col; } accept(JFXTokenId.IDENTIFIER); if (wrapStyle != CodeStyle.WrapStyle.WRAP_NEVER && col > rightMargin && c > indent && (wrapDepth == 0 || c <= rightMargin)) { rollback(index, c, d); newline(); accept(JFXTokenId.IDENTIFIER); } } else { wrapExtendsTree(wrapStyle, alignIndent, cs.spaceAfterComma() ? 1 : 0, tree); } first = false; if (it.hasNext()) { spaces(cs.spaceBeforeComma() ? 1 : 0); accept(JFXTokenId.COMMA); } } } private void wrapFunctionalParamList(CodeStyle.WrapStyle wrapStyle, boolean align, List<? extends TypeTree> trees) { boolean first = true; int alignIndent = -1; for (Iterator<? extends TypeTree> it = trees.iterator(); it.hasNext();) { accept(JFXTokenId.COLON); spaces(cs.spaceAroundAssignOps() ? 1 : 0); // TODO space around colon in the type definition TypeTree param = it.next(); if (param.getJavaFXKind() == JavaFXKind.ERRONEOUS) { scan(param, null); } else if (first) { int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (align) { alignIndent = col; } scan(param, null); if (wrapStyle != CodeStyle.WrapStyle.WRAP_NEVER && col > rightMargin && c > indent && (wrapDepth == 0 || c <= rightMargin)) { rollback(index, c, d); newline(); scan(param, null); } } else { wrapTree(wrapStyle, alignIndent, cs.spaceAfterComma() ? 1 : 0, param); } first = false; if (it.hasNext()) { spaces(cs.spaceBeforeComma() ? 1 : 0); accept(JFXTokenId.COMMA); } } } private void wrapLiteralList(CodeStyle.WrapStyle wrapStyle, boolean align, Set<Tree> trees) { boolean first = true; int alignIndent = -1; for (Iterator<Tree> it = trees.iterator(); it.hasNext();) { Tree part = it.next(); if (part.getJavaFXKind() == JavaFXKind.ERRONEOUS) { scan(part, null); } else if (first) { int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (align) { alignIndent = col; } scan(part, null); if (wrapStyle != CodeStyle.WrapStyle.WRAP_NEVER && col > rightMargin && c > indent && (wrapDepth == 0 || c <= rightMargin)) { rollback(index, c, d); newline(); scan(part, null); } } else { wrapTree(wrapStyle, alignIndent, cs.spaceAfterComma() ? 1 : 0, part); } first = false; int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); JFXTokenId accepted = accept(JFXTokenId.COMMA, JFXTokenId.SEMI); if (accepted != JFXTokenId.COMMA && accepted != JFXTokenId.SEMI) { rollback(index, c, d); } } } private void indentComment() { if (tokens.token().id() != JFXTokenId.COMMENT && tokens.token().id() != JFXTokenId.DOC_COMMENT) { return; } String _indent = getIndent(); String text = tokens.token().text().toString(); int idx = 0; while ((idx = text.indexOf(NEWLINE, idx)) >= 0) { int i = idx + 1; while (i < text.length() && text.charAt(i) <= ' ' && text.charAt(i) != '\n') { // NOI18N i++; } if (i >= text.length()) { break; } String s = text.charAt(i) == '*' ? _indent + SPACE : _indent; // NOI18N if (!s.equals(text.substring(idx + 1, i))) { addDiff(new Diff(tokens.offset() + idx + 1, tokens.offset() + i, s)); //NOI18N } idx = i; } } private String getSpaces(int count) { if (count <= 0) { return EMPTY; } if (count == 1) { return SPACE; } StringBuilder sb = new StringBuilder(); while (count-- > 0) { sb.append(SPACE); } return sb.toString(); } private String getNewlines(int count) { if (count <= 0) { return EMPTY; } if (count == 1) { return NEWLINE; } StringBuilder sb = new StringBuilder(); while (count-- > 0) { sb.append(NEWLINE); } return sb.toString(); } private String getIndent() { StringBuilder sb = new StringBuilder(); int _col = 0; if (!expandTabToSpaces) { while (_col + tabSize <= indent) { sb.append('\t'); //NOI18N _col += tabSize; } } while (_col < indent) { sb.append(SPACE); _col++; } return sb.toString(); } private int getIndentLevel(TokenSequence<JFXTokenId> tokens, JavaFXTreePath path) { if (path.getLeaf().getJavaFXKind() == JavaFXKind.COMPILATION_UNIT) { return 0; } Tree lastTree = null; int _indent = -1; while (path != null) { int offset = (int) sp.getStartPosition(path.getCompilationUnit(), path.getLeaf()); if (offset < 0) { return _indent; } tokens.move(offset); String text = null; while (tokens.movePrevious()) { Token<JFXTokenId> token = tokens.token(); if (token.id() == JFXTokenId.WS) { text = token.text().toString(); int idx = text.lastIndexOf(NEWLINE); if (idx >= 0) { text = text.substring(idx + 1); _indent = getCol(text); break; } } else if (token.id() == JFXTokenId.LINE_COMMENT) { _indent = text != null ? getCol(text) : 0; break; } else if (token.id() == JFXTokenId.COMMENT || token.id() == JFXTokenId.DOC_COMMENT) { text = null; } else { break; } } if (_indent >= 0) { break; } lastTree = path.getLeaf(); path = path.getParentPath(); } if (lastTree != null && path != null) { switch (path.getLeaf().getJavaFXKind()) { case CLASS_DECLARATION: for (Tree tree : ((ClassDeclarationTree) path.getLeaf()).getClassMembers()) { if (tree == lastTree) { _indent += tabSize; break; } } break; case BLOCK_EXPRESSION: for (Tree tree : ((BlockExpressionTree) path.getLeaf()).getStatements()) { if (tree == lastTree) { _indent += tabSize; break; } } break; } } return _indent; } private int getCol(String text) { int _col = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c == '\t') { // NOI18N _col += tabSize; _col -= (_col % tabSize); } else { _col++; } } return _col; } private boolean isSynthetic(JFXTree node) { if (node instanceof BlockExpressionTree) { JavaFXTreePath pp = getCurrentPath().getParentPath(); if (pp != null && pp instanceof FunctionValueTree) { pp = pp.getParentPath(); JFXTree tree = (JFXTree) pp.getLeaf(); if (tree instanceof FunctionDefinitionTree) { return synthetic(tree); } } } return synthetic(node); } private boolean synthetic(JFXTree node) { return node.getGenType() == SyntheticTree.SynthType.SYNTHETIC || getStartPos(node) == getEndPos(node); } private long getEndPos(Tree node) { return sp.getEndPosition(root, node); } private long getStartPos(Tree node) { return sp.getStartPosition(root, node); } // TODO check flags when it will work // TODO create issue for compiler private static boolean hasModifiers(ModifiersTree mods) { if (mods == null) { return false; } final String p1 = "synthetic"; // NOI18N final String p2 = "script only (default)"; // NOI18N final String p3 = "static script only (default)"; // NOI18N final String m = mods.toString().trim(); return m.indexOf(p1) == -1 && !m.contentEquals(p2) && !m.contentEquals(p3); } private static class FakeBlock extends JFXBlock { // private ExpressionTree stat; private FakeBlock(ExpressionTree stat) { super(0L, com.sun.tools.mjavac.util.List.of((JFXExpression) stat), (JFXExpression) stat); // this.stat = stat; } } private static class DanglingElseChecker extends SimpleJavaFXTreeVisitor<Void, Void> { private boolean foundDanglingElse; public boolean hasDanglingElse(Tree t) { if (t == null) return false; foundDanglingElse = false; visit(t, null); return foundDanglingElse; } @Override public Void visitBlockExpression(BlockExpressionTree node, Void p) { // Do dangling else checks on single statement blocks since // they often get eliminated and replaced by their constained statement Iterator<? extends ExpressionTree> it = node.getStatements().iterator(); ExpressionTree stat = it.hasNext() ? it.next() : null; if (stat != null && !it.hasNext()) { visit(stat, p); } return null; } @Override public Void visitForExpressionInClause(ForExpressionInClauseTree node, Void p) { return visit(node.getWhereExpression(), p); } @Override public Void visitConditionalExpression(ConditionalExpressionTree node, Void p) { if (node.getFalseExpression() == null) foundDanglingElse = true; else visit(node.getFalseExpression(), p); return null; } @Override public Void visitWhileLoop(WhileLoopTree node, Void p) { return visit(node.getStatement(), p); } } } private static class Diff { private int start; private int end; private String text; private Diff(int start, int end, String text) { this.start = start; this.end = end; this.text = text; } public int getStartOffset() { return start; } public int getEndOffset() { return end; } public String getText() { return text; } @Override public String toString() { return "Diff<" + start + "," + end + ">:" + text; //NOI18N } } }
false
true
public Boolean visitBlockExpression(BlockExpressionTree node, Void p) { if (node.isStatic()) { accept(JFXTokenId.STATIC); } CodeStyle.BracePlacement bracePlacement; boolean spaceBeforeLeftBrace = false; Tree parentTree = getCurrentPath().getParentPath().getLeaf(); boolean magicFunc = false; if (parentTree instanceof JFXFunctionDefinition) { String name = ((JFXFunctionDefinition) parentTree).getName().toString(); magicFunc = MAGIC_FUNCTION.contentEquals(name) && isSynthetic((JFXTree) parentTree); } int halfIndent = 0; int old = 0; if (!magicFunc) { switch (parentTree.getJavaFXKind()) { case CLASS_DECLARATION: case INSTANTIATE_NEW: case INSTANTIATE_OBJECT_LITERAL: case ON_REPLACE: bracePlacement = cs.getOtherBracePlacement(); if (node.isStatic()) { spaceBeforeLeftBrace = cs.spaceBeforeStaticInitLeftBrace(); } break; case FUNCTION_DEFINITION: case FUNCTION_VALUE: bracePlacement = cs.getMethodDeclBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeMethodDeclLeftBrace(); break; case TRY: bracePlacement = cs.getOtherBracePlacement(); if (((TryTree) parentTree).getBlock() == node) { spaceBeforeLeftBrace = cs.spaceBeforeTryLeftBrace(); } else { spaceBeforeLeftBrace = cs.spaceBeforeFinallyLeftBrace(); } break; case CATCH: bracePlacement = cs.getOtherBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeCatchLeftBrace(); break; case WHILE_LOOP: bracePlacement = cs.getOtherBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeWhileLeftBrace(); break; case FOR_EXPRESSION_FOR: bracePlacement = cs.getOtherBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeForLeftBrace(); break; case CONDITIONAL_EXPRESSION: bracePlacement = cs.getOtherBracePlacement(); if (((JFXIfExpression) parentTree).getTrueExpression() == node) { spaceBeforeLeftBrace = cs.spaceBeforeIfLeftBrace(); } else { spaceBeforeLeftBrace = cs.spaceBeforeElseLeftBrace(); } break; default: bracePlacement = cs.getOtherBracePlacement(); break; } old = indent; halfIndent = indent; switch (bracePlacement) { case SAME_LINE: spaces(spaceBeforeLeftBrace ? 1 : 0); if (node instanceof FakeBlock) { appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); } indent += indentSize; break; case NEW_LINE: newline(); if (node instanceof FakeBlock) { indent += indentSize; appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); indent += indentSize; } break; case NEW_LINE_HALF_INDENTED: indent += (indentSize >> 1); halfIndent = indent; newline(); if (node instanceof FakeBlock) { indent = old + indentSize; appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); indent = old + indentSize; } break; case NEW_LINE_INDENTED: indent += indentSize; halfIndent = indent; newline(); if (node instanceof FakeBlock) { appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); } break; } } // boolean isEmpty = true; final List<ExpressionTree> expressions = new ArrayList<ExpressionTree>(); expressions.addAll(node.getStatements()); // JFXC-3284 if (expressions.isEmpty()) { final ExpressionTree value = node.getValue(); if (value != null) { expressions.add(value); } } for (ExpressionTree stat : expressions) { if (magicFunc || !isSynthetic((JFXTree) node)) { // isEmpty = false; if (node instanceof FakeBlock) { appendToDiff(getNewlines(1) + getIndent()); col = indent; } else { blankLines(); } // Missing return statement, compliler bug http://javafx-jira.kenai.com/browse/JFXC-3528 int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.RETURN) != JFXTokenId.RETURN) { rollback(index, c, d); } else { space(); } processExpression(stat, p); } } // if (isEmpty || templateEdit) { if (templateEdit) { newline(); } if (node instanceof FakeBlock) { indent = halfIndent; int i = tokens.index(); boolean loop = true; while (loop) { switch (tokens.token().id()) { case WS: if (tokens.token().text().toString().indexOf(NEWLINE) < 0) { tokens.moveNext(); } else { loop = false; appendToDiff(NEWLINE); col = 0; } break; case LINE_COMMENT: loop = false; case COMMENT: tokens.moveNext(); break; default: if (tokens.index() != i) { tokens.moveIndex(i); tokens.moveNext(); } loop = false; appendToDiff(NEWLINE); col = 0; } } appendToDiff(getIndent() + RCBRACE); col = indent + 1; lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { if (!magicFunc) { blankLines(); indent = halfIndent; Diff diff = diffs.isEmpty() ? null : diffs.getFirst(); if (diff != null && diff.end == tokens.offset()) { if (diff.text != null) { int idx = diff.text.lastIndexOf(NEWLINE); if (idx < 0) { diff.text = getIndent(); } else { diff.text = diff.text.substring(0, idx + 1) + getIndent(); } } String spaces = diff.text != null ? diff.text : getIndent(); if (spaces.equals(fText.substring(diff.start, diff.end))) { diffs.removeFirst(); } } else if (tokens.movePrevious()) { if (tokens.token().id() == JFXTokenId.WS) { String text = tokens.token().text().toString(); int idx = text.lastIndexOf(NEWLINE); if (idx >= 0) { text = text.substring(idx + 1); String ind = getIndent(); if (!ind.equals(text)) { addDiff(new Diff(tokens.offset() + idx + 1, tokens.offset() + tokens.token().length(), ind)); } } } tokens.moveNext(); } JFXTokenId accept = accept(JFXTokenId.RBRACE); indent = old; } } return true; }
public Boolean visitBlockExpression(BlockExpressionTree node, Void p) { if (node.isStatic()) { accept(JFXTokenId.STATIC); } CodeStyle.BracePlacement bracePlacement; boolean spaceBeforeLeftBrace = false; Tree parentTree = getCurrentPath().getParentPath().getLeaf(); boolean magicFunc = false; if (parentTree instanceof JFXFunctionDefinition) { String name = ((JFXFunctionDefinition) parentTree).getName().toString(); magicFunc = MAGIC_FUNCTION.contentEquals(name) && isSynthetic((JFXTree) parentTree); } int halfIndent = 0; int old = 0; if (!magicFunc) { switch (parentTree.getJavaFXKind()) { case CLASS_DECLARATION: case INSTANTIATE_NEW: case INSTANTIATE_OBJECT_LITERAL: case ON_REPLACE: bracePlacement = cs.getOtherBracePlacement(); if (node.isStatic()) { spaceBeforeLeftBrace = cs.spaceBeforeStaticInitLeftBrace(); } break; case FUNCTION_DEFINITION: case FUNCTION_VALUE: bracePlacement = cs.getMethodDeclBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeMethodDeclLeftBrace(); break; case TRY: bracePlacement = cs.getOtherBracePlacement(); if (((TryTree) parentTree).getBlock() == node) { spaceBeforeLeftBrace = cs.spaceBeforeTryLeftBrace(); } else { spaceBeforeLeftBrace = cs.spaceBeforeFinallyLeftBrace(); } break; case CATCH: bracePlacement = cs.getOtherBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeCatchLeftBrace(); break; case WHILE_LOOP: bracePlacement = cs.getOtherBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeWhileLeftBrace(); break; case FOR_EXPRESSION_FOR: bracePlacement = cs.getOtherBracePlacement(); spaceBeforeLeftBrace = cs.spaceBeforeForLeftBrace(); break; case CONDITIONAL_EXPRESSION: bracePlacement = cs.getOtherBracePlacement(); if (((JFXIfExpression) parentTree).getTrueExpression() == node) { spaceBeforeLeftBrace = cs.spaceBeforeIfLeftBrace(); } else { spaceBeforeLeftBrace = cs.spaceBeforeElseLeftBrace(); } break; default: bracePlacement = cs.getOtherBracePlacement(); break; } old = indent; halfIndent = indent; switch (bracePlacement) { case SAME_LINE: spaces(spaceBeforeLeftBrace ? 1 : 0); if (node instanceof FakeBlock) { appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); } indent += indentSize; break; case NEW_LINE: newline(); if (node instanceof FakeBlock) { indent += indentSize; appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); indent += indentSize; } break; case NEW_LINE_HALF_INDENTED: indent += (indentSize >> 1); halfIndent = indent; newline(); if (node instanceof FakeBlock) { indent = old + indentSize; appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); indent = old + indentSize; } break; case NEW_LINE_INDENTED: indent += indentSize; halfIndent = indent; newline(); if (node instanceof FakeBlock) { appendToDiff(LCBRACE); lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { accept(JFXTokenId.LBRACE); } break; } } // boolean isEmpty = true; final List<ExpressionTree> expressions = new ArrayList<ExpressionTree>(); expressions.addAll(node.getStatements()); // JFXC-3284 if (expressions.isEmpty()) { final ExpressionTree value = node.getValue(); if (value != null) { expressions.add(value); } } for (ExpressionTree stat : expressions) { if (magicFunc || !isSynthetic((JFXTree) node)) { // isEmpty = false; if (node instanceof FakeBlock) { appendToDiff(getNewlines(1) + getIndent()); col = indent; } else if (parentTree.getJavaFXKind() == JavaFXKind.FUNCTION_DEFINITION || parentTree.getJavaFXKind() == JavaFXKind.INSTANTIATE_OBJECT_LITERAL) { spaces(1, true); } else { blankLines(); } // Missing return statement, compliler bug http://javafx-jira.kenai.com/browse/JFXC-3528 int index = tokens.index(); int c = col; Diff d = diffs.isEmpty() ? null : diffs.getFirst(); if (accept(JFXTokenId.RETURN) != JFXTokenId.RETURN) { rollback(index, c, d); } else { space(); } processExpression(stat, p); } } // if (isEmpty || templateEdit) { if (templateEdit) { newline(); } if (node instanceof FakeBlock) { indent = halfIndent; int i = tokens.index(); boolean loop = true; while (loop) { switch (tokens.token().id()) { case WS: if (tokens.token().text().toString().indexOf(NEWLINE) < 0) { tokens.moveNext(); } else { loop = false; appendToDiff(NEWLINE); col = 0; } break; case LINE_COMMENT: loop = false; case COMMENT: tokens.moveNext(); break; default: if (tokens.index() != i) { tokens.moveIndex(i); tokens.moveNext(); } loop = false; appendToDiff(NEWLINE); col = 0; } } appendToDiff(getIndent() + RCBRACE); col = indent + 1; lastBlankLines = -1; lastBlankLinesTokenIndex = -1; lastBlankLinesDiff = null; } else { if (!magicFunc) { if (parentTree.getJavaFXKind() == JavaFXKind.FUNCTION_DEFINITION || parentTree.getJavaFXKind() == JavaFXKind.INSTANTIATE_OBJECT_LITERAL) { spaces(1, true); } else { blankLines(); } indent = halfIndent; Diff diff = diffs.isEmpty() ? null : diffs.getFirst(); if (diff != null && diff.end == tokens.offset()) { if (diff.text != null) { int idx = diff.text.lastIndexOf(NEWLINE); if (idx < 0) { diff.text = getIndent(); } else { diff.text = diff.text.substring(0, idx + 1) + getIndent(); } } String spaces = diff.text != null ? diff.text : getIndent(); if (spaces.equals(fText.substring(diff.start, diff.end))) { diffs.removeFirst(); } } else if (tokens.movePrevious()) { if (tokens.token().id() == JFXTokenId.WS) { String text = tokens.token().text().toString(); int idx = text.lastIndexOf(NEWLINE); if (idx >= 0) { text = text.substring(idx + 1); String ind = getIndent(); if (!ind.equals(text)) { addDiff(new Diff(tokens.offset() + idx + 1, tokens.offset() + tokens.token().length(), ind)); } } } tokens.moveNext(); } JFXTokenId accept = accept(JFXTokenId.RBRACE); indent = old; } } return true; }
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java index b6aca86e7..3bacc0c9a 100644 --- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java +++ b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java @@ -1,279 +1,279 @@ /******************************************************************************* * Copyright (c) 2008, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Cloudsmith Inc - bug fixes *******************************************************************************/ package org.eclipse.equinox.internal.p2.artifact.repository; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.core.helpers.Tracing; import org.eclipse.equinox.internal.p2.repository.DownloadStatus; import org.eclipse.equinox.internal.p2.repository.RepositoryTransport; import org.eclipse.equinox.internal.provisional.p2.repository.IRepository; import org.w3c.dom.*; import org.xml.sax.InputSource; /** * Mirror support class for repositories. This class implements * mirror support equivalent to the mirroring of update manager sites. A repository * optionally provides a mirror URL via the {@link IRepository#PROP_MIRRORS_URL} key. * The contents of the file at this URL is expected to be an XML document * containing a list of <mirror> elements. The mirrors are assumed to be already * sorted geographically with closer mirrors first. */ public class MirrorSelector { private static final double LOG2 = Math.log(2); /** * Encapsulates information about a single mirror */ public static class MirrorInfo implements Comparable { long bytesPerSecond; int failureCount; private final int initialRank; String locationString; public MirrorInfo(String location, int initialRank) { this.initialRank = initialRank; this.locationString = location; if (!locationString.endsWith("/")) //$NON-NLS-1$ locationString = locationString + "/"; //$NON-NLS-1$ failureCount = 0; bytesPerSecond = DownloadStatus.UNKNOWN_RATE; } /** * Comparison used to sort mirrors. */ public int compareTo(Object o) { if (!(o instanceof MirrorInfo)) return 0; MirrorInfo that = (MirrorInfo) o; //less failures is better if (this.failureCount != that.failureCount) return this.failureCount - that.failureCount; //faster is better if (this.bytesPerSecond != that.bytesPerSecond) return (int) (that.bytesPerSecond - this.bytesPerSecond); //trust that initial rank indicates geographical proximity return this.initialRank - that.initialRank; } public void incrementFailureCount() { this.failureCount++; } public void setBytesPerSecond(long newValue) { this.bytesPerSecond = newValue; } public String toString() { return "Mirror(" + locationString + ',' + failureCount + ',' + bytesPerSecond + ')'; //$NON-NLS-1$ } } /** * The URI of the base repository being mirrored. */ URI baseURI; MirrorInfo[] mirrors; private final IRepository repository; private final Random random = new Random(); /** * Constructs a mirror support class for the given repository. Mirrors are * not contacted and the mirrorsURL document is not parsed until a * mirror location request is sent. */ public MirrorSelector(IRepository repository) { this.repository = repository; try { String base = (String) repository.getProperties().get(IRepository.PROP_MIRRORS_BASE_URL); if (base != null) { this.baseURI = new URI(base); } else { URI repositoryLocation = repository.getLocation(); if (repositoryLocation != null) this.baseURI = repositoryLocation; } } catch (URISyntaxException e) { log("Error initializing mirrors for: " + repository.getLocation(), e); //$NON-NLS-1$ } } /** * Parses the given mirror URL to obtain the list of mirrors. Returns the mirrors, * or null if mirrors could not be computed. * * Originally copied from DefaultSiteParser.getMirrors in org.eclipse.update.core */ private MirrorInfo[] computeMirrors(String mirrorsURL) { try { String countryCode = Locale.getDefault().getCountry().toLowerCase(); int timeZone = (new GregorianCalendar()).get(Calendar.ZONE_OFFSET) / (60 * 60 * 1000); if (mirrorsURL.indexOf('?') != -1) { mirrorsURL = mirrorsURL + '&'; } else { mirrorsURL = mirrorsURL + '?'; } - mirrorsURL = mirrorsURL + "countryCode=" + countryCode + "&timeZone=" + timeZone + "&responseType=xml"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + mirrorsURL = mirrorsURL + "countryCode=" + countryCode + "&timeZone=" + timeZone + "&format=xml"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document document = null; // Use Transport to read the mirrors list (to benefit from proxy support, authentication, etc) RepositoryTransport transport = RepositoryTransport.getInstance(); InputSource input = new InputSource(mirrorsURL); input.setByteStream(transport.stream(URIUtil.fromString(mirrorsURL))); document = builder.parse(input); if (document == null) return null; NodeList mirrorNodes = document.getElementsByTagName("mirror"); //$NON-NLS-1$ int mirrorCount = mirrorNodes.getLength(); MirrorInfo[] infos = new MirrorInfo[mirrorCount + 1]; for (int i = 0; i < mirrorCount; i++) { Element mirrorNode = (Element) mirrorNodes.item(i); String infoURL = mirrorNode.getAttribute("url"); //$NON-NLS-1$ infos[i] = new MirrorInfo(infoURL, i); } //p2: add the base site as the last resort mirror so we can track download speed and failure rate infos[mirrorCount] = new MirrorInfo(baseURI.toString(), mirrorCount); return infos; } catch (Exception e) { // log if absolute url if (mirrorsURL != null && (mirrorsURL.startsWith("http://") //$NON-NLS-1$ || mirrorsURL.startsWith("https://") //$NON-NLS-1$ || mirrorsURL.startsWith("file://") //$NON-NLS-1$ || mirrorsURL.startsWith("ftp://") //$NON-NLS-1$ || mirrorsURL.startsWith("jar://"))) //$NON-NLS-1$ log("Error processing mirrors URL: " + mirrorsURL, e); //$NON-NLS-1$ return null; } } /** * Returns an equivalent location for the given artifact location in the base * repository. Always falls back to the given input location in case of failure * to compute mirrors. Never returns null. */ public synchronized URI getMirrorLocation(URI inputLocation) { Assert.isNotNull(inputLocation); if (baseURI == null) return inputLocation; URI relativeLocation = baseURI.relativize(inputLocation); //if we failed to relativize the location, we can't select a mirror if (relativeLocation == null || relativeLocation.isAbsolute()) return inputLocation; MirrorInfo selectedMirror = selectMirror(); if (selectedMirror == null) return inputLocation; if (Tracing.DEBUG_MIRRORS) Tracing.debug("Selected mirror for artifact " + inputLocation + ": " + selectedMirror); //$NON-NLS-1$ //$NON-NLS-2$ try { return new URI(selectedMirror.locationString + relativeLocation.getPath()); } catch (URISyntaxException e) { log("Unable to make location " + inputLocation + " relative to mirror " + selectedMirror.locationString, e); //$NON-NLS-1$ //$NON-NLS-2$ } return inputLocation; } /** * Returns the mirror locations for this repository, or <code>null</code> if * they could not be computed. */ private MirrorInfo[] initMirrors() { if (mirrors != null) return mirrors; String mirrorsURL = (String) repository.getProperties().get(IRepository.PROP_MIRRORS_URL); if (mirrorsURL != null) mirrors = computeMirrors(mirrorsURL); return mirrors; } private void log(String message, Throwable exception) { LogHelper.log(new Status(IStatus.ERROR, Activator.ID, message, exception)); } /** * Reports the result of a mirror download */ public synchronized void reportResult(String toDownload, IStatus result) { if (mirrors == null) return; for (int i = 0; i < mirrors.length; i++) { MirrorInfo mirror = mirrors[i]; if (toDownload.startsWith(mirror.locationString)) { if (!result.isOK() && result.getSeverity() != IStatus.CANCEL) mirror.incrementFailureCount(); if (result instanceof DownloadStatus) { long oldRate = mirror.bytesPerSecond; long newRate = ((DownloadStatus) result).getTransferRate(); //average old and new rate so one slow download doesn't ruin the mirror's reputation if (oldRate > 0) newRate = (oldRate + newRate) / 2; mirror.setBytesPerSecond(newRate); } if (Tracing.DEBUG_MIRRORS) Tracing.debug("Updated mirror " + mirror); //$NON-NLS-1$ Arrays.sort(mirrors); return; } } } /** * Return whether or not all the mirrors for this selector have proven to be invalid * @return whether or not there is a valid mirror in this selector. */ public synchronized boolean hasValidMirror() { // return true if there is a mirror and it has not failed. Since the mirrors // list is sorted with failures last, we only have to test the first element for failure. return mirrors != null && mirrors.length > 0 && mirrors[0].failureCount == 0; } /** * Selects a mirror from the given list of mirrors. Returns null if a mirror * could not be found. */ private MirrorInfo selectMirror() { initMirrors(); int mirrorCount; if (mirrors == null || (mirrorCount = mirrors.length) == 0) return null; //this is a function that randomly selects a mirror based on a logarithmic //distribution. Mirror 0 has a 1/2 chance of being selected, mirror 1 has a 1/4 chance, // mirror 2 has a 1/8 chance, etc. This introduces some variation in the mirror //selection, while still heavily favoring better mirrors //the algorithm computes the most significant digit in a binary number by computing the base 2 logarithm //if the first digit is most significant, mirror 0 is selected, if the second is most significant, mirror 1 is selected, etc int highestMirror = Math.min(15, mirrorCount); int result = (int) (Math.log(random.nextInt(1 << highestMirror) + 1) / LOG2); if (result >= highestMirror || result < 0) result = highestMirror - 1; MirrorInfo selected = mirrors[highestMirror - 1 - result]; //if we selected a mirror that has failed in the past, revert to best available mirror if (selected.failureCount > 0) selected = mirrors[0]; //for now, don't tolerate failing mirrors if (selected.failureCount > 0) return null; return selected; } }
true
true
private MirrorInfo[] computeMirrors(String mirrorsURL) { try { String countryCode = Locale.getDefault().getCountry().toLowerCase(); int timeZone = (new GregorianCalendar()).get(Calendar.ZONE_OFFSET) / (60 * 60 * 1000); if (mirrorsURL.indexOf('?') != -1) { mirrorsURL = mirrorsURL + '&'; } else { mirrorsURL = mirrorsURL + '?'; } mirrorsURL = mirrorsURL + "countryCode=" + countryCode + "&timeZone=" + timeZone + "&responseType=xml"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document document = null; // Use Transport to read the mirrors list (to benefit from proxy support, authentication, etc) RepositoryTransport transport = RepositoryTransport.getInstance(); InputSource input = new InputSource(mirrorsURL); input.setByteStream(transport.stream(URIUtil.fromString(mirrorsURL))); document = builder.parse(input); if (document == null) return null; NodeList mirrorNodes = document.getElementsByTagName("mirror"); //$NON-NLS-1$ int mirrorCount = mirrorNodes.getLength(); MirrorInfo[] infos = new MirrorInfo[mirrorCount + 1]; for (int i = 0; i < mirrorCount; i++) { Element mirrorNode = (Element) mirrorNodes.item(i); String infoURL = mirrorNode.getAttribute("url"); //$NON-NLS-1$ infos[i] = new MirrorInfo(infoURL, i); } //p2: add the base site as the last resort mirror so we can track download speed and failure rate infos[mirrorCount] = new MirrorInfo(baseURI.toString(), mirrorCount); return infos; } catch (Exception e) { // log if absolute url if (mirrorsURL != null && (mirrorsURL.startsWith("http://") //$NON-NLS-1$ || mirrorsURL.startsWith("https://") //$NON-NLS-1$ || mirrorsURL.startsWith("file://") //$NON-NLS-1$ || mirrorsURL.startsWith("ftp://") //$NON-NLS-1$ || mirrorsURL.startsWith("jar://"))) //$NON-NLS-1$ log("Error processing mirrors URL: " + mirrorsURL, e); //$NON-NLS-1$ return null; } }
private MirrorInfo[] computeMirrors(String mirrorsURL) { try { String countryCode = Locale.getDefault().getCountry().toLowerCase(); int timeZone = (new GregorianCalendar()).get(Calendar.ZONE_OFFSET) / (60 * 60 * 1000); if (mirrorsURL.indexOf('?') != -1) { mirrorsURL = mirrorsURL + '&'; } else { mirrorsURL = mirrorsURL + '?'; } mirrorsURL = mirrorsURL + "countryCode=" + countryCode + "&timeZone=" + timeZone + "&format=xml"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document document = null; // Use Transport to read the mirrors list (to benefit from proxy support, authentication, etc) RepositoryTransport transport = RepositoryTransport.getInstance(); InputSource input = new InputSource(mirrorsURL); input.setByteStream(transport.stream(URIUtil.fromString(mirrorsURL))); document = builder.parse(input); if (document == null) return null; NodeList mirrorNodes = document.getElementsByTagName("mirror"); //$NON-NLS-1$ int mirrorCount = mirrorNodes.getLength(); MirrorInfo[] infos = new MirrorInfo[mirrorCount + 1]; for (int i = 0; i < mirrorCount; i++) { Element mirrorNode = (Element) mirrorNodes.item(i); String infoURL = mirrorNode.getAttribute("url"); //$NON-NLS-1$ infos[i] = new MirrorInfo(infoURL, i); } //p2: add the base site as the last resort mirror so we can track download speed and failure rate infos[mirrorCount] = new MirrorInfo(baseURI.toString(), mirrorCount); return infos; } catch (Exception e) { // log if absolute url if (mirrorsURL != null && (mirrorsURL.startsWith("http://") //$NON-NLS-1$ || mirrorsURL.startsWith("https://") //$NON-NLS-1$ || mirrorsURL.startsWith("file://") //$NON-NLS-1$ || mirrorsURL.startsWith("ftp://") //$NON-NLS-1$ || mirrorsURL.startsWith("jar://"))) //$NON-NLS-1$ log("Error processing mirrors URL: " + mirrorsURL, e); //$NON-NLS-1$ return null; } }
diff --git a/maven-cli/src/main/java/org/apache/maven/cli/MavenCli.java b/maven-cli/src/main/java/org/apache/maven/cli/MavenCli.java index 2ab966497..b3c6b3f27 100644 --- a/maven-cli/src/main/java/org/apache/maven/cli/MavenCli.java +++ b/maven-cli/src/main/java/org/apache/maven/cli/MavenCli.java @@ -1,508 +1,509 @@ package org.apache.maven.cli; /* * 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.apache.commons.cli.CommandLine; import org.apache.commons.cli.ParseException; import org.apache.maven.MavenTransferListener; import org.apache.maven.SettingsConfigurationException; import org.apache.maven.embedder.MavenEmbedder; import org.apache.maven.embedder.MavenEmbedderException; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.reactor.MavenExecutionException; import org.apache.maven.settings.Settings; import org.codehaus.classworlds.ClassWorld; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; /** * @author jason van zyl * @version $Id$ * @noinspection UseOfSystemOutOrSystemErr,ACCESS_STATIC_VIA_INSTANCE */ public class MavenCli { /** * @noinspection ConfusingMainMethod */ public static int main( String[] args, ClassWorld classWorld ) { // ---------------------------------------------------------------------- // Setup the command line parser // ---------------------------------------------------------------------- CLIManager cliManager = new CLIManager(); CommandLine commandLine; try { commandLine = cliManager.parse( args ); } catch ( ParseException e ) { System.err.println( "Unable to parse command line options: " + e.getMessage() ); cliManager.displayHelp(); return 1; } // TODO: maybe classworlds could handle this requirement... if ( System.getProperty( "java.class.version", "44.0" ).compareTo( "48.0" ) < 0 ) { System.err.println( "Sorry, but JDK 1.4 or above is required to execute Maven" ); System.err.println( "You appear to be using Java version: " + System.getProperty( "java.version", "<unknown>" ) ); return 1; } boolean debug = commandLine.hasOption( CLIManager.DEBUG ); + boolean quiet = !debug && commandLine.hasOption( CLIManager.QUIET ); boolean showErrors = debug || commandLine.hasOption( CLIManager.ERRORS ); if ( showErrors ) { System.out.println( "+ Error stacktraces are turned on." ); } // ---------------------------------------------------------------------- // Process particular command line options // ---------------------------------------------------------------------- if ( commandLine.hasOption( CLIManager.HELP ) ) { cliManager.displayHelp(); return 0; } if ( commandLine.hasOption( CLIManager.VERSION ) ) { showVersion(); return 0; } else if ( debug ) { showVersion(); } // ---------------------------------------------------------------------- // Now that we have everything that we need we will fire up plexus and // bring the maven component to life for use. // ---------------------------------------------------------------------- //** use CLI option values directly in request where possible MavenEmbedder mavenEmbedder = new MavenEmbedder(); try { mavenEmbedder.setClassWorld( classWorld ); mavenEmbedder.start(); } catch ( MavenEmbedderException e ) { showFatalError( "Unable to start the embedded plexus container", e, showErrors ); return 1; } boolean interactive = true; if ( commandLine.hasOption( CLIManager.BATCH_MODE ) ) { interactive = false; } boolean usePluginRegistry = true; if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_REGISTRY ) ) { usePluginRegistry = false; } Boolean pluginUpdateOverride = Boolean.FALSE; if ( commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES ) || commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES2 ) ) { pluginUpdateOverride = Boolean.TRUE; } else if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_UPDATES ) ) { pluginUpdateOverride = Boolean.FALSE; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- try { List goals = commandLine.getArgList(); boolean recursive = true; String reactorFailureBehaviour = null; if ( commandLine.hasOption( CLIManager.NON_RECURSIVE ) ) { recursive = false; } - else if ( commandLine.hasOption( CLIManager.QUIET ) ) - { - // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level. - // Ideally, we could use Warn across the board - loggerManager.setThreshold( Logger.LEVEL_ERROR ); - // TODO:Additionally, we can't change the mojo level because the component key includes the version and it isn't known ahead of time. This seems worth changing. - } if ( commandLine.hasOption( CLIManager.FAIL_FAST ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; } else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END; } else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER; } boolean offline = false; if ( commandLine.hasOption( CLIManager.OFFLINE ) ) { offline = true; } boolean updateSnapshots = false; if ( commandLine.hasOption( CLIManager.UPDATE_SNAPSHOTS ) ) { updateSnapshots = true; } String globalChecksumPolicy = null; if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) ) { // todo; log System.out.println( "+ Enabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL; } else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) ) { // todo: log System.out.println( "+ Disabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN; } File baseDirectory = new File( System.getProperty( "user.dir" ) ); // ---------------------------------------------------------------------- // Profile Activation // ---------------------------------------------------------------------- List activeProfiles = new ArrayList(); List inactiveProfiles = new ArrayList(); if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) ) { String profilesLine = commandLine.getOptionValue( CLIManager.ACTIVATE_PROFILES ); StringTokenizer profileTokens = new StringTokenizer( profilesLine, "," ); while ( profileTokens.hasMoreTokens() ) { String profileAction = profileTokens.nextToken().trim(); if ( profileAction.startsWith( "-" ) ) { activeProfiles.add( profileAction.substring( 1 ) ); } else if ( profileAction.startsWith( "+" ) ) { inactiveProfiles.add( profileAction.substring( 1 ) ); } else { // TODO: deprecate this eventually! activeProfiles.add( profileAction ); } } } MavenTransferListener transferListener; if ( interactive ) { transferListener = new ConsoleDownloadMonitor(); } else { transferListener = new BatchModeDownloadMonitor(); } boolean reactorActive = false; if ( commandLine.hasOption( CLIManager.REACTOR ) ) { reactorActive = true; } String alternatePomFile = null; if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) ) { alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE ); } // ---------------------------------------------------------------------- // From here we are CLI free // ---------------------------------------------------------------------- // -> baseDirectory // -> goals // -> debug: use to set the threshold on the logger manager // -> active profiles (settings) // -> inactive profiles (settings) // -> offline (settings) // -> interactive (settings) // -> Settings // -> localRepository // -> interactiveMode // -> usePluginRegistry // -> offline // -> proxies // -> servers // -> mirrors // -> profiles // -> activeProfiles // -> pluginGroups // -> executionProperties // -> reactorFailureBehaviour: fail fast, fail at end, fail never // -> globalChecksumPolicy: fail, warn // -> showErrors (this is really CLI is but used inside Maven internals // -> recursive // -> updateSnapshots // -> reactorActive // -> transferListener: in the CLI this is batch or console // We have a general problem with plexus components that are singletons in that they use // the same logger for their lifespan. This is not good in that many requests may be fired // off and the singleton plexus component will continue to funnel their output to the same // logger. We need to be able to swap the logger. // the local repository should just be a path and we should look here: // in the system property // user specified settings.xml // default ~/.m2/settings.xml // and with that maven internals should contruct the ArtifactRepository object int loggingLevel; if ( debug ) { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_DEBUG; } + else if ( quiet ) + { + // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level. + // Ideally, we could use Warn across the board + loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_ERROR; + // TODO:Additionally, we can't change the mojo level because the component key includes the version and it isn't known ahead of time. This seems worth changing. + } else { - loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_WARN; + loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_INFO; } Properties executionProperties = getExecutionProperties( commandLine ); File userSettingsPath = mavenEmbedder.getUserSettingsPath( commandLine.getOptionValue( CLIManager.ALTERNATE_USER_SETTINGS ) ); File globalSettingsFile = mavenEmbedder.getGlobalSettingsPath(); Settings settings = mavenEmbedder.buildSettings( userSettingsPath, globalSettingsFile, interactive, offline, usePluginRegistry, pluginUpdateOverride ); String localRepositoryPath = mavenEmbedder.getLocalRepositoryPath( settings ); // @todo we either make Settings the official configuration mechanism or allow the indiviaul setting in the request // for each of the things in the settings object. Seems redundant to configure some things via settings and // some via the request. The Settings object is used in about 16 different places in the core so something // to consider. MavenExecutionRequest request = new DefaultMavenExecutionRequest() .setBasedir( baseDirectory ) .setGoals( goals ) .setLocalRepositoryPath( localRepositoryPath ) .setProperties( executionProperties ) .setFailureBehavior( reactorFailureBehaviour ) .setRecursive( recursive ) .setReactorActive( reactorActive ) .setPomFile( alternatePomFile ) .setShowErrors( showErrors ) .setInteractive( interactive ) .addActiveProfiles( activeProfiles ) .addInactiveProfiles( inactiveProfiles ) .setLoggingLevel( loggingLevel ) .activateDefaultEventMonitor() .setSettings( settings ) .setTransferListener( transferListener ) .setOffline( offline ) .setUpdateSnapshots( updateSnapshots ) .setGlobalChecksumPolicy( globalChecksumPolicy ); mavenEmbedder.execute( request ); } catch ( SettingsConfigurationException e ) { showError( "Error reading settings.xml: " + e.getMessage(), e, showErrors ); return 1; } catch ( MavenExecutionException e ) { showFatalError( "Unable to configure the Maven application", e, showErrors ); return 1; } return 0; } private static void showFatalError( String message, Exception e, boolean show ) { System.err.println( "FATAL ERROR: " + message ); if ( show ) { System.err.println( "Error stacktrace:" ); e.printStackTrace(); } else { System.err.println( "For more information, run with the -e flag" ); } } private static void showError( String message, Exception e, boolean show ) { System.err.println( message ); if ( show ) { System.err.println( "Error stacktrace:" ); e.printStackTrace(); } } private static void showVersion() { InputStream resourceAsStream; try { Properties properties = new Properties(); resourceAsStream = MavenCli.class.getClassLoader().getResourceAsStream( "META-INF/maven/org.apache.maven/maven-core/pom.properties" ); properties.load( resourceAsStream ); if ( properties.getProperty( "builtOn" ) != null ) { System.out.println( "Maven version: " + properties.getProperty( "version", "unknown" ) + " built on " + properties.getProperty( "builtOn" ) ); } else { System.out.println( "Maven version: " + properties.getProperty( "version", "unknown" ) ); } } catch ( IOException e ) { System.err.println( "Unable determine version from JAR file: " + e.getMessage() ); } } // ---------------------------------------------------------------------- // System properties handling // ---------------------------------------------------------------------- private static Properties getExecutionProperties( CommandLine commandLine ) { Properties executionProperties = new Properties(); // ---------------------------------------------------------------------- // Options that are set on the command line become system properties // and therefore are set in the session properties. System properties // are most dominant. // ---------------------------------------------------------------------- if ( commandLine.hasOption( CLIManager.SET_SYSTEM_PROPERTY ) ) { String[] defStrs = commandLine.getOptionValues( CLIManager.SET_SYSTEM_PROPERTY ); for ( int i = 0; i < defStrs.length; ++i ) { setCliProperty( defStrs[i], executionProperties ); } } executionProperties.putAll( System.getProperties() ); return executionProperties; } private static void setCliProperty( String property, Properties executionProperties ) { String name; String value; int i = property.indexOf( "=" ); if ( i <= 0 ) { name = property.trim(); value = "true"; } else { name = property.substring( 0, i ).trim(); value = property.substring( i + 1 ).trim(); } executionProperties.setProperty( name, value ); // ---------------------------------------------------------------------- // I'm leaving the setting of system properties here as not to break // the SystemPropertyProfileActivator. This won't harm embedding. jvz. // ---------------------------------------------------------------------- System.setProperty( name, value ); } }
false
true
public static int main( String[] args, ClassWorld classWorld ) { // ---------------------------------------------------------------------- // Setup the command line parser // ---------------------------------------------------------------------- CLIManager cliManager = new CLIManager(); CommandLine commandLine; try { commandLine = cliManager.parse( args ); } catch ( ParseException e ) { System.err.println( "Unable to parse command line options: " + e.getMessage() ); cliManager.displayHelp(); return 1; } // TODO: maybe classworlds could handle this requirement... if ( System.getProperty( "java.class.version", "44.0" ).compareTo( "48.0" ) < 0 ) { System.err.println( "Sorry, but JDK 1.4 or above is required to execute Maven" ); System.err.println( "You appear to be using Java version: " + System.getProperty( "java.version", "<unknown>" ) ); return 1; } boolean debug = commandLine.hasOption( CLIManager.DEBUG ); boolean showErrors = debug || commandLine.hasOption( CLIManager.ERRORS ); if ( showErrors ) { System.out.println( "+ Error stacktraces are turned on." ); } // ---------------------------------------------------------------------- // Process particular command line options // ---------------------------------------------------------------------- if ( commandLine.hasOption( CLIManager.HELP ) ) { cliManager.displayHelp(); return 0; } if ( commandLine.hasOption( CLIManager.VERSION ) ) { showVersion(); return 0; } else if ( debug ) { showVersion(); } // ---------------------------------------------------------------------- // Now that we have everything that we need we will fire up plexus and // bring the maven component to life for use. // ---------------------------------------------------------------------- //** use CLI option values directly in request where possible MavenEmbedder mavenEmbedder = new MavenEmbedder(); try { mavenEmbedder.setClassWorld( classWorld ); mavenEmbedder.start(); } catch ( MavenEmbedderException e ) { showFatalError( "Unable to start the embedded plexus container", e, showErrors ); return 1; } boolean interactive = true; if ( commandLine.hasOption( CLIManager.BATCH_MODE ) ) { interactive = false; } boolean usePluginRegistry = true; if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_REGISTRY ) ) { usePluginRegistry = false; } Boolean pluginUpdateOverride = Boolean.FALSE; if ( commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES ) || commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES2 ) ) { pluginUpdateOverride = Boolean.TRUE; } else if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_UPDATES ) ) { pluginUpdateOverride = Boolean.FALSE; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- try { List goals = commandLine.getArgList(); boolean recursive = true; String reactorFailureBehaviour = null; if ( commandLine.hasOption( CLIManager.NON_RECURSIVE ) ) { recursive = false; } else if ( commandLine.hasOption( CLIManager.QUIET ) ) { // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level. // Ideally, we could use Warn across the board loggerManager.setThreshold( Logger.LEVEL_ERROR ); // TODO:Additionally, we can't change the mojo level because the component key includes the version and it isn't known ahead of time. This seems worth changing. } if ( commandLine.hasOption( CLIManager.FAIL_FAST ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; } else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END; } else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER; } boolean offline = false; if ( commandLine.hasOption( CLIManager.OFFLINE ) ) { offline = true; } boolean updateSnapshots = false; if ( commandLine.hasOption( CLIManager.UPDATE_SNAPSHOTS ) ) { updateSnapshots = true; } String globalChecksumPolicy = null; if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) ) { // todo; log System.out.println( "+ Enabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL; } else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) ) { // todo: log System.out.println( "+ Disabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN; } File baseDirectory = new File( System.getProperty( "user.dir" ) ); // ---------------------------------------------------------------------- // Profile Activation // ---------------------------------------------------------------------- List activeProfiles = new ArrayList(); List inactiveProfiles = new ArrayList(); if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) ) { String profilesLine = commandLine.getOptionValue( CLIManager.ACTIVATE_PROFILES ); StringTokenizer profileTokens = new StringTokenizer( profilesLine, "," ); while ( profileTokens.hasMoreTokens() ) { String profileAction = profileTokens.nextToken().trim(); if ( profileAction.startsWith( "-" ) ) { activeProfiles.add( profileAction.substring( 1 ) ); } else if ( profileAction.startsWith( "+" ) ) { inactiveProfiles.add( profileAction.substring( 1 ) ); } else { // TODO: deprecate this eventually! activeProfiles.add( profileAction ); } } } MavenTransferListener transferListener; if ( interactive ) { transferListener = new ConsoleDownloadMonitor(); } else { transferListener = new BatchModeDownloadMonitor(); } boolean reactorActive = false; if ( commandLine.hasOption( CLIManager.REACTOR ) ) { reactorActive = true; } String alternatePomFile = null; if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) ) { alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE ); } // ---------------------------------------------------------------------- // From here we are CLI free // ---------------------------------------------------------------------- // -> baseDirectory // -> goals // -> debug: use to set the threshold on the logger manager // -> active profiles (settings) // -> inactive profiles (settings) // -> offline (settings) // -> interactive (settings) // -> Settings // -> localRepository // -> interactiveMode // -> usePluginRegistry // -> offline // -> proxies // -> servers // -> mirrors // -> profiles // -> activeProfiles // -> pluginGroups // -> executionProperties // -> reactorFailureBehaviour: fail fast, fail at end, fail never // -> globalChecksumPolicy: fail, warn // -> showErrors (this is really CLI is but used inside Maven internals // -> recursive // -> updateSnapshots // -> reactorActive // -> transferListener: in the CLI this is batch or console // We have a general problem with plexus components that are singletons in that they use // the same logger for their lifespan. This is not good in that many requests may be fired // off and the singleton plexus component will continue to funnel their output to the same // logger. We need to be able to swap the logger. // the local repository should just be a path and we should look here: // in the system property // user specified settings.xml // default ~/.m2/settings.xml // and with that maven internals should contruct the ArtifactRepository object int loggingLevel; if ( debug ) { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_DEBUG; } else { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_WARN; } Properties executionProperties = getExecutionProperties( commandLine ); File userSettingsPath = mavenEmbedder.getUserSettingsPath( commandLine.getOptionValue( CLIManager.ALTERNATE_USER_SETTINGS ) ); File globalSettingsFile = mavenEmbedder.getGlobalSettingsPath(); Settings settings = mavenEmbedder.buildSettings( userSettingsPath, globalSettingsFile, interactive, offline, usePluginRegistry, pluginUpdateOverride ); String localRepositoryPath = mavenEmbedder.getLocalRepositoryPath( settings ); // @todo we either make Settings the official configuration mechanism or allow the indiviaul setting in the request // for each of the things in the settings object. Seems redundant to configure some things via settings and // some via the request. The Settings object is used in about 16 different places in the core so something // to consider. MavenExecutionRequest request = new DefaultMavenExecutionRequest() .setBasedir( baseDirectory ) .setGoals( goals ) .setLocalRepositoryPath( localRepositoryPath ) .setProperties( executionProperties ) .setFailureBehavior( reactorFailureBehaviour ) .setRecursive( recursive ) .setReactorActive( reactorActive ) .setPomFile( alternatePomFile ) .setShowErrors( showErrors ) .setInteractive( interactive ) .addActiveProfiles( activeProfiles ) .addInactiveProfiles( inactiveProfiles ) .setLoggingLevel( loggingLevel ) .activateDefaultEventMonitor() .setSettings( settings ) .setTransferListener( transferListener ) .setOffline( offline ) .setUpdateSnapshots( updateSnapshots ) .setGlobalChecksumPolicy( globalChecksumPolicy ); mavenEmbedder.execute( request ); } catch ( SettingsConfigurationException e ) { showError( "Error reading settings.xml: " + e.getMessage(), e, showErrors ); return 1; } catch ( MavenExecutionException e ) { showFatalError( "Unable to configure the Maven application", e, showErrors ); return 1; } return 0; }
public static int main( String[] args, ClassWorld classWorld ) { // ---------------------------------------------------------------------- // Setup the command line parser // ---------------------------------------------------------------------- CLIManager cliManager = new CLIManager(); CommandLine commandLine; try { commandLine = cliManager.parse( args ); } catch ( ParseException e ) { System.err.println( "Unable to parse command line options: " + e.getMessage() ); cliManager.displayHelp(); return 1; } // TODO: maybe classworlds could handle this requirement... if ( System.getProperty( "java.class.version", "44.0" ).compareTo( "48.0" ) < 0 ) { System.err.println( "Sorry, but JDK 1.4 or above is required to execute Maven" ); System.err.println( "You appear to be using Java version: " + System.getProperty( "java.version", "<unknown>" ) ); return 1; } boolean debug = commandLine.hasOption( CLIManager.DEBUG ); boolean quiet = !debug && commandLine.hasOption( CLIManager.QUIET ); boolean showErrors = debug || commandLine.hasOption( CLIManager.ERRORS ); if ( showErrors ) { System.out.println( "+ Error stacktraces are turned on." ); } // ---------------------------------------------------------------------- // Process particular command line options // ---------------------------------------------------------------------- if ( commandLine.hasOption( CLIManager.HELP ) ) { cliManager.displayHelp(); return 0; } if ( commandLine.hasOption( CLIManager.VERSION ) ) { showVersion(); return 0; } else if ( debug ) { showVersion(); } // ---------------------------------------------------------------------- // Now that we have everything that we need we will fire up plexus and // bring the maven component to life for use. // ---------------------------------------------------------------------- //** use CLI option values directly in request where possible MavenEmbedder mavenEmbedder = new MavenEmbedder(); try { mavenEmbedder.setClassWorld( classWorld ); mavenEmbedder.start(); } catch ( MavenEmbedderException e ) { showFatalError( "Unable to start the embedded plexus container", e, showErrors ); return 1; } boolean interactive = true; if ( commandLine.hasOption( CLIManager.BATCH_MODE ) ) { interactive = false; } boolean usePluginRegistry = true; if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_REGISTRY ) ) { usePluginRegistry = false; } Boolean pluginUpdateOverride = Boolean.FALSE; if ( commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES ) || commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES2 ) ) { pluginUpdateOverride = Boolean.TRUE; } else if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_UPDATES ) ) { pluginUpdateOverride = Boolean.FALSE; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- try { List goals = commandLine.getArgList(); boolean recursive = true; String reactorFailureBehaviour = null; if ( commandLine.hasOption( CLIManager.NON_RECURSIVE ) ) { recursive = false; } if ( commandLine.hasOption( CLIManager.FAIL_FAST ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; } else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END; } else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER; } boolean offline = false; if ( commandLine.hasOption( CLIManager.OFFLINE ) ) { offline = true; } boolean updateSnapshots = false; if ( commandLine.hasOption( CLIManager.UPDATE_SNAPSHOTS ) ) { updateSnapshots = true; } String globalChecksumPolicy = null; if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) ) { // todo; log System.out.println( "+ Enabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL; } else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) ) { // todo: log System.out.println( "+ Disabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN; } File baseDirectory = new File( System.getProperty( "user.dir" ) ); // ---------------------------------------------------------------------- // Profile Activation // ---------------------------------------------------------------------- List activeProfiles = new ArrayList(); List inactiveProfiles = new ArrayList(); if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) ) { String profilesLine = commandLine.getOptionValue( CLIManager.ACTIVATE_PROFILES ); StringTokenizer profileTokens = new StringTokenizer( profilesLine, "," ); while ( profileTokens.hasMoreTokens() ) { String profileAction = profileTokens.nextToken().trim(); if ( profileAction.startsWith( "-" ) ) { activeProfiles.add( profileAction.substring( 1 ) ); } else if ( profileAction.startsWith( "+" ) ) { inactiveProfiles.add( profileAction.substring( 1 ) ); } else { // TODO: deprecate this eventually! activeProfiles.add( profileAction ); } } } MavenTransferListener transferListener; if ( interactive ) { transferListener = new ConsoleDownloadMonitor(); } else { transferListener = new BatchModeDownloadMonitor(); } boolean reactorActive = false; if ( commandLine.hasOption( CLIManager.REACTOR ) ) { reactorActive = true; } String alternatePomFile = null; if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) ) { alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE ); } // ---------------------------------------------------------------------- // From here we are CLI free // ---------------------------------------------------------------------- // -> baseDirectory // -> goals // -> debug: use to set the threshold on the logger manager // -> active profiles (settings) // -> inactive profiles (settings) // -> offline (settings) // -> interactive (settings) // -> Settings // -> localRepository // -> interactiveMode // -> usePluginRegistry // -> offline // -> proxies // -> servers // -> mirrors // -> profiles // -> activeProfiles // -> pluginGroups // -> executionProperties // -> reactorFailureBehaviour: fail fast, fail at end, fail never // -> globalChecksumPolicy: fail, warn // -> showErrors (this is really CLI is but used inside Maven internals // -> recursive // -> updateSnapshots // -> reactorActive // -> transferListener: in the CLI this is batch or console // We have a general problem with plexus components that are singletons in that they use // the same logger for their lifespan. This is not good in that many requests may be fired // off and the singleton plexus component will continue to funnel their output to the same // logger. We need to be able to swap the logger. // the local repository should just be a path and we should look here: // in the system property // user specified settings.xml // default ~/.m2/settings.xml // and with that maven internals should contruct the ArtifactRepository object int loggingLevel; if ( debug ) { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_DEBUG; } else if ( quiet ) { // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level. // Ideally, we could use Warn across the board loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_ERROR; // TODO:Additionally, we can't change the mojo level because the component key includes the version and it isn't known ahead of time. This seems worth changing. } else { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_INFO; } Properties executionProperties = getExecutionProperties( commandLine ); File userSettingsPath = mavenEmbedder.getUserSettingsPath( commandLine.getOptionValue( CLIManager.ALTERNATE_USER_SETTINGS ) ); File globalSettingsFile = mavenEmbedder.getGlobalSettingsPath(); Settings settings = mavenEmbedder.buildSettings( userSettingsPath, globalSettingsFile, interactive, offline, usePluginRegistry, pluginUpdateOverride ); String localRepositoryPath = mavenEmbedder.getLocalRepositoryPath( settings ); // @todo we either make Settings the official configuration mechanism or allow the indiviaul setting in the request // for each of the things in the settings object. Seems redundant to configure some things via settings and // some via the request. The Settings object is used in about 16 different places in the core so something // to consider. MavenExecutionRequest request = new DefaultMavenExecutionRequest() .setBasedir( baseDirectory ) .setGoals( goals ) .setLocalRepositoryPath( localRepositoryPath ) .setProperties( executionProperties ) .setFailureBehavior( reactorFailureBehaviour ) .setRecursive( recursive ) .setReactorActive( reactorActive ) .setPomFile( alternatePomFile ) .setShowErrors( showErrors ) .setInteractive( interactive ) .addActiveProfiles( activeProfiles ) .addInactiveProfiles( inactiveProfiles ) .setLoggingLevel( loggingLevel ) .activateDefaultEventMonitor() .setSettings( settings ) .setTransferListener( transferListener ) .setOffline( offline ) .setUpdateSnapshots( updateSnapshots ) .setGlobalChecksumPolicy( globalChecksumPolicy ); mavenEmbedder.execute( request ); } catch ( SettingsConfigurationException e ) { showError( "Error reading settings.xml: " + e.getMessage(), e, showErrors ); return 1; } catch ( MavenExecutionException e ) { showFatalError( "Unable to configure the Maven application", e, showErrors ); return 1; } return 0; }
diff --git a/hk2/core/src/java/com/sun/enterprise/module/bootstrap/Main.java b/hk2/core/src/java/com/sun/enterprise/module/bootstrap/Main.java index 65926b6a5..64a3899c7 100644 --- a/hk2/core/src/java/com/sun/enterprise/module/bootstrap/Main.java +++ b/hk2/core/src/java/com/sun/enterprise/module/bootstrap/Main.java @@ -1,489 +1,489 @@ /* * * 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. */ /* * Main.java * * Created on October 17, 2006, 11:28 AM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.sun.enterprise.module.bootstrap; import com.sun.enterprise.module.ManifestConstants; import com.sun.enterprise.module.InhabitantsDescriptor; import com.sun.enterprise.module.impl.HK2Factory; import com.sun.enterprise.module.Repository; import com.sun.enterprise.module.ModulesRegistry; import com.sun.enterprise.module.Module; import com.sun.enterprise.module.common_impl.DirectoryBasedRepository; import com.sun.enterprise.module.common_impl.AbstractFactory; import com.sun.enterprise.module.common_impl.LogHelper; import com.sun.hk2.component.ExistingSingletonInhabitant; import static com.sun.hk2.component.InhabitantsFile.CLASS_KEY; import static com.sun.hk2.component.InhabitantsFile.INDEX_KEY; import com.sun.hk2.component.InhabitantParser; import com.sun.hk2.component.KeyValuePairParser; import com.sun.hk2.component.InhabitantsParser; import org.jvnet.hk2.component.*; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.Properties; import java.util.StringTokenizer; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * CLI entry point that will setup the module subsystem and delegate the * main execution to the first archive in its import list... * * TODO: reusability of this class needs to be improved. * * @author dochez */ public class Main { public static void main(final String[] args) { (new Main()).run(args); } public Main() { HK2Factory.initialize(); } public void run(final String[] args) { try { final Main main = this; Thread thread = new Thread() { public void run() { try { main.start(args); } catch(BootException e) { e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } } }; thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } catch (Throwable t) { t.printStackTrace(); } } /** * We need to determine which jar file has been used to load this class * Using the getResourceURL we can get this information, after that, it * is just a bit of detective work to get the file path for the jar file. * * @return * the path to the jar file containing this class. * always returns non-null. * * @throws BootException * If failed to determine the bootstrap file name. */ protected File getBootstrapFile() throws BootException { try { return Which.jarFile(getClass()); } catch (IOException e) { throw new BootException("Failed to get bootstrap path",e); } } /** * Start the server from the command line * @param args the command line arguments */ public void start(String[] args) throws BootException { File bootstrap = this.getBootstrapFile(); File root = bootstrap.getAbsoluteFile().getParentFile(); // root is the directory in which this bootstrap.jar is located // For most cases, this is the lib directory although this is completely // dependent on the usage of this facility. if (root==null) { throw new BootException("Cannot find root installation from "+bootstrap); } String targetModule = findMainModuleName(bootstrap); // get the ModuleStartup implementation. ModulesRegistry mr = AbstractFactory.getInstance().createModulesRegistry(); Manifest mf; try { mf = (new JarFile(bootstrap)).getManifest(); } catch (IOException e) { throw new BootException("Failed to read manifest from "+bootstrap); } createRepository(root,bootstrap,mf,mr); StartupContext context = new StartupContext(ArgumentManager.argsToMap(args)); launch(mr, targetModule, context); } protected void setParentClassLoader(StartupContext context, ModulesRegistry mr) throws BootException { mr.setParentClassLoader(this.getClass().getClassLoader()); } /** * Creates repositories needed for the launch and * adds the repositories to {@link ModulesRegistry} * * @param bootstrapJar * The file from which manifest entries are loaded. Used for error reporting */ protected void createRepository(File root, File bootstrapJar, Manifest mf, ModulesRegistry mr) throws BootException { String repos = mf.getMainAttributes().getValue(ManifestConstants.REPOSITORIES); if (repos!=null) { StringTokenizer st = new StringTokenizer(repos); while (st.hasMoreTokens()) { final String repoId = st.nextToken(); final String repoKey = "HK2-Repository-"+repoId; final String repoInfo; try { repoInfo = mf.getMainAttributes().getValue(repoKey); } catch (Exception e) { throw new BootException("Invalid repository id " + repoId+" in "+bootstrapJar, e); } if (repoInfo!=null) { addRepo(root, repoId, repoInfo, mr); } } } else { // by default, adding the boot archive directory addRepo(root, "lib", "uri=. type=directory", mr); } } private void addRepo(File root, String repoId, String repoInfo, ModulesRegistry mr) throws BootException { StringTokenizer st = new StringTokenizer(repoInfo); Properties props = new Properties(); Pattern p = Pattern.compile("([^=]*)=(.*)"); while(st.hasMoreTokens()) { Matcher m = p.matcher(st.nextToken()); if (m.matches()) { props.put(m.group(1), m.group(2)); } } String uri = props.getProperty("uri"); if (uri==null) { uri = "."; } String type = props.getProperty("type"); String weight = props.getProperty("weight"); // need a plugability layer here... if ("directory".equalsIgnoreCase(type)) { File location = new File(uri); if (!location.isAbsolute()) { location = new File(root, uri); } if (!location.exists()) throw new BootException("Non-existent directory: "+location); /* bnevins 3/21/08 * location might be something like "/gf/modules/." * The "." can cause all sorts of trouble later, so sanitize * the name now! * here's an example of the trouble: * new File("/foo/.").getParentFile().getPath() --> "/foo", not "/" * JDK treats the dot as a file in the foo directory!! */ try { location = location.getCanonicalFile(); } catch(Exception e) { // I've never seen this happen! location = location.getAbsoluteFile(); } try { Repository repo = new DirectoryBasedRepository(repoId, location); addRepo(repo, mr, weight); } catch (IOException e) { throw new BootException("Exception while adding " + repoId + " repository", e); } } else { throw new BootException("Invalid attributes for modules repository " + repoId + " : " + repoInfo); } } protected void addRepo(Repository repo, ModulesRegistry mr, String weight) throws IOException { repo.initialize(); int iWeight=50; if (weight!=null) { try { iWeight = Integer.parseInt(weight); } catch (NumberFormatException e) { // ignore } } mr.addRepository(repo, iWeight); } /** * Launches the module system and hand over the execution to the {@link ModuleStartup} * implementation of the main module. * * <p> * This version of the method auto-discoveres the main module. * If there's more than one {@link ModuleStartup} implementation, it is an error. * * <p> * All the <tt>launch</tt> methods start additional threads and run GFv3, * then return from the method. * * @param context * startup context instance * * @return * the entry point to all the components in this newly launched GlassFish. */ public Habitat launch(ModulesRegistry registry, StartupContext context) throws BootException { return launch(registry, null, context); } private static final String HABITAT_NAME = "default"; // TODO: take this as a parameter public Habitat launch(ModulesRegistry registry, String mainModuleName, StartupContext context) throws BootException { Habitat habitat = createHabitat(registry, context); launch(registry, habitat,mainModuleName,context); return habitat; } /** * Launches the module system and hand over the execution to the {@link ModuleStartup} * implementation of the main module. * * @param mainModuleName * The module that will provide {@link ModuleStartup}. If null, * one will be auto-discovered. * @param context * startup context instance * @return The ModuleStartup service */ public ModuleStartup launch(ModulesRegistry registry, Habitat habitat, String mainModuleName, StartupContext context) throws BootException { // now go figure out the start up module ModuleStartup startupCode=null; final Module mainModule; if(mainModuleName!=null) { // instantiate the main module, this is the entry point of the application // code. it is supposed to have 1 ModuleStartup implementation. Collection<Module> modules = registry.getModules(mainModuleName); if (modules.size() != 1) { if(registry.getModules().isEmpty()) throw new BootException("Registry has no module at all"); else throw new BootException("Cannot find main module " + mainModuleName+" : no such module"); } mainModule = modules.iterator().next(); String targetClassName = findModuleStartup(mainModule,context.getPlatformMainServiceName(), HABITAT_NAME); if (targetClassName==null) { throw new BootException("Cannot find a ModuleStartup implementation in the META-INF/services/com.sun.enterprise.v3.ModuleStartup file, aborting"); } Class<? extends ModuleStartup> targetClass=null; ClassLoader currentCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(mainModule.getClassLoader()); try { targetClass = mainModule.getClassLoader().loadClass(targetClassName).asSubclass(ModuleStartup.class); startupCode = habitat.getComponent(targetClass); } catch (ClassNotFoundException e) { - throw new BootException("Unable to load "+targetClassName,e); + throw new BootException("Unable to load component of type " + targetClassName,e); } catch (ComponentException e) { - throw new BootException("Unable to load "+targetClass,e); + throw new BootException("Unable to load component of type " + targetClassName,e); } finally { Thread.currentThread().setContextClassLoader(currentCL); } } else { Collection<Inhabitant<? extends ModuleStartup>> startups = habitat.getInhabitants(ModuleStartup.class); if(startups.isEmpty()) throw new BootException("No module has a ModuleStartup implementation"); if(startups.size()>1) { // maybe the user specified a main String mainServiceName = context.getPlatformMainServiceName(); for (Inhabitant<? extends ModuleStartup> startup : startups) { Collection<String> regNames = Inhabitants.getNamesFor(startup, ModuleStartup.class.getName()); if (regNames.isEmpty() && mainServiceName==null) { startupCode = startup.get(); } else { for (String regName : regNames) { if (regName.equals(mainServiceName)) { startupCode = startup.get(); } } } } if (startupCode==null) { if (mainServiceName==null) { Iterator<Inhabitant<? extends ModuleStartup>> itr = startups.iterator(); ModuleStartup a = itr.next().get(); ModuleStartup b = itr.next().get(); Module am = registry.find(a.getClass()); Module bm = registry.find(b.getClass()); throw new BootException(String.format("Multiple ModuleStartup found: %s from %s and %s from %s",a,am,b,bm)); } else { throw new BootException(String.format("Cannot find %s ModuleStartup", mainServiceName)); } } } else { startupCode = startups.iterator().next().get(); } mainModule = registry.find(startupCode.getClass()); } habitat.addIndex(Inhabitants.create(startupCode), ModuleStartup.class.getName(), habitat.DEFAULT_NAME); mainModule.setSticky(true); launch(startupCode, context, mainModule); return startupCode; } protected Habitat createHabitat(ModulesRegistry registry, StartupContext context) throws BootException { // set the parent class loader before we start loading modules setParentClassLoader(context, registry); // create a habitat and initialize them Habitat habitat = registry.newHabitat(); habitat.add(new ExistingSingletonInhabitant<StartupContext>(context)); habitat.add(new ExistingSingletonInhabitant<Logger>(Logger.global)); // the root registry must be added as other components sometimes inject it habitat.add(new ExistingSingletonInhabitant(ModulesRegistry.class, registry)); ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { registry.createHabitat(HABITAT_NAME, createInhabitantsParser(habitat)); } finally { Thread.currentThread().setContextClassLoader(oldCL); } return habitat; } /** * Creates {@link InhabitantsParser} to fill in {@link Habitat}. * Override for customizing the behavior. */ protected InhabitantsParser createInhabitantsParser(Habitat habitat) { return new InhabitantsParser(habitat); } protected String findMainModuleName(File bootstrap) throws BootException { String targetModule; try { JarFile jarFile = new JarFile(bootstrap); Manifest manifest = jarFile.getManifest(); Attributes attr = manifest.getMainAttributes(); targetModule = attr.getValue(ManifestConstants.MAIN_BUNDLE); if (targetModule==null) { LogHelper.getDefaultLogger().warning( "No Main-Bundle module found in manifest of " + bootstrap.getAbsoluteFile()); } } catch(IOException ioe) { throw new BootException("Cannot get manifest from " + bootstrap.getAbsolutePath(), ioe); } return targetModule; } protected void launch(ModuleStartup startupCode, StartupContext context, Module mainModule) throws BootException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { startupCode.setStartupContext(context); Thread.currentThread().setContextClassLoader(mainModule.getClassLoader()); startupCode.start(); } finally { Thread.currentThread().setContextClassLoader(cl); } } /** * Finds {@link ModuleStartup} implementation class name to perform the launch. * * <p> * This implementation does so by looking it up from services. */ protected String findModuleStartup(Module mainModule, String serviceName, String habitatName) throws BootException { String index = (serviceName==null || serviceName.isEmpty()?ModuleStartup.class.getName():ModuleStartup.class.getName()+":"+serviceName); for(InhabitantsDescriptor d : mainModule.getMetadata().getHabitats(habitatName)) { try { for (InhabitantParser parser : d.createScanner()) { for (String v : parser.getIndexes()) { if(v.equals(index)) { parser.rewind(); return parser.getImplName(); } } } } catch (IOException e) { throw new BootException("Failed to parse "+d.getSystemId(),e); } } throw new BootException("No "+ModuleStartup.class.getName()+" in "+mainModule); } }
false
true
public ModuleStartup launch(ModulesRegistry registry, Habitat habitat, String mainModuleName, StartupContext context) throws BootException { // now go figure out the start up module ModuleStartup startupCode=null; final Module mainModule; if(mainModuleName!=null) { // instantiate the main module, this is the entry point of the application // code. it is supposed to have 1 ModuleStartup implementation. Collection<Module> modules = registry.getModules(mainModuleName); if (modules.size() != 1) { if(registry.getModules().isEmpty()) throw new BootException("Registry has no module at all"); else throw new BootException("Cannot find main module " + mainModuleName+" : no such module"); } mainModule = modules.iterator().next(); String targetClassName = findModuleStartup(mainModule,context.getPlatformMainServiceName(), HABITAT_NAME); if (targetClassName==null) { throw new BootException("Cannot find a ModuleStartup implementation in the META-INF/services/com.sun.enterprise.v3.ModuleStartup file, aborting"); } Class<? extends ModuleStartup> targetClass=null; ClassLoader currentCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(mainModule.getClassLoader()); try { targetClass = mainModule.getClassLoader().loadClass(targetClassName).asSubclass(ModuleStartup.class); startupCode = habitat.getComponent(targetClass); } catch (ClassNotFoundException e) { throw new BootException("Unable to load "+targetClassName,e); } catch (ComponentException e) { throw new BootException("Unable to load "+targetClass,e); } finally { Thread.currentThread().setContextClassLoader(currentCL); } } else { Collection<Inhabitant<? extends ModuleStartup>> startups = habitat.getInhabitants(ModuleStartup.class); if(startups.isEmpty()) throw new BootException("No module has a ModuleStartup implementation"); if(startups.size()>1) { // maybe the user specified a main String mainServiceName = context.getPlatformMainServiceName(); for (Inhabitant<? extends ModuleStartup> startup : startups) { Collection<String> regNames = Inhabitants.getNamesFor(startup, ModuleStartup.class.getName()); if (regNames.isEmpty() && mainServiceName==null) { startupCode = startup.get(); } else { for (String regName : regNames) { if (regName.equals(mainServiceName)) { startupCode = startup.get(); } } } } if (startupCode==null) { if (mainServiceName==null) { Iterator<Inhabitant<? extends ModuleStartup>> itr = startups.iterator(); ModuleStartup a = itr.next().get(); ModuleStartup b = itr.next().get(); Module am = registry.find(a.getClass()); Module bm = registry.find(b.getClass()); throw new BootException(String.format("Multiple ModuleStartup found: %s from %s and %s from %s",a,am,b,bm)); } else { throw new BootException(String.format("Cannot find %s ModuleStartup", mainServiceName)); } } } else { startupCode = startups.iterator().next().get(); } mainModule = registry.find(startupCode.getClass()); } habitat.addIndex(Inhabitants.create(startupCode), ModuleStartup.class.getName(), habitat.DEFAULT_NAME); mainModule.setSticky(true); launch(startupCode, context, mainModule); return startupCode; }
public ModuleStartup launch(ModulesRegistry registry, Habitat habitat, String mainModuleName, StartupContext context) throws BootException { // now go figure out the start up module ModuleStartup startupCode=null; final Module mainModule; if(mainModuleName!=null) { // instantiate the main module, this is the entry point of the application // code. it is supposed to have 1 ModuleStartup implementation. Collection<Module> modules = registry.getModules(mainModuleName); if (modules.size() != 1) { if(registry.getModules().isEmpty()) throw new BootException("Registry has no module at all"); else throw new BootException("Cannot find main module " + mainModuleName+" : no such module"); } mainModule = modules.iterator().next(); String targetClassName = findModuleStartup(mainModule,context.getPlatformMainServiceName(), HABITAT_NAME); if (targetClassName==null) { throw new BootException("Cannot find a ModuleStartup implementation in the META-INF/services/com.sun.enterprise.v3.ModuleStartup file, aborting"); } Class<? extends ModuleStartup> targetClass=null; ClassLoader currentCL = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(mainModule.getClassLoader()); try { targetClass = mainModule.getClassLoader().loadClass(targetClassName).asSubclass(ModuleStartup.class); startupCode = habitat.getComponent(targetClass); } catch (ClassNotFoundException e) { throw new BootException("Unable to load component of type " + targetClassName,e); } catch (ComponentException e) { throw new BootException("Unable to load component of type " + targetClassName,e); } finally { Thread.currentThread().setContextClassLoader(currentCL); } } else { Collection<Inhabitant<? extends ModuleStartup>> startups = habitat.getInhabitants(ModuleStartup.class); if(startups.isEmpty()) throw new BootException("No module has a ModuleStartup implementation"); if(startups.size()>1) { // maybe the user specified a main String mainServiceName = context.getPlatformMainServiceName(); for (Inhabitant<? extends ModuleStartup> startup : startups) { Collection<String> regNames = Inhabitants.getNamesFor(startup, ModuleStartup.class.getName()); if (regNames.isEmpty() && mainServiceName==null) { startupCode = startup.get(); } else { for (String regName : regNames) { if (regName.equals(mainServiceName)) { startupCode = startup.get(); } } } } if (startupCode==null) { if (mainServiceName==null) { Iterator<Inhabitant<? extends ModuleStartup>> itr = startups.iterator(); ModuleStartup a = itr.next().get(); ModuleStartup b = itr.next().get(); Module am = registry.find(a.getClass()); Module bm = registry.find(b.getClass()); throw new BootException(String.format("Multiple ModuleStartup found: %s from %s and %s from %s",a,am,b,bm)); } else { throw new BootException(String.format("Cannot find %s ModuleStartup", mainServiceName)); } } } else { startupCode = startups.iterator().next().get(); } mainModule = registry.find(startupCode.getClass()); } habitat.addIndex(Inhabitants.create(startupCode), ModuleStartup.class.getName(), habitat.DEFAULT_NAME); mainModule.setSticky(true); launch(startupCode, context, mainModule); return startupCode; }
diff --git a/src/fr/ravenfeld/livewallpaper/library/objects/simple/AImageGIF.java b/src/fr/ravenfeld/livewallpaper/library/objects/simple/AImageGIF.java index 14dee26..dbadf7a 100644 --- a/src/fr/ravenfeld/livewallpaper/library/objects/simple/AImageGIF.java +++ b/src/fr/ravenfeld/livewallpaper/library/objects/simple/AImageGIF.java @@ -1,52 +1,53 @@ package fr.ravenfeld.livewallpaper.library.objects.simple; import rajawali.materials.Material; import rajawali.materials.textures.ASingleTexture; import rajawali.materials.textures.ATexture; import rajawali.materials.textures.AnimatedGIFTexture; import rajawali.materials.textures.Texture; import rajawali.primitives.Plane; public abstract class AImageGIF extends AElement{ protected AnimatedGIFTexture mTexture; public AnimatedGIFTexture getTexture(){ return mTexture; } public void setLoop(boolean loop) { mTexture.setLoop(loop); } public void rewind() { mTexture.rewind(); } public void animate() { mTexture.animate(); } public void stopAnimation() { mTexture.stopAnimation(); } public void update() throws ATexture.TextureException { mTexture.update(); } @Override public int getWidth() { return mTexture.getWidth(); } @Override public int getHeight() { return mTexture.getHeight(); } @Override public void surfaceDestroyed() throws ATexture.TextureException { mMaterial.removeTexture(mTexture); mTexture.reset(); + mTexture.remove(); } }
true
true
public void surfaceDestroyed() throws ATexture.TextureException { mMaterial.removeTexture(mTexture); mTexture.reset(); }
public void surfaceDestroyed() throws ATexture.TextureException { mMaterial.removeTexture(mTexture); mTexture.reset(); mTexture.remove(); }
diff --git a/src/org/openstreetmap/josm/gui/MainApplication.java b/src/org/openstreetmap/josm/gui/MainApplication.java index 421b4d2b..7623f912 100644 --- a/src/org/openstreetmap/josm/gui/MainApplication.java +++ b/src/org/openstreetmap/josm/gui/MainApplication.java @@ -1,237 +1,238 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others //Licence: GPL package org.openstreetmap.josm.gui; import org.xnap.commons.i18n.I18nFactory; import static org.openstreetmap.josm.tools.I18n.i18n; import static org.openstreetmap.josm.tools.I18n.tr; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import javax.swing.JFrame; import javax.swing.JOptionPane; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.plugins.PluginDownloader; import org.openstreetmap.josm.tools.BugReportExceptionHandler; import org.openstreetmap.josm.tools.ImageProvider; /** * Main window class application. * * @author imi */ public class MainApplication extends Main { /** * Allow subclassing (see JOSM.java) */ public MainApplication() {} /** * Construct an main frame, ready sized and operating. Does not * display the frame. */ public MainApplication(JFrame mainFrame) { super(); mainFrame.setContentPane(contentPane); mainFrame.setJMenuBar(menu); mainFrame.setBounds(bounds); mainFrame.setIconImage(ImageProvider.get("logo.png").getImage()); mainFrame.addWindowListener(new WindowAdapter(){ @Override public void windowClosing(final WindowEvent arg0) { if (Main.breakBecauseUnsavedChanges()) return; System.exit(0); } }); mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); } /** * Main application Startup */ public static void main(final String[] argArray) { ///////////////////////////////////////////////////////////////////////// // TO ALL TRANSLATORS ///////////////////////////////////////////////////////////////////////// // Do not translate the early strings below until the locale is set up. // (By the eager loaded plugins) // // These strings cannot be translated. That's life. Really. Sorry. // // Imi. ///////////////////////////////////////////////////////////////////////// Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler()); // initialize the plaform hook, and Main.determinePlatformHook(); // call the really early hook before we anything else Main.platform.preStartupHook(); // construct argument table List<String> argList = Arrays.asList(argArray); final Map<String, Collection<String>> args = new HashMap<String, Collection<String>>(); for (String arg : argArray) { if (!arg.startsWith("--")) arg = "--download="+arg; int i = arg.indexOf('='); String key = i == -1 ? arg.substring(2) : arg.substring(2,i); String value = i == -1 ? "" : arg.substring(i+1); Collection<String> v = args.get(key); if (v == null) v = new LinkedList<String>(); v.add(value); args.put(key, v); } if (argList.contains("--help") || argList.contains("-?") || argList.contains("-h")) { // TODO: put in a platformHook for system that have no console by default System.out.println(tr("Java OpenStreetMap Editor")+"\n\n"+ tr("usage")+":\n"+ "\tjava -jar josm.jar <option> <option> <option>...\n\n"+ tr("options")+":\n"+ "\t--help|-?|-h "+tr("Show this help")+"\n"+ "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+"\n"+ "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+"\n"+ "\t[--download=]<url> "+tr("Download the location at the url (with lat=x&lon=y&zoom=z)")+"\n"+ "\t[--download=]<filename> "+tr("Open file (as raw gps, if .gpx)")+"\n"+ "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw gps")+"\n"+ "\t--selection=<searchstring> "+tr("Select with the given search")+"\n"+ "\t--no-fullscreen "+tr("Don't launch in fullscreen mode")+"\n"+ "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+ "\t--language=<language> "+tr("Set the language.")+"\n\n"+ tr("examples")+":\n"+ "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+ "\tjava -jar josm.jar http://www.openstreetmap.org/index.html?lat=43.2&lon=11.1&zoom=13\n"+ "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+ "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n\n"+ tr("Parameters are read in the order they are specified, so make sure you load\n"+ "some data before --selection")+"\n\n"+ tr("Instead of --download=<bbox> you may specify osm://<bbox>\n")); System.exit(0); } // get the preferences. final File prefDir = new File(Main.pref.getPreferencesDir()); // check if preferences directory has moved (TODO: Update code. Remove this after some time) File oldPrefDir = new File(System.getProperty("user.home"), ".josm"); if (!prefDir.isDirectory() && oldPrefDir.isDirectory()) { if (oldPrefDir.renameTo(prefDir)) { // do not translate this JOptionPane.showMessageDialog(null, "The preference directory has been moved to "+prefDir); } else { JOptionPane.showMessageDialog(null, "The preference directory location has changed. Please move "+oldPrefDir+" to "+prefDir); } } if (prefDir.exists() && !prefDir.isDirectory()) { JOptionPane.showMessageDialog(null, "Cannot open preferences directory: "+Main.pref.getPreferencesDir()); return; } if (!prefDir.exists()) prefDir.mkdirs(); if (!new File(Main.pref.getPreferencesDir()+"preferences").exists()) { Main.pref.resetToDefault(); } try { if (args.containsKey("reset-preferences")) { Main.pref.resetToDefault(); } else { Main.pref.load(); } } catch (final IOException e1) { e1.printStackTrace(); String backup = Main.pref.getPreferencesDir() + "preferences.bak"; JOptionPane.showMessageDialog(null, "Preferences file had errors. Making backup of old one to " + backup); new File(Main.pref.getPreferencesDir() + "preferences").renameTo(new File(backup)); Main.pref.save(); } // TODO remove this in early 2009 - just here to weed out color setting we don't use any more Main.pref.put("downloaded Area", null); String localeName = null; //The locale to use //Check if passed as parameter if(args.containsKey("language")) localeName = (String)(args.get("language").toArray()[0]); if (localeName == null) { localeName = Main.pref.get("language", null); } if (localeName != null) { Locale l; int i = localeName.indexOf('_'); if (i > 0) { l = new Locale(localeName.substring(0, i), localeName.substring(i + 1)); } else { l = new Locale(localeName); } Locale.setDefault(l); } try { i18n = I18nFactory.getI18n(MainApplication.class); } catch (MissingResourceException ex) { if(!Locale.getDefault().getLanguage().equals("en")) { System.out.println("Unable to find translation for the locale: " + Locale.getDefault().getDisplayName() + " reverting to English."); + Locale.setDefault(Locale.ENGLISH); } } SplashScreen splash = new SplashScreen(Main.pref.getBoolean("draw.splashscreen", true)); splash.setStatus(tr("Activating updated plugins")); if (!PluginDownloader.moveUpdatedPlugins()) { JOptionPane.showMessageDialog(null, tr("Activating the updated plugins failed. Check if JOSM has the permission to overwrite the existing ones."), tr("Plugins"), JOptionPane.ERROR_MESSAGE); } // load the early plugins splash.setStatus(tr("Loading early plugins")); Main.loadPlugins(true); splash.setStatus(tr("Setting defaults")); preConstructorInit(args); splash.setStatus(tr("Creating main GUI")); JFrame mainFrame = new JFrame(tr("Java OpenStreetMap - Editor")); Main.parent = mainFrame; final Main main = new MainApplication(mainFrame); splash.setStatus(tr("Loading plugins")); Main.loadPlugins(false); toolbar.refreshToolbarControl(); mainFrame.setVisible(true); splash.closeSplash(); if (!args.containsKey("no-fullscreen") && !args.containsKey("geometry") && Toolkit.getDefaultToolkit().isFrameStateSupported(JFrame.MAXIMIZED_BOTH)) mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); EventQueue.invokeLater(new Runnable(){ public void run() { main.postConstructorProcessCmdLine(args); } }); } }
true
true
public static void main(final String[] argArray) { ///////////////////////////////////////////////////////////////////////// // TO ALL TRANSLATORS ///////////////////////////////////////////////////////////////////////// // Do not translate the early strings below until the locale is set up. // (By the eager loaded plugins) // // These strings cannot be translated. That's life. Really. Sorry. // // Imi. ///////////////////////////////////////////////////////////////////////// Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler()); // initialize the plaform hook, and Main.determinePlatformHook(); // call the really early hook before we anything else Main.platform.preStartupHook(); // construct argument table List<String> argList = Arrays.asList(argArray); final Map<String, Collection<String>> args = new HashMap<String, Collection<String>>(); for (String arg : argArray) { if (!arg.startsWith("--")) arg = "--download="+arg; int i = arg.indexOf('='); String key = i == -1 ? arg.substring(2) : arg.substring(2,i); String value = i == -1 ? "" : arg.substring(i+1); Collection<String> v = args.get(key); if (v == null) v = new LinkedList<String>(); v.add(value); args.put(key, v); } if (argList.contains("--help") || argList.contains("-?") || argList.contains("-h")) { // TODO: put in a platformHook for system that have no console by default System.out.println(tr("Java OpenStreetMap Editor")+"\n\n"+ tr("usage")+":\n"+ "\tjava -jar josm.jar <option> <option> <option>...\n\n"+ tr("options")+":\n"+ "\t--help|-?|-h "+tr("Show this help")+"\n"+ "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+"\n"+ "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+"\n"+ "\t[--download=]<url> "+tr("Download the location at the url (with lat=x&lon=y&zoom=z)")+"\n"+ "\t[--download=]<filename> "+tr("Open file (as raw gps, if .gpx)")+"\n"+ "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw gps")+"\n"+ "\t--selection=<searchstring> "+tr("Select with the given search")+"\n"+ "\t--no-fullscreen "+tr("Don't launch in fullscreen mode")+"\n"+ "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+ "\t--language=<language> "+tr("Set the language.")+"\n\n"+ tr("examples")+":\n"+ "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+ "\tjava -jar josm.jar http://www.openstreetmap.org/index.html?lat=43.2&lon=11.1&zoom=13\n"+ "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+ "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n\n"+ tr("Parameters are read in the order they are specified, so make sure you load\n"+ "some data before --selection")+"\n\n"+ tr("Instead of --download=<bbox> you may specify osm://<bbox>\n")); System.exit(0); } // get the preferences. final File prefDir = new File(Main.pref.getPreferencesDir()); // check if preferences directory has moved (TODO: Update code. Remove this after some time) File oldPrefDir = new File(System.getProperty("user.home"), ".josm"); if (!prefDir.isDirectory() && oldPrefDir.isDirectory()) { if (oldPrefDir.renameTo(prefDir)) { // do not translate this JOptionPane.showMessageDialog(null, "The preference directory has been moved to "+prefDir); } else { JOptionPane.showMessageDialog(null, "The preference directory location has changed. Please move "+oldPrefDir+" to "+prefDir); } } if (prefDir.exists() && !prefDir.isDirectory()) { JOptionPane.showMessageDialog(null, "Cannot open preferences directory: "+Main.pref.getPreferencesDir()); return; } if (!prefDir.exists()) prefDir.mkdirs(); if (!new File(Main.pref.getPreferencesDir()+"preferences").exists()) { Main.pref.resetToDefault(); } try { if (args.containsKey("reset-preferences")) { Main.pref.resetToDefault(); } else { Main.pref.load(); } } catch (final IOException e1) { e1.printStackTrace(); String backup = Main.pref.getPreferencesDir() + "preferences.bak"; JOptionPane.showMessageDialog(null, "Preferences file had errors. Making backup of old one to " + backup); new File(Main.pref.getPreferencesDir() + "preferences").renameTo(new File(backup)); Main.pref.save(); } // TODO remove this in early 2009 - just here to weed out color setting we don't use any more Main.pref.put("downloaded Area", null); String localeName = null; //The locale to use //Check if passed as parameter if(args.containsKey("language")) localeName = (String)(args.get("language").toArray()[0]); if (localeName == null) { localeName = Main.pref.get("language", null); } if (localeName != null) { Locale l; int i = localeName.indexOf('_'); if (i > 0) { l = new Locale(localeName.substring(0, i), localeName.substring(i + 1)); } else { l = new Locale(localeName); } Locale.setDefault(l); } try { i18n = I18nFactory.getI18n(MainApplication.class); } catch (MissingResourceException ex) { if(!Locale.getDefault().getLanguage().equals("en")) { System.out.println("Unable to find translation for the locale: " + Locale.getDefault().getDisplayName() + " reverting to English."); } } SplashScreen splash = new SplashScreen(Main.pref.getBoolean("draw.splashscreen", true)); splash.setStatus(tr("Activating updated plugins")); if (!PluginDownloader.moveUpdatedPlugins()) { JOptionPane.showMessageDialog(null, tr("Activating the updated plugins failed. Check if JOSM has the permission to overwrite the existing ones."), tr("Plugins"), JOptionPane.ERROR_MESSAGE); } // load the early plugins splash.setStatus(tr("Loading early plugins")); Main.loadPlugins(true); splash.setStatus(tr("Setting defaults")); preConstructorInit(args); splash.setStatus(tr("Creating main GUI")); JFrame mainFrame = new JFrame(tr("Java OpenStreetMap - Editor")); Main.parent = mainFrame; final Main main = new MainApplication(mainFrame); splash.setStatus(tr("Loading plugins")); Main.loadPlugins(false); toolbar.refreshToolbarControl(); mainFrame.setVisible(true); splash.closeSplash(); if (!args.containsKey("no-fullscreen") && !args.containsKey("geometry") && Toolkit.getDefaultToolkit().isFrameStateSupported(JFrame.MAXIMIZED_BOTH)) mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); EventQueue.invokeLater(new Runnable(){ public void run() { main.postConstructorProcessCmdLine(args); } }); }
public static void main(final String[] argArray) { ///////////////////////////////////////////////////////////////////////// // TO ALL TRANSLATORS ///////////////////////////////////////////////////////////////////////// // Do not translate the early strings below until the locale is set up. // (By the eager loaded plugins) // // These strings cannot be translated. That's life. Really. Sorry. // // Imi. ///////////////////////////////////////////////////////////////////////// Thread.setDefaultUncaughtExceptionHandler(new BugReportExceptionHandler()); // initialize the plaform hook, and Main.determinePlatformHook(); // call the really early hook before we anything else Main.platform.preStartupHook(); // construct argument table List<String> argList = Arrays.asList(argArray); final Map<String, Collection<String>> args = new HashMap<String, Collection<String>>(); for (String arg : argArray) { if (!arg.startsWith("--")) arg = "--download="+arg; int i = arg.indexOf('='); String key = i == -1 ? arg.substring(2) : arg.substring(2,i); String value = i == -1 ? "" : arg.substring(i+1); Collection<String> v = args.get(key); if (v == null) v = new LinkedList<String>(); v.add(value); args.put(key, v); } if (argList.contains("--help") || argList.contains("-?") || argList.contains("-h")) { // TODO: put in a platformHook for system that have no console by default System.out.println(tr("Java OpenStreetMap Editor")+"\n\n"+ tr("usage")+":\n"+ "\tjava -jar josm.jar <option> <option> <option>...\n\n"+ tr("options")+":\n"+ "\t--help|-?|-h "+tr("Show this help")+"\n"+ "\t--geometry=widthxheight(+|-)x(+|-)y "+tr("Standard unix geometry argument")+"\n"+ "\t[--download=]minlat,minlon,maxlat,maxlon "+tr("Download the bounding box")+"\n"+ "\t[--download=]<url> "+tr("Download the location at the url (with lat=x&lon=y&zoom=z)")+"\n"+ "\t[--download=]<filename> "+tr("Open file (as raw gps, if .gpx)")+"\n"+ "\t--downloadgps=minlat,minlon,maxlat,maxlon "+tr("Download the bounding box as raw gps")+"\n"+ "\t--selection=<searchstring> "+tr("Select with the given search")+"\n"+ "\t--no-fullscreen "+tr("Don't launch in fullscreen mode")+"\n"+ "\t--reset-preferences "+tr("Reset the preferences to default")+"\n\n"+ "\t--language=<language> "+tr("Set the language.")+"\n\n"+ tr("examples")+":\n"+ "\tjava -jar josm.jar track1.gpx track2.gpx london.osm\n"+ "\tjava -jar josm.jar http://www.openstreetmap.org/index.html?lat=43.2&lon=11.1&zoom=13\n"+ "\tjava -jar josm.jar london.osm --selection=http://www.ostertag.name/osm/OSM_errors_node-duplicate.xml\n"+ "\tjava -jar josm.jar 43.2,11.1,43.4,11.4\n\n"+ tr("Parameters are read in the order they are specified, so make sure you load\n"+ "some data before --selection")+"\n\n"+ tr("Instead of --download=<bbox> you may specify osm://<bbox>\n")); System.exit(0); } // get the preferences. final File prefDir = new File(Main.pref.getPreferencesDir()); // check if preferences directory has moved (TODO: Update code. Remove this after some time) File oldPrefDir = new File(System.getProperty("user.home"), ".josm"); if (!prefDir.isDirectory() && oldPrefDir.isDirectory()) { if (oldPrefDir.renameTo(prefDir)) { // do not translate this JOptionPane.showMessageDialog(null, "The preference directory has been moved to "+prefDir); } else { JOptionPane.showMessageDialog(null, "The preference directory location has changed. Please move "+oldPrefDir+" to "+prefDir); } } if (prefDir.exists() && !prefDir.isDirectory()) { JOptionPane.showMessageDialog(null, "Cannot open preferences directory: "+Main.pref.getPreferencesDir()); return; } if (!prefDir.exists()) prefDir.mkdirs(); if (!new File(Main.pref.getPreferencesDir()+"preferences").exists()) { Main.pref.resetToDefault(); } try { if (args.containsKey("reset-preferences")) { Main.pref.resetToDefault(); } else { Main.pref.load(); } } catch (final IOException e1) { e1.printStackTrace(); String backup = Main.pref.getPreferencesDir() + "preferences.bak"; JOptionPane.showMessageDialog(null, "Preferences file had errors. Making backup of old one to " + backup); new File(Main.pref.getPreferencesDir() + "preferences").renameTo(new File(backup)); Main.pref.save(); } // TODO remove this in early 2009 - just here to weed out color setting we don't use any more Main.pref.put("downloaded Area", null); String localeName = null; //The locale to use //Check if passed as parameter if(args.containsKey("language")) localeName = (String)(args.get("language").toArray()[0]); if (localeName == null) { localeName = Main.pref.get("language", null); } if (localeName != null) { Locale l; int i = localeName.indexOf('_'); if (i > 0) { l = new Locale(localeName.substring(0, i), localeName.substring(i + 1)); } else { l = new Locale(localeName); } Locale.setDefault(l); } try { i18n = I18nFactory.getI18n(MainApplication.class); } catch (MissingResourceException ex) { if(!Locale.getDefault().getLanguage().equals("en")) { System.out.println("Unable to find translation for the locale: " + Locale.getDefault().getDisplayName() + " reverting to English."); Locale.setDefault(Locale.ENGLISH); } } SplashScreen splash = new SplashScreen(Main.pref.getBoolean("draw.splashscreen", true)); splash.setStatus(tr("Activating updated plugins")); if (!PluginDownloader.moveUpdatedPlugins()) { JOptionPane.showMessageDialog(null, tr("Activating the updated plugins failed. Check if JOSM has the permission to overwrite the existing ones."), tr("Plugins"), JOptionPane.ERROR_MESSAGE); } // load the early plugins splash.setStatus(tr("Loading early plugins")); Main.loadPlugins(true); splash.setStatus(tr("Setting defaults")); preConstructorInit(args); splash.setStatus(tr("Creating main GUI")); JFrame mainFrame = new JFrame(tr("Java OpenStreetMap - Editor")); Main.parent = mainFrame; final Main main = new MainApplication(mainFrame); splash.setStatus(tr("Loading plugins")); Main.loadPlugins(false); toolbar.refreshToolbarControl(); mainFrame.setVisible(true); splash.closeSplash(); if (!args.containsKey("no-fullscreen") && !args.containsKey("geometry") && Toolkit.getDefaultToolkit().isFrameStateSupported(JFrame.MAXIMIZED_BOTH)) mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); EventQueue.invokeLater(new Runnable(){ public void run() { main.postConstructorProcessCmdLine(args); } }); }
diff --git a/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/immutable/mysql/datatype/MySQLCollectionTypeBase.java b/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/immutable/mysql/datatype/MySQLCollectionTypeBase.java index fef74ac..a37fc10 100644 --- a/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/immutable/mysql/datatype/MySQLCollectionTypeBase.java +++ b/Madz.DatabaseMetaData/src/main/java/net/madz/db/core/meta/immutable/mysql/datatype/MySQLCollectionTypeBase.java @@ -1,64 +1,64 @@ package net.madz.db.core.meta.immutable.mysql.datatype; import java.util.LinkedList; import java.util.List; import net.madz.db.core.meta.mutable.mysql.MySQLColumnMetaDataBuilder; import net.madz.db.utils.MessageConsts; public abstract class MySQLCollectionTypeBase implements DataType { private List<String> values; private String charsetName; private String collationName; public List<String> getValues() { return values; } public MySQLCollectionTypeBase addValue(String value) { if ( null == value ) { return this; } if ( null == values ) { values = new LinkedList<String>(); } values.add(value); return this; } public String getCharsetName() { return charsetName; } public void setCharsetName(String charsetName) { this.charsetName = charsetName; } public String getCollationName() { return collationName; } public void setCollationName(String collationName) { this.collationName = collationName; } @Override public void build(MySQLColumnMetaDataBuilder builder) { builder.setSqlTypeName(getName()); final StringBuilder result = new StringBuilder(); result.append(getName()); if ( 0 >= values.size() ) { throw new IllegalArgumentException(MessageConsts.COLLECTION_DATA_TYPE_SHOULD_NOT_BE_NULL); } result.append("("); for ( String value : values ) { builder.addTypeValue(value); - result.append(value); + result.append("'").append(value).append("'"); result.append(","); } result.deleteCharAt(result.length() - 1); result.append(")"); builder.setColumnType(result.toString()); } }
true
true
public void build(MySQLColumnMetaDataBuilder builder) { builder.setSqlTypeName(getName()); final StringBuilder result = new StringBuilder(); result.append(getName()); if ( 0 >= values.size() ) { throw new IllegalArgumentException(MessageConsts.COLLECTION_DATA_TYPE_SHOULD_NOT_BE_NULL); } result.append("("); for ( String value : values ) { builder.addTypeValue(value); result.append(value); result.append(","); } result.deleteCharAt(result.length() - 1); result.append(")"); builder.setColumnType(result.toString()); }
public void build(MySQLColumnMetaDataBuilder builder) { builder.setSqlTypeName(getName()); final StringBuilder result = new StringBuilder(); result.append(getName()); if ( 0 >= values.size() ) { throw new IllegalArgumentException(MessageConsts.COLLECTION_DATA_TYPE_SHOULD_NOT_BE_NULL); } result.append("("); for ( String value : values ) { builder.addTypeValue(value); result.append("'").append(value).append("'"); result.append(","); } result.deleteCharAt(result.length() - 1); result.append(")"); builder.setColumnType(result.toString()); }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/search/SearchResultsLabelProvider.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/search/SearchResultsLabelProvider.java index fba970216..d4bf43870 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/search/SearchResultsLabelProvider.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/search/SearchResultsLabelProvider.java @@ -1,66 +1,67 @@ /******************************************************************************* * Copyright (c) 2004, 2008 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.search; import java.text.MessageFormat; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.mylyn.internal.tasks.core.Person; import org.eclipse.mylyn.internal.tasks.core.TaskGroup; import org.eclipse.mylyn.tasks.ui.TaskElementLabelProvider; /** * @author Mik Kersten * @author Steffen Pingel */ public class SearchResultsLabelProvider extends TaskElementLabelProvider { private final SearchResultContentProvider contentProvider; private final TreeViewer viewer; public SearchResultsLabelProvider(SearchResultContentProvider contentProvider, TreeViewer viewer) { super(true); this.contentProvider = contentProvider; this.viewer = viewer; } @Override public String getText(Object object) { if (object instanceof TaskGroup || object instanceof Person) { Object[] children = contentProvider.getChildren(object); ViewerFilter[] filters = viewer.getFilters(); int filtered = 0; if (filters.length > 0) { for (Object child : children) { for (ViewerFilter filter : filters) { if (!filter.select(viewer, object, child)) { filtered++; + break; //don't count a child more the once } } } } if (filtered > 0) { return super.getText(object) + " (" //$NON-NLS-1$ + MessageFormat.format(Messages.SearchResultsLabelProvider_OF, (children.length - filtered), children.length) + ")"; //$NON-NLS-1$ } else { return super.getText(object) + " (" + children.length + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } } else { return super.getText(object); } } }
true
true
public String getText(Object object) { if (object instanceof TaskGroup || object instanceof Person) { Object[] children = contentProvider.getChildren(object); ViewerFilter[] filters = viewer.getFilters(); int filtered = 0; if (filters.length > 0) { for (Object child : children) { for (ViewerFilter filter : filters) { if (!filter.select(viewer, object, child)) { filtered++; } } } } if (filtered > 0) { return super.getText(object) + " (" //$NON-NLS-1$ + MessageFormat.format(Messages.SearchResultsLabelProvider_OF, (children.length - filtered), children.length) + ")"; //$NON-NLS-1$ } else { return super.getText(object) + " (" + children.length + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } } else { return super.getText(object); } }
public String getText(Object object) { if (object instanceof TaskGroup || object instanceof Person) { Object[] children = contentProvider.getChildren(object); ViewerFilter[] filters = viewer.getFilters(); int filtered = 0; if (filters.length > 0) { for (Object child : children) { for (ViewerFilter filter : filters) { if (!filter.select(viewer, object, child)) { filtered++; break; //don't count a child more the once } } } } if (filtered > 0) { return super.getText(object) + " (" //$NON-NLS-1$ + MessageFormat.format(Messages.SearchResultsLabelProvider_OF, (children.length - filtered), children.length) + ")"; //$NON-NLS-1$ } else { return super.getText(object) + " (" + children.length + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } } else { return super.getText(object); } }
diff --git a/src/main/java/com/sobey/cmop/mvc/service/redmine/RedmineUtilService.java b/src/main/java/com/sobey/cmop/mvc/service/redmine/RedmineUtilService.java index c372981..9fd6997 100644 --- a/src/main/java/com/sobey/cmop/mvc/service/redmine/RedmineUtilService.java +++ b/src/main/java/com/sobey/cmop/mvc/service/redmine/RedmineUtilService.java @@ -1,625 +1,625 @@ package com.sobey.cmop.mvc.service.redmine; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sobey.cmop.mvc.comm.BaseSevcie; import com.sobey.cmop.mvc.constant.ApplyConstant; import com.sobey.cmop.mvc.constant.FieldNameConstant; import com.sobey.cmop.mvc.constant.IpPoolConstant; import com.sobey.cmop.mvc.constant.RedmineConstant; import com.sobey.cmop.mvc.constant.ResourcesConstant; import com.sobey.cmop.mvc.entity.Apply; import com.sobey.cmop.mvc.entity.Change; import com.sobey.cmop.mvc.entity.ChangeItem; import com.sobey.cmop.mvc.entity.ComputeItem; import com.sobey.cmop.mvc.entity.CpItem; import com.sobey.cmop.mvc.entity.Failure; import com.sobey.cmop.mvc.entity.MdnItem; import com.sobey.cmop.mvc.entity.MonitorCompute; import com.sobey.cmop.mvc.entity.MonitorElb; import com.sobey.cmop.mvc.entity.MonitorMail; import com.sobey.cmop.mvc.entity.MonitorPhone; import com.sobey.cmop.mvc.entity.NetworkDnsItem; import com.sobey.cmop.mvc.entity.NetworkEipItem; import com.sobey.cmop.mvc.entity.NetworkElbItem; import com.sobey.cmop.mvc.entity.Resources; import com.sobey.cmop.mvc.entity.ServiceTag; import com.sobey.cmop.mvc.entity.StorageItem; import com.sobey.cmop.mvc.entity.User; import com.sobey.framework.utils.DateUtil; /** * 生成满足 Redmine格式的文本(用于通过API插入redmine). * * @author liukai * */ @Service @Transactional(readOnly = true) public class RedmineUtilService extends BaseSevcie { private static Logger logger = LoggerFactory.getLogger(RedmineUtilService.class); /** * 换行 */ private static final String NEWLINE = "\r\n"; /** * 一个空格 */ private static final String BLANK = " "; /** * 箭头.用于资源变更时旧值和新值的比较 */ private static final String RARR = BLANK + "→" + BLANK; /** * 生成满足redmine显示的服务申请Apply文本. */ public String applyRedmineDesc(Apply apply) { try { StringBuilder content = new StringBuilder(); content.append("*服务申请的详细信息*").append(NEWLINE + NEWLINE); content.append("# +*基本信息*+").append(NEWLINE); content.append("<pre>").append(NEWLINE); content.append("申请标题: ").append(apply.getTitle()).append(NEWLINE); content.append("服务标签: ").append(apply.getServiceTag()).append(NEWLINE); content.append("优先级: ").append(RedmineConstant.Priority.get(apply.getPriority())).append(NEWLINE); content.append("服务起止日期: ").append(apply.getServiceStart()).append(" 至 ").append(apply.getServiceEnd()).append(NEWLINE); content.append("用途描述: ").append(apply.getDescription()).append(NEWLINE); content.append("申请人: ").append(apply.getUser().getName()).append(NEWLINE); content.append("申请时间: ").append(DateUtil.formatDate(apply.getCreateTime())).append(NEWLINE); content.append("</pre>"); content.append(NEWLINE); // 拼装计算资源Compute信息 this.generateContentByLists(apply.getUser(), content, new ArrayList<ComputeItem>(apply.getComputeItems()), new ArrayList<StorageItem>(apply.getStorageItems()), new ArrayList<NetworkElbItem>(apply.getNetworkElbItems()), new ArrayList<NetworkEipItem>(apply.getNetworkEipItems()), new ArrayList<NetworkDnsItem>(apply.getNetworkDnsItems()), new ArrayList<MonitorMail>(apply.getMonitorMails()), new ArrayList<MonitorPhone>(apply.getMonitorPhones()), new ArrayList<MonitorCompute>(apply.getMonitorComputes()), new ArrayList<MonitorElb>(apply.getMonitorElbs()), new ArrayList<MdnItem>(apply.getMdnItems()), new ArrayList<CpItem>(apply.getCpItems())); return content.toString(); } catch (Exception e) { logger.error("--->服务申请Apply拼装Redmine内容出错:" + e.getMessage()); return null; } } /** * 生成满足redmine显示的资源回收Resources文本. */ public String recycleResourcesRedmineDesc(User user, List<ComputeItem> computeItems, List<StorageItem> storageItems, List<NetworkElbItem> elbItems, List<NetworkEipItem> eipItems, List<NetworkDnsItem> dnsItems, List<MonitorMail> monitorMails, List<MonitorPhone> monitorPhones, List<MonitorCompute> monitorComputes, List<MonitorElb> monitorElbs, List<MdnItem> mdnItems, List<CpItem> cpItems) { try { StringBuilder content = new StringBuilder(); // 拼装资源信息 this.generateContentByLists(user, content, computeItems, storageItems, elbItems, eipItems, dnsItems, monitorMails, monitorPhones, monitorComputes, monitorElbs, mdnItems, cpItems); return content.toString(); } catch (Exception e) { logger.error("--->资源变更Resources拼装Redmine内容出错:" + e.getMessage()); return null; } } /** * 生成满足redmine显示的故障申报Failure文本. */ public String failureResourcesRedmineDesc(Failure failure, List<ComputeItem> computeItems, List<StorageItem> storageItems, List<NetworkElbItem> elbItems, List<NetworkEipItem> eipItems, List<NetworkDnsItem> dnsItems, List<MonitorMail> monitorMails, List<MonitorPhone> monitorPhones, List<MonitorCompute> monitorComputes, List<MonitorElb> monitorElbs, List<MdnItem> mdnItems, List<CpItem> cpItems) { try { StringBuilder content = new StringBuilder(); content.append("# +*故障申报信息*+").append(NEWLINE); content.append("<pre>").append(NEWLINE); content.append("申报人:").append(failure.getUser().getName()).append(NEWLINE); content.append("申报标题:").append(failure.getTitle()).append(NEWLINE); content.append("申报时间:").append(failure.getCreateTime()).append(NEWLINE); content.append("故障类型:").append(ApplyConstant.ServiceType.get(failure.getFaultType())).append(NEWLINE); content.append("优先级:").append(RedmineConstant.Priority.get(failure.getLevel())).append(NEWLINE); content.append("受理人:").append(RedmineConstant.Assignee.get(failure.getAssignee())).append(NEWLINE); content.append("故障现象及描述:").append(failure.getDescription()).append(NEWLINE); content.append("</pre>"); this.generateContentByLists(failure.getUser(), content, computeItems, storageItems, elbItems, eipItems, dnsItems, monitorMails, monitorPhones, monitorComputes, monitorElbs, mdnItems, cpItems); return content.toString(); } catch (Exception e) { logger.error("--->故障申报Failure拼装Redmine内容出错:" + e.getMessage()); return null; } } /** * 将各个资源相关的参数生成符合redmine格式的文本. * * @param user * 资源创建人 * @param content * @param computeItems * @param storageItems * @param elbItems * @param eipItems * @param dnsItems * @param monitorMails * @param monitorPhones * @param monitorComputes * @param monitorElbs * @param mdnItems * @param cpItems */ private void generateContentByLists(User user, StringBuilder content, List<ComputeItem> computeItems, List<StorageItem> storageItems, List<NetworkElbItem> elbItems, List<NetworkEipItem> eipItems, List<NetworkDnsItem> dnsItems, List<MonitorMail> monitorMails, List<MonitorPhone> monitorPhones, List<MonitorCompute> monitorComputes, List<MonitorElb> monitorElbs, List<MdnItem> mdnItems, List<CpItem> cpItems) { RedmineTextUtil.generateCompute(content, computeItems); RedmineTextUtil.generateStorage(content, storageItems); RedmineTextUtil.generateElb(content, elbItems); RedmineTextUtil.generateEip(content, eipItems); RedmineTextUtil.generateDNS(content, dnsItems); RedmineTextUtil.generateMonitorMail(content, monitorMails); RedmineTextUtil.generateMonitorPhone(content, monitorPhones); RedmineTextUtil.generateMonitorCompute(content, monitorComputes); RedmineTextUtil.generateMonitorElb(content, monitorElbs); RedmineTextUtil.generateMonitorMdn(content, mdnItems); RedmineTextUtil.generateMonitorCP(content, cpItems); } /** * 生成满足redmine显示的资源变更Resources文本. */ public String resourcesRedmineDesc(ServiceTag serviceTag) { try { StringBuilder content = new StringBuilder(); content.append("*服务变更的详细信息*").append(NEWLINE + NEWLINE); content.append("* +*服务标签基本信息*+").append(NEWLINE); content.append("<pre>").append(NEWLINE); content.append("标签名: ").append(serviceTag.getName()).append(NEWLINE); content.append("优先级: ").append(RedmineConstant.Priority.get(serviceTag.getPriority())).append(NEWLINE); content.append("服务起止日期: ").append(serviceTag.getServiceStart()).append(" 至 ").append(serviceTag.getServiceEnd()).append(NEWLINE); content.append("用途描述: ").append(serviceTag.getDescription()).append(NEWLINE); content.append("申请人: ").append(serviceTag.getUser().getName()).append(NEWLINE); content.append("</pre>"); content.append(NEWLINE + NEWLINE); content.append("* +*变更信息*+").append(NEWLINE); content.append("<pre>").append(NEWLINE); List<Resources> resourcesList = comm.resourcesService.getCommitedResourcesListByServiceTagId(serviceTag.getId()); for (Resources resources : resourcesList) { Integer serviceType = resources.getServiceType(); for (Change change : resources.getChanges()) { // 资源标识符(标识符) + 变更说明 content.append("变更资源标识符:" + BLANK).append(resources.getServiceIdentifier()); // 只有当ip不为0.0.0.0时才插入IP(即资源本身有IP时,像DNS,ES3这些没有IP的资源将不显示ip) if (!IpPoolConstant.DEFAULT_IPADDRESS.equals(resources.getIpAddress())) { content.append("(" + resources.getIpAddress() + ")"); } content.append(BLANK + BLANK).append("变更描述:" + BLANK).append(change.getDescription()).append(NEWLINE); content.append("变更项:"); if (change.getSubResourcesId() != null) { content.append("(服务子项ID:" + change.getSubResourcesId() + ")"); } content.append(BLANK + "旧值").append(RARR).append("新值").append(NEWLINE); for (ChangeItem changeItem : change.getChangeItems()) { String fieldName = changeItem.getFieldName(); if (serviceType.equals(ResourcesConstant.ServiceType.PCS.toInteger()) || serviceType.equals(ResourcesConstant.ServiceType.ECS.toInteger())) { // 计算资源Compute信息 if (FieldNameConstant.Compate.操作系统.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.操作系统 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.操作位数.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.操作位数 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.规格.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.规格 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.用途信息.toString().equals(fieldName)) { - content.append(FieldNameConstant.Compate.用途信息 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getOldString()).append(NEWLINE); + content.append(FieldNameConstant.Compate.用途信息 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.应用信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.应用信息 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.ESG.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.ESG + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.ES3.toInteger())) { // 存储空间Storage信息 if (FieldNameConstant.Storage.存储类型.toString().equals(fieldName)) { content.append(FieldNameConstant.Storage.存储类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Storage.容量空间.toString().equals(fieldName)) { content.append(FieldNameConstant.Storage.容量空间 + ":" + BLANK).append(changeItem.getOldString()).append("GB").append(RARR).append(changeItem.getNewString()).append("GB") .append(NEWLINE); } else if (FieldNameConstant.Storage.挂载实例.toString().equals(fieldName)) { content.append(FieldNameConstant.Storage.挂载实例 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.ELB.toInteger())) { // 变更负载均衡器ELB if (FieldNameConstant.Elb.是否保持会话.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.是否保持会话 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Elb.端口信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.端口信息 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Elb.关联实例.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.关联实例 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.EIP.toInteger())) { // EIP if (FieldNameConstant.Eip.关联实例.toString().equals(fieldName)) { content.append(FieldNameConstant.Eip.关联实例 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Eip.关联ELB.toString().equals(fieldName)) { content.append(FieldNameConstant.Eip.关联ELB + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Eip.端口信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.端口信息 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.DNS.toInteger())) { // 拼装DNS信息 if (FieldNameConstant.Dns.域名类型.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.域名类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Dns.域名.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Dns.CNAME域名.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.CNAME域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Dns.目标IP.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.目标IP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.MONITOR_COMPUTE.toInteger())) { // monitorCompute if (FieldNameConstant.monitorCompute.监控实例.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.监控实例 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.监控端口.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.监控端口 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.监控进程.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.监控进程 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.挂载路径.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.挂载路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.CPU占用率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.CPU占用率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.CPU占用率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.CPU占用率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.内存占用率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.内存占用率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.内存占用率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.内存占用率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络丢包率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络丢包率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络丢包率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络丢包率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.硬盘可用率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络丢包率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.硬盘可用率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.硬盘可用率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络延时率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络延时率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络延时率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络延时率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.最大进程数报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.最大进程数报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.最大进程数警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.最大进程数警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.MONITOR_ELB.toInteger())) { // monitorElb if (FieldNameConstant.monitorElb.监控ELB.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorElb.监控ELB + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.MDN.toInteger())) { // MDN if (FieldNameConstant.MdnItem.重点覆盖地域.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnItem.重点覆盖地域 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnItem.重点覆盖ISP.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnItem.重点覆盖ISP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } // MDNVod if (FieldNameConstant.MdnVodItem.点播服务域名.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播服务域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.点播播放协议选择.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播播放协议选择 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.点播加速服务带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播加速服务带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.点播出口带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播出口带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.Streamer地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.Streamer地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } // MDNLive if (FieldNameConstant.MdnLiveItem.直播服务域名.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播服务域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播播放协议选择.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播播放协议选择 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播加速服务带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播加速服务带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播出口带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播出口带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.频道名称.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.频道名称 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.频道GUID.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.频道GUID + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播流输出模式.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播流输出模式 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.编码器模式.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.编码器模式 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.HTTP流地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.HTTP流地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.HTTP流混合码率.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.HTTP流混合码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.M3U8流地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.M3U8流地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.M3U8流混合码率.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.M3U8流混合码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.RTSP流地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.RTSP流地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.RTSP流混合码率.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.RTSP流混合码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } content.append(NEWLINE); } else if (serviceType.equals(ResourcesConstant.ServiceType.CP.toInteger())) { if (FieldNameConstant.CpItem.收录流URL.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录流URL + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.收录码率.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.输出编码.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.输出编码 + ":" + NEWLINE); content.append(changeItem.getOldString()).append(NEWLINE + RARR + NEWLINE).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.收录类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.收录时段.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录时段 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.发布接口地址.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.发布接口地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.是否推送内容交易平台.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.是否推送内容交易平台 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP上传IP.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP上传IP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频端口.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频端口 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP用户名.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP用户名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP密码.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP密码 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP根路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP根路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP上传路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP上传路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频输出组类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频输出组类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.输出方式配置.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.输出方式配置 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP上传IP.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP上传IP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片端口.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片端口 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP用户名.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP用户名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP密码.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP密码 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP根路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP根路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP上传路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP上传路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片输出组类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片输出组类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.输出媒体类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.输出媒体类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } } } content.append(NEWLINE); } content.append("</pre>").append(NEWLINE); return content.toString(); } catch (Exception e) { e.printStackTrace(); logger.error("--->拼装Redmine内容出错:" + e.getMessage()); return null; } } }
true
true
public String resourcesRedmineDesc(ServiceTag serviceTag) { try { StringBuilder content = new StringBuilder(); content.append("*服务变更的详细信息*").append(NEWLINE + NEWLINE); content.append("* +*服务标签基本信息*+").append(NEWLINE); content.append("<pre>").append(NEWLINE); content.append("标签名: ").append(serviceTag.getName()).append(NEWLINE); content.append("优先级: ").append(RedmineConstant.Priority.get(serviceTag.getPriority())).append(NEWLINE); content.append("服务起止日期: ").append(serviceTag.getServiceStart()).append(" 至 ").append(serviceTag.getServiceEnd()).append(NEWLINE); content.append("用途描述: ").append(serviceTag.getDescription()).append(NEWLINE); content.append("申请人: ").append(serviceTag.getUser().getName()).append(NEWLINE); content.append("</pre>"); content.append(NEWLINE + NEWLINE); content.append("* +*变更信息*+").append(NEWLINE); content.append("<pre>").append(NEWLINE); List<Resources> resourcesList = comm.resourcesService.getCommitedResourcesListByServiceTagId(serviceTag.getId()); for (Resources resources : resourcesList) { Integer serviceType = resources.getServiceType(); for (Change change : resources.getChanges()) { // 资源标识符(标识符) + 变更说明 content.append("变更资源标识符:" + BLANK).append(resources.getServiceIdentifier()); // 只有当ip不为0.0.0.0时才插入IP(即资源本身有IP时,像DNS,ES3这些没有IP的资源将不显示ip) if (!IpPoolConstant.DEFAULT_IPADDRESS.equals(resources.getIpAddress())) { content.append("(" + resources.getIpAddress() + ")"); } content.append(BLANK + BLANK).append("变更描述:" + BLANK).append(change.getDescription()).append(NEWLINE); content.append("变更项:"); if (change.getSubResourcesId() != null) { content.append("(服务子项ID:" + change.getSubResourcesId() + ")"); } content.append(BLANK + "旧值").append(RARR).append("新值").append(NEWLINE); for (ChangeItem changeItem : change.getChangeItems()) { String fieldName = changeItem.getFieldName(); if (serviceType.equals(ResourcesConstant.ServiceType.PCS.toInteger()) || serviceType.equals(ResourcesConstant.ServiceType.ECS.toInteger())) { // 计算资源Compute信息 if (FieldNameConstant.Compate.操作系统.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.操作系统 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.操作位数.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.操作位数 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.规格.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.规格 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.用途信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.用途信息 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getOldString()).append(NEWLINE); } else if (FieldNameConstant.Compate.应用信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.应用信息 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.ESG.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.ESG + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.ES3.toInteger())) { // 存储空间Storage信息 if (FieldNameConstant.Storage.存储类型.toString().equals(fieldName)) { content.append(FieldNameConstant.Storage.存储类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Storage.容量空间.toString().equals(fieldName)) { content.append(FieldNameConstant.Storage.容量空间 + ":" + BLANK).append(changeItem.getOldString()).append("GB").append(RARR).append(changeItem.getNewString()).append("GB") .append(NEWLINE); } else if (FieldNameConstant.Storage.挂载实例.toString().equals(fieldName)) { content.append(FieldNameConstant.Storage.挂载实例 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.ELB.toInteger())) { // 变更负载均衡器ELB if (FieldNameConstant.Elb.是否保持会话.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.是否保持会话 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Elb.端口信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.端口信息 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Elb.关联实例.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.关联实例 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.EIP.toInteger())) { // EIP if (FieldNameConstant.Eip.关联实例.toString().equals(fieldName)) { content.append(FieldNameConstant.Eip.关联实例 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Eip.关联ELB.toString().equals(fieldName)) { content.append(FieldNameConstant.Eip.关联ELB + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Eip.端口信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.端口信息 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.DNS.toInteger())) { // 拼装DNS信息 if (FieldNameConstant.Dns.域名类型.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.域名类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Dns.域名.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Dns.CNAME域名.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.CNAME域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Dns.目标IP.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.目标IP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.MONITOR_COMPUTE.toInteger())) { // monitorCompute if (FieldNameConstant.monitorCompute.监控实例.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.监控实例 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.监控端口.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.监控端口 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.监控进程.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.监控进程 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.挂载路径.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.挂载路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.CPU占用率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.CPU占用率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.CPU占用率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.CPU占用率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.内存占用率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.内存占用率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.内存占用率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.内存占用率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络丢包率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络丢包率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络丢包率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络丢包率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.硬盘可用率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络丢包率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.硬盘可用率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.硬盘可用率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络延时率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络延时率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络延时率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络延时率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.最大进程数报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.最大进程数报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.最大进程数警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.最大进程数警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.MONITOR_ELB.toInteger())) { // monitorElb if (FieldNameConstant.monitorElb.监控ELB.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorElb.监控ELB + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.MDN.toInteger())) { // MDN if (FieldNameConstant.MdnItem.重点覆盖地域.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnItem.重点覆盖地域 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnItem.重点覆盖ISP.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnItem.重点覆盖ISP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } // MDNVod if (FieldNameConstant.MdnVodItem.点播服务域名.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播服务域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.点播播放协议选择.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播播放协议选择 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.点播加速服务带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播加速服务带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.点播出口带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播出口带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.Streamer地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.Streamer地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } // MDNLive if (FieldNameConstant.MdnLiveItem.直播服务域名.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播服务域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播播放协议选择.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播播放协议选择 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播加速服务带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播加速服务带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播出口带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播出口带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.频道名称.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.频道名称 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.频道GUID.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.频道GUID + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播流输出模式.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播流输出模式 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.编码器模式.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.编码器模式 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.HTTP流地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.HTTP流地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.HTTP流混合码率.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.HTTP流混合码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.M3U8流地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.M3U8流地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.M3U8流混合码率.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.M3U8流混合码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.RTSP流地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.RTSP流地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.RTSP流混合码率.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.RTSP流混合码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } content.append(NEWLINE); } else if (serviceType.equals(ResourcesConstant.ServiceType.CP.toInteger())) { if (FieldNameConstant.CpItem.收录流URL.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录流URL + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.收录码率.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.输出编码.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.输出编码 + ":" + NEWLINE); content.append(changeItem.getOldString()).append(NEWLINE + RARR + NEWLINE).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.收录类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.收录时段.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录时段 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.发布接口地址.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.发布接口地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.是否推送内容交易平台.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.是否推送内容交易平台 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP上传IP.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP上传IP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频端口.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频端口 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP用户名.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP用户名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP密码.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP密码 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP根路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP根路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP上传路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP上传路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频输出组类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频输出组类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.输出方式配置.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.输出方式配置 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP上传IP.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP上传IP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片端口.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片端口 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP用户名.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP用户名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP密码.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP密码 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP根路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP根路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP上传路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP上传路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片输出组类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片输出组类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.输出媒体类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.输出媒体类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } } } content.append(NEWLINE); } content.append("</pre>").append(NEWLINE); return content.toString(); } catch (Exception e) { e.printStackTrace(); logger.error("--->拼装Redmine内容出错:" + e.getMessage()); return null; } }
public String resourcesRedmineDesc(ServiceTag serviceTag) { try { StringBuilder content = new StringBuilder(); content.append("*服务变更的详细信息*").append(NEWLINE + NEWLINE); content.append("* +*服务标签基本信息*+").append(NEWLINE); content.append("<pre>").append(NEWLINE); content.append("标签名: ").append(serviceTag.getName()).append(NEWLINE); content.append("优先级: ").append(RedmineConstant.Priority.get(serviceTag.getPriority())).append(NEWLINE); content.append("服务起止日期: ").append(serviceTag.getServiceStart()).append(" 至 ").append(serviceTag.getServiceEnd()).append(NEWLINE); content.append("用途描述: ").append(serviceTag.getDescription()).append(NEWLINE); content.append("申请人: ").append(serviceTag.getUser().getName()).append(NEWLINE); content.append("</pre>"); content.append(NEWLINE + NEWLINE); content.append("* +*变更信息*+").append(NEWLINE); content.append("<pre>").append(NEWLINE); List<Resources> resourcesList = comm.resourcesService.getCommitedResourcesListByServiceTagId(serviceTag.getId()); for (Resources resources : resourcesList) { Integer serviceType = resources.getServiceType(); for (Change change : resources.getChanges()) { // 资源标识符(标识符) + 变更说明 content.append("变更资源标识符:" + BLANK).append(resources.getServiceIdentifier()); // 只有当ip不为0.0.0.0时才插入IP(即资源本身有IP时,像DNS,ES3这些没有IP的资源将不显示ip) if (!IpPoolConstant.DEFAULT_IPADDRESS.equals(resources.getIpAddress())) { content.append("(" + resources.getIpAddress() + ")"); } content.append(BLANK + BLANK).append("变更描述:" + BLANK).append(change.getDescription()).append(NEWLINE); content.append("变更项:"); if (change.getSubResourcesId() != null) { content.append("(服务子项ID:" + change.getSubResourcesId() + ")"); } content.append(BLANK + "旧值").append(RARR).append("新值").append(NEWLINE); for (ChangeItem changeItem : change.getChangeItems()) { String fieldName = changeItem.getFieldName(); if (serviceType.equals(ResourcesConstant.ServiceType.PCS.toInteger()) || serviceType.equals(ResourcesConstant.ServiceType.ECS.toInteger())) { // 计算资源Compute信息 if (FieldNameConstant.Compate.操作系统.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.操作系统 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.操作位数.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.操作位数 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.规格.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.规格 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.用途信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.用途信息 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.应用信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.应用信息 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Compate.ESG.toString().equals(fieldName)) { content.append(FieldNameConstant.Compate.ESG + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.ES3.toInteger())) { // 存储空间Storage信息 if (FieldNameConstant.Storage.存储类型.toString().equals(fieldName)) { content.append(FieldNameConstant.Storage.存储类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Storage.容量空间.toString().equals(fieldName)) { content.append(FieldNameConstant.Storage.容量空间 + ":" + BLANK).append(changeItem.getOldString()).append("GB").append(RARR).append(changeItem.getNewString()).append("GB") .append(NEWLINE); } else if (FieldNameConstant.Storage.挂载实例.toString().equals(fieldName)) { content.append(FieldNameConstant.Storage.挂载实例 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.ELB.toInteger())) { // 变更负载均衡器ELB if (FieldNameConstant.Elb.是否保持会话.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.是否保持会话 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Elb.端口信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.端口信息 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Elb.关联实例.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.关联实例 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.EIP.toInteger())) { // EIP if (FieldNameConstant.Eip.关联实例.toString().equals(fieldName)) { content.append(FieldNameConstant.Eip.关联实例 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Eip.关联ELB.toString().equals(fieldName)) { content.append(FieldNameConstant.Eip.关联ELB + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Eip.端口信息.toString().equals(fieldName)) { content.append(FieldNameConstant.Elb.端口信息 + ":" + BLANK).append(NEWLINE).append(changeItem.getOldString()).append(RARR).append(NEWLINE) .append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.DNS.toInteger())) { // 拼装DNS信息 if (FieldNameConstant.Dns.域名类型.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.域名类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Dns.域名.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Dns.CNAME域名.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.CNAME域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.Dns.目标IP.toString().equals(fieldName)) { content.append(FieldNameConstant.Dns.目标IP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.MONITOR_COMPUTE.toInteger())) { // monitorCompute if (FieldNameConstant.monitorCompute.监控实例.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.监控实例 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.监控端口.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.监控端口 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.监控进程.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.监控进程 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.挂载路径.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.挂载路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.CPU占用率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.CPU占用率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.CPU占用率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.CPU占用率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK) .append(changeItem.getNewString()).append(NEWLINE); } else if (FieldNameConstant.monitorCompute.内存占用率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.内存占用率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.内存占用率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.内存占用率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络丢包率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络丢包率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络丢包率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络丢包率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.硬盘可用率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络丢包率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.硬盘可用率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.硬盘可用率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络延时率报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络延时率报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.网络延时率警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.网络延时率警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.最大进程数报警阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.最大进程数报警阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } else if (FieldNameConstant.monitorCompute.最大进程数警告阀值.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorCompute.最大进程数警告阀值 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(BLANK).append(changeItem.getNewString()) .append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.MONITOR_ELB.toInteger())) { // monitorElb if (FieldNameConstant.monitorElb.监控ELB.toString().equals(fieldName)) { content.append(FieldNameConstant.monitorElb.监控ELB + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } else if (serviceType.equals(ResourcesConstant.ServiceType.MDN.toInteger())) { // MDN if (FieldNameConstant.MdnItem.重点覆盖地域.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnItem.重点覆盖地域 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnItem.重点覆盖ISP.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnItem.重点覆盖ISP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } // MDNVod if (FieldNameConstant.MdnVodItem.点播服务域名.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播服务域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.点播播放协议选择.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播播放协议选择 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.点播加速服务带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播加速服务带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.点播出口带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.点播出口带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnVodItem.Streamer地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnVodItem.Streamer地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } // MDNLive if (FieldNameConstant.MdnLiveItem.直播服务域名.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播服务域名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播播放协议选择.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播播放协议选择 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播加速服务带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播加速服务带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播出口带宽.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播出口带宽 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.频道名称.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.频道名称 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.频道GUID.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.频道GUID + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.直播流输出模式.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.直播流输出模式 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.编码器模式.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.编码器模式 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.HTTP流地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.HTTP流地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.HTTP流混合码率.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.HTTP流混合码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.M3U8流地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.M3U8流地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.M3U8流混合码率.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.M3U8流混合码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.RTSP流地址.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.RTSP流地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.MdnLiveItem.RTSP流混合码率.toString().equals(fieldName)) { content.append(FieldNameConstant.MdnLiveItem.RTSP流混合码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } content.append(NEWLINE); } else if (serviceType.equals(ResourcesConstant.ServiceType.CP.toInteger())) { if (FieldNameConstant.CpItem.收录流URL.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录流URL + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.收录码率.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录码率 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.输出编码.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.输出编码 + ":" + NEWLINE); content.append(changeItem.getOldString()).append(NEWLINE + RARR + NEWLINE).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.收录类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.收录时段.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.收录时段 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.发布接口地址.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.发布接口地址 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.是否推送内容交易平台.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.是否推送内容交易平台 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP上传IP.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP上传IP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频端口.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频端口 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP用户名.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP用户名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP密码.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP密码 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP根路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP根路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频FTP上传路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频FTP上传路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.视频输出组类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.视频输出组类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.输出方式配置.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.输出方式配置 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP上传IP.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP上传IP + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片端口.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片端口 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP用户名.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP用户名 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP密码.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP密码 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP根路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP根路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片FTP上传路径.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片FTP上传路径 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.图片输出组类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.图片输出组类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } if (FieldNameConstant.CpItem.输出媒体类型.toString().equals(fieldName)) { content.append(FieldNameConstant.CpItem.输出媒体类型 + ":" + BLANK).append(changeItem.getOldString()).append(RARR).append(changeItem.getNewString()).append(NEWLINE); } } } } content.append(NEWLINE); } content.append("</pre>").append(NEWLINE); return content.toString(); } catch (Exception e) { e.printStackTrace(); logger.error("--->拼装Redmine内容出错:" + e.getMessage()); return null; } }
diff --git a/hot-deploy/opentaps-common/src/common/org/opentaps/gwt/common/server/lookup/SalesOrderLookupService.java b/hot-deploy/opentaps-common/src/common/org/opentaps/gwt/common/server/lookup/SalesOrderLookupService.java index 0352a80c3..57deb84d2 100644 --- a/hot-deploy/opentaps-common/src/common/org/opentaps/gwt/common/server/lookup/SalesOrderLookupService.java +++ b/hot-deploy/opentaps-common/src/common/org/opentaps/gwt/common/server/lookup/SalesOrderLookupService.java @@ -1,210 +1,210 @@ /* * Copyright (c) 2009 - 2009 Open Source Strategies, Inc. * * Opentaps is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Opentaps is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Opentaps. If not, see <http://www.gnu.org/licenses/>. */ package org.opentaps.gwt.common.server.lookup; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.ofbiz.base.util.Debug; import org.ofbiz.base.util.UtilProperties; import org.ofbiz.base.util.UtilValidate; import org.opentaps.domain.order.OrderViewForListing; import org.opentaps.domain.order.SalesOrderLookupRepositoryInterface; import org.opentaps.foundation.entity.EntityInterface; import org.opentaps.foundation.infrastructure.InfrastructureException; import org.opentaps.foundation.repository.RepositoryException; import org.opentaps.gwt.common.client.lookup.configuration.SalesOrderLookupConfiguration; import org.opentaps.gwt.common.server.HttpInputProvider; import org.opentaps.gwt.common.server.InputProviderInterface; /** * The RPC service used to populate the OrderListView and Order autocompleters widgets. * @author <a href="mailto:jeremy@iznogoud">Wickersheimer Jeremy</a> * @version 1.0 */ public class SalesOrderLookupService extends EntityLookupAndSuggestService { private static final String MODULE = SalesOrderLookupService.class.getName(); /** * Creates a new <code>PartyLookupService</code> instance. * @param provider an <code>InputProviderInterface</code> value */ public SalesOrderLookupService(InputProviderInterface provider) { super(provider, SalesOrderLookupConfiguration.LIST_OUT_FIELDS); } /** * AJAX event to perform lookups on Orders. * @param request a <code>HttpServletRequest</code> value * @param response a <code>HttpServletResponse</code> value * @return the resulting JSON response * @throws InfrastructureException if an error occurs */ public static String findOrders(HttpServletRequest request, HttpServletResponse response) throws InfrastructureException { InputProviderInterface provider = new HttpInputProvider(request); JsonResponse json = new JsonResponse(response); SalesOrderLookupService service = new SalesOrderLookupService(provider); // The GWT date input is always using the US locale -- (it should be using the user locale though ...) service.findOrders(Locale.US); return json.makeLookupResponse(SalesOrderLookupConfiguration.INOUT_ORDER_ID, service, request.getSession(true).getServletContext()); } /** * Finds a list of <code>Order</code>. * @return the list of <code>Order</code>, or <code>null</code> if an error occurred */ public List<OrderViewForListing> findOrders() { return findOrders(getProvider().getLocale()); } /** * Finds a list of <code>Order</code>. * @param locale force a <code>Locale</code> value * @return the list of <code>Order</code>, or <code>null</code> if an error occurred */ public List<OrderViewForListing> findOrders(Locale locale) { try { SalesOrderLookupRepositoryInterface salesOrderLookupRepository = getDomainsDirectory().getOrderDomain().getSalesOrderLookupRepository(); String organizationPartyId = UtilProperties.getPropertyValue("opentaps", "organizationPartyId"); String userLoginId = null; if (getProvider().getUser().getOfbizUserLogin() != null) { userLoginId = getProvider().getUser().getOfbizUserLogin().getString("userLoginId"); } else { Debug.logError("Current session do not have any UserLogin set.", MODULE); } // pass locale and timeZone instances for format the date string // use Locale.US for change gwt date input -- is this required to be US ?? salesOrderLookupRepository.setLocale(locale); salesOrderLookupRepository.setTimeZone(getProvider().getTimeZone()); // pass parameters into repository salesOrderLookupRepository.setUserLoginId(userLoginId); salesOrderLookupRepository.setOrganizationPartyId(organizationPartyId); if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_FROM_DATE))) { salesOrderLookupRepository.setFromDate(getProvider().getParameter(SalesOrderLookupConfiguration.IN_FROM_DATE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_THRU_DATE))) { salesOrderLookupRepository.setThruDate(getProvider().getParameter(SalesOrderLookupConfiguration.IN_THRU_DATE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_RESPONSIBILTY))) { salesOrderLookupRepository.setViewPref(getProvider().getParameter(SalesOrderLookupConfiguration.IN_RESPONSIBILTY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_ID))) { salesOrderLookupRepository.setOrderId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_EXTERNAL_ID))) { salesOrderLookupRepository.setExteralOrderId(getProvider().getParameter(SalesOrderLookupConfiguration.IN_EXTERNAL_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_NAME))) { salesOrderLookupRepository.setOrderName(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_NAME)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_PARTY_ID))) { salesOrderLookupRepository.setCustomerPartyId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_PARTY_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_PRODUCT_STORE_ID))) { salesOrderLookupRepository.setProductStoreId(getProvider().getParameter(SalesOrderLookupConfiguration.IN_PRODUCT_STORE_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_STATUS_ID))) { salesOrderLookupRepository.setStatusId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_STATUS_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_CORRESPONDING_PO_ID))) { salesOrderLookupRepository.setPurchaseOrderId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_CORRESPONDING_PO_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_CREATED_BY))) { salesOrderLookupRepository.setCreatedBy(getProvider().getParameter(SalesOrderLookupConfiguration.IN_CREATED_BY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_LOT_ID))) { salesOrderLookupRepository.setLotId(getProvider().getParameter(SalesOrderLookupConfiguration.IN_LOT_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SERIAL_NUMBER))) { salesOrderLookupRepository.setSerialNumber(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SERIAL_NUMBER)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ADDRESS))) { salesOrderLookupRepository.setShippingAddress(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ADDRESS)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_CITY))) { - salesOrderLookupRepository.setShippingCountry(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_CITY)); + salesOrderLookupRepository.setShippingCity(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_CITY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_COUNTRY))) { - salesOrderLookupRepository.setShippingStateProvince(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_COUNTRY)); + salesOrderLookupRepository.setShippingCountry(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_COUNTRY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_STATE))) { - salesOrderLookupRepository.setShippingCity(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_STATE)); + salesOrderLookupRepository.setShippingStateProvince(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_STATE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_POSTAL_CODE))) { salesOrderLookupRepository.setShippingPostalCode(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_POSTAL_CODE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_TO_NAME))) { salesOrderLookupRepository.setShippingToName(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_TO_NAME)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ATTENTION_NAME))) { salesOrderLookupRepository.setShippingAttnName(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ATTENTION_NAME)); } // takes into account order statuses // activeOnly & desired flags aren't mutually exclusive, activeOnly statuses is a superset // of desired statuses. String findAll = getProvider().getParameter(SalesOrderLookupConfiguration.IN_FIND_ALL); if (UtilValidate.isNotEmpty(findAll) && "Y".equals(findAll)) { salesOrderLookupRepository.setFindActiveOnly(false); } else { salesOrderLookupRepository.setFindActiveOnly(true); } String isDesired = getProvider().getParameter(SalesOrderLookupConfiguration.IN_DESIRED); if (UtilValidate.isNotEmpty(isDesired) && "Y".equals(isDesired)) { salesOrderLookupRepository.setFindDesiredOnly(true); } // set sort conditions salesOrderLookupRepository.setOrderBy(getOrderBy()); // set the pagination salesOrderLookupRepository.setPageStart(getPager().getPageStart()); salesOrderLookupRepository.setPageSize(getPager().getPageSize()); // return the matching result List<OrderViewForListing> results = salesOrderLookupRepository.findOrders(); setResults(results); setResultTotalCount(salesOrderLookupRepository.getResultSize()); return results; } catch (RepositoryException e) { storeException(e); return null; } } @Override public String makeSuggestDisplayedText(EntityInterface value) { StringBuffer sb = new StringBuffer(); String orderName = value.getString(OrderViewForListing.Fields.orderName.name()); String orderId = value.getString(OrderViewForListing.Fields.orderId.name()); if (UtilValidate.isNotEmpty(orderName)) { sb.append(orderName); } sb.append(" (").append(orderId).append(")"); return sb.toString(); } }
false
true
public List<OrderViewForListing> findOrders(Locale locale) { try { SalesOrderLookupRepositoryInterface salesOrderLookupRepository = getDomainsDirectory().getOrderDomain().getSalesOrderLookupRepository(); String organizationPartyId = UtilProperties.getPropertyValue("opentaps", "organizationPartyId"); String userLoginId = null; if (getProvider().getUser().getOfbizUserLogin() != null) { userLoginId = getProvider().getUser().getOfbizUserLogin().getString("userLoginId"); } else { Debug.logError("Current session do not have any UserLogin set.", MODULE); } // pass locale and timeZone instances for format the date string // use Locale.US for change gwt date input -- is this required to be US ?? salesOrderLookupRepository.setLocale(locale); salesOrderLookupRepository.setTimeZone(getProvider().getTimeZone()); // pass parameters into repository salesOrderLookupRepository.setUserLoginId(userLoginId); salesOrderLookupRepository.setOrganizationPartyId(organizationPartyId); if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_FROM_DATE))) { salesOrderLookupRepository.setFromDate(getProvider().getParameter(SalesOrderLookupConfiguration.IN_FROM_DATE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_THRU_DATE))) { salesOrderLookupRepository.setThruDate(getProvider().getParameter(SalesOrderLookupConfiguration.IN_THRU_DATE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_RESPONSIBILTY))) { salesOrderLookupRepository.setViewPref(getProvider().getParameter(SalesOrderLookupConfiguration.IN_RESPONSIBILTY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_ID))) { salesOrderLookupRepository.setOrderId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_EXTERNAL_ID))) { salesOrderLookupRepository.setExteralOrderId(getProvider().getParameter(SalesOrderLookupConfiguration.IN_EXTERNAL_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_NAME))) { salesOrderLookupRepository.setOrderName(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_NAME)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_PARTY_ID))) { salesOrderLookupRepository.setCustomerPartyId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_PARTY_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_PRODUCT_STORE_ID))) { salesOrderLookupRepository.setProductStoreId(getProvider().getParameter(SalesOrderLookupConfiguration.IN_PRODUCT_STORE_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_STATUS_ID))) { salesOrderLookupRepository.setStatusId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_STATUS_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_CORRESPONDING_PO_ID))) { salesOrderLookupRepository.setPurchaseOrderId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_CORRESPONDING_PO_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_CREATED_BY))) { salesOrderLookupRepository.setCreatedBy(getProvider().getParameter(SalesOrderLookupConfiguration.IN_CREATED_BY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_LOT_ID))) { salesOrderLookupRepository.setLotId(getProvider().getParameter(SalesOrderLookupConfiguration.IN_LOT_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SERIAL_NUMBER))) { salesOrderLookupRepository.setSerialNumber(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SERIAL_NUMBER)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ADDRESS))) { salesOrderLookupRepository.setShippingAddress(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ADDRESS)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_CITY))) { salesOrderLookupRepository.setShippingCountry(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_CITY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_COUNTRY))) { salesOrderLookupRepository.setShippingStateProvince(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_COUNTRY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_STATE))) { salesOrderLookupRepository.setShippingCity(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_STATE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_POSTAL_CODE))) { salesOrderLookupRepository.setShippingPostalCode(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_POSTAL_CODE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_TO_NAME))) { salesOrderLookupRepository.setShippingToName(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_TO_NAME)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ATTENTION_NAME))) { salesOrderLookupRepository.setShippingAttnName(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ATTENTION_NAME)); } // takes into account order statuses // activeOnly & desired flags aren't mutually exclusive, activeOnly statuses is a superset // of desired statuses. String findAll = getProvider().getParameter(SalesOrderLookupConfiguration.IN_FIND_ALL); if (UtilValidate.isNotEmpty(findAll) && "Y".equals(findAll)) { salesOrderLookupRepository.setFindActiveOnly(false); } else { salesOrderLookupRepository.setFindActiveOnly(true); } String isDesired = getProvider().getParameter(SalesOrderLookupConfiguration.IN_DESIRED); if (UtilValidate.isNotEmpty(isDesired) && "Y".equals(isDesired)) { salesOrderLookupRepository.setFindDesiredOnly(true); } // set sort conditions salesOrderLookupRepository.setOrderBy(getOrderBy()); // set the pagination salesOrderLookupRepository.setPageStart(getPager().getPageStart()); salesOrderLookupRepository.setPageSize(getPager().getPageSize()); // return the matching result List<OrderViewForListing> results = salesOrderLookupRepository.findOrders(); setResults(results); setResultTotalCount(salesOrderLookupRepository.getResultSize()); return results; } catch (RepositoryException e) { storeException(e); return null; } }
public List<OrderViewForListing> findOrders(Locale locale) { try { SalesOrderLookupRepositoryInterface salesOrderLookupRepository = getDomainsDirectory().getOrderDomain().getSalesOrderLookupRepository(); String organizationPartyId = UtilProperties.getPropertyValue("opentaps", "organizationPartyId"); String userLoginId = null; if (getProvider().getUser().getOfbizUserLogin() != null) { userLoginId = getProvider().getUser().getOfbizUserLogin().getString("userLoginId"); } else { Debug.logError("Current session do not have any UserLogin set.", MODULE); } // pass locale and timeZone instances for format the date string // use Locale.US for change gwt date input -- is this required to be US ?? salesOrderLookupRepository.setLocale(locale); salesOrderLookupRepository.setTimeZone(getProvider().getTimeZone()); // pass parameters into repository salesOrderLookupRepository.setUserLoginId(userLoginId); salesOrderLookupRepository.setOrganizationPartyId(organizationPartyId); if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_FROM_DATE))) { salesOrderLookupRepository.setFromDate(getProvider().getParameter(SalesOrderLookupConfiguration.IN_FROM_DATE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_THRU_DATE))) { salesOrderLookupRepository.setThruDate(getProvider().getParameter(SalesOrderLookupConfiguration.IN_THRU_DATE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_RESPONSIBILTY))) { salesOrderLookupRepository.setViewPref(getProvider().getParameter(SalesOrderLookupConfiguration.IN_RESPONSIBILTY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_ID))) { salesOrderLookupRepository.setOrderId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_EXTERNAL_ID))) { salesOrderLookupRepository.setExteralOrderId(getProvider().getParameter(SalesOrderLookupConfiguration.IN_EXTERNAL_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_NAME))) { salesOrderLookupRepository.setOrderName(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_ORDER_NAME)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_PARTY_ID))) { salesOrderLookupRepository.setCustomerPartyId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_PARTY_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_PRODUCT_STORE_ID))) { salesOrderLookupRepository.setProductStoreId(getProvider().getParameter(SalesOrderLookupConfiguration.IN_PRODUCT_STORE_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_STATUS_ID))) { salesOrderLookupRepository.setStatusId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_STATUS_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_CORRESPONDING_PO_ID))) { salesOrderLookupRepository.setPurchaseOrderId(getProvider().getParameter(SalesOrderLookupConfiguration.INOUT_CORRESPONDING_PO_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_CREATED_BY))) { salesOrderLookupRepository.setCreatedBy(getProvider().getParameter(SalesOrderLookupConfiguration.IN_CREATED_BY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_LOT_ID))) { salesOrderLookupRepository.setLotId(getProvider().getParameter(SalesOrderLookupConfiguration.IN_LOT_ID)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SERIAL_NUMBER))) { salesOrderLookupRepository.setSerialNumber(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SERIAL_NUMBER)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ADDRESS))) { salesOrderLookupRepository.setShippingAddress(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ADDRESS)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_CITY))) { salesOrderLookupRepository.setShippingCity(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_CITY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_COUNTRY))) { salesOrderLookupRepository.setShippingCountry(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_COUNTRY)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_STATE))) { salesOrderLookupRepository.setShippingStateProvince(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_STATE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_POSTAL_CODE))) { salesOrderLookupRepository.setShippingPostalCode(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_POSTAL_CODE)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_TO_NAME))) { salesOrderLookupRepository.setShippingToName(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_TO_NAME)); } if (UtilValidate.isNotEmpty(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ATTENTION_NAME))) { salesOrderLookupRepository.setShippingAttnName(getProvider().getParameter(SalesOrderLookupConfiguration.IN_SHIPPING_ATTENTION_NAME)); } // takes into account order statuses // activeOnly & desired flags aren't mutually exclusive, activeOnly statuses is a superset // of desired statuses. String findAll = getProvider().getParameter(SalesOrderLookupConfiguration.IN_FIND_ALL); if (UtilValidate.isNotEmpty(findAll) && "Y".equals(findAll)) { salesOrderLookupRepository.setFindActiveOnly(false); } else { salesOrderLookupRepository.setFindActiveOnly(true); } String isDesired = getProvider().getParameter(SalesOrderLookupConfiguration.IN_DESIRED); if (UtilValidate.isNotEmpty(isDesired) && "Y".equals(isDesired)) { salesOrderLookupRepository.setFindDesiredOnly(true); } // set sort conditions salesOrderLookupRepository.setOrderBy(getOrderBy()); // set the pagination salesOrderLookupRepository.setPageStart(getPager().getPageStart()); salesOrderLookupRepository.setPageSize(getPager().getPageSize()); // return the matching result List<OrderViewForListing> results = salesOrderLookupRepository.findOrders(); setResults(results); setResultTotalCount(salesOrderLookupRepository.getResultSize()); return results; } catch (RepositoryException e) { storeException(e); return null; } }
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java index b1cb93781..b9b0632ea 100644 --- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java +++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgCommit.java @@ -1,434 +1,439 @@ package org.tmatesoft.svn.core.internal.wc2.ng; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import org.tmatesoft.svn.core.SVNCancelException; import org.tmatesoft.svn.core.SVNCommitInfo; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNProperties; import org.tmatesoft.svn.core.SVNPropertyValue; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.util.SVNDate; import org.tmatesoft.svn.core.internal.util.SVNPathUtil; import org.tmatesoft.svn.core.internal.util.SVNSkel; import org.tmatesoft.svn.core.internal.wc.SVNCommitUtil; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNEventFactory; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager; import org.tmatesoft.svn.core.internal.wc17.SVNCommitMediator17; import org.tmatesoft.svn.core.internal.wc17.SVNCommitter17; import org.tmatesoft.svn.core.internal.wc17.SVNWCContext; import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.SVNWCDbKind; import org.tmatesoft.svn.core.internal.wc17.db.ISVNWCDb.SVNWCDbStatus; import org.tmatesoft.svn.core.internal.wc17.db.Structure; import org.tmatesoft.svn.core.internal.wc17.db.StructureFields.NodeInfo; import org.tmatesoft.svn.core.internal.wc2.ISvnCommitRunner; import org.tmatesoft.svn.core.internal.wc2.ng.SvnNgCommitUtil.ISvnUrlKindCallback; import org.tmatesoft.svn.core.io.ISVNEditor; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.wc.ISVNEventHandler; import org.tmatesoft.svn.core.wc.SVNEventAction; import org.tmatesoft.svn.core.wc2.SvnChecksum; import org.tmatesoft.svn.core.wc2.SvnCommit; import org.tmatesoft.svn.core.wc2.SvnCommitItem; import org.tmatesoft.svn.core.wc2.SvnCommitPacket; import org.tmatesoft.svn.core.wc2.SvnTarget; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; public class SvnNgCommit extends SvnNgOperationRunner<SVNCommitInfo, SvnCommit> implements ISvnCommitRunner, ISvnUrlKindCallback { public SvnCommitPacket collectCommitItems(SvnCommit operation) throws SVNException { setOperation(operation); SvnCommitPacket packet = new SvnCommitPacket(); Collection<String> targets = new ArrayList<String>(); String[] validatedPaths = new String[getOperation().getTargets().size()]; int i = 0; for(SvnTarget target : getOperation().getTargets()) { validatedPaths[i] = target.getFile().getAbsolutePath(); validatedPaths[i] = validatedPaths[i].replace(File.separatorChar, '/'); i++; } String rootPath = SVNPathUtil.condencePaths(validatedPaths, targets, false); if (rootPath == null) { return packet; } File baseDir = new File(rootPath).getAbsoluteFile(); if (targets.isEmpty()) { targets.add(""); } Collection<File> lockTargets = determineLockTargets(baseDir, targets); Collection<File> lockedRoots = new HashSet<File>(); try { for (File lockTarget : lockTargets) { File lockRoot = getWcContext().acquireWriteLock(lockTarget, false, true); lockedRoots.add(lockRoot); } packet.setLockingContext(this, lockedRoots); Map<SVNURL, String> lockTokens = new HashMap<SVNURL, String>(); SvnNgCommitUtil.harvestCommittables(getWcContext(), packet, lockTokens, baseDir, targets, getOperation().getDepth(), !getOperation().isKeepLocks(), getOperation().getApplicableChangelists(), this, getOperation().getCommitParameters(), null); packet.setLockTokens(lockTokens); if (getOperation().isFailOnMultipleRepositories() && packet.getRepositoryRoots().size() > 1) { SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Commit can only commit to a single repository at a time.\n" + "Are all targets part of the same working copy?"); SVNErrorManager.error(err, SVNLogType.WC); } if (!packet.isEmpty()) { return packet; } else { packet.dispose(); return new SvnCommitPacket(); } } catch (SVNException e) { packet.dispose(); SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err, SVNLogType.WC); } return null; } @Override protected SVNCommitInfo run(SVNWCContext context) throws SVNException { final SvnCommitPacket[] packets = getOperation().splitCommitPackets(getOperation().isCombinePackets()); SVNCommitInfo result = SVNCommitInfo.NULL; for(int i = 0; i < packets.length; i++) { if (packets[i] == null || packets[i].isEmpty()) { continue; } packets[i] = packets[i].removeSkippedItems(); final SVNURL repositoryRoot = packets[i].getRepositoryRoots().iterator().next(); result = doRun(context, packets[i]); if (result != null) { getOperation().receive(SvnTarget.fromURL(repositoryRoot), result); } } return result; } protected SVNCommitInfo doRun(SVNWCContext context, SvnCommitPacket packet) throws SVNException { SVNProperties revisionProperties = getOperation().getRevisionProperties(); SVNPropertiesManager.validateRevisionProperties(revisionProperties); String commitMessage = getOperation().getCommitMessage(); if (getOperation().getCommitHandler() != null) { Collection<SvnCommitItem> items = new ArrayList<SvnCommitItem>(); for (SVNURL rootUrl : packet.getRepositoryRoots()) { items.addAll(packet.getItems(rootUrl)); } SvnCommitItem[] itemsArray = items.toArray(new SvnCommitItem[items.size()]); - commitMessage = getOperation().getCommitHandler().getCommitMessage(commitMessage, itemsArray); - if (commitMessage == null) { - return SVNCommitInfo.NULL; + try { + commitMessage = getOperation().getCommitHandler().getCommitMessage(commitMessage, itemsArray); + if (commitMessage == null) { + return SVNCommitInfo.NULL; + } + revisionProperties = getOperation().getCommitHandler().getRevisionProperties(commitMessage, itemsArray, revisionProperties); + } catch (SVNException e) { + SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); + SVNErrorManager.error(err, SVNLogType.WC); } - revisionProperties = getOperation().getCommitHandler().getRevisionProperties(commitMessage, itemsArray, revisionProperties); } commitMessage = commitMessage == null ? "" : SVNCommitUtil.validateCommitMessage(commitMessage); boolean keepLocks = getOperation().isKeepLocks(); SVNException bumpError = null; SVNCommitInfo info = null; try { SVNURL repositoryRootUrl = packet.getRepositoryRoots().iterator().next(); if (packet.isEmpty(repositoryRootUrl)) { return SVNCommitInfo.NULL; } Map<String, SvnCommitItem> committables = new TreeMap<String, SvnCommitItem>(); Map<File, SvnChecksum> md5Checksums = new HashMap<File, SvnChecksum>(); Map<File, SvnChecksum> sha1Checksums = new HashMap<File, SvnChecksum>(); SVNURL baseURL = SvnNgCommitUtil.translateCommitables(packet.getItems(repositoryRootUrl), committables); Map<String, String> lockTokens = SvnNgCommitUtil.translateLockTokens(packet.getLockTokens(), baseURL); SvnCommitItem firstItem = packet.getItems(repositoryRootUrl).iterator().next(); SVNRepository repository = getRepositoryAccess().createRepository(baseURL, firstItem.getPath()); SVNCommitMediator17 mediator = new SVNCommitMediator17(context, committables); ISVNEditor commitEditor = null; try { commitEditor = repository.getCommitEditor(commitMessage, lockTokens, keepLocks, revisionProperties, mediator); SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRootUrl, mediator.getTmpFiles(), md5Checksums, sha1Checksums); SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1); committer.sendTextDeltas(commitEditor); info = commitEditor.closeEdit(); commitEditor = null; if (info.getErrorMessage() == null || info.getErrorMessage().getErrorCode() == SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED) { // do some post processing, make sure not to unlock wc (to dipose packet) in case there // is an error on post processing. SvnCommittedQueue queue = new SvnCommittedQueue(); try { for (SvnCommitItem item : packet.getItems(repositoryRootUrl)) { postProcessCommitItem(queue, item, getOperation().isKeepChangelists(), getOperation().isKeepLocks(), sha1Checksums.get(item.getPath())); } processCommittedQueue(queue, info.getNewRevision(), info.getDate(), info.getAuthor()); deleteDeleteFiles(committer, getOperation().getCommitParameters()); } catch (SVNException e) { // this is bump error. bumpError = e; throw e; } finally { // only for the last packet in chain. if (packet.isLastPacket()) { sleepForTimestamp(); } } } handleEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, SVNEventAction.COMMIT_COMPLETED, null, null, -1, -1)); } catch (SVNException e) { if (e instanceof SVNCancelException) { throw e; } SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); info = new SVNCommitInfo(-1, null, null, err); handleEvent(SVNEventFactory.createErrorEvent(err, SVNEventAction.COMMIT_COMPLETED), ISVNEventHandler.UNKNOWN); if (packet.getRepositoryRoots().size() == 1) { SVNErrorManager.error(err, SVNLogType.WC); } } finally { if (commitEditor != null) { try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().log(SVNLogType.CLIENT, e, Level.WARNING); //the exception should not mask original exception } } for (File tmpFile : mediator.getTmpFiles()) { SVNFileUtil.deleteFile(tmpFile); } } } finally { if (bumpError == null) { packet.dispose(); } } return info; } private void postProcessCommitItem(SvnCommittedQueue queue, SvnCommitItem item, boolean keepChangelists, boolean keepLocks, SvnChecksum sha1Checksum) throws SVNException { boolean removeLock = !keepLocks && item.hasFlag(SvnCommitItem.LOCK); Map<String, SVNPropertyValue> wcPropChanges = item.getIncomingProperties(); SVNProperties wcProps = null; if (wcPropChanges != null) { try { wcProps = getWcContext().getDb().getBaseDavCache(item.getPath()); } catch (SVNException e) { // missing properties. } if (wcProps == null) { wcProps = new SVNProperties(); } for (String name : wcPropChanges.keySet()) { SVNPropertyValue pv = wcPropChanges.get(name); if (pv == null) { wcProps.remove(name); } else { wcProps.put(name, pv); } } } queueCommitted(queue, item.getPath(), false, wcProps, removeLock, !keepChangelists, sha1Checksum); } public SVNNodeKind getUrlKind(SVNURL url, long revision) throws SVNException { return getRepositoryAccess().createRepository(url, null).checkPath("", revision); } private Collection<File> determineLockTargets(File baseDirectory, Collection<String> targets) throws SVNException { Map<File, Collection<File>> wcItems = new HashMap<File, Collection<File>>(); for (String t: targets) { File target = SVNFileUtil.createFilePath(baseDirectory, t); File wcRoot = null; try { wcRoot = getWcContext().getDb().getWCRoot(target); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_PATH_NOT_FOUND) { continue; } throw e; } Collection<File> wcTargets = wcItems.get(wcRoot); if (wcTargets == null) { wcTargets = new HashSet<File>(); wcItems.put(wcRoot, wcTargets); } wcTargets.add(target); } Collection<File> lockTargets = new HashSet<File>(); for (File wcRoot : wcItems.keySet()) { Collection<File> wcTargets = wcItems.get(wcRoot); if (wcTargets.size() == 1) { if (wcRoot.equals(wcTargets.iterator().next())) { lockTargets.add(wcRoot); } else { lockTargets.add(SVNFileUtil.getParentFile(wcTargets.iterator().next())); } } else if (wcTargets.size() > 1) { lockTargets.add(wcRoot); } } return lockTargets; } public Object splitLockingContext(Object lockingContext, SvnCommitPacket newPacket) { if (!(lockingContext instanceof Collection)) { return lockingContext; } @SuppressWarnings("unchecked") final Collection<File> lockedPaths = (Collection<File>) lockingContext; final Collection<File> newLockedPaths = new ArrayList<File>(); for (SVNURL root : newPacket.getRepositoryRoots()) { for(SvnCommitItem item : newPacket.getItems(root)) { final File path = item.getPath(); for (File lockedPath : lockedPaths) { if (path.equals(lockedPath) || (path.isFile() && path.getParentFile().equals(lockedPath))) { newLockedPaths.add(lockedPath); break; } } } } return newLockedPaths; }; public void disposeCommitPacket(Object lockingContext, boolean disposeParentContext) throws SVNException { if (!(lockingContext instanceof Collection)) { if (disposeParentContext) { getWcContext().close(); } return; } if (disposeParentContext) { @SuppressWarnings("unchecked") Collection<File> lockedPaths = (Collection<File>) lockingContext; for (File lockedPath : lockedPaths) { try { getWcContext().releaseWriteLock(lockedPath); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode() != SVNErrorCode.WC_NOT_LOCKED) { throw e; } } } getWcContext().close(); } } private void queueCommitted(SvnCommittedQueue queue, File localAbsPath, boolean recurse, SVNProperties wcPropChanges, boolean removeLock, boolean removeChangelist, SvnChecksum sha1Checksum) { SvnCommittedQueueItem cqi = new SvnCommittedQueueItem(); cqi.localAbspath = localAbsPath; cqi.recurse = recurse; cqi.noUnlock = !removeLock; cqi.keepChangelist = !removeChangelist; cqi.sha1Checksum = sha1Checksum; cqi.newDavCache = wcPropChanges; queue.queue.put(localAbsPath, cqi); } private void processCommittedQueue(SvnCommittedQueue queue, long newRevision, Date revDate, String revAuthor) throws SVNException { Collection<File> roots = new HashSet<File>(); for (SvnCommittedQueueItem cqi : queue.queue.values()) { processCommittedInternal(cqi.localAbspath, cqi.recurse, true, newRevision, new SVNDate(revDate.getTime(), 0), revAuthor, cqi.newDavCache, cqi.noUnlock, cqi.keepChangelist, cqi.sha1Checksum, queue); File root = getWcContext().getDb().getWCRoot(cqi.localAbspath); roots.add(root); } for (File root : roots) { getWcContext().wqRun(root); } queue.queue.clear(); } private void processCommittedInternal(File localAbspath, boolean recurse, boolean topOfRecurse, long newRevision, SVNDate revDate, String revAuthor, SVNProperties newDavCache, boolean noUnlock, boolean keepChangelist, SvnChecksum sha1Checksum, SvnCommittedQueue queue) throws SVNException { processCommittedLeaf(localAbspath, !topOfRecurse, newRevision, revDate, revAuthor, newDavCache, noUnlock, keepChangelist, sha1Checksum); } private void processCommittedLeaf(File localAbspath, boolean viaRecurse, long newRevnum, SVNDate newChangedDate, String newChangedAuthor, SVNProperties newDavCache, boolean noUnlock, boolean keepChangelist, SvnChecksum checksum) throws SVNException { long newChangedRev = newRevnum; assert (SVNFileUtil.isAbsolute(localAbspath)); Structure<NodeInfo> nodeInfo = getWcContext().getDb().readInfo(localAbspath, NodeInfo.status, NodeInfo.kind, NodeInfo.checksum, NodeInfo.hadProps, NodeInfo.propsMod, NodeInfo.haveBase, NodeInfo.haveWork); File admAbspath; if (nodeInfo.get(NodeInfo.kind) == SVNWCDbKind.Dir) { admAbspath = localAbspath; } else { admAbspath = SVNFileUtil.getFileDir(localAbspath); } getWcContext().writeCheck(admAbspath); if (nodeInfo.get(NodeInfo.status) == SVNWCDbStatus.Deleted) { getWcContext().getDb().opRemoveNode(localAbspath, nodeInfo.is(NodeInfo.haveBase) && !viaRecurse ? newRevnum : -1, nodeInfo.<SVNWCDbKind>get(NodeInfo.kind)); nodeInfo.release(); return; } else if (nodeInfo.get(NodeInfo.status) == SVNWCDbStatus.NotPresent) { nodeInfo.release(); return; } SVNSkel workItem = null; SVNWCDbKind kind = nodeInfo.get(NodeInfo.kind); if (kind != SVNWCDbKind.Dir) { if (checksum == null) { checksum = nodeInfo.get(NodeInfo.checksum); if (viaRecurse && !nodeInfo.is(NodeInfo.propsMod)) { Structure<NodeInfo> moreInfo = getWcContext().getDb(). readInfo(localAbspath, NodeInfo.changedRev, NodeInfo.changedDate, NodeInfo.changedAuthor); newChangedRev = moreInfo.lng(NodeInfo.changedRev); newChangedDate = moreInfo.get(NodeInfo.changedDate); newChangedAuthor = moreInfo.get(NodeInfo.changedAuthor); moreInfo.release(); } } workItem = getWcContext().wqBuildFileCommit(localAbspath, nodeInfo.is(NodeInfo.propsMod)); } getWcContext().getDb().globalCommit(localAbspath, newRevnum, newChangedRev, newChangedDate, newChangedAuthor, checksum, null, newDavCache, keepChangelist, noUnlock, workItem); } private static class SvnCommittedQueue { @SuppressWarnings("unchecked") public Map<File, SvnCommittedQueueItem> queue = new TreeMap<File, SvnCommittedQueueItem>(SVNCommitUtil.FILE_COMPARATOR); }; private static class SvnCommittedQueueItem { public File localAbspath; public boolean recurse; public boolean noUnlock; public boolean keepChangelist; public SvnChecksum sha1Checksum; public SVNProperties newDavCache; } }
false
true
protected SVNCommitInfo doRun(SVNWCContext context, SvnCommitPacket packet) throws SVNException { SVNProperties revisionProperties = getOperation().getRevisionProperties(); SVNPropertiesManager.validateRevisionProperties(revisionProperties); String commitMessage = getOperation().getCommitMessage(); if (getOperation().getCommitHandler() != null) { Collection<SvnCommitItem> items = new ArrayList<SvnCommitItem>(); for (SVNURL rootUrl : packet.getRepositoryRoots()) { items.addAll(packet.getItems(rootUrl)); } SvnCommitItem[] itemsArray = items.toArray(new SvnCommitItem[items.size()]); commitMessage = getOperation().getCommitHandler().getCommitMessage(commitMessage, itemsArray); if (commitMessage == null) { return SVNCommitInfo.NULL; } revisionProperties = getOperation().getCommitHandler().getRevisionProperties(commitMessage, itemsArray, revisionProperties); } commitMessage = commitMessage == null ? "" : SVNCommitUtil.validateCommitMessage(commitMessage); boolean keepLocks = getOperation().isKeepLocks(); SVNException bumpError = null; SVNCommitInfo info = null; try { SVNURL repositoryRootUrl = packet.getRepositoryRoots().iterator().next(); if (packet.isEmpty(repositoryRootUrl)) { return SVNCommitInfo.NULL; } Map<String, SvnCommitItem> committables = new TreeMap<String, SvnCommitItem>(); Map<File, SvnChecksum> md5Checksums = new HashMap<File, SvnChecksum>(); Map<File, SvnChecksum> sha1Checksums = new HashMap<File, SvnChecksum>(); SVNURL baseURL = SvnNgCommitUtil.translateCommitables(packet.getItems(repositoryRootUrl), committables); Map<String, String> lockTokens = SvnNgCommitUtil.translateLockTokens(packet.getLockTokens(), baseURL); SvnCommitItem firstItem = packet.getItems(repositoryRootUrl).iterator().next(); SVNRepository repository = getRepositoryAccess().createRepository(baseURL, firstItem.getPath()); SVNCommitMediator17 mediator = new SVNCommitMediator17(context, committables); ISVNEditor commitEditor = null; try { commitEditor = repository.getCommitEditor(commitMessage, lockTokens, keepLocks, revisionProperties, mediator); SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRootUrl, mediator.getTmpFiles(), md5Checksums, sha1Checksums); SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1); committer.sendTextDeltas(commitEditor); info = commitEditor.closeEdit(); commitEditor = null; if (info.getErrorMessage() == null || info.getErrorMessage().getErrorCode() == SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED) { // do some post processing, make sure not to unlock wc (to dipose packet) in case there // is an error on post processing. SvnCommittedQueue queue = new SvnCommittedQueue(); try { for (SvnCommitItem item : packet.getItems(repositoryRootUrl)) { postProcessCommitItem(queue, item, getOperation().isKeepChangelists(), getOperation().isKeepLocks(), sha1Checksums.get(item.getPath())); } processCommittedQueue(queue, info.getNewRevision(), info.getDate(), info.getAuthor()); deleteDeleteFiles(committer, getOperation().getCommitParameters()); } catch (SVNException e) { // this is bump error. bumpError = e; throw e; } finally { // only for the last packet in chain. if (packet.isLastPacket()) { sleepForTimestamp(); } } } handleEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, SVNEventAction.COMMIT_COMPLETED, null, null, -1, -1)); } catch (SVNException e) { if (e instanceof SVNCancelException) { throw e; } SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); info = new SVNCommitInfo(-1, null, null, err); handleEvent(SVNEventFactory.createErrorEvent(err, SVNEventAction.COMMIT_COMPLETED), ISVNEventHandler.UNKNOWN); if (packet.getRepositoryRoots().size() == 1) { SVNErrorManager.error(err, SVNLogType.WC); } } finally { if (commitEditor != null) { try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().log(SVNLogType.CLIENT, e, Level.WARNING); //the exception should not mask original exception } } for (File tmpFile : mediator.getTmpFiles()) { SVNFileUtil.deleteFile(tmpFile); } } } finally { if (bumpError == null) { packet.dispose(); } } return info; }
protected SVNCommitInfo doRun(SVNWCContext context, SvnCommitPacket packet) throws SVNException { SVNProperties revisionProperties = getOperation().getRevisionProperties(); SVNPropertiesManager.validateRevisionProperties(revisionProperties); String commitMessage = getOperation().getCommitMessage(); if (getOperation().getCommitHandler() != null) { Collection<SvnCommitItem> items = new ArrayList<SvnCommitItem>(); for (SVNURL rootUrl : packet.getRepositoryRoots()) { items.addAll(packet.getItems(rootUrl)); } SvnCommitItem[] itemsArray = items.toArray(new SvnCommitItem[items.size()]); try { commitMessage = getOperation().getCommitHandler().getCommitMessage(commitMessage, itemsArray); if (commitMessage == null) { return SVNCommitInfo.NULL; } revisionProperties = getOperation().getCommitHandler().getRevisionProperties(commitMessage, itemsArray, revisionProperties); } catch (SVNException e) { SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); SVNErrorManager.error(err, SVNLogType.WC); } } commitMessage = commitMessage == null ? "" : SVNCommitUtil.validateCommitMessage(commitMessage); boolean keepLocks = getOperation().isKeepLocks(); SVNException bumpError = null; SVNCommitInfo info = null; try { SVNURL repositoryRootUrl = packet.getRepositoryRoots().iterator().next(); if (packet.isEmpty(repositoryRootUrl)) { return SVNCommitInfo.NULL; } Map<String, SvnCommitItem> committables = new TreeMap<String, SvnCommitItem>(); Map<File, SvnChecksum> md5Checksums = new HashMap<File, SvnChecksum>(); Map<File, SvnChecksum> sha1Checksums = new HashMap<File, SvnChecksum>(); SVNURL baseURL = SvnNgCommitUtil.translateCommitables(packet.getItems(repositoryRootUrl), committables); Map<String, String> lockTokens = SvnNgCommitUtil.translateLockTokens(packet.getLockTokens(), baseURL); SvnCommitItem firstItem = packet.getItems(repositoryRootUrl).iterator().next(); SVNRepository repository = getRepositoryAccess().createRepository(baseURL, firstItem.getPath()); SVNCommitMediator17 mediator = new SVNCommitMediator17(context, committables); ISVNEditor commitEditor = null; try { commitEditor = repository.getCommitEditor(commitMessage, lockTokens, keepLocks, revisionProperties, mediator); SVNCommitter17 committer = new SVNCommitter17(context, committables, repositoryRootUrl, mediator.getTmpFiles(), md5Checksums, sha1Checksums); SVNCommitUtil.driveCommitEditor(committer, committables.keySet(), commitEditor, -1); committer.sendTextDeltas(commitEditor); info = commitEditor.closeEdit(); commitEditor = null; if (info.getErrorMessage() == null || info.getErrorMessage().getErrorCode() == SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED) { // do some post processing, make sure not to unlock wc (to dipose packet) in case there // is an error on post processing. SvnCommittedQueue queue = new SvnCommittedQueue(); try { for (SvnCommitItem item : packet.getItems(repositoryRootUrl)) { postProcessCommitItem(queue, item, getOperation().isKeepChangelists(), getOperation().isKeepLocks(), sha1Checksums.get(item.getPath())); } processCommittedQueue(queue, info.getNewRevision(), info.getDate(), info.getAuthor()); deleteDeleteFiles(committer, getOperation().getCommitParameters()); } catch (SVNException e) { // this is bump error. bumpError = e; throw e; } finally { // only for the last packet in chain. if (packet.isLastPacket()) { sleepForTimestamp(); } } } handleEvent(SVNEventFactory.createSVNEvent(null, SVNNodeKind.NONE, null, info.getNewRevision(), SVNEventAction.COMMIT_COMPLETED, SVNEventAction.COMMIT_COMPLETED, null, null, -1, -1)); } catch (SVNException e) { if (e instanceof SVNCancelException) { throw e; } SVNErrorMessage err = e.getErrorMessage().wrap("Commit failed (details follow):"); info = new SVNCommitInfo(-1, null, null, err); handleEvent(SVNEventFactory.createErrorEvent(err, SVNEventAction.COMMIT_COMPLETED), ISVNEventHandler.UNKNOWN); if (packet.getRepositoryRoots().size() == 1) { SVNErrorManager.error(err, SVNLogType.WC); } } finally { if (commitEditor != null) { try { commitEditor.abortEdit(); } catch (SVNException e) { SVNDebugLog.getDefaultLog().log(SVNLogType.CLIENT, e, Level.WARNING); //the exception should not mask original exception } } for (File tmpFile : mediator.getTmpFiles()) { SVNFileUtil.deleteFile(tmpFile); } } } finally { if (bumpError == null) { packet.dispose(); } } return info; }
diff --git a/src/test/java/eu/playproject/platform/service/bootstrap/CreationTest.java b/src/test/java/eu/playproject/platform/service/bootstrap/CreationTest.java index e34c539..f352a87 100644 --- a/src/test/java/eu/playproject/platform/service/bootstrap/CreationTest.java +++ b/src/test/java/eu/playproject/platform/service/bootstrap/CreationTest.java @@ -1,157 +1,158 @@ /** * * Copyright (c) 2012, PetalsLink * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ package eu.playproject.platform.service.bootstrap; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.ws.wsaddressing.W3CEndpointReference; import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; import eu.playproject.governance.api.GovernanceExeption; import eu.playproject.governance.api.bean.Metadata; import eu.playproject.governance.api.bean.Topic; import eu.playproject.platform.service.bootstrap.api.GovernanceClient; import eu.playproject.platform.service.bootstrap.api.Subscription; public class CreationTest extends TestCase { @Test public void testCreate() throws Exception { Topic t1 = new Topic(); t1.setName("T1"); t1.setNs("http://foo"); t1.setPrefix("pre"); Topic t2 = new Topic(); t2.setName("T2"); t2.setNs("http://foo"); t2.setPrefix("pre"); final List<Topic> topics = new ArrayList<Topic>(); topics.add(t1); topics.add(t2); final List<Topic> filtered = new ArrayList<Topic>(); filtered.add(t1); String ecEndpoint = "http://localhost:4568/EventCloudService"; String subscriberEndpoint = "http://localhost:4569/SubscriberService"; DSBSubscribesToECBootstrapServiceImpl service = new DSBSubscribesToECBootstrapServiceImpl(); service.setEventCloudClientFactory(new EventCloudClientFactoryMock( ecEndpoint)); service.setTopicManager(new TopicManagerMock()); + service.setSubscriptionRegistry(new SubscriptionRegistryServiceImpl()); service.setGovernanceClient(new GovernanceClient() { @Override public void loadResources(InputStream arg0) throws GovernanceExeption { } @Override public List<Topic> getTopics() { return topics; } @Override public List<QName> findTopicsByElement(QName arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public List<W3CEndpointReference> findEventProducersByTopics( List<QName> arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public List<W3CEndpointReference> findEventProducersByElements( List<QName> arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public void createTopic(Topic arg0) throws GovernanceExeption { // TODO Auto-generated method stub } @Override public void removeMetadata(Topic arg0, Metadata arg1) throws GovernanceExeption { // TODO Auto-generated method stub } @Override public List<Topic> getTopicsWithMeta(List<Metadata> arg0) throws GovernanceExeption { System.out.println("Get topics with meta " + arg0); return filtered; } @Override public Metadata getMetadataValue(Topic arg0, String arg1) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public List<Metadata> getMetaData(Topic arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public boolean deleteMetaData(Topic arg0) throws GovernanceExeption { // TODO Auto-generated method stub return false; } @Override public void addMetadata(Topic arg0, Metadata arg1) throws GovernanceExeption { // TODO Auto-generated method stub } }); List<Subscription> result = service.bootstrap(ecEndpoint, subscriberEndpoint); System.out.println(result); Assert.assertTrue(result.size() == 1); } }
true
true
public void testCreate() throws Exception { Topic t1 = new Topic(); t1.setName("T1"); t1.setNs("http://foo"); t1.setPrefix("pre"); Topic t2 = new Topic(); t2.setName("T2"); t2.setNs("http://foo"); t2.setPrefix("pre"); final List<Topic> topics = new ArrayList<Topic>(); topics.add(t1); topics.add(t2); final List<Topic> filtered = new ArrayList<Topic>(); filtered.add(t1); String ecEndpoint = "http://localhost:4568/EventCloudService"; String subscriberEndpoint = "http://localhost:4569/SubscriberService"; DSBSubscribesToECBootstrapServiceImpl service = new DSBSubscribesToECBootstrapServiceImpl(); service.setEventCloudClientFactory(new EventCloudClientFactoryMock( ecEndpoint)); service.setTopicManager(new TopicManagerMock()); service.setGovernanceClient(new GovernanceClient() { @Override public void loadResources(InputStream arg0) throws GovernanceExeption { } @Override public List<Topic> getTopics() { return topics; } @Override public List<QName> findTopicsByElement(QName arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public List<W3CEndpointReference> findEventProducersByTopics( List<QName> arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public List<W3CEndpointReference> findEventProducersByElements( List<QName> arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public void createTopic(Topic arg0) throws GovernanceExeption { // TODO Auto-generated method stub } @Override public void removeMetadata(Topic arg0, Metadata arg1) throws GovernanceExeption { // TODO Auto-generated method stub } @Override public List<Topic> getTopicsWithMeta(List<Metadata> arg0) throws GovernanceExeption { System.out.println("Get topics with meta " + arg0); return filtered; } @Override public Metadata getMetadataValue(Topic arg0, String arg1) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public List<Metadata> getMetaData(Topic arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public boolean deleteMetaData(Topic arg0) throws GovernanceExeption { // TODO Auto-generated method stub return false; } @Override public void addMetadata(Topic arg0, Metadata arg1) throws GovernanceExeption { // TODO Auto-generated method stub } }); List<Subscription> result = service.bootstrap(ecEndpoint, subscriberEndpoint); System.out.println(result); Assert.assertTrue(result.size() == 1); }
public void testCreate() throws Exception { Topic t1 = new Topic(); t1.setName("T1"); t1.setNs("http://foo"); t1.setPrefix("pre"); Topic t2 = new Topic(); t2.setName("T2"); t2.setNs("http://foo"); t2.setPrefix("pre"); final List<Topic> topics = new ArrayList<Topic>(); topics.add(t1); topics.add(t2); final List<Topic> filtered = new ArrayList<Topic>(); filtered.add(t1); String ecEndpoint = "http://localhost:4568/EventCloudService"; String subscriberEndpoint = "http://localhost:4569/SubscriberService"; DSBSubscribesToECBootstrapServiceImpl service = new DSBSubscribesToECBootstrapServiceImpl(); service.setEventCloudClientFactory(new EventCloudClientFactoryMock( ecEndpoint)); service.setTopicManager(new TopicManagerMock()); service.setSubscriptionRegistry(new SubscriptionRegistryServiceImpl()); service.setGovernanceClient(new GovernanceClient() { @Override public void loadResources(InputStream arg0) throws GovernanceExeption { } @Override public List<Topic> getTopics() { return topics; } @Override public List<QName> findTopicsByElement(QName arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public List<W3CEndpointReference> findEventProducersByTopics( List<QName> arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public List<W3CEndpointReference> findEventProducersByElements( List<QName> arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public void createTopic(Topic arg0) throws GovernanceExeption { // TODO Auto-generated method stub } @Override public void removeMetadata(Topic arg0, Metadata arg1) throws GovernanceExeption { // TODO Auto-generated method stub } @Override public List<Topic> getTopicsWithMeta(List<Metadata> arg0) throws GovernanceExeption { System.out.println("Get topics with meta " + arg0); return filtered; } @Override public Metadata getMetadataValue(Topic arg0, String arg1) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public List<Metadata> getMetaData(Topic arg0) throws GovernanceExeption { // TODO Auto-generated method stub return null; } @Override public boolean deleteMetaData(Topic arg0) throws GovernanceExeption { // TODO Auto-generated method stub return false; } @Override public void addMetadata(Topic arg0, Metadata arg1) throws GovernanceExeption { // TODO Auto-generated method stub } }); List<Subscription> result = service.bootstrap(ecEndpoint, subscriberEndpoint); System.out.println(result); Assert.assertTrue(result.size() == 1); }
diff --git a/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsAllPacketLoader.java b/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsAllPacketLoader.java index 5ff1703..6fe4269 100644 --- a/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsAllPacketLoader.java +++ b/lib/packetpig/src/main/java/com/packetloop/packetpig/loaders/pcap/packet/DnsAllPacketLoader.java @@ -1,26 +1,26 @@ package com.packetloop.packetpig.loaders.pcap.packet; import com.packetloop.packetpig.loaders.pcap.PcapLoader; import org.apache.hadoop.mapreduce.InputFormat; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.pig.data.Tuple; import java.io.IOException; public class DnsAllPacketLoader extends PcapLoader { public DnsAllPacketLoader(){} @Override public InputFormat getInputFormat() throws IOException { return new FileInputFormat<Long, Tuple>() { @Override public RecordReader<Long, Tuple> createRecordReader(InputSplit split, TaskAttemptContext context) { - return new DnsPacketRecordReader(); + return new DnsPacketAllRecordReader(); } }; } }
true
true
public InputFormat getInputFormat() throws IOException { return new FileInputFormat<Long, Tuple>() { @Override public RecordReader<Long, Tuple> createRecordReader(InputSplit split, TaskAttemptContext context) { return new DnsPacketRecordReader(); } }; }
public InputFormat getInputFormat() throws IOException { return new FileInputFormat<Long, Tuple>() { @Override public RecordReader<Long, Tuple> createRecordReader(InputSplit split, TaskAttemptContext context) { return new DnsPacketAllRecordReader(); } }; }
diff --git a/load-and-display-dataset/src/main/java/LoadAndDisplayDataset.java b/load-and-display-dataset/src/main/java/LoadAndDisplayDataset.java index 5f3c435..f8e160d 100644 --- a/load-and-display-dataset/src/main/java/LoadAndDisplayDataset.java +++ b/load-and-display-dataset/src/main/java/LoadAndDisplayDataset.java @@ -1,41 +1,41 @@ /* * To the extent possible under law, the ImageJ developers have waived * all copyright and related or neighboring rights to this tutorial code. * * See the CC0 1.0 Universal license for details: * http://creativecommons.org/publicdomain/zero/1.0/ */ import imagej.ImageJ; import imagej.data.Dataset; import imagej.ext.display.DisplayService; import imagej.io.IOService; import java.io.File; import javax.swing.JFileChooser; /** Loads and displays a dataset using the ImageJ API. */ public class LoadAndDisplayDataset { public static void main(final String... args) throws Exception { - // create the ImageJ application context with all available services + // create the ImageJ application context with all available services final ImageJ context = ImageJ.createContext(); - // ask the user for a file to open - final JFileChooser chooser = new JFileChooser(); - final int returnVal = chooser.showOpenDialog(null); - if (returnVal != JFileChooser.APPROVE_OPTION) return; - final File file = chooser.getSelectedFile(); + // ask the user for a file to open + final JFileChooser chooser = new JFileChooser(); + final int returnVal = chooser.showOpenDialog(null); + if (returnVal != JFileChooser.APPROVE_OPTION) return; + final File file = chooser.getSelectedFile(); // load the dataset final IOService ioService = context.getService(IOService.class); final Dataset dataset = ioService.loadDataset(file.getAbsolutePath()); // display the dataset final DisplayService displayService = context.getService(DisplayService.class); displayService.createDisplay(file.getName(), dataset); } }
false
true
public static void main(final String... args) throws Exception { // create the ImageJ application context with all available services final ImageJ context = ImageJ.createContext(); // ask the user for a file to open final JFileChooser chooser = new JFileChooser(); final int returnVal = chooser.showOpenDialog(null); if (returnVal != JFileChooser.APPROVE_OPTION) return; final File file = chooser.getSelectedFile(); // load the dataset final IOService ioService = context.getService(IOService.class); final Dataset dataset = ioService.loadDataset(file.getAbsolutePath()); // display the dataset final DisplayService displayService = context.getService(DisplayService.class); displayService.createDisplay(file.getName(), dataset); }
public static void main(final String... args) throws Exception { // create the ImageJ application context with all available services final ImageJ context = ImageJ.createContext(); // ask the user for a file to open final JFileChooser chooser = new JFileChooser(); final int returnVal = chooser.showOpenDialog(null); if (returnVal != JFileChooser.APPROVE_OPTION) return; final File file = chooser.getSelectedFile(); // load the dataset final IOService ioService = context.getService(IOService.class); final Dataset dataset = ioService.loadDataset(file.getAbsolutePath()); // display the dataset final DisplayService displayService = context.getService(DisplayService.class); displayService.createDisplay(file.getName(), dataset); }
diff --git a/src/org/apache/hadoop/hive/contrib/serde2/JsonSerde.java b/src/org/apache/hadoop/hive/contrib/serde2/JsonSerde.java index 4322d98..a2668fc 100644 --- a/src/org/apache/hadoop/hive/contrib/serde2/JsonSerde.java +++ b/src/org/apache/hadoop/hive/contrib/serde2/JsonSerde.java @@ -1,296 +1,298 @@ /** * JSON SerDe for Hive */ package org.apache.hadoop.hive.contrib.serde2; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.HashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.serde.Constants; import org.apache.hadoop.hive.serde2.SerDe; import org.apache.hadoop.hive.serde2.SerDeException; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.json.JSONException; import org.json.JSONObject; /** * JSON SerDe for Hive * <p> * This SerDe can be used to read data in JSON format. For example, if your JSON * files had the following contents: * * <pre> * {"field1":"data1","field2":100,"field3":"more data1"} * {"field1":"data2","field2":200,"field3":"more data2"} * {"field1":"data3","field2":300,"field3":"more data3"} * {"field1":"data4","field2":400,"field3":"more data4"} * </pre> * * The following steps can be used to read this data: * <ol> * <li>Build this project using <code>ant build</code></li> * <li>Copy <code>hive-json-serde.jar</code> to the Hive server</li> * <li>Inside the Hive client, run * * <pre> * ADD JAR /home/hadoop/hive-json-serde.jar; * </pre> * * </li> * <li>Create a table that uses files where each line is JSON object * * <pre> * CREATE EXTERNAL TABLE IF NOT EXISTS my_table ( * field1 string, field2 int, field3 string * ) * ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.JsonSerde' * LOCATION '/my_data/my_table/'; * </pre> * * </li> * <li>Copy your JSON files to <code>/my_data/my_table/</code>. You can now * select data using normal SELECT statements * * <pre> * SELECT * FROM my_table LIMIT 10; * </pre> * * * </li> * </ol> * <p> * The table does not have to have the same columns as the JSON files, and * vice-versa. If the table has a column that does not exist in the JSON object, * it will have a NULL value. If the JSON file contains fields that are not * columns in the table, they will be ignored and not visible to the table. * * * @see <a href="http://code.google.com/p/hive-json-serde/">hive-json-serde on * Google Code</a> * @author Peter Sankauskas */ public class JsonSerde implements SerDe { /** * Apache commons logger */ private static final Log LOG = LogFactory.getLog(JsonSerde.class.getName()); /** * The number of columns in the table this SerDe is being used with */ private int numColumns; /** * List of column names in the table */ private List<String> columnNames; /** * An ObjectInspector to be used as meta-data about a deserialized row */ private StructObjectInspector rowOI; /** * List of row objects */ private ArrayList<Object> row; /** * List of column type information */ private List<TypeInfo> columnTypes; /** * A map from column names to json names. */ private HashMap<String, String> renames; /** * Initialize this SerDe with the system properties and table properties * */ @Override public void initialize(Configuration sysProps, Properties tblProps) throws SerDeException { LOG.debug("Initializing JsonSerde"); // Get the names of the columns for the table this SerDe is being used // with String columnNameProperty = tblProps .getProperty(Constants.LIST_COLUMNS); columnNames = Arrays.asList(columnNameProperty.split(",")); // Convert column types from text to TypeInfo objects String columnTypeProperty = tblProps .getProperty(Constants.LIST_COLUMN_TYPES); columnTypes = TypeInfoUtils .getTypeInfosFromTypeString(columnTypeProperty); assert columnNames.size() == columnTypes.size(); numColumns = columnNames.size(); // Create ObjectInspectors from the type information for each column List<ObjectInspector> columnOIs = new ArrayList<ObjectInspector>( columnNames.size()); ObjectInspector oi; for (int c = 0; c < numColumns; c++) { oi = TypeInfoUtils .getStandardJavaObjectInspectorFromTypeInfo(columnTypes .get(c)); columnOIs.add(oi); } rowOI = ObjectInspectorFactory.getStandardStructObjectInspector( columnNames, columnOIs); // Create an empty row object to be reused during deserialization row = new ArrayList<Object>(numColumns); for (int c = 0; c < numColumns; c++) { row.add(null); } // Read rename properties. renames = new HashMap<String, String>(); String renameProperty = tblProps .getProperty("rename_columns"); if (renameProperty != null) { String[] individualRenames = renameProperty.split(","); for (String rename : individualRenames) { String[] fromTo = rename.split(">"); renames.put(fromTo[1], fromTo[0]); } } LOG.debug("JsonSerde initialization complete"); } /** * Gets the ObjectInspector for a row deserialized by this SerDe */ @Override public ObjectInspector getObjectInspector() throws SerDeException { return rowOI; } /** * Deserialize a JSON Object into a row for the table */ @Override public Object deserialize(Writable blob) throws SerDeException { Text rowText = (Text) blob; LOG.debug("Deserialize row: " + rowText.toString()); // Try parsing row into JSON object JSONObject jObj; try { jObj = new JSONObject(rowText.toString()) { /** * In Hive column names are case insensitive, so lower-case all * field names * * @see org.json.JSONObject#put(java.lang.String, * java.lang.Object) */ @Override public JSONObject put(String key, Object value) throws JSONException { return super.put(key.toLowerCase(), value); } }; } catch (JSONException e) { // If row is not a JSON object, make the whole row NULL LOG.error("Row is not a valid JSON Object - JSONException: " + e.getMessage()); return null; } // Loop over columns in table and set values String colName; Object value; for (int c = 0; c < numColumns; c++) { colName = columnNames.get(c); if (renames.containsKey(colName)) { colName = renames.get(colName); } TypeInfo ti = columnTypes.get(c); try { // Get type-safe JSON values if (jObj.isNull(colName)) { value = null; } else if (ti.getTypeName().equalsIgnoreCase( Constants.DOUBLE_TYPE_NAME)) { value = jObj.getDouble(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.BIGINT_TYPE_NAME)) { value = jObj.getLong(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.INT_TYPE_NAME)) { value = jObj.getInt(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.TINYINT_TYPE_NAME)) { value = Byte.valueOf(jObj.getString(colName)); } else if (ti.getTypeName().equalsIgnoreCase( Constants.FLOAT_TYPE_NAME)) { value = Float.valueOf(jObj.getString(colName)); } else if (ti.getTypeName().equalsIgnoreCase( Constants.BOOLEAN_TYPE_NAME)) { value = jObj.getBoolean(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.STRING_TYPE_NAME) && jObj.get(colName) instanceof java.lang.Number) { // convert numbers to strings if need be value = jObj.getString(colName); } else { // Fall back, just get an object value = jObj.get(colName); } } catch (JSONException e) { // If the column cannot be found, just make it a NULL value and // skip over it - LOG.warn("Column '" + colName + "' not found in row: " + if (LOG.isDebugEnabled()) { + LOG.debug("Column '" + colName + "' not found in row: " + rowText.toString() + " - JSONException: " + e.getMessage()); + } value = null; } row.set(c, value); } return row; } /** * Not sure - something to do with serialization of data */ @Override public Class<? extends Writable> getSerializedClass() { return Text.class; } /** * Serializes a row of data into a JSON object * * @todo Implement this - sorry! */ @Override public Writable serialize(Object obj, ObjectInspector objInspector) throws SerDeException { LOG.info("-----------------------------"); LOG.info("--------- serialize ---------"); LOG.info("-----------------------------"); LOG.info(obj.toString()); LOG.info(objInspector.toString()); return null; } }
false
true
public Object deserialize(Writable blob) throws SerDeException { Text rowText = (Text) blob; LOG.debug("Deserialize row: " + rowText.toString()); // Try parsing row into JSON object JSONObject jObj; try { jObj = new JSONObject(rowText.toString()) { /** * In Hive column names are case insensitive, so lower-case all * field names * * @see org.json.JSONObject#put(java.lang.String, * java.lang.Object) */ @Override public JSONObject put(String key, Object value) throws JSONException { return super.put(key.toLowerCase(), value); } }; } catch (JSONException e) { // If row is not a JSON object, make the whole row NULL LOG.error("Row is not a valid JSON Object - JSONException: " + e.getMessage()); return null; } // Loop over columns in table and set values String colName; Object value; for (int c = 0; c < numColumns; c++) { colName = columnNames.get(c); if (renames.containsKey(colName)) { colName = renames.get(colName); } TypeInfo ti = columnTypes.get(c); try { // Get type-safe JSON values if (jObj.isNull(colName)) { value = null; } else if (ti.getTypeName().equalsIgnoreCase( Constants.DOUBLE_TYPE_NAME)) { value = jObj.getDouble(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.BIGINT_TYPE_NAME)) { value = jObj.getLong(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.INT_TYPE_NAME)) { value = jObj.getInt(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.TINYINT_TYPE_NAME)) { value = Byte.valueOf(jObj.getString(colName)); } else if (ti.getTypeName().equalsIgnoreCase( Constants.FLOAT_TYPE_NAME)) { value = Float.valueOf(jObj.getString(colName)); } else if (ti.getTypeName().equalsIgnoreCase( Constants.BOOLEAN_TYPE_NAME)) { value = jObj.getBoolean(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.STRING_TYPE_NAME) && jObj.get(colName) instanceof java.lang.Number) { // convert numbers to strings if need be value = jObj.getString(colName); } else { // Fall back, just get an object value = jObj.get(colName); } } catch (JSONException e) { // If the column cannot be found, just make it a NULL value and // skip over it LOG.warn("Column '" + colName + "' not found in row: " + rowText.toString() + " - JSONException: " + e.getMessage()); value = null; } row.set(c, value); } return row; }
public Object deserialize(Writable blob) throws SerDeException { Text rowText = (Text) blob; LOG.debug("Deserialize row: " + rowText.toString()); // Try parsing row into JSON object JSONObject jObj; try { jObj = new JSONObject(rowText.toString()) { /** * In Hive column names are case insensitive, so lower-case all * field names * * @see org.json.JSONObject#put(java.lang.String, * java.lang.Object) */ @Override public JSONObject put(String key, Object value) throws JSONException { return super.put(key.toLowerCase(), value); } }; } catch (JSONException e) { // If row is not a JSON object, make the whole row NULL LOG.error("Row is not a valid JSON Object - JSONException: " + e.getMessage()); return null; } // Loop over columns in table and set values String colName; Object value; for (int c = 0; c < numColumns; c++) { colName = columnNames.get(c); if (renames.containsKey(colName)) { colName = renames.get(colName); } TypeInfo ti = columnTypes.get(c); try { // Get type-safe JSON values if (jObj.isNull(colName)) { value = null; } else if (ti.getTypeName().equalsIgnoreCase( Constants.DOUBLE_TYPE_NAME)) { value = jObj.getDouble(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.BIGINT_TYPE_NAME)) { value = jObj.getLong(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.INT_TYPE_NAME)) { value = jObj.getInt(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.TINYINT_TYPE_NAME)) { value = Byte.valueOf(jObj.getString(colName)); } else if (ti.getTypeName().equalsIgnoreCase( Constants.FLOAT_TYPE_NAME)) { value = Float.valueOf(jObj.getString(colName)); } else if (ti.getTypeName().equalsIgnoreCase( Constants.BOOLEAN_TYPE_NAME)) { value = jObj.getBoolean(colName); } else if (ti.getTypeName().equalsIgnoreCase( Constants.STRING_TYPE_NAME) && jObj.get(colName) instanceof java.lang.Number) { // convert numbers to strings if need be value = jObj.getString(colName); } else { // Fall back, just get an object value = jObj.get(colName); } } catch (JSONException e) { // If the column cannot be found, just make it a NULL value and // skip over it if (LOG.isDebugEnabled()) { LOG.debug("Column '" + colName + "' not found in row: " + rowText.toString() + " - JSONException: " + e.getMessage()); } value = null; } row.set(c, value); } return row; }
diff --git a/module-bdbxml/src/test/java/org/xbrlapi/data/bdbxml/tests/SecAsyncGrabberImplTest.java b/module-bdbxml/src/test/java/org/xbrlapi/data/bdbxml/tests/SecAsyncGrabberImplTest.java index 1680e613..a63bfed7 100644 --- a/module-bdbxml/src/test/java/org/xbrlapi/data/bdbxml/tests/SecAsyncGrabberImplTest.java +++ b/module-bdbxml/src/test/java/org/xbrlapi/data/bdbxml/tests/SecAsyncGrabberImplTest.java @@ -1,54 +1,53 @@ package org.xbrlapi.data.bdbxml.tests; import java.net.URI; import java.util.List; import org.xbrlapi.data.bdbxml.BaseTestCase; import org.xbrlapi.grabber.Grabber; import org.xbrlapi.grabber.SecGrabberImpl; import org.xbrlapi.loader.discoverer.DiscoveryManager; public class SecAsyncGrabberImplTest extends BaseTestCase { public SecAsyncGrabberImplTest(String arg0) { super(arg0); } private List<URI> resources = null; protected void setUp() throws Exception { super.setUp(); String secFeed = configuration.getProperty("real.data.sec"); URI feedURI = new URI(secFeed); Grabber grabber = new SecGrabberImpl(feedURI); resources = grabber.getResources(); assertTrue("# resources = " + resources.size(),resources.size() > 50); } protected void tearDown() throws Exception { super.tearDown(); } public void testSecGrabberResourceRetrieval() { try { int cnt = 2; List<URI> r1 = resources.subList(0,cnt); - DiscoveryManager d1 = new DiscoveryManager(loader, r1, 20000); - Thread t1 = new Thread(d1); - t1.start(); + Thread discoveryThread = new Thread(new DiscoveryManager(loader, r1, 20000)); + discoveryThread.start(); - while (t1.isAlive()) { + while (discoveryThread.isAlive()) { Thread.sleep(2000); - if (store.getDocumentURIs().size()>10) + if (store.getDocumentURIs().size()>2) loader.requestInterrupt(); } } catch (Exception e) { e.printStackTrace(); fail("An unexpected exception was thrown."); } } }
false
true
public void testSecGrabberResourceRetrieval() { try { int cnt = 2; List<URI> r1 = resources.subList(0,cnt); DiscoveryManager d1 = new DiscoveryManager(loader, r1, 20000); Thread t1 = new Thread(d1); t1.start(); while (t1.isAlive()) { Thread.sleep(2000); if (store.getDocumentURIs().size()>10) loader.requestInterrupt(); } } catch (Exception e) { e.printStackTrace(); fail("An unexpected exception was thrown."); } }
public void testSecGrabberResourceRetrieval() { try { int cnt = 2; List<URI> r1 = resources.subList(0,cnt); Thread discoveryThread = new Thread(new DiscoveryManager(loader, r1, 20000)); discoveryThread.start(); while (discoveryThread.isAlive()) { Thread.sleep(2000); if (store.getDocumentURIs().size()>2) loader.requestInterrupt(); } } catch (Exception e) { e.printStackTrace(); fail("An unexpected exception was thrown."); } }
diff --git a/server/src/main/java/org/apache/accumulo/server/trace/TraceServer.java b/server/src/main/java/org/apache/accumulo/server/trace/TraceServer.java index 520f812d6..025c975fa 100644 --- a/server/src/main/java/org/apache/accumulo/server/trace/TraceServer.java +++ b/server/src/main/java/org/apache/accumulo/server/trace/TraceServer.java @@ -1,292 +1,292 @@ /* * 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.accumulo.server.trace; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.nio.channels.ServerSocketChannel; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.BatchWriterConfig; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.Instance; import org.apache.accumulo.core.client.IteratorSetting; import org.apache.accumulo.core.client.MutationsRejectedException; import org.apache.accumulo.core.client.security.tokens.AuthenticationToken; import org.apache.accumulo.core.client.security.tokens.AuthenticationToken.Properties; import org.apache.accumulo.core.client.security.tokens.PasswordToken; import org.apache.accumulo.core.conf.AccumuloConfiguration; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.iterators.user.AgeOffFilter; import org.apache.accumulo.core.security.SecurityUtil; import org.apache.accumulo.core.trace.TraceFormatter; import org.apache.accumulo.core.util.UtilWaitThread; import org.apache.accumulo.core.zookeeper.ZooUtil; import org.apache.accumulo.fate.zookeeper.IZooReaderWriter; import org.apache.accumulo.server.Accumulo; import org.apache.accumulo.server.ServerOpts; import org.apache.accumulo.server.client.HdfsZooInstance; import org.apache.accumulo.server.conf.ServerConfiguration; import org.apache.accumulo.server.fs.VolumeManager; import org.apache.accumulo.server.fs.VolumeManagerImpl; import org.apache.accumulo.server.util.time.SimpleTimer; import org.apache.accumulo.server.zookeeper.ZooReaderWriter; import org.apache.accumulo.start.classloader.AccumuloClassLoader; import org.apache.accumulo.trace.instrument.Span; import org.apache.accumulo.trace.thrift.RemoteSpan; import org.apache.accumulo.trace.thrift.SpanReceiver.Iface; import org.apache.accumulo.trace.thrift.SpanReceiver.Processor; import org.apache.hadoop.io.Text; import org.apache.log4j.Logger; import org.apache.thrift.TByteArrayOutputStream; import org.apache.thrift.TException; import org.apache.thrift.protocol.TCompactProtocol; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TServerSocket; import org.apache.thrift.transport.TServerTransport; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; public class TraceServer implements Watcher { final private static Logger log = Logger.getLogger(TraceServer.class); final private ServerConfiguration serverConfiguration; final private TServer server; private BatchWriter writer = null; private Connector connector; final String table; private static void put(Mutation m, String cf, String cq, byte[] bytes, int len) { m.put(new Text(cf), new Text(cq), new Value(bytes, 0, len)); } static class ByteArrayTransport extends TTransport { TByteArrayOutputStream out = new TByteArrayOutputStream(); @Override public boolean isOpen() { return true; } @Override public void open() throws TTransportException {} @Override public void close() {} @Override public int read(byte[] buf, int off, int len) { return 0; } @Override public void write(byte[] buf, int off, int len) throws TTransportException { out.write(buf, off, len); } public byte[] get() { return out.get(); } public int len() { return out.len(); } } class Receiver implements Iface { @Override public void span(RemoteSpan s) throws TException { String idString = Long.toHexString(s.traceId); String startString = Long.toHexString(s.start); Mutation spanMutation = new Mutation(new Text(idString)); Mutation indexMutation = new Mutation(new Text("idx:" + s.svc + ":" + startString)); long diff = s.stop - s.start; indexMutation.put(new Text(s.description), new Text(s.sender), new Value((idString + ":" + Long.toHexString(diff)).getBytes())); ByteArrayTransport transport = new ByteArrayTransport(); TCompactProtocol protocol = new TCompactProtocol(transport); s.write(protocol); String parentString = Long.toHexString(s.parentId); if (s.parentId == Span.ROOT_SPAN_ID) parentString = ""; put(spanMutation, "span", parentString + ":" + Long.toHexString(s.spanId), transport.get(), transport.len()); // Map the root span to time so we can look up traces by time Mutation timeMutation = null; if (s.parentId == Span.ROOT_SPAN_ID) { timeMutation = new Mutation(new Text("start:" + startString)); put(timeMutation, "id", idString, transport.get(), transport.len()); } try { if (writer == null) resetWriter(); if (writer == null) return; writer.addMutation(spanMutation); writer.addMutation(indexMutation); if (timeMutation != null) writer.addMutation(timeMutation); } catch (Exception ex) { log.error("Unable to write mutation to table: " + spanMutation, ex); } } } public TraceServer(ServerConfiguration serverConfiguration, String hostname) throws Exception { this.serverConfiguration = serverConfiguration; AccumuloConfiguration conf = serverConfiguration.getConfiguration(); table = conf.get(Property.TRACE_TABLE); while (true) { try { String principal = conf.get(Property.TRACE_USER); AuthenticationToken at; Map<String,String> loginMap = conf.getAllPropertiesWithPrefix(Property.TRACE_TOKEN_PROPERTY_PREFIX); if (loginMap.isEmpty()) { Property p = Property.TRACE_PASSWORD; at = new PasswordToken(conf.get(p).getBytes()); } else { Properties props = new Properties(); AuthenticationToken token = AccumuloClassLoader.getClassLoader().loadClass(conf.get(Property.TRACE_TOKEN_TYPE)).asSubclass(AuthenticationToken.class) .newInstance(); int prefixLength = Property.TRACE_TOKEN_PROPERTY_PREFIX.getKey().length() + 1; for (Entry<String,String> entry : loginMap.entrySet()) { props.put(entry.getKey().substring(prefixLength), entry.getValue()); } token.init(props); at = token; } connector = serverConfiguration.getInstance().getConnector(principal, at); if (!connector.tableOperations().exists(table)) { connector.tableOperations().create(table); IteratorSetting setting = new IteratorSetting(10, "ageoff", AgeOffFilter.class.getName()); AgeOffFilter.setTTL(setting, 7 * 24 * 60 * 60 * 1000l); connector.tableOperations().attachIterator(table, setting); } connector.tableOperations().setProperty(table, Property.TABLE_FORMATTER_CLASS.getKey(), TraceFormatter.class.getName()); break; } catch (Exception ex) { log.info("waiting to checking/create the trace table: " + ex); UtilWaitThread.sleep(1000); } } int port = conf.getPort(Property.TRACE_PORT); final ServerSocket sock = ServerSocketChannel.open().socket(); sock.setReuseAddress(true); sock.bind(new InetSocketAddress(hostname, port)); final TServerTransport transport = new TServerSocket(sock); TThreadPoolServer.Args options = new TThreadPoolServer.Args(transport); options.processor(new Processor<Iface>(new Receiver())); server = new TThreadPoolServer(options); - registerInZooKeeper(sock.getInetAddress() + ":" + sock.getLocalPort()); + registerInZooKeeper(sock.getInetAddress().getHostAddress() + ":" + sock.getLocalPort()); writer = connector.createBatchWriter(table, new BatchWriterConfig().setMaxLatency(5, TimeUnit.SECONDS)); } public void run() throws Exception { SimpleTimer.getInstance().schedule(new Runnable() { @Override public void run() { flush(); } }, 1000, 1000); server.serve(); } private void flush() { try { writer.flush(); } catch (MutationsRejectedException e) { log.error("Error flushing traces", e); resetWriter(); } } synchronized private void resetWriter() { try { if (writer != null) writer.close(); } catch (Exception ex) { log.error("Error closing batch writer", ex); } finally { writer = null; try { writer = connector.createBatchWriter(table, new BatchWriterConfig()); } catch (Exception ex) { log.error("Unable to create a batch writer: " + ex); } } } private void registerInZooKeeper(String name) throws Exception { String root = ZooUtil.getRoot(serverConfiguration.getInstance()) + Constants.ZTRACERS; IZooReaderWriter zoo = ZooReaderWriter.getInstance(); String path = zoo.putEphemeralSequential(root + "/trace-", name.getBytes()); zoo.exists(path, this); } public static void main(String[] args) throws Exception { SecurityUtil.serverLogin(); ServerOpts opts = new ServerOpts(); opts.parseArgs("tracer", args); Instance instance = HdfsZooInstance.getInstance(); ServerConfiguration conf = new ServerConfiguration(instance); VolumeManager fs = VolumeManagerImpl.get(); Accumulo.init(fs, conf, "tracer"); String hostname = opts.getAddress(); TraceServer server = new TraceServer(conf, hostname); Accumulo.enableTracing(hostname, "tserver"); server.run(); log.info("tracer stopping"); } @Override public void process(WatchedEvent event) { log.debug("event " + event.getPath() + " " + event.getType() + " " + event.getState()); if (event.getState() == KeeperState.Expired) { log.warn("Trace server lost zookeeper registration at " + event.getPath()); server.stop(); } else if (event.getType() == EventType.NodeDeleted) { log.warn("Trace server zookeeper entry lost " + event.getPath()); server.stop(); } if (event.getPath() != null) { try { if (ZooReaderWriter.getInstance().exists(event.getPath(), this)) return; } catch (Exception ex) { log.error(ex, ex); } log.warn("Trace server unable to reset watch on zookeeper registration"); server.stop(); } } }
true
true
public TraceServer(ServerConfiguration serverConfiguration, String hostname) throws Exception { this.serverConfiguration = serverConfiguration; AccumuloConfiguration conf = serverConfiguration.getConfiguration(); table = conf.get(Property.TRACE_TABLE); while (true) { try { String principal = conf.get(Property.TRACE_USER); AuthenticationToken at; Map<String,String> loginMap = conf.getAllPropertiesWithPrefix(Property.TRACE_TOKEN_PROPERTY_PREFIX); if (loginMap.isEmpty()) { Property p = Property.TRACE_PASSWORD; at = new PasswordToken(conf.get(p).getBytes()); } else { Properties props = new Properties(); AuthenticationToken token = AccumuloClassLoader.getClassLoader().loadClass(conf.get(Property.TRACE_TOKEN_TYPE)).asSubclass(AuthenticationToken.class) .newInstance(); int prefixLength = Property.TRACE_TOKEN_PROPERTY_PREFIX.getKey().length() + 1; for (Entry<String,String> entry : loginMap.entrySet()) { props.put(entry.getKey().substring(prefixLength), entry.getValue()); } token.init(props); at = token; } connector = serverConfiguration.getInstance().getConnector(principal, at); if (!connector.tableOperations().exists(table)) { connector.tableOperations().create(table); IteratorSetting setting = new IteratorSetting(10, "ageoff", AgeOffFilter.class.getName()); AgeOffFilter.setTTL(setting, 7 * 24 * 60 * 60 * 1000l); connector.tableOperations().attachIterator(table, setting); } connector.tableOperations().setProperty(table, Property.TABLE_FORMATTER_CLASS.getKey(), TraceFormatter.class.getName()); break; } catch (Exception ex) { log.info("waiting to checking/create the trace table: " + ex); UtilWaitThread.sleep(1000); } } int port = conf.getPort(Property.TRACE_PORT); final ServerSocket sock = ServerSocketChannel.open().socket(); sock.setReuseAddress(true); sock.bind(new InetSocketAddress(hostname, port)); final TServerTransport transport = new TServerSocket(sock); TThreadPoolServer.Args options = new TThreadPoolServer.Args(transport); options.processor(new Processor<Iface>(new Receiver())); server = new TThreadPoolServer(options); registerInZooKeeper(sock.getInetAddress() + ":" + sock.getLocalPort()); writer = connector.createBatchWriter(table, new BatchWriterConfig().setMaxLatency(5, TimeUnit.SECONDS)); }
public TraceServer(ServerConfiguration serverConfiguration, String hostname) throws Exception { this.serverConfiguration = serverConfiguration; AccumuloConfiguration conf = serverConfiguration.getConfiguration(); table = conf.get(Property.TRACE_TABLE); while (true) { try { String principal = conf.get(Property.TRACE_USER); AuthenticationToken at; Map<String,String> loginMap = conf.getAllPropertiesWithPrefix(Property.TRACE_TOKEN_PROPERTY_PREFIX); if (loginMap.isEmpty()) { Property p = Property.TRACE_PASSWORD; at = new PasswordToken(conf.get(p).getBytes()); } else { Properties props = new Properties(); AuthenticationToken token = AccumuloClassLoader.getClassLoader().loadClass(conf.get(Property.TRACE_TOKEN_TYPE)).asSubclass(AuthenticationToken.class) .newInstance(); int prefixLength = Property.TRACE_TOKEN_PROPERTY_PREFIX.getKey().length() + 1; for (Entry<String,String> entry : loginMap.entrySet()) { props.put(entry.getKey().substring(prefixLength), entry.getValue()); } token.init(props); at = token; } connector = serverConfiguration.getInstance().getConnector(principal, at); if (!connector.tableOperations().exists(table)) { connector.tableOperations().create(table); IteratorSetting setting = new IteratorSetting(10, "ageoff", AgeOffFilter.class.getName()); AgeOffFilter.setTTL(setting, 7 * 24 * 60 * 60 * 1000l); connector.tableOperations().attachIterator(table, setting); } connector.tableOperations().setProperty(table, Property.TABLE_FORMATTER_CLASS.getKey(), TraceFormatter.class.getName()); break; } catch (Exception ex) { log.info("waiting to checking/create the trace table: " + ex); UtilWaitThread.sleep(1000); } } int port = conf.getPort(Property.TRACE_PORT); final ServerSocket sock = ServerSocketChannel.open().socket(); sock.setReuseAddress(true); sock.bind(new InetSocketAddress(hostname, port)); final TServerTransport transport = new TServerSocket(sock); TThreadPoolServer.Args options = new TThreadPoolServer.Args(transport); options.processor(new Processor<Iface>(new Receiver())); server = new TThreadPoolServer(options); registerInZooKeeper(sock.getInetAddress().getHostAddress() + ":" + sock.getLocalPort()); writer = connector.createBatchWriter(table, new BatchWriterConfig().setMaxLatency(5, TimeUnit.SECONDS)); }
diff --git a/src/uk/co/mentalspace/android/bustimes/utils/BusTimeComparator.java b/src/uk/co/mentalspace/android/bustimes/utils/BusTimeComparator.java index eaf9f13..8e2d8ed 100644 --- a/src/uk/co/mentalspace/android/bustimes/utils/BusTimeComparator.java +++ b/src/uk/co/mentalspace/android/bustimes/utils/BusTimeComparator.java @@ -1,50 +1,50 @@ package uk.co.mentalspace.android.bustimes.utils; import java.util.Comparator; import uk.co.mentalspace.android.bustimes.BusTime; public class BusTimeComparator implements Comparator<BusTime> { @Override public int compare(BusTime bt1, BusTime bt2) { boolean bt1IsNumber = false; boolean bt1IsValue = false; Integer bt1Value = null; if (null != bt1) { bt1IsValue = true; try { bt1Value = Integer.parseInt(bt1.getEstimatedArrivalTime()); bt1IsNumber = true; } catch (NumberFormatException nfe) { //do nothing - just testing if a numeric value was supplied } } boolean bt2IsNumber = false; boolean bt2IsValue = false; Integer bt2Value = null; if (null != bt2) { bt2IsValue = true; try { bt2Value = Integer.parseInt(bt2.getEstimatedArrivalTime()); bt2IsNumber = true; } catch (NumberFormatException nfe) { //do nothing - just testing if a numeric value was supplied } } if (bt1IsValue && !bt2IsValue) return 1; //value (bt1) comes first if (!bt1IsValue && bt2IsValue) return -1; //value (bt2) comes first if (!bt1IsValue && !bt2IsValue) return 0; //both non-values - doesn't matter in order (but return here to avoid next tests - if (bt1IsNumber && !bt2IsNumber) return -1; //non-number (e.g. 'Due') comes first - if (!bt1IsNumber && bt2IsNumber) return 1; // non-number (e.g. 'Due') comes first + if (bt1IsNumber && !bt2IsNumber) return 1; //non-number (e.g. 'Due') comes first + if (!bt1IsNumber && bt2IsNumber) return -1; //non-number (e.g. 'Due') comes first //both have values, and both are numeric - so use standard integer comparison if (bt1IsNumber && bt2IsNumber) return bt1Value.compareTo(bt2Value); //both have values, and neither are numeric - so use standard string comparison return bt1.getEstimatedArrivalTime().compareTo(bt2.getEstimatedArrivalTime()); } }
true
true
public int compare(BusTime bt1, BusTime bt2) { boolean bt1IsNumber = false; boolean bt1IsValue = false; Integer bt1Value = null; if (null != bt1) { bt1IsValue = true; try { bt1Value = Integer.parseInt(bt1.getEstimatedArrivalTime()); bt1IsNumber = true; } catch (NumberFormatException nfe) { //do nothing - just testing if a numeric value was supplied } } boolean bt2IsNumber = false; boolean bt2IsValue = false; Integer bt2Value = null; if (null != bt2) { bt2IsValue = true; try { bt2Value = Integer.parseInt(bt2.getEstimatedArrivalTime()); bt2IsNumber = true; } catch (NumberFormatException nfe) { //do nothing - just testing if a numeric value was supplied } } if (bt1IsValue && !bt2IsValue) return 1; //value (bt1) comes first if (!bt1IsValue && bt2IsValue) return -1; //value (bt2) comes first if (!bt1IsValue && !bt2IsValue) return 0; //both non-values - doesn't matter in order (but return here to avoid next tests if (bt1IsNumber && !bt2IsNumber) return -1; //non-number (e.g. 'Due') comes first if (!bt1IsNumber && bt2IsNumber) return 1; // non-number (e.g. 'Due') comes first //both have values, and both are numeric - so use standard integer comparison if (bt1IsNumber && bt2IsNumber) return bt1Value.compareTo(bt2Value); //both have values, and neither are numeric - so use standard string comparison return bt1.getEstimatedArrivalTime().compareTo(bt2.getEstimatedArrivalTime()); }
public int compare(BusTime bt1, BusTime bt2) { boolean bt1IsNumber = false; boolean bt1IsValue = false; Integer bt1Value = null; if (null != bt1) { bt1IsValue = true; try { bt1Value = Integer.parseInt(bt1.getEstimatedArrivalTime()); bt1IsNumber = true; } catch (NumberFormatException nfe) { //do nothing - just testing if a numeric value was supplied } } boolean bt2IsNumber = false; boolean bt2IsValue = false; Integer bt2Value = null; if (null != bt2) { bt2IsValue = true; try { bt2Value = Integer.parseInt(bt2.getEstimatedArrivalTime()); bt2IsNumber = true; } catch (NumberFormatException nfe) { //do nothing - just testing if a numeric value was supplied } } if (bt1IsValue && !bt2IsValue) return 1; //value (bt1) comes first if (!bt1IsValue && bt2IsValue) return -1; //value (bt2) comes first if (!bt1IsValue && !bt2IsValue) return 0; //both non-values - doesn't matter in order (but return here to avoid next tests if (bt1IsNumber && !bt2IsNumber) return 1; //non-number (e.g. 'Due') comes first if (!bt1IsNumber && bt2IsNumber) return -1; //non-number (e.g. 'Due') comes first //both have values, and both are numeric - so use standard integer comparison if (bt1IsNumber && bt2IsNumber) return bt1Value.compareTo(bt2Value); //both have values, and neither are numeric - so use standard string comparison return bt1.getEstimatedArrivalTime().compareTo(bt2.getEstimatedArrivalTime()); }
diff --git a/assets/src/org/ruboto/Script.java b/assets/src/org/ruboto/Script.java index bbf2af7..a8ad4c0 100644 --- a/assets/src/org/ruboto/Script.java +++ b/assets/src/org/ruboto/Script.java @@ -1,605 +1,609 @@ package org.ruboto; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetManager; import android.os.Environment; import android.util.Log; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import dalvik.system.PathClassLoader; public class Script { private static String scriptsDir = "scripts"; private static File scriptsDirFile = null; private String name = null; private static Object ruby; private static boolean isDebugBuild = false; private static PrintStream output = null; private static boolean initialized = false; private static String localContextScope = "SINGLETON"; private static String localVariableBehavior = "TRANSIENT"; public static final String TAG = "RUBOTO"; // for logging private static String JRUBY_VERSION; private static String RUBOTO_CORE_VERSION_NAME; /************************************************************************************************* * * Static Methods: ScriptingContainer config */ public static void setLocalContextScope(String val) { localContextScope = val; } public static void setLocalVariableBehavior(String val) { localVariableBehavior = val; } /************************************************************************************************* * * Static Methods: JRuby Execution */ public static final FilenameFilter RUBY_FILES = new FilenameFilter() { public boolean accept(File dir, String fname) { return fname.endsWith(".rb"); } }; public static synchronized boolean isInitialized() { return initialized; } public static boolean usesPlatformApk() { return RUBOTO_CORE_VERSION_NAME != null; } public static String getPlatformVersionName() { return RUBOTO_CORE_VERSION_NAME; } public static synchronized boolean setUpJRuby(Context appContext) { return setUpJRuby(appContext, output == null ? System.out : output); } @SuppressWarnings({ "unchecked", "rawtypes" }) public static synchronized boolean setUpJRuby(Context appContext, PrintStream out) { if (!initialized) { + // BEGIN Ruboto HeapAlloc + byte[] arrayForHeapAllocation = new byte[13 * 1024 * 1024]; + arrayForHeapAllocation = null; + // END Ruboto HeapAlloc setDebugBuild(appContext); Log.d(TAG, "Setting up JRuby runtime (" + (isDebugBuild ? "DEBUG" : "RELEASE") + ")"); System.setProperty("jruby.bytecode.version", "1.6"); System.setProperty("jruby.interfaces.useProxy", "true"); System.setProperty("jruby.management.enabled", "false"); System.setProperty("jruby.objectspace.enabled", "false"); System.setProperty("jruby.thread.pooling", "true"); System.setProperty("jruby.native.enabled", "false"); // System.setProperty("jruby.compat.version", "RUBY1_8"); // RUBY1_9 is the default // Uncomment these to debug Ruby source loading // System.setProperty("jruby.debug.loadService", "true"); // System.setProperty("jruby.debug.loadService.timing", "true"); ClassLoader classLoader; Class<?> scriptingContainerClass; String apkName = null; try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer"); System.out.println("Found JRuby in this APK"); classLoader = Script.class.getClassLoader(); try { apkName = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), 0).sourceDir; } catch (NameNotFoundException e) {} } catch (ClassNotFoundException e1) { String packageName = "org.ruboto.core"; try { PackageInfo pkgInfo = appContext.getPackageManager().getPackageInfo(packageName, 0); apkName = pkgInfo.applicationInfo.sourceDir; RUBOTO_CORE_VERSION_NAME = pkgInfo.versionName; } catch (PackageManager.NameNotFoundException e2) { out.println("JRuby not found in local APK:"); e1.printStackTrace(out); out.println("JRuby not found in platform APK:"); e2.printStackTrace(out); return false; } System.out.println("Found JRuby in platform APK"); if (true) { classLoader = new PathClassLoader(apkName, Script.class.getClassLoader()); } else { // Alternative way to get the class loader. The other way is rumoured to have memory leaks. try { Context platformAppContext = appContext.createPackageContext(packageName, Context.CONTEXT_INCLUDE_CODE + Context.CONTEXT_IGNORE_SECURITY); classLoader = platformAppContext.getClassLoader(); } catch (PackageManager.NameNotFoundException e) { System.out.println("Could not create package context even if application info could be found. Should never happen."); return false; } } try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer", true, classLoader); } catch (ClassNotFoundException e) { // FIXME(uwe): ScriptingContainer not found in the platform APK... e.printStackTrace(); return false; } } try { try { JRUBY_VERSION = (String) Class.forName("org.jruby.runtime.Constants", true, classLoader).getDeclaredField("VERSION").get(String.class); } catch (java.lang.NoSuchFieldException nsfex) { nsfex.printStackTrace(); JRUBY_VERSION = "ERROR"; } Class scopeClass = Class.forName("org.jruby.embed.LocalContextScope", true, scriptingContainerClass.getClassLoader()); Class behaviorClass = Class.forName("org.jruby.embed.LocalVariableBehavior", true, scriptingContainerClass.getClassLoader()); ruby = scriptingContainerClass .getConstructor(scopeClass, behaviorClass) .newInstance(Enum.valueOf(scopeClass, localContextScope), Enum.valueOf(behaviorClass, localVariableBehavior)); Class compileModeClass = Class.forName("org.jruby.RubyInstanceConfig$CompileMode", true, classLoader); callScriptingContainerMethod(Void.class, "setCompileMode", Enum.valueOf(compileModeClass, "OFF")); // Class traceTypeClass = Class.forName("org.jruby.runtime.backtrace.TraceType", true, classLoader); // Method traceTypeForMethod = traceTypeClass.getMethod("traceTypeFor", String.class); // Object traceTypeRaw = traceTypeForMethod.invoke(null, "raw"); // callScriptingContainerMethod(Void.class, "setTraceType", traceTypeRaw); // FIXME(uwe): Write tutorial on profiling. // container.getProvider().getRubyInstanceConfig().setProfilingMode(mode); // callScriptingContainerMethod(Void.class, "setClassLoader", classLoader); Method setClassLoaderMethod = ruby.getClass().getMethod("setClassLoader", ClassLoader.class); setClassLoaderMethod.invoke(ruby, classLoader); Thread.currentThread().setContextClassLoader(classLoader); String defaultCurrentDir = appContext.getFilesDir().getPath(); Log.d(TAG, "Setting JRuby current directory to " + defaultCurrentDir); callScriptingContainerMethod(Void.class, "setCurrentDirectory", defaultCurrentDir); if (out != null) { output = out; setOutputStream(out); } else if (output != null) { setOutputStream(output); } String jrubyHome = "file:" + apkName + "!"; Log.i(TAG, "Setting JRUBY_HOME: " + jrubyHome); System.setProperty("jruby.home", jrubyHome); String extraScriptsDir = scriptsDirName(appContext); Log.i(TAG, "Checking scripts in " + extraScriptsDir); if (configDir(extraScriptsDir)) { Log.i(TAG, "Added extra scripts path: " + extraScriptsDir); } initialized = true; } catch (ClassNotFoundException e) { handleInitException(e); } catch (IllegalArgumentException e) { handleInitException(e); } catch (SecurityException e) { handleInitException(e); } catch (InstantiationException e) { handleInitException(e); } catch (IllegalAccessException e) { handleInitException(e); } catch (InvocationTargetException e) { handleInitException(e); } catch (NoSuchMethodException e) { handleInitException(e); } } return initialized; } public static void setOutputStream(PrintStream out) { if (ruby == null) { output = out; } else { try { Method setOutputMethod = ruby.getClass().getMethod("setOutput", PrintStream.class); setOutputMethod.invoke(ruby, out); Method setErrorMethod = ruby.getClass().getMethod("setError", PrintStream.class); setErrorMethod.invoke(ruby, out); } catch (IllegalArgumentException e) { handleInitException(e); } catch (SecurityException e) { handleInitException(e); } catch (IllegalAccessException e) { handleInitException(e); } catch (InvocationTargetException e) { handleInitException(e); } catch (NoSuchMethodException e) { handleInitException(e); } } } private static void handleInitException(Exception e) { Log.e(TAG, "Exception starting JRuby"); Log.e(TAG, e.getMessage() != null ? e.getMessage() : e.getClass().getName()); e.printStackTrace(); ruby = null; } @SuppressWarnings("unchecked") public static <T> T callScriptingContainerMethod(Class<T> returnType, String methodName, Object... args) { Class<?>[] argClasses = new Class[args.length]; for (int i = 0; i < argClasses.length; i++) { argClasses[i] = args[i].getClass(); } try { Method method = ruby.getClass().getMethod(methodName, argClasses); System.out.println("callScriptingContainerMethod: method: " + method); T result = (T) method.invoke(ruby, args); System.out.println("callScriptingContainerMethod: result: " + result); return result; } catch (RuntimeException re) { re.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { printStackTrace(e); } catch (NoSuchMethodException e) { e.printStackTrace(); } return null; } public static String execute(String code) { Object result = exec(code); return result != null ? result.toString() : "nil"; // TODO: Why is callMethod returning "main"? // return result != null ? callMethod(result, "inspect", String.class) : "null"; } public static Object exec(String code) { // return callScriptingContainerMethod(Object.class, "runScriptlet", code); try { Method runScriptletMethod = ruby.getClass().getMethod("runScriptlet", String.class); return runScriptletMethod.invoke(ruby, code); } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { if (isDebugBuild) { throw ((RuntimeException) ite.getCause()); } else { return null; } } } public static void defineGlobalConstant(String name, Object object) { put(name, object); } public static void put(String name, Object object) { // callScriptingContainerMethod(Void.class, "put", name, object); try { Method putMethod = ruby.getClass().getMethod("put", String.class, Object.class); putMethod.invoke(ruby, name, object); } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { throw new RuntimeException(ite); } } public static void defineGlobalVariable(String name, Object object) { defineGlobalConstant(name, object); } /************************************************************************************************* * * Static Methods: Scripts Directory */ public static void setDir(String dir) { scriptsDir = dir; scriptsDirFile = new File(dir); if (ruby != null) { Log.d(TAG, "Changing JRuby current directory to " + scriptsDir); callScriptingContainerMethod(Void.class, "setCurrentDirectory", scriptsDir); } } public static String getDir() { return scriptsDir; } public static File getDirFile() { return scriptsDirFile; } public static Boolean configDir(String scriptsDir) { if (new File(scriptsDir).exists()) { Log.i(TAG, "Found extra scripts dir: " + scriptsDir); setDir(scriptsDir); exec("$:.unshift '" + scriptsDir + "' ; $:.uniq!"); return true; } else { Log.i(TAG, "Extra scripts dir not present: " + scriptsDir); return false; } } private static void copyScripts(String from, File to, AssetManager assets) { try { byte[] buffer = new byte[8192]; for (String f : assets.list(from)) { File dest = new File(to, f); if (dest.exists()) { continue; } Log.d(TAG, "copying file from " + from + "/" + f + " to " + dest); if (assets.list(from + "/" + f).length == 0) { InputStream is = assets.open(from + "/" + f); OutputStream fos = new BufferedOutputStream(new FileOutputStream(dest), 8192); int n; while ((n = is.read(buffer, 0, buffer.length)) != -1) { fos.write(buffer, 0, n); } is.close(); fos.close(); } else { dest.mkdir(); copyScripts(from + "/" + f, dest, assets); } } } catch (IOException iox) { Log.e(TAG, "error copying scripts", iox); } } public static void copyAssets(Context context, String directory) { File dest = new File(scriptsDirFile.getParentFile(), directory); if (dest.exists() || dest.mkdir()) { copyScripts(directory, dest, context.getAssets()); } else { throw new RuntimeException("Unable to create scripts directory: " + dest); } } private static void setDebugBuild(Context context) { PackageManager pm = context.getPackageManager(); PackageInfo pi; try { pi = pm.getPackageInfo(context.getPackageName(), 0); isDebugBuild = ((pi.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); } catch (NameNotFoundException e) { isDebugBuild = false; } } private static String scriptsDirName(Context context) { File storageDir = null; if (isDebugBuild) { // FIXME(uwe): Simplify this as soon as we drop support for android-7 or JRuby 1.5.6 or JRuby 1.6.2 Log.i(TAG, "JRuby VERSION: " + JRUBY_VERSION); if (!JRUBY_VERSION.equals("1.5.6") && !JRUBY_VERSION.equals("1.6.2") && android.os.Build.VERSION.SDK_INT >= 8) { try { Method method = context.getClass().getMethod("getExternalFilesDir", String.class); storageDir = (File) method.invoke(context, (Object) null); } catch (SecurityException e) { printStackTrace(e); } catch (NoSuchMethodException e) { printStackTrace(e); } catch (IllegalArgumentException e) { printStackTrace(e); } catch (IllegalAccessException e) { printStackTrace(e); } catch (InvocationTargetException e) { printStackTrace(e); } } else { storageDir = new File(Environment.getExternalStorageDirectory(), "Android/data/" + context.getPackageName() + "/files"); Log.e(TAG, "Calculated path to sdcard the old way: " + storageDir); } // FIXME end if (storageDir == null || (!storageDir.exists() && !storageDir.mkdirs())) { Log.e(TAG, "Development mode active, but sdcard is not available. Make sure you have added\n<uses-permission android:name='android.permission.WRITE_EXTERNAL_STORAGE' />\nto your AndroidManifest.xml file."); storageDir = context.getFilesDir(); } } else { storageDir = context.getFilesDir(); } return storageDir.getAbsolutePath() + "/scripts"; } /************************************************************************************************* * * Constructors */ public Script(String name) { this.name = name; } /************************************************************************************************* * * Attribute Access */ public String getName() { return name; } public File getFile() { return new File(getDir(), name); } public Script setName(String name) { this.name = name; return this; } public String getContents() throws IOException { InputStream is; if (new File(scriptsDir + "/" + name).exists()) { is = new java.io.FileInputStream(scriptsDir + "/" + name); } else { is = getClass().getClassLoader().getResourceAsStream(name); } BufferedReader buffer = new BufferedReader(new java.io.InputStreamReader(is), 8192); StringBuilder source = new StringBuilder(); while (true) { String line = buffer.readLine(); if (line == null) { break; } source.append(line).append("\n"); } buffer.close(); return source.toString(); } /************************************************************************************************* * * Script Actions */ public static String getScriptFilename() { return (String)callScriptingContainerMethod(String.class, "getScriptFilename"); } public static void setScriptFilename(String name) { callScriptingContainerMethod(Void.class, "setScriptFilename", name); } public String execute() throws IOException { Script.setScriptFilename(getClass().getClassLoader().getResource(name).getPath()); return Script.execute(getContents()); } public static void callMethod(Object receiver, String methodName, Object[] args) { try { Method callMethodMethod = ruby.getClass().getMethod("callMethod", Object.class, String.class, Object[].class); callMethodMethod.invoke(ruby, receiver, methodName, args); } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { printStackTrace(ite); if (isDebugBuild) { throw new RuntimeException(ite); } } } public static void callMethod(Object object, String methodName, Object arg) { callMethod(object, methodName, new Object[] { arg }); } public static void callMethod(Object object, String methodName) { callMethod(object, methodName, new Object[] {}); } @SuppressWarnings("unchecked") public static <T> T callMethod(Object receiver, String methodName, Object[] args, Class<T> returnType) { try { Method callMethodMethod = ruby.getClass().getMethod("callMethod", Object.class, String.class, Object[].class, Class.class); return (T) callMethodMethod.invoke(ruby, receiver, methodName, args, returnType); } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { printStackTrace(ite); } return null; } @SuppressWarnings("unchecked") public static <T> T callMethod(Object receiver, String methodName, Object arg, Class<T> returnType) { try { Method callMethodMethod = ruby.getClass().getMethod("callMethod", Object.class, String.class, Object.class, Class.class); return (T) callMethodMethod.invoke(ruby, receiver, methodName, arg, returnType); } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { printStackTrace(ite); } return null; } @SuppressWarnings("unchecked") public static <T> T callMethod(Object receiver, String methodName, Class<T> returnType) { try { Method callMethodMethod = ruby.getClass().getMethod("callMethod", Object.class, String.class, Class.class); return (T) callMethodMethod.invoke(ruby, receiver, methodName, returnType); } catch (NoSuchMethodException nsme) { throw new RuntimeException(nsme); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } catch (java.lang.reflect.InvocationTargetException ite) { printStackTrace(ite); } return null; } private static void printStackTrace(Throwable t) { PrintStream out; try { Method getOutputMethod = ruby.getClass().getMethod("getOutput"); out = (PrintStream) getOutputMethod.invoke(ruby); } catch (java.lang.NoSuchMethodException nsme) { throw new RuntimeException("ScriptingContainer#getOutput method not found.", nsme); } catch (java.lang.IllegalAccessException iae) { throw new RuntimeException("ScriptingContainer#getOutput method not accessable.", iae); } catch (java.lang.reflect.InvocationTargetException ite) { throw new RuntimeException("ScriptingContainer#getOutput failed.", ite); } // TODO(uwe): Simplify this when Issue #144 is resolved try { t.printStackTrace(out); } catch (NullPointerException npe) { // TODO(uwe): printStackTrace should not fail for (java.lang.StackTraceElement ste : t.getStackTrace()) { out.append(ste.toString() + "\n"); } } } }
true
true
public static synchronized boolean setUpJRuby(Context appContext, PrintStream out) { if (!initialized) { setDebugBuild(appContext); Log.d(TAG, "Setting up JRuby runtime (" + (isDebugBuild ? "DEBUG" : "RELEASE") + ")"); System.setProperty("jruby.bytecode.version", "1.6"); System.setProperty("jruby.interfaces.useProxy", "true"); System.setProperty("jruby.management.enabled", "false"); System.setProperty("jruby.objectspace.enabled", "false"); System.setProperty("jruby.thread.pooling", "true"); System.setProperty("jruby.native.enabled", "false"); // System.setProperty("jruby.compat.version", "RUBY1_8"); // RUBY1_9 is the default // Uncomment these to debug Ruby source loading // System.setProperty("jruby.debug.loadService", "true"); // System.setProperty("jruby.debug.loadService.timing", "true"); ClassLoader classLoader; Class<?> scriptingContainerClass; String apkName = null; try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer"); System.out.println("Found JRuby in this APK"); classLoader = Script.class.getClassLoader(); try { apkName = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), 0).sourceDir; } catch (NameNotFoundException e) {} } catch (ClassNotFoundException e1) { String packageName = "org.ruboto.core"; try { PackageInfo pkgInfo = appContext.getPackageManager().getPackageInfo(packageName, 0); apkName = pkgInfo.applicationInfo.sourceDir; RUBOTO_CORE_VERSION_NAME = pkgInfo.versionName; } catch (PackageManager.NameNotFoundException e2) { out.println("JRuby not found in local APK:"); e1.printStackTrace(out); out.println("JRuby not found in platform APK:"); e2.printStackTrace(out); return false; } System.out.println("Found JRuby in platform APK"); if (true) { classLoader = new PathClassLoader(apkName, Script.class.getClassLoader()); } else { // Alternative way to get the class loader. The other way is rumoured to have memory leaks. try { Context platformAppContext = appContext.createPackageContext(packageName, Context.CONTEXT_INCLUDE_CODE + Context.CONTEXT_IGNORE_SECURITY); classLoader = platformAppContext.getClassLoader(); } catch (PackageManager.NameNotFoundException e) { System.out.println("Could not create package context even if application info could be found. Should never happen."); return false; } } try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer", true, classLoader); } catch (ClassNotFoundException e) { // FIXME(uwe): ScriptingContainer not found in the platform APK... e.printStackTrace(); return false; } } try { try { JRUBY_VERSION = (String) Class.forName("org.jruby.runtime.Constants", true, classLoader).getDeclaredField("VERSION").get(String.class); } catch (java.lang.NoSuchFieldException nsfex) { nsfex.printStackTrace(); JRUBY_VERSION = "ERROR"; } Class scopeClass = Class.forName("org.jruby.embed.LocalContextScope", true, scriptingContainerClass.getClassLoader()); Class behaviorClass = Class.forName("org.jruby.embed.LocalVariableBehavior", true, scriptingContainerClass.getClassLoader()); ruby = scriptingContainerClass .getConstructor(scopeClass, behaviorClass) .newInstance(Enum.valueOf(scopeClass, localContextScope), Enum.valueOf(behaviorClass, localVariableBehavior)); Class compileModeClass = Class.forName("org.jruby.RubyInstanceConfig$CompileMode", true, classLoader); callScriptingContainerMethod(Void.class, "setCompileMode", Enum.valueOf(compileModeClass, "OFF")); // Class traceTypeClass = Class.forName("org.jruby.runtime.backtrace.TraceType", true, classLoader); // Method traceTypeForMethod = traceTypeClass.getMethod("traceTypeFor", String.class); // Object traceTypeRaw = traceTypeForMethod.invoke(null, "raw"); // callScriptingContainerMethod(Void.class, "setTraceType", traceTypeRaw); // FIXME(uwe): Write tutorial on profiling. // container.getProvider().getRubyInstanceConfig().setProfilingMode(mode); // callScriptingContainerMethod(Void.class, "setClassLoader", classLoader); Method setClassLoaderMethod = ruby.getClass().getMethod("setClassLoader", ClassLoader.class); setClassLoaderMethod.invoke(ruby, classLoader); Thread.currentThread().setContextClassLoader(classLoader); String defaultCurrentDir = appContext.getFilesDir().getPath(); Log.d(TAG, "Setting JRuby current directory to " + defaultCurrentDir); callScriptingContainerMethod(Void.class, "setCurrentDirectory", defaultCurrentDir); if (out != null) { output = out; setOutputStream(out); } else if (output != null) { setOutputStream(output); } String jrubyHome = "file:" + apkName + "!"; Log.i(TAG, "Setting JRUBY_HOME: " + jrubyHome); System.setProperty("jruby.home", jrubyHome); String extraScriptsDir = scriptsDirName(appContext); Log.i(TAG, "Checking scripts in " + extraScriptsDir); if (configDir(extraScriptsDir)) { Log.i(TAG, "Added extra scripts path: " + extraScriptsDir); } initialized = true; } catch (ClassNotFoundException e) { handleInitException(e); } catch (IllegalArgumentException e) { handleInitException(e); } catch (SecurityException e) { handleInitException(e); } catch (InstantiationException e) { handleInitException(e); } catch (IllegalAccessException e) { handleInitException(e); } catch (InvocationTargetException e) { handleInitException(e); } catch (NoSuchMethodException e) { handleInitException(e); } } return initialized; }
public static synchronized boolean setUpJRuby(Context appContext, PrintStream out) { if (!initialized) { // BEGIN Ruboto HeapAlloc byte[] arrayForHeapAllocation = new byte[13 * 1024 * 1024]; arrayForHeapAllocation = null; // END Ruboto HeapAlloc setDebugBuild(appContext); Log.d(TAG, "Setting up JRuby runtime (" + (isDebugBuild ? "DEBUG" : "RELEASE") + ")"); System.setProperty("jruby.bytecode.version", "1.6"); System.setProperty("jruby.interfaces.useProxy", "true"); System.setProperty("jruby.management.enabled", "false"); System.setProperty("jruby.objectspace.enabled", "false"); System.setProperty("jruby.thread.pooling", "true"); System.setProperty("jruby.native.enabled", "false"); // System.setProperty("jruby.compat.version", "RUBY1_8"); // RUBY1_9 is the default // Uncomment these to debug Ruby source loading // System.setProperty("jruby.debug.loadService", "true"); // System.setProperty("jruby.debug.loadService.timing", "true"); ClassLoader classLoader; Class<?> scriptingContainerClass; String apkName = null; try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer"); System.out.println("Found JRuby in this APK"); classLoader = Script.class.getClassLoader(); try { apkName = appContext.getPackageManager().getApplicationInfo(appContext.getPackageName(), 0).sourceDir; } catch (NameNotFoundException e) {} } catch (ClassNotFoundException e1) { String packageName = "org.ruboto.core"; try { PackageInfo pkgInfo = appContext.getPackageManager().getPackageInfo(packageName, 0); apkName = pkgInfo.applicationInfo.sourceDir; RUBOTO_CORE_VERSION_NAME = pkgInfo.versionName; } catch (PackageManager.NameNotFoundException e2) { out.println("JRuby not found in local APK:"); e1.printStackTrace(out); out.println("JRuby not found in platform APK:"); e2.printStackTrace(out); return false; } System.out.println("Found JRuby in platform APK"); if (true) { classLoader = new PathClassLoader(apkName, Script.class.getClassLoader()); } else { // Alternative way to get the class loader. The other way is rumoured to have memory leaks. try { Context platformAppContext = appContext.createPackageContext(packageName, Context.CONTEXT_INCLUDE_CODE + Context.CONTEXT_IGNORE_SECURITY); classLoader = platformAppContext.getClassLoader(); } catch (PackageManager.NameNotFoundException e) { System.out.println("Could not create package context even if application info could be found. Should never happen."); return false; } } try { scriptingContainerClass = Class.forName("org.jruby.embed.ScriptingContainer", true, classLoader); } catch (ClassNotFoundException e) { // FIXME(uwe): ScriptingContainer not found in the platform APK... e.printStackTrace(); return false; } } try { try { JRUBY_VERSION = (String) Class.forName("org.jruby.runtime.Constants", true, classLoader).getDeclaredField("VERSION").get(String.class); } catch (java.lang.NoSuchFieldException nsfex) { nsfex.printStackTrace(); JRUBY_VERSION = "ERROR"; } Class scopeClass = Class.forName("org.jruby.embed.LocalContextScope", true, scriptingContainerClass.getClassLoader()); Class behaviorClass = Class.forName("org.jruby.embed.LocalVariableBehavior", true, scriptingContainerClass.getClassLoader()); ruby = scriptingContainerClass .getConstructor(scopeClass, behaviorClass) .newInstance(Enum.valueOf(scopeClass, localContextScope), Enum.valueOf(behaviorClass, localVariableBehavior)); Class compileModeClass = Class.forName("org.jruby.RubyInstanceConfig$CompileMode", true, classLoader); callScriptingContainerMethod(Void.class, "setCompileMode", Enum.valueOf(compileModeClass, "OFF")); // Class traceTypeClass = Class.forName("org.jruby.runtime.backtrace.TraceType", true, classLoader); // Method traceTypeForMethod = traceTypeClass.getMethod("traceTypeFor", String.class); // Object traceTypeRaw = traceTypeForMethod.invoke(null, "raw"); // callScriptingContainerMethod(Void.class, "setTraceType", traceTypeRaw); // FIXME(uwe): Write tutorial on profiling. // container.getProvider().getRubyInstanceConfig().setProfilingMode(mode); // callScriptingContainerMethod(Void.class, "setClassLoader", classLoader); Method setClassLoaderMethod = ruby.getClass().getMethod("setClassLoader", ClassLoader.class); setClassLoaderMethod.invoke(ruby, classLoader); Thread.currentThread().setContextClassLoader(classLoader); String defaultCurrentDir = appContext.getFilesDir().getPath(); Log.d(TAG, "Setting JRuby current directory to " + defaultCurrentDir); callScriptingContainerMethod(Void.class, "setCurrentDirectory", defaultCurrentDir); if (out != null) { output = out; setOutputStream(out); } else if (output != null) { setOutputStream(output); } String jrubyHome = "file:" + apkName + "!"; Log.i(TAG, "Setting JRUBY_HOME: " + jrubyHome); System.setProperty("jruby.home", jrubyHome); String extraScriptsDir = scriptsDirName(appContext); Log.i(TAG, "Checking scripts in " + extraScriptsDir); if (configDir(extraScriptsDir)) { Log.i(TAG, "Added extra scripts path: " + extraScriptsDir); } initialized = true; } catch (ClassNotFoundException e) { handleInitException(e); } catch (IllegalArgumentException e) { handleInitException(e); } catch (SecurityException e) { handleInitException(e); } catch (InstantiationException e) { handleInitException(e); } catch (IllegalAccessException e) { handleInitException(e); } catch (InvocationTargetException e) { handleInitException(e); } catch (NoSuchMethodException e) { handleInitException(e); } } return initialized; }
diff --git a/src/test/java/com/netflix/simianarmy/basic/TestBasicScheduler.java b/src/test/java/com/netflix/simianarmy/basic/TestBasicScheduler.java index 5fa2b1e..c99198c 100644 --- a/src/test/java/com/netflix/simianarmy/basic/TestBasicScheduler.java +++ b/src/test/java/com/netflix/simianarmy/basic/TestBasicScheduler.java @@ -1,117 +1,116 @@ // CHECKSTYLE IGNORE Javadoc /* * * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.simianarmy.basic; import static org.mockito.Mockito.*; import java.util.Calendar; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import org.testng.Assert; import org.testng.annotations.Test; import com.google.common.util.concurrent.Callables; import com.netflix.simianarmy.EventType; import com.netflix.simianarmy.Monkey; import com.netflix.simianarmy.MonkeyType; import com.netflix.simianarmy.TestMonkeyContext; // CHECKSTYLE IGNORE MagicNumber public class TestBasicScheduler { @Test public void testConstructors() { BasicScheduler sched = new BasicScheduler(); Assert.assertNotNull(sched); Assert.assertEquals(sched.frequency(), 1); Assert.assertEquals(sched.frequencyUnit(), TimeUnit.HOURS); BasicScheduler sched2 = new BasicScheduler(12, TimeUnit.MINUTES, 2); Assert.assertEquals(sched2.frequency(), 12); Assert.assertEquals(sched2.frequencyUnit(), TimeUnit.MINUTES); } private enum Enums implements MonkeyType { MONKEY }; private enum EventEnums implements EventType { EVENT } @Test public void testRunner() throws InterruptedException { BasicScheduler sched = new BasicScheduler(200, TimeUnit.MILLISECONDS, 1); Monkey mockMonkey = mock(Monkey.class); when(mockMonkey.context()).thenReturn(new TestMonkeyContext(Enums.MONKEY)); when(mockMonkey.type()).thenReturn(Enums.MONKEY).thenReturn(Enums.MONKEY); final AtomicLong counter = new AtomicLong(0L); sched.start(mockMonkey, new Runnable() { @Override public void run() { counter.incrementAndGet(); } }); Thread.sleep(100); Assert.assertEquals(counter.get(), 1); Thread.sleep(200); Assert.assertEquals(counter.get(), 2); sched.stop(mockMonkey); Thread.sleep(200); Assert.assertEquals(counter.get(), 2); } @Test public void testDelayedStart() throws Exception { BasicScheduler sched = new BasicScheduler(1, TimeUnit.HOURS, 1); TestMonkeyContext context = new TestMonkeyContext(Enums.MONKEY); Monkey mockMonkey = mock(Monkey.class); when(mockMonkey.context()).thenReturn(context).thenReturn(context); when(mockMonkey.type()).thenReturn(Enums.MONKEY).thenReturn(Enums.MONKEY); // first monkey has no previous events, so it runs practically immediately FutureTask<Void> task = new FutureTask<Void>(Callables.<Void>returning(null)); sched.start(mockMonkey, task); // make sure that the task gets completed within 100ms task.get(100L, TimeUnit.MILLISECONDS); sched.stop(mockMonkey); // create an event 5 min ago Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, -5); BasicRecorderEvent evt = new BasicRecorderEvent(Enums.MONKEY, EventEnums.EVENT, "region", "test-id", cal.getTime() .getTime()); context.recorder().recordEvent(evt); // this time when it runs it will not run immediately since it should be scheduled for 55m from now. task = new FutureTask<Void>(Callables.<Void>returning(null)); sched.start(mockMonkey, task); try { task.get(100, TimeUnit.MILLISECONDS); Assert.fail("The task shouldn't have been completed in 100ms"); - } catch (TimeoutException e) { - // This is expected. + } catch (TimeoutException e) { // NOPMD - This is an expected exception } sched.stop(mockMonkey); } }
true
true
public void testDelayedStart() throws Exception { BasicScheduler sched = new BasicScheduler(1, TimeUnit.HOURS, 1); TestMonkeyContext context = new TestMonkeyContext(Enums.MONKEY); Monkey mockMonkey = mock(Monkey.class); when(mockMonkey.context()).thenReturn(context).thenReturn(context); when(mockMonkey.type()).thenReturn(Enums.MONKEY).thenReturn(Enums.MONKEY); // first monkey has no previous events, so it runs practically immediately FutureTask<Void> task = new FutureTask<Void>(Callables.<Void>returning(null)); sched.start(mockMonkey, task); // make sure that the task gets completed within 100ms task.get(100L, TimeUnit.MILLISECONDS); sched.stop(mockMonkey); // create an event 5 min ago Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, -5); BasicRecorderEvent evt = new BasicRecorderEvent(Enums.MONKEY, EventEnums.EVENT, "region", "test-id", cal.getTime() .getTime()); context.recorder().recordEvent(evt); // this time when it runs it will not run immediately since it should be scheduled for 55m from now. task = new FutureTask<Void>(Callables.<Void>returning(null)); sched.start(mockMonkey, task); try { task.get(100, TimeUnit.MILLISECONDS); Assert.fail("The task shouldn't have been completed in 100ms"); } catch (TimeoutException e) { // This is expected. } sched.stop(mockMonkey); }
public void testDelayedStart() throws Exception { BasicScheduler sched = new BasicScheduler(1, TimeUnit.HOURS, 1); TestMonkeyContext context = new TestMonkeyContext(Enums.MONKEY); Monkey mockMonkey = mock(Monkey.class); when(mockMonkey.context()).thenReturn(context).thenReturn(context); when(mockMonkey.type()).thenReturn(Enums.MONKEY).thenReturn(Enums.MONKEY); // first monkey has no previous events, so it runs practically immediately FutureTask<Void> task = new FutureTask<Void>(Callables.<Void>returning(null)); sched.start(mockMonkey, task); // make sure that the task gets completed within 100ms task.get(100L, TimeUnit.MILLISECONDS); sched.stop(mockMonkey); // create an event 5 min ago Calendar cal = Calendar.getInstance(); cal.add(Calendar.MINUTE, -5); BasicRecorderEvent evt = new BasicRecorderEvent(Enums.MONKEY, EventEnums.EVENT, "region", "test-id", cal.getTime() .getTime()); context.recorder().recordEvent(evt); // this time when it runs it will not run immediately since it should be scheduled for 55m from now. task = new FutureTask<Void>(Callables.<Void>returning(null)); sched.start(mockMonkey, task); try { task.get(100, TimeUnit.MILLISECONDS); Assert.fail("The task shouldn't have been completed in 100ms"); } catch (TimeoutException e) { // NOPMD - This is an expected exception } sched.stop(mockMonkey); }
diff --git a/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/BasicPopulation.java b/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/BasicPopulation.java index 1c9c74739..210426fc3 100644 --- a/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/BasicPopulation.java +++ b/opentripplanner-analyst/src/main/java/org/opentripplanner/analyst/batch/BasicPopulation.java @@ -1,188 +1,190 @@ /* 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentripplanner.analyst.batch; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import lombok.Getter; import lombok.Setter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.csvreader.CsvWriter; public class BasicPopulation implements Population { private static final Logger LOG = LoggerFactory.getLogger(BasicPopulation.class); @Setter public String sourceFilename; @Setter @Getter public List<Individual> individuals = new ArrayList<Individual>(); @Setter @Getter public List<IndividualFilter> filterChain = null; private boolean[] skip = null; public BasicPopulation() { } public BasicPopulation(Individual... individuals) { this.individuals = Arrays.asList(individuals); } public BasicPopulation(Collection<Individual> individuals) { this.individuals = new ArrayList<Individual>(individuals); } @Override public void addIndividual(Individual individual) { this.individuals.add(individual); } @Override public Iterator<Individual> iterator() { return new PopulationIterator(); } @Override public void clearIndividuals(List<Individual> individuals) { this.individuals.clear(); } @Override public void createIndividuals() { // nothing to do in the basic population case } @Override public int size() { return this.individuals.size(); } protected void writeCsv(String outFileName, ResultSet results) { LOG.debug("Writing population to CSV: {}", outFileName); try { CsvWriter writer = new CsvWriter(outFileName, ',', Charset.forName("UTF8")); writer.writeRecord( new String[] {"label", "lat", "lon", "input", "output"} ); int i = 0; + int j = 0; // using internal list rather than filtered iterator for (Individual indiv : this.individuals) { if ( ! this.skip[i]) { String[] entries = new String[] { indiv.label, Double.toString(indiv.lat), Double.toString(indiv.lon), - Double.toString(indiv.input), Double.toString(results.results[i]) + Double.toString(indiv.input), Double.toString(results.results[j]) }; writer.writeRecord(entries); + j++; } i++; } writer.close(); // flush writes and close } catch (Exception e) { LOG.error("Error while writing to CSV file: {}", e.getMessage()); return; } LOG.debug("Done writing population to CSV at {}.", outFileName); } @Override public void writeAppropriateFormat(String outFileName, ResultSet results) { // as a default, save to CSV. override this method in subclasses when more is known about data structure. this.writeCsv(outFileName, results); } // TODO maybe store skip values in the samples themselves? /** * If a filter chain is specified, apply it to the individuals. Must be called after loading * or generating the individuals. Filtering does not actually remove individuals from the * population, it merely tags them as rejected. This is important for structured populations * like rasters, where we may need to write out all individuals including those that were * skipped. */ private void applyFilterChain() { this.skip = new boolean[individuals.size()]; // initialized to false if (filterChain == null) // no filter chain, do not reject any individuals return; for (IndividualFilter filter : filterChain) { LOG.info("applying filter {}", filter); int rejected = 0; int i = 0; for (Individual individual : this.individuals) { boolean skipThis = ! filter.filter(individual); if (skipThis) rejected += 1; skip[i++] |= skipThis; } LOG.info("accepted {} rejected {}", skip.length - rejected, rejected); } int rejected = 0; for (boolean s : skip) if (s) rejected += 1; LOG.info("TOTALS: accepted {} rejected {}", skip.length - rejected, rejected); } @Override public void setup() { // call the subclass-specific file loading method this.createIndividuals(); // call the shared filter chain method this.applyFilterChain(); } class PopulationIterator implements Iterator<Individual> { int i = 0; int n = individuals.size(); Iterator<Individual> iter = individuals.iterator(); public boolean hasNext() { while (i < n && skip[i]) { //LOG.debug("in iter, i = {}", i); if (! iter.hasNext()) return false; i += 1; iter.next(); } //LOG.debug("done skipping at {}", i); return iter.hasNext(); } public Individual next() { if (this.hasNext()) { Individual ret = iter.next(); i += 1; return ret; } else { throw new NoSuchElementException(); } } public void remove() { throw new UnsupportedOperationException(); } } }
false
true
protected void writeCsv(String outFileName, ResultSet results) { LOG.debug("Writing population to CSV: {}", outFileName); try { CsvWriter writer = new CsvWriter(outFileName, ',', Charset.forName("UTF8")); writer.writeRecord( new String[] {"label", "lat", "lon", "input", "output"} ); int i = 0; // using internal list rather than filtered iterator for (Individual indiv : this.individuals) { if ( ! this.skip[i]) { String[] entries = new String[] { indiv.label, Double.toString(indiv.lat), Double.toString(indiv.lon), Double.toString(indiv.input), Double.toString(results.results[i]) }; writer.writeRecord(entries); } i++; } writer.close(); // flush writes and close } catch (Exception e) { LOG.error("Error while writing to CSV file: {}", e.getMessage()); return; } LOG.debug("Done writing population to CSV at {}.", outFileName); }
protected void writeCsv(String outFileName, ResultSet results) { LOG.debug("Writing population to CSV: {}", outFileName); try { CsvWriter writer = new CsvWriter(outFileName, ',', Charset.forName("UTF8")); writer.writeRecord( new String[] {"label", "lat", "lon", "input", "output"} ); int i = 0; int j = 0; // using internal list rather than filtered iterator for (Individual indiv : this.individuals) { if ( ! this.skip[i]) { String[] entries = new String[] { indiv.label, Double.toString(indiv.lat), Double.toString(indiv.lon), Double.toString(indiv.input), Double.toString(results.results[j]) }; writer.writeRecord(entries); j++; } i++; } writer.close(); // flush writes and close } catch (Exception e) { LOG.error("Error while writing to CSV file: {}", e.getMessage()); return; } LOG.debug("Done writing population to CSV at {}.", outFileName); }
diff --git a/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java b/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java index 5df8d0fc2..bc8c13744 100644 --- a/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java +++ b/test/web/org/codehaus/groovy/grails/web/pages/ParseTests.java @@ -1,139 +1,138 @@ package org.codehaus.groovy.grails.web.pages; import junit.framework.TestCase; import org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException; import java.io.*; /** * Tests the GSP parser. This can detect issues caused by improper * GSP->Groovy conversion. Normally, to compare the code, you can * run the page with a showSource parameter specified. * * The methods parseCode() and trimAndRemoveCR() have been added * to simplify test case code. * * @author Daiji * */ public class ParseTests extends TestCase { public void testParse() throws Exception { String output = parseCode("myTest", "<div>hi</div>"); String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n"+ "\n"+ "class myTest extends GroovyPage {\n"+ "public Object run() {\n"+ "out.print('<div>hi</div>')\n"+ "}\n"+ "}"; assertEquals(expected, trimAndRemoveCR(output)); } public void testParseWithUnclosedSquareBracket() throws Exception { String output = parseCode("myTest", "<g:message code=\"[\"/>"); String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n"+ "\n"+ "class myTest extends GroovyPage {\n"+ "public Object run() {\n"+ "attrs1 = [\"code\":\"[\"]\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('message','g',attrs1,body1)\n"+ "}\n"+ "}"; assertEquals(expected, trimAndRemoveCR(output)); } public void testParseWithUnclosedGstringThrowsException() throws IOException { try{ parseCode("myTest", "<g:message value=\"${boom\">"); }catch(GrailsTagException e){ assertEquals("Unexpected end of file encountered parsing Tag [message] for myTest. Are you missing a closing brace '}'?", e.getMessage()); return; } fail("Expected parse exception not thrown"); } /** * Eliminate potential issues caused by operating system differences * and minor output differences that we don't care about. * * Note: this code is inefficient and could stand to be optimized. */ public String trimAndRemoveCR(String s) { int index; StringBuffer sb = new StringBuffer(s.trim()); while ((index = sb.toString().indexOf('\r')) != -1) { sb.deleteCharAt(index); } return sb.toString(); } public String parseCode(String uri, String gsp) throws IOException { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); InputStream gspIn = new ByteArrayInputStream(gsp.getBytes()); Parse parse = new Parse(uri, gspIn); InputStream in = parse.parse(); send(in, pw); return sw.toString(); } public void testParseGTagsWithNamespaces() throws Exception { String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n" + "\n" + "class myTest extends GroovyPage {\n" + "public Object run() {\n" + "out.print(STATIC_HTML_CONTENT_0)\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('form','tt',[:],body1)\n" + "out.print(STATIC_HTML_CONTENT_1)\n" + "}\n" + "static final STATIC_HTML_CONTENT_1 = '''</tbody>\n" + "'''\n" + "\n" + - "static final STATIC_HTML_CONTENT_0 = '''<tbody>\n" + - "'''\n" + + "static final STATIC_HTML_CONTENT_0 = '''<tbody>'''\n" + "\n" + "}"; String output = parseCode("myTest", "<tbody>\n" + " <tt:form />\n" + "</tbody>"); //System.out.println(output); assertEquals(trimAndRemoveCR(expected), trimAndRemoveCR(output)); } /** * Copy all of input to output. * @param in * @param out * @throws IOException */ public static void send(InputStream in, Writer out) throws IOException { try { Reader reader = new InputStreamReader(in); char[] buf = new char[8192]; for (;;) { int read = reader.read(buf); if (read <= 0) break; out.write(buf, 0, read); } } finally { out.close(); in.close(); } } // writeInputStreamToResponse() }
true
true
public void testParseGTagsWithNamespaces() throws Exception { String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n" + "\n" + "class myTest extends GroovyPage {\n" + "public Object run() {\n" + "out.print(STATIC_HTML_CONTENT_0)\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('form','tt',[:],body1)\n" + "out.print(STATIC_HTML_CONTENT_1)\n" + "}\n" + "static final STATIC_HTML_CONTENT_1 = '''</tbody>\n" + "'''\n" + "\n" + "static final STATIC_HTML_CONTENT_0 = '''<tbody>\n" + "'''\n" + "\n" + "}"; String output = parseCode("myTest", "<tbody>\n" + " <tt:form />\n" + "</tbody>"); //System.out.println(output); assertEquals(trimAndRemoveCR(expected), trimAndRemoveCR(output)); }
public void testParseGTagsWithNamespaces() throws Exception { String expected = "import org.codehaus.groovy.grails.web.pages.GroovyPage\n" + "import org.codehaus.groovy.grails.web.taglib.*\n" + "\n" + "class myTest extends GroovyPage {\n" + "public Object run() {\n" + "out.print(STATIC_HTML_CONTENT_0)\n" + "body1 = new GroovyPageTagBody(this,binding.webRequest) {\n" + "}\n" + "invokeTag('form','tt',[:],body1)\n" + "out.print(STATIC_HTML_CONTENT_1)\n" + "}\n" + "static final STATIC_HTML_CONTENT_1 = '''</tbody>\n" + "'''\n" + "\n" + "static final STATIC_HTML_CONTENT_0 = '''<tbody>'''\n" + "\n" + "}"; String output = parseCode("myTest", "<tbody>\n" + " <tt:form />\n" + "</tbody>"); //System.out.println(output); assertEquals(trimAndRemoveCR(expected), trimAndRemoveCR(output)); }
diff --git a/src/main/java/org/jahia/modules/wiki/errors/NewWikiPageHandler.java b/src/main/java/org/jahia/modules/wiki/errors/NewWikiPageHandler.java index 6a3fecc..665bc0c 100644 --- a/src/main/java/org/jahia/modules/wiki/errors/NewWikiPageHandler.java +++ b/src/main/java/org/jahia/modules/wiki/errors/NewWikiPageHandler.java @@ -1,123 +1,123 @@ /** * This file is part of Jahia: An integrated WCM, DMS and Portal Solution * Copyright (C) 2002-2010 Jahia Solutions Group SA. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * As a special exception to the terms and conditions of version 2.0 of * the GPL (or any later version), you may redistribute this Program in connection * with Free/Libre and Open Source Software ("FLOSS") applications as described * in Jahia's FLOSS exception. You should have received a copy of the text * describing the FLOSS exception, and it is also available here: * http://www.jahia.com/license * * Commercial and Supported Versions of the program * Alternatively, commercial and supported versions of the program may be used * in accordance with the terms contained in a separate written agreement * between you and Jahia Solutions Group SA. If you are unsure which license is appropriate * for your use, please contact the sales department at [email protected]. */ package org.jahia.modules.wiki.errors; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.jahia.bin.errors.ErrorHandler; import org.jahia.services.content.JCRContentUtils; import org.jahia.services.content.JCRNodeWrapper; import org.jahia.services.content.JCRSessionFactory; import org.jahia.services.content.JCRSessionWrapper; import org.jahia.services.render.URLResolver; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.PathNotFoundException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLEncoder; import java.util.List; /** * Wiki page creation handler. * User: toto * Date: Dec 2, 2009 * Time: 4:11:46 PM */ public class NewWikiPageHandler implements ErrorHandler { private static final Logger logger = org.slf4j.LoggerFactory.getLogger(NewWikiPageHandler.class); public boolean handle(Throwable e, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { if (!(e instanceof PathNotFoundException)) { return false; } - URLResolver urlResolver = new URLResolver(request.getPathInfo(), request.getServerName()); + URLResolver urlResolver = new URLResolver(request.getPathInfo(), request.getServerName(), request); JCRNodeWrapper pageNode; String parentPath = StringUtils.substringBeforeLast(urlResolver.getPath(), "/"); String newName = StringUtils.substringAfterLast(urlResolver.getPath(), "/"); newName = StringUtils.substringBefore(newName, ".html"); JCRSessionWrapper session = JCRSessionFactory.getInstance().getCurrentUserSession( urlResolver.getWorkspace(), urlResolver.getLocale()); try { JCRNodeWrapper parent = session.getNode(parentPath); if (parent.isNodeType("jnt:page")) { pageNode = parent; } else { pageNode = JCRContentUtils.getParentOfType(parent, "jnt:page"); } // test if pageNode is wiki boolean isWiki = false; - if (pageNode.hasProperty("j:templateNode")) { + if (pageNode != null && pageNode.hasProperty("j:templateNode")) { NodeIterator iterator = JCRContentUtils.getDescendantNodes((JCRNodeWrapper) pageNode.getProperty("j:templateNode").getNode(), "jnt:wikiPageFormCreation"); if (iterator.hasNext()) { isWiki = true; } } if (pageNode == null || !isWiki) { return false; } try { JCRNodeWrapper node = pageNode.getNode(newName); String link = request.getContextPath() + request.getServletPath() + "/" + StringUtils.substringBefore( request.getPathInfo().substring(1), "/") + "/" + urlResolver.getWorkspace() + "/" + urlResolver.getLocale() + node.getPath(); link += ".html"; response.sendRedirect(link); } catch (PathNotFoundException e1) { if (null != pageNode) { String link = request.getContextPath() + request.getServletPath() + "/" + StringUtils.substringBefore( request.getPathInfo().substring(1), "/") + "/" + urlResolver.getWorkspace() + "/" + urlResolver.getLocale() + pageNode.getPath(); link += ".html?displayTab=create-new-page&newPageName=" + URLEncoder.encode(newName, "UTF-8"); response.sendRedirect(link); return true; } logger.debug("Wiki page not found ask for creation",e1); } } catch (PathNotFoundException e1) { return false; } } catch (Exception e1) { logger.error(e1.getMessage(), e1); } return false; } }
false
true
public boolean handle(Throwable e, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { if (!(e instanceof PathNotFoundException)) { return false; } URLResolver urlResolver = new URLResolver(request.getPathInfo(), request.getServerName()); JCRNodeWrapper pageNode; String parentPath = StringUtils.substringBeforeLast(urlResolver.getPath(), "/"); String newName = StringUtils.substringAfterLast(urlResolver.getPath(), "/"); newName = StringUtils.substringBefore(newName, ".html"); JCRSessionWrapper session = JCRSessionFactory.getInstance().getCurrentUserSession( urlResolver.getWorkspace(), urlResolver.getLocale()); try { JCRNodeWrapper parent = session.getNode(parentPath); if (parent.isNodeType("jnt:page")) { pageNode = parent; } else { pageNode = JCRContentUtils.getParentOfType(parent, "jnt:page"); } // test if pageNode is wiki boolean isWiki = false; if (pageNode.hasProperty("j:templateNode")) { NodeIterator iterator = JCRContentUtils.getDescendantNodes((JCRNodeWrapper) pageNode.getProperty("j:templateNode").getNode(), "jnt:wikiPageFormCreation"); if (iterator.hasNext()) { isWiki = true; } } if (pageNode == null || !isWiki) { return false; } try { JCRNodeWrapper node = pageNode.getNode(newName); String link = request.getContextPath() + request.getServletPath() + "/" + StringUtils.substringBefore( request.getPathInfo().substring(1), "/") + "/" + urlResolver.getWorkspace() + "/" + urlResolver.getLocale() + node.getPath(); link += ".html"; response.sendRedirect(link); } catch (PathNotFoundException e1) { if (null != pageNode) { String link = request.getContextPath() + request.getServletPath() + "/" + StringUtils.substringBefore( request.getPathInfo().substring(1), "/") + "/" + urlResolver.getWorkspace() + "/" + urlResolver.getLocale() + pageNode.getPath(); link += ".html?displayTab=create-new-page&newPageName=" + URLEncoder.encode(newName, "UTF-8"); response.sendRedirect(link); return true; } logger.debug("Wiki page not found ask for creation",e1); } } catch (PathNotFoundException e1) { return false; } } catch (Exception e1) { logger.error(e1.getMessage(), e1); } return false; }
public boolean handle(Throwable e, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { if (!(e instanceof PathNotFoundException)) { return false; } URLResolver urlResolver = new URLResolver(request.getPathInfo(), request.getServerName(), request); JCRNodeWrapper pageNode; String parentPath = StringUtils.substringBeforeLast(urlResolver.getPath(), "/"); String newName = StringUtils.substringAfterLast(urlResolver.getPath(), "/"); newName = StringUtils.substringBefore(newName, ".html"); JCRSessionWrapper session = JCRSessionFactory.getInstance().getCurrentUserSession( urlResolver.getWorkspace(), urlResolver.getLocale()); try { JCRNodeWrapper parent = session.getNode(parentPath); if (parent.isNodeType("jnt:page")) { pageNode = parent; } else { pageNode = JCRContentUtils.getParentOfType(parent, "jnt:page"); } // test if pageNode is wiki boolean isWiki = false; if (pageNode != null && pageNode.hasProperty("j:templateNode")) { NodeIterator iterator = JCRContentUtils.getDescendantNodes((JCRNodeWrapper) pageNode.getProperty("j:templateNode").getNode(), "jnt:wikiPageFormCreation"); if (iterator.hasNext()) { isWiki = true; } } if (pageNode == null || !isWiki) { return false; } try { JCRNodeWrapper node = pageNode.getNode(newName); String link = request.getContextPath() + request.getServletPath() + "/" + StringUtils.substringBefore( request.getPathInfo().substring(1), "/") + "/" + urlResolver.getWorkspace() + "/" + urlResolver.getLocale() + node.getPath(); link += ".html"; response.sendRedirect(link); } catch (PathNotFoundException e1) { if (null != pageNode) { String link = request.getContextPath() + request.getServletPath() + "/" + StringUtils.substringBefore( request.getPathInfo().substring(1), "/") + "/" + urlResolver.getWorkspace() + "/" + urlResolver.getLocale() + pageNode.getPath(); link += ".html?displayTab=create-new-page&newPageName=" + URLEncoder.encode(newName, "UTF-8"); response.sendRedirect(link); return true; } logger.debug("Wiki page not found ask for creation",e1); } } catch (PathNotFoundException e1) { return false; } } catch (Exception e1) { logger.error(e1.getMessage(), e1); } return false; }
diff --git a/src/org/opensolaris/opengrok/history/BazaarHistoryParser.java b/src/org/opensolaris/opengrok/history/BazaarHistoryParser.java index 58d2f4a..671ad55 100644 --- a/src/org/opensolaris/opengrok/history/BazaarHistoryParser.java +++ b/src/org/opensolaris/opengrok/history/BazaarHistoryParser.java @@ -1,176 +1,177 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ package org.opensolaris.opengrok.history; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.logging.Level; import org.opensolaris.opengrok.OpenGrokLogger; import org.opensolaris.opengrok.configuration.RuntimeEnvironment; import org.opensolaris.opengrok.util.Executor; /** * Parse a stream of Bazaar log comments. */ class BazaarHistoryParser implements HistoryParser, Executor.StreamHandler { private String myDir; private int rootLength; private History history; public History parse(File file, Repository repos) throws HistoryException { myDir = repos.getDirectoryName()+ File.separator; rootLength = RuntimeEnvironment.getInstance().getSourceRootPath().length(); Executor executor = ((BazaarRepository) repos).getHistoryLogExecutor(file); int status = executor.exec(true, this); if (status != 0) { OpenGrokLogger.getLogger().log(Level.INFO, "Failed to get history for: \"" + file.getAbsolutePath() + "\" Exit code: " + status); } return history; } /** * Process the output from the log command and insert the HistoryEntries * into the history field. * * @param input The output from the process * @throws java.io.IOException If an error occurs while reading the stream */ public void processStream(InputStream input) throws IOException { SimpleDateFormat df = new SimpleDateFormat("EEE yyyy-MM-dd hh:mm:ss ZZZZ", Locale.US); ArrayList<HistoryEntry> entries = new ArrayList<HistoryEntry>(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); String s; HistoryEntry entry = null; int state = 0; int ident = 0; while ((s = in.readLine()) != null) { int nident = 0; int len = s.length(); while (nident < len && s.charAt(nident) == ' ') { ++nident; } s = s.trim(); if ("------------------------------------------------------------".equals(s)) { if (entry != null && state == 4) { entries.add(entry); } entry = new HistoryEntry(); entry.setActive(true); state = 0; ident = nident; continue; } switch (state) { case 0: if (ident == nident && s.startsWith("revno:")) { String rev = s.substring("revno:".length()).trim(); entry.setRevision(rev); ++state; } break; case 1: if (ident == nident && s.startsWith("committer:")) { entry.setAuthor(s.substring("committer:".length()).trim()); ++state; } break; case 2: if (ident == nident && s.startsWith("timestamp:")) { try { Date date = df.parse(s.substring("timestamp:".length()).trim()); entry.setDate(date); } catch (ParseException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to parse history timestamp:" + s, e); } ++state; } break; case 3: if (!(ident == nident && s.startsWith("message:"))) { if (ident == nident && (s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:"))) { ++state; } else { entry.appendMessage(s); } } break; case 4: if (!(s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:"))) { int idx = s.indexOf(" => "); if (idx != -1) { s = s.substring(idx + 4); } File f = new File(myDir, s); String name = f.getCanonicalPath().substring(rootLength); entry.addFile(name); } break; default: OpenGrokLogger.getLogger().warning("Unknown parser state: " + state); break; } } if (entry != null && state == 4) { entries.add(entry); } + history = new History(); history.setHistoryEntries(entries); } /** * Parse the given string. * * @param buffer The string to be parsed * @return The parsed history * @throws IOException if we fail to parse the buffer */ public History parse(String buffer) throws IOException { myDir = File.separator; rootLength = 0; processStream(new ByteArrayInputStream(buffer.getBytes("UTF-8"))); return history; } }
true
true
public void processStream(InputStream input) throws IOException { SimpleDateFormat df = new SimpleDateFormat("EEE yyyy-MM-dd hh:mm:ss ZZZZ", Locale.US); ArrayList<HistoryEntry> entries = new ArrayList<HistoryEntry>(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); String s; HistoryEntry entry = null; int state = 0; int ident = 0; while ((s = in.readLine()) != null) { int nident = 0; int len = s.length(); while (nident < len && s.charAt(nident) == ' ') { ++nident; } s = s.trim(); if ("------------------------------------------------------------".equals(s)) { if (entry != null && state == 4) { entries.add(entry); } entry = new HistoryEntry(); entry.setActive(true); state = 0; ident = nident; continue; } switch (state) { case 0: if (ident == nident && s.startsWith("revno:")) { String rev = s.substring("revno:".length()).trim(); entry.setRevision(rev); ++state; } break; case 1: if (ident == nident && s.startsWith("committer:")) { entry.setAuthor(s.substring("committer:".length()).trim()); ++state; } break; case 2: if (ident == nident && s.startsWith("timestamp:")) { try { Date date = df.parse(s.substring("timestamp:".length()).trim()); entry.setDate(date); } catch (ParseException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to parse history timestamp:" + s, e); } ++state; } break; case 3: if (!(ident == nident && s.startsWith("message:"))) { if (ident == nident && (s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:"))) { ++state; } else { entry.appendMessage(s); } } break; case 4: if (!(s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:"))) { int idx = s.indexOf(" => "); if (idx != -1) { s = s.substring(idx + 4); } File f = new File(myDir, s); String name = f.getCanonicalPath().substring(rootLength); entry.addFile(name); } break; default: OpenGrokLogger.getLogger().warning("Unknown parser state: " + state); break; } } if (entry != null && state == 4) { entries.add(entry); } history.setHistoryEntries(entries); }
public void processStream(InputStream input) throws IOException { SimpleDateFormat df = new SimpleDateFormat("EEE yyyy-MM-dd hh:mm:ss ZZZZ", Locale.US); ArrayList<HistoryEntry> entries = new ArrayList<HistoryEntry>(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); String s; HistoryEntry entry = null; int state = 0; int ident = 0; while ((s = in.readLine()) != null) { int nident = 0; int len = s.length(); while (nident < len && s.charAt(nident) == ' ') { ++nident; } s = s.trim(); if ("------------------------------------------------------------".equals(s)) { if (entry != null && state == 4) { entries.add(entry); } entry = new HistoryEntry(); entry.setActive(true); state = 0; ident = nident; continue; } switch (state) { case 0: if (ident == nident && s.startsWith("revno:")) { String rev = s.substring("revno:".length()).trim(); entry.setRevision(rev); ++state; } break; case 1: if (ident == nident && s.startsWith("committer:")) { entry.setAuthor(s.substring("committer:".length()).trim()); ++state; } break; case 2: if (ident == nident && s.startsWith("timestamp:")) { try { Date date = df.parse(s.substring("timestamp:".length()).trim()); entry.setDate(date); } catch (ParseException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to parse history timestamp:" + s, e); } ++state; } break; case 3: if (!(ident == nident && s.startsWith("message:"))) { if (ident == nident && (s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:"))) { ++state; } else { entry.appendMessage(s); } } break; case 4: if (!(s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:"))) { int idx = s.indexOf(" => "); if (idx != -1) { s = s.substring(idx + 4); } File f = new File(myDir, s); String name = f.getCanonicalPath().substring(rootLength); entry.addFile(name); } break; default: OpenGrokLogger.getLogger().warning("Unknown parser state: " + state); break; } } if (entry != null && state == 4) { entries.add(entry); } history = new History(); history.setHistoryEntries(entries); }
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedImportStatementInfo.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedImportStatementInfo.java index f1d8b185..be526770 100644 --- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedImportStatementInfo.java +++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedImportStatementInfo.java @@ -1,183 +1,184 @@ package jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved; import java.util.Collection; import java.util.SortedSet; import java.util.TreeSet; import jp.ac.osaka_u.ist.sel.metricstool.main.data.DataManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.CallableUnitInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ExternalClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FieldInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ImportStatementInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodInfoManager; import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetClassInfo; import jp.ac.osaka_u.ist.sel.metricstool.main.security.MetricsToolSecurityManager; /** * AST�p�[�X�̍ہC�Q�ƌ^�ϐ��̗��p�”\�Ȗ��O��Ԗ��C�܂��͊��S���薼��\���N���X * * @author higo * */ public final class UnresolvedImportStatementInfo extends UnresolvedUnitInfo<ImportStatementInfo> { /** * ���p�”\���O��Ԗ��Ƃ���ȉ��̃N���X�S�ẴN���X�����p�”\���ǂ�����\��boolean��^���ăI�u�W�F�N�g��������. * <p> * import aaa.bbb.ccc.DDD�G // new AvailableNamespace({"aaa","bbb","ccc","DDD"}, false); <br> * import aaa.bbb.ccc.*; // new AvailableNamespace({"aaa","bbb","ccc"},true); <br> * </p> * * @param namespace ���p�”\���O��Ԗ� * @param allClasses �S�ẴN���X�����p�”\���ǂ��� */ public UnresolvedImportStatementInfo(final String[] namespace, final boolean allClasses) { // �s���ȌĂяo���łȂ������`�F�b�N MetricsToolSecurityManager.getInstance().checkAccess(); if (null == namespace) { throw new NullPointerException(); } this.importName = namespace; this.allClasses = allClasses; } /** * �ΏۃI�u�W�F�N�g�Ɠ��������ǂ�����Ԃ� * * @param o �ΏۃI�u�W�F�N�g * @return �������ꍇ true�C�����łȂ��ꍇ false */ @Override public boolean equals(Object o) { if (null == o) { throw new NullPointerException(); } if (!(o instanceof UnresolvedImportStatementInfo)) { return false; } String[] importName = this.getImportName(); String[] correspondImportName = ((UnresolvedImportStatementInfo) o).getImportName(); if (importName.length != correspondImportName.length) { return false; } for (int i = 0; i < importName.length; i++) { if (!importName[i].equals(correspondImportName[i])) { return false; } } return true; } @Override public ImportStatementInfo resolve(final TargetClassInfo usingClass, final CallableUnitInfo usingMethod, final ClassInfoManager classInfoManager, final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) { // �s���ȌĂяo���łȂ������`�F�b�N MetricsToolSecurityManager.getInstance().checkAccess(); if (null == classInfoManager) { throw new NullPointerException(); } // ���ɉ����ς݂ł���ꍇ�́C�L���b�V����Ԃ� if (this.alreadyResolved()) { return this.getResolved(); } final int fromLine = this.getFromLine(); final int fromColumn = this.getFromColumn(); final int toLine = this.getToLine(); final int toColumn = this.getToColumn(); final SortedSet<ClassInfo> accessibleClasses = new TreeSet<ClassInfo>(); if (this.isAllClasses()) { final String[] namespace = this.getNamespace(); final Collection<ClassInfo> specifiedClasses = classInfoManager .getClassInfos(namespace); accessibleClasses.addAll(specifiedClasses); } else { final String[] importName = this.getImportName(); ClassInfo specifiedClass = classInfoManager.getClassInfo(importName); if (null == specifiedClass) { specifiedClass = new ExternalClassInfo(importName); + accessibleClasses.add(specifiedClass); } } this.resolvedInfo = new ImportStatementInfo(fromLine, fromColumn, toLine, toColumn, accessibleClasses); return this.resolvedInfo; } /** * ���O��Ԗ���Ԃ� * * @return ���O��Ԗ� */ public String[] getImportName() { return this.importName; } /** * ���O��Ԗ���Ԃ��D * * @return ���O��Ԗ� */ public String[] getNamespace() { final String[] importName = this.getImportName(); if (this.isAllClasses()) { return importName; } final String[] namespace = new String[importName.length - 1]; System.arraycopy(importName, 0, namespace, 0, importName.length - 1); return namespace; } /** * ���̃I�u�W�F�N�g�̃n�b�V���R�[�h��Ԃ� * * @return ���̃I�u�W�F�N�g�̃n�b�V���R�[�h */ @Override public int hashCode() { int hash = 0; String[] namespace = this.getNamespace(); for (int i = 0; i < namespace.length; i++) { hash += namespace.hashCode(); } return hash; } /** * �S�ẴN���X�����p�”\���ǂ��� * * @return ���p�”\�ł���ꍇ�� true, �����łȂ��ꍇ�� false */ public boolean isAllClasses() { return this.allClasses; } /** * ���O��Ԗ���\���ϐ� */ private final String[] importName; /** * �S�ẴN���X�����p�”\���ǂ�����\���ϐ� */ private final boolean allClasses; }
true
true
public ImportStatementInfo resolve(final TargetClassInfo usingClass, final CallableUnitInfo usingMethod, final ClassInfoManager classInfoManager, final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) { // �s���ȌĂяo���łȂ������`�F�b�N MetricsToolSecurityManager.getInstance().checkAccess(); if (null == classInfoManager) { throw new NullPointerException(); } // ���ɉ����ς݂ł���ꍇ�́C�L���b�V����Ԃ� if (this.alreadyResolved()) { return this.getResolved(); } final int fromLine = this.getFromLine(); final int fromColumn = this.getFromColumn(); final int toLine = this.getToLine(); final int toColumn = this.getToColumn(); final SortedSet<ClassInfo> accessibleClasses = new TreeSet<ClassInfo>(); if (this.isAllClasses()) { final String[] namespace = this.getNamespace(); final Collection<ClassInfo> specifiedClasses = classInfoManager .getClassInfos(namespace); accessibleClasses.addAll(specifiedClasses); } else { final String[] importName = this.getImportName(); ClassInfo specifiedClass = classInfoManager.getClassInfo(importName); if (null == specifiedClass) { specifiedClass = new ExternalClassInfo(importName); } } this.resolvedInfo = new ImportStatementInfo(fromLine, fromColumn, toLine, toColumn, accessibleClasses); return this.resolvedInfo; }
public ImportStatementInfo resolve(final TargetClassInfo usingClass, final CallableUnitInfo usingMethod, final ClassInfoManager classInfoManager, final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) { // �s���ȌĂяo���łȂ������`�F�b�N MetricsToolSecurityManager.getInstance().checkAccess(); if (null == classInfoManager) { throw new NullPointerException(); } // ���ɉ����ς݂ł���ꍇ�́C�L���b�V����Ԃ� if (this.alreadyResolved()) { return this.getResolved(); } final int fromLine = this.getFromLine(); final int fromColumn = this.getFromColumn(); final int toLine = this.getToLine(); final int toColumn = this.getToColumn(); final SortedSet<ClassInfo> accessibleClasses = new TreeSet<ClassInfo>(); if (this.isAllClasses()) { final String[] namespace = this.getNamespace(); final Collection<ClassInfo> specifiedClasses = classInfoManager .getClassInfos(namespace); accessibleClasses.addAll(specifiedClasses); } else { final String[] importName = this.getImportName(); ClassInfo specifiedClass = classInfoManager.getClassInfo(importName); if (null == specifiedClass) { specifiedClass = new ExternalClassInfo(importName); accessibleClasses.add(specifiedClass); } } this.resolvedInfo = new ImportStatementInfo(fromLine, fromColumn, toLine, toColumn, accessibleClasses); return this.resolvedInfo; }
diff --git a/bndtools.core/src/bndtools/editor/model/conversions/EnumFormatter.java b/bndtools.core/src/bndtools/editor/model/conversions/EnumFormatter.java index 0bbafc8b..d164f9f9 100644 --- a/bndtools.core/src/bndtools/editor/model/conversions/EnumFormatter.java +++ b/bndtools.core/src/bndtools/editor/model/conversions/EnumFormatter.java @@ -1,54 +1,54 @@ package bndtools.editor.model.conversions; /** * Formats an enum type. Outputs {@code null} when the value of the enum is * equal to a default value. * * @param <E> * @author Neil Bartlett */ public class EnumFormatter<E extends Enum<E>> implements Converter<String, E> { private final Class<E> enumType; private final E defaultValue; /** * Construct a new formatter with no default value, i.e. any non-null value * of the enum will print that value. * * @param enumType * The enum type. * @return */ public static <E extends Enum<E>> EnumFormatter<E> create(Class<E> enumType) { return new EnumFormatter<E>(enumType, null); } /** * Construct a new formatter with the specified default value. * * @param enumType * The enum type. * @param defaultValue * The default value, which will never be output. * @return */ public static <E extends Enum<E>> EnumFormatter<E> create(Class<E> enumType, E defaultValue) { return new EnumFormatter<E>(enumType, defaultValue); } private EnumFormatter(Class<E> enumType, E defaultValue) { this.enumType = enumType; this.defaultValue = defaultValue; } public String convert(E input) throws IllegalArgumentException { String result; if (input == defaultValue) result = null; else - result = input.toString(); + result = input != null ? input.toString() : null; return result; } }
true
true
public String convert(E input) throws IllegalArgumentException { String result; if (input == defaultValue) result = null; else result = input.toString(); return result; }
public String convert(E input) throws IllegalArgumentException { String result; if (input == defaultValue) result = null; else result = input != null ? input.toString() : null; return result; }
diff --git a/GuerraVaixellsMylyn/src/Tauler.java b/GuerraVaixellsMylyn/src/Tauler.java index 388fed3..f043644 100644 --- a/GuerraVaixellsMylyn/src/Tauler.java +++ b/GuerraVaixellsMylyn/src/Tauler.java @@ -1,64 +1,64 @@ public class Tauler { int alc, ampl; Casella casella [][]; public Tauler(int amplada, int alcada) { alc=alcada; ampl=amplada; casella = new Casella[alc][ampl]; FerTotAigua(); } public void FerTotAigua() { for(int i=0;i<alc;++i) for(int j=0;j<ampl;++j) casella[i][j]=Casella.AIGUA; } public boolean ColocarVaixell(int y, int x, Vaixell v) { - int incrX=0; + int incrX=0 ; int incrY=0; switch (v.getOrientacio()) { case V: incrX=0; incrY=1; break; case H: incrX=1; incrY=0; break; } // Copiem el vaixell int xPointer=x; int yPointer=y; for(int i=0;i<v.getMida();++i) { casella[yPointer][xPointer]=Casella.VAIXELL; yPointer+=incrY; xPointer+=incrX; } return true; } public Casella Tret(int x, int y) { } }
true
true
public boolean ColocarVaixell(int y, int x, Vaixell v) { int incrX=0; int incrY=0; switch (v.getOrientacio()) { case V: incrX=0; incrY=1; break; case H: incrX=1; incrY=0; break; } // Copiem el vaixell int xPointer=x; int yPointer=y; for(int i=0;i<v.getMida();++i) { casella[yPointer][xPointer]=Casella.VAIXELL; yPointer+=incrY; xPointer+=incrX; } return true; }
public boolean ColocarVaixell(int y, int x, Vaixell v) { int incrX=0 ; int incrY=0; switch (v.getOrientacio()) { case V: incrX=0; incrY=1; break; case H: incrX=1; incrY=0; break; } // Copiem el vaixell int xPointer=x; int yPointer=y; for(int i=0;i<v.getMida();++i) { casella[yPointer][xPointer]=Casella.VAIXELL; yPointer+=incrY; xPointer+=incrX; } return true; }
diff --git a/src/com/neuron/trafikanten/tasks/SearchAddressTask.java b/src/com/neuron/trafikanten/tasks/SearchAddressTask.java index e794f44..5251548 100644 --- a/src/com/neuron/trafikanten/tasks/SearchAddressTask.java +++ b/src/com/neuron/trafikanten/tasks/SearchAddressTask.java @@ -1,172 +1,172 @@ package com.neuron.trafikanten.tasks; import java.io.IOException; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.location.Address; import android.location.Geocoder; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.View.OnKeyListener; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.neuron.trafikanten.R; import com.neuron.trafikanten.tasks.handlers.ReturnCoordinatesHandler; public class SearchAddressTask implements GenericTask { private static final String TAG = "Trafikanten-SearchAddressTask"; private Activity activity; private List<Address> addresses; ReturnCoordinatesHandler handler; private Dialog dialog; public SearchAddressTask(Activity activity, ReturnCoordinatesHandler handler) { this.activity = activity; this.handler = handler; showAddressField(); } /* * Show the address field dialog and wait for input */ private void showAddressField() { dialog = new Dialog(activity); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_searchaddress); final TextView message = (TextView) dialog.findViewById(R.id.message); message.setText(R.string.searchAddressTask); final EditText searchEdit = (EditText) dialog.findViewById(R.id.search); searchEdit.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() != KeyEvent.ACTION_DOWN) { return false; } switch (keyCode) { case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_DPAD_CENTER: dialog.dismiss(); geoMap(searchEdit.getText().toString()); return true; } return false; } }); /* * Handler onCancel */ dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { handler.onCanceled(); } }); dialog.show(); } private void showAddressSelection() { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.searchAddressTask); /* * First take all addresses, convert them into strings and check for duplicates. */ ArrayList<String> addressStrings = new ArrayList<String>(); for(Address address : addresses) { Log.d(TAG,"Got address " + address.toString()); String result = address.getAddressLine(0); for (int i = 1; i <= address.getMaxAddressLineIndex(); i++) { result = result + ", " + address.getAddressLine(i); } if (!addressStrings.contains(result)) { addressStrings.add(result); } } /* * Then convert it into the array setItems wants */ final String[] items = new String[addressStrings.size()]; addressStrings.toArray(items); /* * Then search for the address */ builder.setItems(items, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - SearchAddressTask.this.foundLocation(addresses.get(which + 1)); + SearchAddressTask.this.foundLocation(addresses.get(which)); } }); dialog = builder.create(); /* * Handler onCancel */ dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { handler.onCanceled(); } }); dialog.show(); } /* * Do geo mapping. */ private void geoMap(String searchAddress) { final Geocoder geocoder = new Geocoder(activity); try { addresses = geocoder.getFromLocationName(searchAddress, 10, 57, 3, 71, 32); switch(addresses.size()) { case 0: Toast.makeText(activity, R.string.failedToFindAddress, Toast.LENGTH_SHORT).show(); handler.onCanceled(); break; case 1: foundLocation(addresses.get(0)); break; default: showAddressSelection(); break; } } catch (IOException e) { /* * Pass exceptions to parent */ handler.onError(e); } } private void foundLocation(Address location) { handler.onFinished(location.getLatitude(), location.getLongitude()); } @Override public void stop() { handler.onCanceled(); dialog.dismiss(); } }
true
true
private void showAddressSelection() { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.searchAddressTask); /* * First take all addresses, convert them into strings and check for duplicates. */ ArrayList<String> addressStrings = new ArrayList<String>(); for(Address address : addresses) { Log.d(TAG,"Got address " + address.toString()); String result = address.getAddressLine(0); for (int i = 1; i <= address.getMaxAddressLineIndex(); i++) { result = result + ", " + address.getAddressLine(i); } if (!addressStrings.contains(result)) { addressStrings.add(result); } } /* * Then convert it into the array setItems wants */ final String[] items = new String[addressStrings.size()]; addressStrings.toArray(items); /* * Then search for the address */ builder.setItems(items, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SearchAddressTask.this.foundLocation(addresses.get(which + 1)); } }); dialog = builder.create(); /* * Handler onCancel */ dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { handler.onCanceled(); } }); dialog.show(); }
private void showAddressSelection() { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.searchAddressTask); /* * First take all addresses, convert them into strings and check for duplicates. */ ArrayList<String> addressStrings = new ArrayList<String>(); for(Address address : addresses) { Log.d(TAG,"Got address " + address.toString()); String result = address.getAddressLine(0); for (int i = 1; i <= address.getMaxAddressLineIndex(); i++) { result = result + ", " + address.getAddressLine(i); } if (!addressStrings.contains(result)) { addressStrings.add(result); } } /* * Then convert it into the array setItems wants */ final String[] items = new String[addressStrings.size()]; addressStrings.toArray(items); /* * Then search for the address */ builder.setItems(items, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SearchAddressTask.this.foundLocation(addresses.get(which)); } }); dialog = builder.create(); /* * Handler onCancel */ dialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { handler.onCanceled(); } }); dialog.show(); }
diff --git a/src/main/java/com/tenfood/api/ApiHandler.java b/src/main/java/com/tenfood/api/ApiHandler.java index 53abbfa..9ce6fbf 100644 --- a/src/main/java/com/tenfood/api/ApiHandler.java +++ b/src/main/java/com/tenfood/api/ApiHandler.java @@ -1,48 +1,48 @@ package com.tenfood.api; import java.io.IOException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.*; import com.tenfood.api.service.FlickrService; import org.codehaus.jackson.map.ObjectMapper; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.*; import com.tenfood.api.resource.PhotoResource; public class ApiHandler extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Context context = new Context(); String path = req.getRequestURI(); Map<String, String[]> queryMap = req.getParameterMap(); context.setQueryMap(queryMap); Object result = null; if ( path.equals("/photo") ) { PhotoResource resource = new PhotoResource(new FlickrService()); result = resource.getPhotos(context); } - resp.getWriter().println("{ \"photos\": {"); + resp.getWriter().println("{ \"photos\": "); resp.getWriter().println(new ObjectMapper().writeValueAsString(result)); - resp.getWriter().println("} ,"); + resp.getWriter().println(","); resp.getWriter().println("\"context\": {"); resp.getWriter().println(new ObjectMapper().writeValueAsString(context.getMessages())); resp.getWriter().println("}}"); } public static void main(String[] args) throws Exception{ Server server = new Server(Integer.valueOf(System.getenv("PORT"))); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new ApiHandler()),"/*"); server.start(); server.join(); } }
false
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Context context = new Context(); String path = req.getRequestURI(); Map<String, String[]> queryMap = req.getParameterMap(); context.setQueryMap(queryMap); Object result = null; if ( path.equals("/photo") ) { PhotoResource resource = new PhotoResource(new FlickrService()); result = resource.getPhotos(context); } resp.getWriter().println("{ \"photos\": {"); resp.getWriter().println(new ObjectMapper().writeValueAsString(result)); resp.getWriter().println("} ,"); resp.getWriter().println("\"context\": {"); resp.getWriter().println(new ObjectMapper().writeValueAsString(context.getMessages())); resp.getWriter().println("}}"); }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Context context = new Context(); String path = req.getRequestURI(); Map<String, String[]> queryMap = req.getParameterMap(); context.setQueryMap(queryMap); Object result = null; if ( path.equals("/photo") ) { PhotoResource resource = new PhotoResource(new FlickrService()); result = resource.getPhotos(context); } resp.getWriter().println("{ \"photos\": "); resp.getWriter().println(new ObjectMapper().writeValueAsString(result)); resp.getWriter().println(","); resp.getWriter().println("\"context\": {"); resp.getWriter().println(new ObjectMapper().writeValueAsString(context.getMessages())); resp.getWriter().println("}}"); }
diff --git a/src/com/modcrafting/ultrabans/commands/Fine.java b/src/com/modcrafting/ultrabans/commands/Fine.java index 83b414f..3865881 100644 --- a/src/com/modcrafting/ultrabans/commands/Fine.java +++ b/src/com/modcrafting/ultrabans/commands/Fine.java @@ -1,157 +1,156 @@ package com.modcrafting.ultrabans.commands; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import com.modcrafting.ultrabans.UltraBan; public class Fine implements CommandExecutor{ public static final Logger log = Logger.getLogger("Minecraft"); UltraBan plugin; public Fine(UltraBan ultraBan) { this.plugin = ultraBan; } public boolean autoComplete; public String expandName(String p) { int m = 0; String Result = ""; for (int n = 0; n < plugin.getServer().getOnlinePlayers().length; n++) { String str = plugin.getServer().getOnlinePlayers()[n].getName(); if (str.matches("(?i).*" + p + ".*")) { m++; Result = str; if(m==2) { return null; } } if (str.equalsIgnoreCase(p)) return str; } if (m == 1) return Result; if (m > 1) { return null; } if (m < 1) { return p; } return p; } public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); if(!plugin.useFines) return true; boolean auth = false; Player player = null; String admin = config.getString("defAdminName", "server"); if (sender instanceof Player){ player = (Player)sender; //new permissions test before reconstruct if (plugin.setupPermissions()){ if (plugin.permission.has(player, "ultraban.fine")) auth = true; }else{ sender.sendMessage(ChatColor.RED + "You do not have the required dependancy: Vault."); return true; // if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node } admin = player.getName(); }else{ auth = true; //if sender is not a player - Console } if (!auth){ sender.sendMessage(ChatColor.RED + "You do not have the required permissions."); return true; } if (args.length < 1) return false; String p = args[0]; if(autoComplete) p = expandName(p); Player victim = plugin.getServer().getPlayer(p); boolean broadcast = true; String amt = args[1]; //set string amount to argument //Going loud if(args.length > 1){ if(args[1].equalsIgnoreCase("-s")){ broadcast = false; amt = combineSplit(2, args, " "); }else{ amt = combineSplit(1, args, " "); } } if(victim != null){ if(!broadcast){ //If silent wake his ass up String fineMsg = config.getString("messages.fineMsgVictim", "You have been fined by %admin% in the amount of %amt%!"); String idoit = victim.getName(); fineMsg = fineMsg.replaceAll("%admin%", admin); fineMsg = fineMsg.replaceAll("%amt%", amt); fineMsg = fineMsg.replaceAll("%victim%", idoit); sender.sendMessage(formatMessage(":S:" + fineMsg)); victim.sendMessage(formatMessage(fineMsg)); } if(plugin.setupEconomy()){ double bal = plugin.economy.getBalance(p); double amtd = Double.valueOf(amt.trim()); int max = config.getInt("maxFineAmt", 0); if (max == 0){ if(amtd > bal){ plugin.economy.withdrawPlayer(victim.getName(), bal); }else{ plugin.economy.withdrawPlayer(victim.getName(), amtd); } }else{ double maxd = Double.valueOf(Integer.toString(max).trim()); if(maxd > amtd){ - //TODO Set Message Config for Overfine - sender.sendMessage("Example"); + sender.sendMessage(ChatColor.RED + "Max Allowable Fine: " + String.valueOf(max)); }else{ if(amtd > bal){ plugin.economy.withdrawPlayer(victim.getName(), bal); }else{ plugin.economy.withdrawPlayer(victim.getName(), amtd); } } } } log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + "."); plugin.db.addPlayer(p, amt, admin, 0, 4); if(broadcast){ String idoit = victim.getName(); String fineMsgAll = config.getString("messages.fineMsgBroadcast", "%victim% was fined by %admin% in the amount of %amt%!!"); fineMsgAll = fineMsgAll.replaceAll("%admin%", admin); fineMsgAll = fineMsgAll.replaceAll("%amt%", amt); fineMsgAll = fineMsgAll.replaceAll("%victim%", idoit); plugin.getServer().broadcastMessage(formatMessage(fineMsgAll)); return true; } return true; }else{ sender.sendMessage(ChatColor.GRAY + "Player must be online!"); return true; } } public String combineSplit(int startIndex, String[] string, String seperator) { StringBuilder builder = new StringBuilder(); for (int i = startIndex; i < string.length; i++) { builder.append(string[i]); builder.append(seperator); } builder.deleteCharAt(builder.length() - seperator.length()); // remove return builder.toString(); } public String formatMessage(String str){ String funnyChar = new Character((char) 167).toString(); str = str.replaceAll("&", funnyChar); return str; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); if(!plugin.useFines) return true; boolean auth = false; Player player = null; String admin = config.getString("defAdminName", "server"); if (sender instanceof Player){ player = (Player)sender; //new permissions test before reconstruct if (plugin.setupPermissions()){ if (plugin.permission.has(player, "ultraban.fine")) auth = true; }else{ sender.sendMessage(ChatColor.RED + "You do not have the required dependancy: Vault."); return true; // if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node } admin = player.getName(); }else{ auth = true; //if sender is not a player - Console } if (!auth){ sender.sendMessage(ChatColor.RED + "You do not have the required permissions."); return true; } if (args.length < 1) return false; String p = args[0]; if(autoComplete) p = expandName(p); Player victim = plugin.getServer().getPlayer(p); boolean broadcast = true; String amt = args[1]; //set string amount to argument //Going loud if(args.length > 1){ if(args[1].equalsIgnoreCase("-s")){ broadcast = false; amt = combineSplit(2, args, " "); }else{ amt = combineSplit(1, args, " "); } } if(victim != null){ if(!broadcast){ //If silent wake his ass up String fineMsg = config.getString("messages.fineMsgVictim", "You have been fined by %admin% in the amount of %amt%!"); String idoit = victim.getName(); fineMsg = fineMsg.replaceAll("%admin%", admin); fineMsg = fineMsg.replaceAll("%amt%", amt); fineMsg = fineMsg.replaceAll("%victim%", idoit); sender.sendMessage(formatMessage(":S:" + fineMsg)); victim.sendMessage(formatMessage(fineMsg)); } if(plugin.setupEconomy()){ double bal = plugin.economy.getBalance(p); double amtd = Double.valueOf(amt.trim()); int max = config.getInt("maxFineAmt", 0); if (max == 0){ if(amtd > bal){ plugin.economy.withdrawPlayer(victim.getName(), bal); }else{ plugin.economy.withdrawPlayer(victim.getName(), amtd); } }else{ double maxd = Double.valueOf(Integer.toString(max).trim()); if(maxd > amtd){ //TODO Set Message Config for Overfine sender.sendMessage("Example"); }else{ if(amtd > bal){ plugin.economy.withdrawPlayer(victim.getName(), bal); }else{ plugin.economy.withdrawPlayer(victim.getName(), amtd); } } } } log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + "."); plugin.db.addPlayer(p, amt, admin, 0, 4); if(broadcast){ String idoit = victim.getName(); String fineMsgAll = config.getString("messages.fineMsgBroadcast", "%victim% was fined by %admin% in the amount of %amt%!!"); fineMsgAll = fineMsgAll.replaceAll("%admin%", admin); fineMsgAll = fineMsgAll.replaceAll("%amt%", amt); fineMsgAll = fineMsgAll.replaceAll("%victim%", idoit); plugin.getServer().broadcastMessage(formatMessage(fineMsgAll)); return true; } return true; }else{ sender.sendMessage(ChatColor.GRAY + "Player must be online!"); return true; } }
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); if(!plugin.useFines) return true; boolean auth = false; Player player = null; String admin = config.getString("defAdminName", "server"); if (sender instanceof Player){ player = (Player)sender; //new permissions test before reconstruct if (plugin.setupPermissions()){ if (plugin.permission.has(player, "ultraban.fine")) auth = true; }else{ sender.sendMessage(ChatColor.RED + "You do not have the required dependancy: Vault."); return true; // if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node } admin = player.getName(); }else{ auth = true; //if sender is not a player - Console } if (!auth){ sender.sendMessage(ChatColor.RED + "You do not have the required permissions."); return true; } if (args.length < 1) return false; String p = args[0]; if(autoComplete) p = expandName(p); Player victim = plugin.getServer().getPlayer(p); boolean broadcast = true; String amt = args[1]; //set string amount to argument //Going loud if(args.length > 1){ if(args[1].equalsIgnoreCase("-s")){ broadcast = false; amt = combineSplit(2, args, " "); }else{ amt = combineSplit(1, args, " "); } } if(victim != null){ if(!broadcast){ //If silent wake his ass up String fineMsg = config.getString("messages.fineMsgVictim", "You have been fined by %admin% in the amount of %amt%!"); String idoit = victim.getName(); fineMsg = fineMsg.replaceAll("%admin%", admin); fineMsg = fineMsg.replaceAll("%amt%", amt); fineMsg = fineMsg.replaceAll("%victim%", idoit); sender.sendMessage(formatMessage(":S:" + fineMsg)); victim.sendMessage(formatMessage(fineMsg)); } if(plugin.setupEconomy()){ double bal = plugin.economy.getBalance(p); double amtd = Double.valueOf(amt.trim()); int max = config.getInt("maxFineAmt", 0); if (max == 0){ if(amtd > bal){ plugin.economy.withdrawPlayer(victim.getName(), bal); }else{ plugin.economy.withdrawPlayer(victim.getName(), amtd); } }else{ double maxd = Double.valueOf(Integer.toString(max).trim()); if(maxd > amtd){ sender.sendMessage(ChatColor.RED + "Max Allowable Fine: " + String.valueOf(max)); }else{ if(amtd > bal){ plugin.economy.withdrawPlayer(victim.getName(), bal); }else{ plugin.economy.withdrawPlayer(victim.getName(), amtd); } } } } log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + "."); plugin.db.addPlayer(p, amt, admin, 0, 4); if(broadcast){ String idoit = victim.getName(); String fineMsgAll = config.getString("messages.fineMsgBroadcast", "%victim% was fined by %admin% in the amount of %amt%!!"); fineMsgAll = fineMsgAll.replaceAll("%admin%", admin); fineMsgAll = fineMsgAll.replaceAll("%amt%", amt); fineMsgAll = fineMsgAll.replaceAll("%victim%", idoit); plugin.getServer().broadcastMessage(formatMessage(fineMsgAll)); return true; } return true; }else{ sender.sendMessage(ChatColor.GRAY + "Player must be online!"); return true; } }
diff --git a/xjc/src/com/sun/tools/xjc/reader/dtd/bindinfo/DTDExtensionBindingChecker.java b/xjc/src/com/sun/tools/xjc/reader/dtd/bindinfo/DTDExtensionBindingChecker.java index 5feb081d..5dbc5647 100644 --- a/xjc/src/com/sun/tools/xjc/reader/dtd/bindinfo/DTDExtensionBindingChecker.java +++ b/xjc/src/com/sun/tools/xjc/reader/dtd/bindinfo/DTDExtensionBindingChecker.java @@ -1,61 +1,64 @@ package com.sun.tools.xjc.reader.dtd.bindinfo; import com.sun.tools.xjc.Options; import com.sun.tools.xjc.reader.AbstractExtensionBindingChecker; import com.sun.tools.xjc.reader.Const; import org.xml.sax.Attributes; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; /** * {@link XMLFilter} that checks the use of extension namespace URIs * (to see if they have corresponding plugins), and otherwise report an error. * * <p> * This code also masks the recognized extensions from the validator that * will be plugged as the next component to this. * * @author Kohsuke Kawaguchi */ final class DTDExtensionBindingChecker extends AbstractExtensionBindingChecker { public DTDExtensionBindingChecker(String schemaLanguage, Options options, ErrorHandler handler) { super(schemaLanguage, options, handler); } /** * Returns true if the elements with the given namespace URI * should be blocked by this filter. */ private boolean needsToBePruned( String uri ) { if( uri.equals(schemaLanguage) ) return false; if( uri.equals(Const.JAXB_NSURI) ) return false; if( uri.equals(Const.XJC_EXTENSION_URI) ) return false; // we don't want validator to see extensions that we understand , // because they will complain. // OTOH, if this is an extension that we didn't understand, // we want the validator to report an error return enabledExtensions.contains(uri); } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if( !isCutting() ) { - checkAndEnable(uri); + if(!uri.equals("")) { + // "" is the standard namespace + checkAndEnable(uri); - verifyTagName(uri, localName, qName); + verifyTagName(uri, localName, qName); - if(needsToBePruned(uri)) - startCutting(); + if(needsToBePruned(uri)) + startCutting(); + } } super.startElement(uri, localName, qName, atts); } }
false
true
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if( !isCutting() ) { checkAndEnable(uri); verifyTagName(uri, localName, qName); if(needsToBePruned(uri)) startCutting(); } super.startElement(uri, localName, qName, atts); }
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if( !isCutting() ) { if(!uri.equals("")) { // "" is the standard namespace checkAndEnable(uri); verifyTagName(uri, localName, qName); if(needsToBePruned(uri)) startCutting(); } } super.startElement(uri, localName, qName, atts); }
diff --git a/illaclient/src/illarion/client/gui/GUIInventoryHandler.java b/illaclient/src/illarion/client/gui/GUIInventoryHandler.java index 9af87edc..d43e7c0f 100644 --- a/illaclient/src/illarion/client/gui/GUIInventoryHandler.java +++ b/illaclient/src/illarion/client/gui/GUIInventoryHandler.java @@ -1,249 +1,249 @@ /* * This file is part of the Illarion Client. * * Copyright © 2011 - Illarion e.V. * * The Illarion Client is free software: you can redistribute i 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. * * The Illarion Client 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 * the Illarion Client. If not, see <http://www.gnu.org/licenses/>. */ package illarion.client.gui; import illarion.client.graphics.Item; import illarion.client.net.server.events.InventoryUpdateEvent; import illarion.client.resources.ItemFactory; import illarion.client.world.Inventory; import illarion.client.world.World; import org.bushe.swing.event.EventBus; import org.bushe.swing.event.EventSubscriber; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.NiftyEventSubscriber; import de.lessvoid.nifty.builder.ImageBuilder; import de.lessvoid.nifty.controls.DraggableDragCanceledEvent; import de.lessvoid.nifty.controls.DraggableDragStartedEvent; import de.lessvoid.nifty.controls.DroppableDroppedEvent; import de.lessvoid.nifty.controls.dragndrop.builder.DraggableBuilder; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.elements.render.ImageRenderer; import de.lessvoid.nifty.render.NiftyImage; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.tools.SizeValue; /** * This handler takes care for showing and hiding objects in the inventory. Also * it monitors all dropping operations on the slots of the inventory. * * @author Martin Karing &lt;[email protected]&gt; */ public class GUIInventoryHandler implements EventSubscriber<InventoryUpdateEvent> { private final String[] slots; private final Element[] dropSlots; private Element inventoryWindow; private Nifty activeNifty; private Screen activeScreen; private static final String INVSLOT_HEAD = "invslot_"; private static final String SLOTITEM_TAIL = "_item"; private static final String SLOTITEMIMAGE_TAIL = "_itemimage"; public GUIInventoryHandler() { slots = new String[Inventory.SLOT_COUNT]; slots[0] = "bag"; slots[1] = "head"; slots[2] = "neck"; slots[3] = "chest"; slots[4] = "hands"; slots[5] = "lhand"; slots[6] = "rhand"; slots[7] = "lfinger"; slots[8] = "rfinger"; slots[9] = "legs"; slots[10] = "feet"; slots[11] = "cloak"; slots[12] = "belt1"; slots[13] = "belt2"; slots[14] = "belt3"; slots[15] = "belt4"; slots[16] = "belt5"; slots[17] = "belt6"; for (int i = 0; i < Inventory.SLOT_COUNT; i++) { slots[i] = INVSLOT_HEAD.concat(slots[i]); } dropSlots = new Element[Inventory.SLOT_COUNT]; } public void bind(final Nifty nifty, final Screen screen) { activeNifty = nifty; activeScreen = screen; inventoryWindow = screen.findElementByName("inventory"); for (int i = 0; i < Inventory.SLOT_COUNT; i++) { dropSlots[i] = inventoryWindow.findElementByName(slots[i]); } activeNifty.subscribeAnnotations(this); EventBus.subscribe(InventoryUpdateEvent.class, this); } public void showInventory() { if (inventoryWindow != null) { inventoryWindow.setVisible(true); } } public void hideInventory() { if (inventoryWindow != null) { inventoryWindow.setVisible(false); } } @NiftyEventSubscriber(pattern = INVSLOT_HEAD + ".*") public void dropInInventory(final String topic, final DroppableDroppedEvent data) { final int slotId = getSlotNumber(topic); System.out.println("Drop in Inventory: " + topic); World.getInteractionManager().dropAtInventory(slotId); } @NiftyEventSubscriber(pattern = INVSLOT_HEAD + ".*") public void dragFromInventory(final String topic, final DraggableDragStartedEvent data) { final int slotId = getSlotNumber(topic); System.out.println("Drag from Inventory: " + topic); World.getInteractionManager().notifyDraggingInventory(slotId); } @NiftyEventSubscriber(pattern = INVSLOT_HEAD + ".*") public void dragFromInventory(final String topic, final DraggableDragCanceledEvent data) { System.out.println("Cancel dragging!"); World.getInteractionManager().cancelDragging(); } private int getSlotNumber(final String name) { for (int i = 0; i < Inventory.SLOT_COUNT; i++) { if (name.startsWith(slots[i])) { return i; } } return -1; } public void setSlotItem(final int slotId, final int itemId, final int count) { if (slotId < 0 || slotId >= Inventory.SLOT_COUNT) { throw new IllegalArgumentException("Slot ID out of valid range."); } final Element dragObject = getSlotItem(slotId, (itemId > 0)); if (itemId > 0) { applyImageToDragSpot(dragObject, slotId, itemId, count); } else if (dragObject != null) { dragObject.markForRemoval(); } } private Element getSlotItem(final int slotId, final boolean create) { final String slotItemName = slots[slotId].concat(SLOTITEM_TAIL); final String slotItemImageName = slots[slotId].concat(SLOTITEMIMAGE_TAIL); Element result = dropSlots[slotId].findElementByName(slotItemName); if (result == null && create) { final Element dragParent = dropSlots[slotId].findElementByName("#droppableContent"); DraggableBuilder dragBuilder = new DraggableBuilder(slotItemName); dragBuilder.alignCenter(); dragBuilder.valignCenter(); dragBuilder.visibleToMouse(); dragBuilder.visible(true); dragBuilder.childLayoutCenter(); dragBuilder.revert(true); dragBuilder.drop(true); dragBuilder.x("0px"); dragBuilder.y("0px"); ImageBuilder imgBuilder = new ImageBuilder(slotItemImageName); dragBuilder.image(imgBuilder); imgBuilder.alignCenter(); imgBuilder.valignCenter(); imgBuilder.x("0px"); imgBuilder.y("0px"); result = dragBuilder .build(activeNifty, activeScreen, dragParent); } return result; } private void applyImageToDragSpot(final Element dragElement, final int slotId, final int itemId, final int count) { final String slotItemImageName = slots[slotId].concat(SLOTITEMIMAGE_TAIL); final Element image = dragElement.findElementByName(slotItemImageName); final Item displayedItem = ItemFactory.getInstance() .getPrototype(itemId); image.getRenderer(ImageRenderer.class).setImage( new NiftyImage(activeNifty.getRenderEngine(), new EntitySlickRenderImage(displayedItem))); final int objectWidth = displayedItem.getWidth(); final int objectHeight = displayedItem.getHeight(); final int parentWidth = dropSlots[slotId].getWidth(); final int parentHeight = dropSlots[slotId].getHeight(); int fixedWidth = objectWidth; int fixedHeight = objectHeight; if (fixedWidth > parentWidth) { - fixedHeight *= (parentWidth / fixedWidth); + fixedHeight *= ((float) parentWidth / fixedWidth); fixedWidth = parentWidth; } if (fixedHeight > parentHeight) { - fixedWidth *= (parentHeight / fixedHeight); + fixedWidth *= ((float) parentHeight / fixedHeight); fixedHeight = parentHeight; } final SizeValue width = generateSizeValue(fixedWidth); final SizeValue height = generateSizeValue(fixedHeight); image.setConstraintWidth(width); image.setConstraintHeight(height); dragElement.setConstraintWidth(width); dragElement.setConstraintHeight(height); dropSlots[slotId].layoutElements(); } private SizeValue generateSizeValue(final int pixels) { return new SizeValue(Integer.toString(pixels).concat("px")); } /** * Fired upon the inventory publishing a update event. * * @param topic the topic of the publisher * @param data the published data */ @Override public void onEvent(final InventoryUpdateEvent data) { setSlotItem(data.getSlotId(), data.getItemId(), data.getCount()); } }
false
true
private void applyImageToDragSpot(final Element dragElement, final int slotId, final int itemId, final int count) { final String slotItemImageName = slots[slotId].concat(SLOTITEMIMAGE_TAIL); final Element image = dragElement.findElementByName(slotItemImageName); final Item displayedItem = ItemFactory.getInstance() .getPrototype(itemId); image.getRenderer(ImageRenderer.class).setImage( new NiftyImage(activeNifty.getRenderEngine(), new EntitySlickRenderImage(displayedItem))); final int objectWidth = displayedItem.getWidth(); final int objectHeight = displayedItem.getHeight(); final int parentWidth = dropSlots[slotId].getWidth(); final int parentHeight = dropSlots[slotId].getHeight(); int fixedWidth = objectWidth; int fixedHeight = objectHeight; if (fixedWidth > parentWidth) { fixedHeight *= (parentWidth / fixedWidth); fixedWidth = parentWidth; } if (fixedHeight > parentHeight) { fixedWidth *= (parentHeight / fixedHeight); fixedHeight = parentHeight; } final SizeValue width = generateSizeValue(fixedWidth); final SizeValue height = generateSizeValue(fixedHeight); image.setConstraintWidth(width); image.setConstraintHeight(height); dragElement.setConstraintWidth(width); dragElement.setConstraintHeight(height); dropSlots[slotId].layoutElements(); }
private void applyImageToDragSpot(final Element dragElement, final int slotId, final int itemId, final int count) { final String slotItemImageName = slots[slotId].concat(SLOTITEMIMAGE_TAIL); final Element image = dragElement.findElementByName(slotItemImageName); final Item displayedItem = ItemFactory.getInstance() .getPrototype(itemId); image.getRenderer(ImageRenderer.class).setImage( new NiftyImage(activeNifty.getRenderEngine(), new EntitySlickRenderImage(displayedItem))); final int objectWidth = displayedItem.getWidth(); final int objectHeight = displayedItem.getHeight(); final int parentWidth = dropSlots[slotId].getWidth(); final int parentHeight = dropSlots[slotId].getHeight(); int fixedWidth = objectWidth; int fixedHeight = objectHeight; if (fixedWidth > parentWidth) { fixedHeight *= ((float) parentWidth / fixedWidth); fixedWidth = parentWidth; } if (fixedHeight > parentHeight) { fixedWidth *= ((float) parentHeight / fixedHeight); fixedHeight = parentHeight; } final SizeValue width = generateSizeValue(fixedWidth); final SizeValue height = generateSizeValue(fixedHeight); image.setConstraintWidth(width); image.setConstraintHeight(height); dragElement.setConstraintWidth(width); dragElement.setConstraintHeight(height); dropSlots[slotId].layoutElements(); }
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/party/panes/CreateVendorPane.java b/OpERP/src/main/java/devopsdistilled/operp/client/party/panes/CreateVendorPane.java index 24fbbe12..273c2293 100644 --- a/OpERP/src/main/java/devopsdistilled/operp/client/party/panes/CreateVendorPane.java +++ b/OpERP/src/main/java/devopsdistilled/operp/client/party/panes/CreateVendorPane.java @@ -1,66 +1,66 @@ package devopsdistilled.operp.client.party.panes; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; import devopsdistilled.operp.client.abstracts.SubTaskPane; import devopsdistilled.operp.client.party.panes.models.observers.CreateVendorPaneModelObserver; public class CreateVendorPane extends SubTaskPane implements CreateVendorPaneModelObserver { private final JPanel pane; private final JTextField nameField; private final JTextField panVatField; private final JButton btnCancel; private final JButton btnCreate; public CreateVendorPane() { pane = new JPanel(); - pane.setLayout(new MigLayout("debug", "[][grow]", "[][][grow][]")); + pane.setLayout(new MigLayout("", "[][grow]", "[][][grow][]")); JLabel lblVendorName = new JLabel("Vendor Name"); pane.add(lblVendorName, "cell 0 0,alignx trailing"); nameField = new JTextField(); pane.add(nameField, "cell 1 0,growx"); nameField.setColumns(10); JLabel lblPanvat = new JLabel("PAN/VAT"); pane.add(lblPanvat, "cell 0 1,alignx trailing"); panVatField = new JTextField(); pane.add(panVatField, "cell 1 1,growx"); panVatField.setColumns(10); btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); } }); pane.add(btnCancel, "flowx,cell 1 3"); btnCreate = new JButton("Create"); pane.add(btnCreate, "cell 1 3"); } @Override public JComponent getPane() { return pane; } public void setContactInfopanel(JPanel contactInfopanel) { pane.add(contactInfopanel, "cell 0 2,grow,span"); pane.validate(); } }
true
true
public CreateVendorPane() { pane = new JPanel(); pane.setLayout(new MigLayout("debug", "[][grow]", "[][][grow][]")); JLabel lblVendorName = new JLabel("Vendor Name"); pane.add(lblVendorName, "cell 0 0,alignx trailing"); nameField = new JTextField(); pane.add(nameField, "cell 1 0,growx"); nameField.setColumns(10); JLabel lblPanvat = new JLabel("PAN/VAT"); pane.add(lblPanvat, "cell 0 1,alignx trailing"); panVatField = new JTextField(); pane.add(panVatField, "cell 1 1,growx"); panVatField.setColumns(10); btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); } }); pane.add(btnCancel, "flowx,cell 1 3"); btnCreate = new JButton("Create"); pane.add(btnCreate, "cell 1 3"); }
public CreateVendorPane() { pane = new JPanel(); pane.setLayout(new MigLayout("", "[][grow]", "[][][grow][]")); JLabel lblVendorName = new JLabel("Vendor Name"); pane.add(lblVendorName, "cell 0 0,alignx trailing"); nameField = new JTextField(); pane.add(nameField, "cell 1 0,growx"); nameField.setColumns(10); JLabel lblPanvat = new JLabel("PAN/VAT"); pane.add(lblPanvat, "cell 0 1,alignx trailing"); panVatField = new JTextField(); pane.add(panVatField, "cell 1 1,growx"); panVatField.setColumns(10); btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); } }); pane.add(btnCancel, "flowx,cell 1 3"); btnCreate = new JButton("Create"); pane.add(btnCreate, "cell 1 3"); }
diff --git a/omod/src/main/java/org/openmrs/module/htmlformentryui/fragment/controller/htmlform/EnterHtmlFormFragmentController.java b/omod/src/main/java/org/openmrs/module/htmlformentryui/fragment/controller/htmlform/EnterHtmlFormFragmentController.java index 6e10845..2814a93 100644 --- a/omod/src/main/java/org/openmrs/module/htmlformentryui/fragment/controller/htmlform/EnterHtmlFormFragmentController.java +++ b/omod/src/main/java/org/openmrs/module/htmlformentryui/fragment/controller/htmlform/EnterHtmlFormFragmentController.java @@ -1,317 +1,317 @@ /* * 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.module.htmlformentryui.fragment.controller.htmlform; import org.joda.time.DateMidnight; import org.openmrs.Encounter; import org.openmrs.Form; import org.openmrs.Patient; import org.openmrs.Visit; import org.openmrs.api.EncounterService; import org.openmrs.api.FormService; import org.openmrs.api.context.Context; import org.openmrs.api.context.ContextAuthenticationException; import org.openmrs.module.appframework.feature.FeatureToggleProperties; import org.openmrs.module.appui.UiSessionContext; import org.openmrs.module.emrapi.adt.AdtService; import org.openmrs.module.emrapi.adt.exception.EncounterDateAfterVisitStopDateException; import org.openmrs.module.emrapi.adt.exception.EncounterDateBeforeVisitStartDateException; import org.openmrs.module.emrapi.encounter.EncounterDomainWrapper; import org.openmrs.module.emrapi.visit.VisitDomainWrapper; import org.openmrs.module.htmlformentry.FormEntryContext; import org.openmrs.module.htmlformentry.FormEntrySession; import org.openmrs.module.htmlformentry.FormSubmissionError; import org.openmrs.module.htmlformentry.HtmlForm; import org.openmrs.module.htmlformentry.HtmlFormEntryService; import org.openmrs.module.htmlformentry.HtmlFormEntryUtil; import org.openmrs.module.htmlformentryui.HtmlFormUtil; import org.openmrs.module.uicommons.UiCommonsConstants; import org.openmrs.ui.framework.SimpleObject; import org.openmrs.ui.framework.UiUtils; import org.openmrs.ui.framework.annotation.FragmentParam; import org.openmrs.ui.framework.annotation.SpringBean; import org.openmrs.ui.framework.fragment.FragmentConfiguration; import org.openmrs.ui.framework.fragment.FragmentModel; import org.openmrs.ui.framework.resource.ResourceFactory; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * */ public class EnterHtmlFormFragmentController { /** * @param config * @param sessionContext * @param htmlFormEntryService * @param formService * @param resourceFactory * @param patient * @param hf * @param form * @param formUuid * @param definitionUiResource * @param encounter * @param visit * @param returnUrl * @param automaticValidation defaults to true. If you don't want HFE's automatic validation, set it to false * @param model * @param httpSession * @throws Exception */ public void controller(FragmentConfiguration config, UiSessionContext sessionContext, UiUtils ui, @SpringBean("htmlFormEntryService") HtmlFormEntryService htmlFormEntryService, @SpringBean("formService") FormService formService, @SpringBean("coreResourceFactory") ResourceFactory resourceFactory, @SpringBean("featureToggles") FeatureToggleProperties featureToggles, @FragmentParam("patient") Patient patient, @FragmentParam(value = "htmlForm", required = false) HtmlForm hf, @FragmentParam(value = "htmlFormId", required = false) Integer htmlFormId, @FragmentParam(value = "formId", required = false) Form form, @FragmentParam(value = "formUuid", required = false) String formUuid, @FragmentParam(value = "definitionUiResource", required = false) String definitionUiResource, @FragmentParam(value = "encounter", required = false) Encounter encounter, @FragmentParam(value = "visit", required = false) VisitDomainWrapper visit, @FragmentParam(value = "createVisit", required = false) Boolean createVisit, @FragmentParam(value = "returnUrl", required = false) String returnUrl, @FragmentParam(value = "automaticValidation", defaultValue = "true") boolean automaticValidation, FragmentModel model, HttpSession httpSession) throws Exception { config.require("patient", "htmlForm | htmlFormId | formId | formUuid | definitionResource | encounter"); if (hf == null) { if (htmlFormId != null) { hf = htmlFormEntryService.getHtmlForm(htmlFormId); } else if (form != null) { hf = htmlFormEntryService.getHtmlFormByForm(form); } else if (formUuid != null) { form = formService.getFormByUuid(formUuid); hf = htmlFormEntryService.getHtmlFormByForm(form); } else if (definitionUiResource != null) { hf = HtmlFormUtil.getHtmlFormFromUiResource(resourceFactory, formService, htmlFormEntryService, definitionUiResource); } } if (hf == null && encounter != null) { form = encounter.getForm(); if (form == null) { throw new IllegalArgumentException("Cannot view a form-less encounter unless you specify which form to use"); } hf = HtmlFormEntryUtil.getService().getHtmlFormByForm(encounter.getForm()); if (hf == null) throw new IllegalArgumentException("The form for the specified encounter (" + encounter.getForm() + ") does not have an HtmlForm associated with it"); } if (hf == null) throw new RuntimeException("Could not find HTML Form"); // the code below doesn't handle the HFFS case where you might want to _add_ data to an existing encounter FormEntrySession fes; if (encounter != null) { fes = new FormEntrySession(patient, encounter, FormEntryContext.Mode.EDIT, hf, null, httpSession, automaticValidation, !automaticValidation); } else { fes = new FormEntrySession(patient, hf, FormEntryContext.Mode.ENTER, null, httpSession, automaticValidation, !automaticValidation); } fes.setAttribute("uiSessionContext", sessionContext); fes.setAttribute("uiUtils", ui); if (StringUtils.hasText(returnUrl)) { fes.setReturnUrl(returnUrl); } fes.addToVelocityContext("visit", visit); fes.addToVelocityContext("sessionContext", sessionContext); fes.addToVelocityContext("ui", ui); fes.addToVelocityContext("featureToggles", featureToggles); model.addAttribute("currentDatetime", new Date()); model.addAttribute("command", fes); model.addAttribute("visit", visit); if (createVisit!=null) { model.addAttribute("createVisit", createVisit.toString()); } else { model.addAttribute("createVisit", "false"); } } /** * Creates a simple object to record if there is an authenticated user * @return the simple object */ public SimpleObject checkIfLoggedIn() { return SimpleObject.create("isLoggedIn", Context.isAuthenticated()); } /** * Tries to authenticate with the given credentials * @param user the username * @param pass the password * @return a simple object to record if successful */ public SimpleObject authenticate(@RequestParam("user") String user, @RequestParam("pass") String pass) { try { Context.authenticate(user, pass); } catch (ContextAuthenticationException ex) { // do nothing } return checkIfLoggedIn(); } /** * Handles a form submit request * @param patient * @param hf * @param encounter * @param visit * @param returnUrl * @param request * @return * @throws Exception */ @Transactional public SimpleObject submit(UiSessionContext sessionContext, @RequestParam("personId") Patient patient, @RequestParam("htmlFormId") HtmlForm hf, @RequestParam(value = "encounterId", required = false) Encounter encounter, @RequestParam(value = "visitId", required = false) Visit visit, @RequestParam(value = "createVisit", required = false) Boolean createVisit, @RequestParam(value = "returnUrl", required = false) String returnUrl, @SpringBean("encounterService") EncounterService encounterService, @SpringBean("adtService") AdtService adtService, @SpringBean("coreResourceFactory") ResourceFactory resourceFactory, - @SpringBean("featureToggleProperties") FeatureToggleProperties featureToggles, + @SpringBean("featureToggles") FeatureToggleProperties featureToggles, UiUtils ui, HttpServletRequest request) throws Exception { // TODO formModifiedTimestamp and encounterModifiedTimestamp boolean editMode = encounter != null; FormEntrySession fes; if (encounter != null) { fes = new FormEntrySession(patient, encounter, FormEntryContext.Mode.EDIT, hf, request.getSession()); } else { fes = new FormEntrySession(patient, hf, FormEntryContext.Mode.ENTER, request.getSession()); } fes.setAttribute("uiSessionContext", sessionContext); fes.setAttribute("uiUtils", ui); fes.addToVelocityContext("visit", visit); fes.addToVelocityContext("sessionContext", sessionContext); fes.addToVelocityContext("ui", ui); fes.addToVelocityContext("featureToggles", featureToggles); if (returnUrl != null) { fes.setReturnUrl(returnUrl); } fes.getHtmlToDisplay(); // Validate and return with errors if any are found List<FormSubmissionError> validationErrors = fes.getSubmissionController().validateSubmission(fes.getContext(), request); if (validationErrors.size() > 0) { return returnHelper(validationErrors, fes.getContext(), null); } // No validation errors found so process form submission fes.prepareForSubmit(); fes.getSubmissionController().handleFormSubmission(fes, request); // Check this form will actually create an encounter if its supposed to if (fes.getContext().getMode() == FormEntryContext.Mode.ENTER && fes.hasEncouterTag() && (fes.getSubmissionActions().getEncountersToCreate() == null || fes.getSubmissionActions().getEncountersToCreate().size() == 0)) { throw new IllegalArgumentException("This form is not going to create an encounter"); } Encounter formEncounter = fes.getContext().getMode() == FormEntryContext.Mode.ENTER ? fes.getSubmissionActions().getEncountersToCreate().get(0) : encounter; // we don't want to lose any time information just because we edited it with a form that only collects date if (fes.getContext().getMode() == FormEntryContext.Mode.EDIT && hasNoTimeComponent(formEncounter.getEncounterDatetime())) { keepTimeComponentOfEncounterIfDateComponentHasNotChanged(fes.getContext().getPreviousEncounterDate(), formEncounter); } // create a visit if necessary // (note that this currently only works in real-time mode) if (createVisit != null && (createVisit) && visit == null) { visit = adtService.ensureActiveVisit(patient, sessionContext.getSessionLocation()); } // attach to the visit if it exists if (visit != null) { try { new EncounterDomainWrapper(formEncounter).attachToVisit(visit); } catch (EncounterDateBeforeVisitStartDateException e) { validationErrors.add(new FormSubmissionError("general-form-error", "Encounter datetime should be after the visit start date")); } catch (EncounterDateAfterVisitStopDateException e) { validationErrors.add(new FormSubmissionError("general-form-error", "Encounter datetime should be before the visit stop date")); } if (validationErrors.size() > 0) { return returnHelper(validationErrors, fes.getContext(), null); } } // Do actual encounter creation/updating fes.applyActions(); request.getSession().setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_INFO_MESSAGE, ui.message(editMode ? "emr.editHtmlForm.successMessage" : "emr.task.enterHtmlForm.successMessage", ui.format(hf.getForm()), ui.format(patient))); request.getSession().setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_TOAST_MESSAGE, "true"); return returnHelper(null, null, formEncounter); } private SimpleObject returnHelper(List<FormSubmissionError> validationErrors, FormEntryContext context, Encounter encounter) { if (validationErrors == null || validationErrors.size() == 0) { return SimpleObject.create("success", true, "encounterId", encounter.getId()); } else { Map<String, String> errors = new HashMap<String, String>(); for (FormSubmissionError err : validationErrors) { if (err.getSourceWidget() != null) errors.put(context.getErrorFieldId(err.getSourceWidget()), err.getError()); else errors.put(err.getId(), err.getError()); } return SimpleObject.create("success", false, "errors", errors); } } private boolean hasNoTimeComponent(Date date) { return new DateMidnight(date).toDate().equals(date); } private void keepTimeComponentOfEncounterIfDateComponentHasNotChanged(Date previousEncounterDate, Encounter formEncounter) { if (previousEncounterDate != null && new DateMidnight(previousEncounterDate).equals(new DateMidnight(formEncounter.getEncounterDatetime()))) { formEncounter.setEncounterDatetime(previousEncounterDate); } } }
true
true
public SimpleObject submit(UiSessionContext sessionContext, @RequestParam("personId") Patient patient, @RequestParam("htmlFormId") HtmlForm hf, @RequestParam(value = "encounterId", required = false) Encounter encounter, @RequestParam(value = "visitId", required = false) Visit visit, @RequestParam(value = "createVisit", required = false) Boolean createVisit, @RequestParam(value = "returnUrl", required = false) String returnUrl, @SpringBean("encounterService") EncounterService encounterService, @SpringBean("adtService") AdtService adtService, @SpringBean("coreResourceFactory") ResourceFactory resourceFactory, @SpringBean("featureToggleProperties") FeatureToggleProperties featureToggles, UiUtils ui, HttpServletRequest request) throws Exception { // TODO formModifiedTimestamp and encounterModifiedTimestamp boolean editMode = encounter != null; FormEntrySession fes; if (encounter != null) { fes = new FormEntrySession(patient, encounter, FormEntryContext.Mode.EDIT, hf, request.getSession()); } else { fes = new FormEntrySession(patient, hf, FormEntryContext.Mode.ENTER, request.getSession()); } fes.setAttribute("uiSessionContext", sessionContext); fes.setAttribute("uiUtils", ui); fes.addToVelocityContext("visit", visit); fes.addToVelocityContext("sessionContext", sessionContext); fes.addToVelocityContext("ui", ui); fes.addToVelocityContext("featureToggles", featureToggles); if (returnUrl != null) { fes.setReturnUrl(returnUrl); } fes.getHtmlToDisplay(); // Validate and return with errors if any are found List<FormSubmissionError> validationErrors = fes.getSubmissionController().validateSubmission(fes.getContext(), request); if (validationErrors.size() > 0) { return returnHelper(validationErrors, fes.getContext(), null); } // No validation errors found so process form submission fes.prepareForSubmit(); fes.getSubmissionController().handleFormSubmission(fes, request); // Check this form will actually create an encounter if its supposed to if (fes.getContext().getMode() == FormEntryContext.Mode.ENTER && fes.hasEncouterTag() && (fes.getSubmissionActions().getEncountersToCreate() == null || fes.getSubmissionActions().getEncountersToCreate().size() == 0)) { throw new IllegalArgumentException("This form is not going to create an encounter"); } Encounter formEncounter = fes.getContext().getMode() == FormEntryContext.Mode.ENTER ? fes.getSubmissionActions().getEncountersToCreate().get(0) : encounter; // we don't want to lose any time information just because we edited it with a form that only collects date if (fes.getContext().getMode() == FormEntryContext.Mode.EDIT && hasNoTimeComponent(formEncounter.getEncounterDatetime())) { keepTimeComponentOfEncounterIfDateComponentHasNotChanged(fes.getContext().getPreviousEncounterDate(), formEncounter); } // create a visit if necessary // (note that this currently only works in real-time mode) if (createVisit != null && (createVisit) && visit == null) { visit = adtService.ensureActiveVisit(patient, sessionContext.getSessionLocation()); } // attach to the visit if it exists if (visit != null) { try { new EncounterDomainWrapper(formEncounter).attachToVisit(visit); } catch (EncounterDateBeforeVisitStartDateException e) { validationErrors.add(new FormSubmissionError("general-form-error", "Encounter datetime should be after the visit start date")); } catch (EncounterDateAfterVisitStopDateException e) { validationErrors.add(new FormSubmissionError("general-form-error", "Encounter datetime should be before the visit stop date")); } if (validationErrors.size() > 0) { return returnHelper(validationErrors, fes.getContext(), null); } } // Do actual encounter creation/updating fes.applyActions(); request.getSession().setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_INFO_MESSAGE, ui.message(editMode ? "emr.editHtmlForm.successMessage" : "emr.task.enterHtmlForm.successMessage", ui.format(hf.getForm()), ui.format(patient))); request.getSession().setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_TOAST_MESSAGE, "true"); return returnHelper(null, null, formEncounter); }
public SimpleObject submit(UiSessionContext sessionContext, @RequestParam("personId") Patient patient, @RequestParam("htmlFormId") HtmlForm hf, @RequestParam(value = "encounterId", required = false) Encounter encounter, @RequestParam(value = "visitId", required = false) Visit visit, @RequestParam(value = "createVisit", required = false) Boolean createVisit, @RequestParam(value = "returnUrl", required = false) String returnUrl, @SpringBean("encounterService") EncounterService encounterService, @SpringBean("adtService") AdtService adtService, @SpringBean("coreResourceFactory") ResourceFactory resourceFactory, @SpringBean("featureToggles") FeatureToggleProperties featureToggles, UiUtils ui, HttpServletRequest request) throws Exception { // TODO formModifiedTimestamp and encounterModifiedTimestamp boolean editMode = encounter != null; FormEntrySession fes; if (encounter != null) { fes = new FormEntrySession(patient, encounter, FormEntryContext.Mode.EDIT, hf, request.getSession()); } else { fes = new FormEntrySession(patient, hf, FormEntryContext.Mode.ENTER, request.getSession()); } fes.setAttribute("uiSessionContext", sessionContext); fes.setAttribute("uiUtils", ui); fes.addToVelocityContext("visit", visit); fes.addToVelocityContext("sessionContext", sessionContext); fes.addToVelocityContext("ui", ui); fes.addToVelocityContext("featureToggles", featureToggles); if (returnUrl != null) { fes.setReturnUrl(returnUrl); } fes.getHtmlToDisplay(); // Validate and return with errors if any are found List<FormSubmissionError> validationErrors = fes.getSubmissionController().validateSubmission(fes.getContext(), request); if (validationErrors.size() > 0) { return returnHelper(validationErrors, fes.getContext(), null); } // No validation errors found so process form submission fes.prepareForSubmit(); fes.getSubmissionController().handleFormSubmission(fes, request); // Check this form will actually create an encounter if its supposed to if (fes.getContext().getMode() == FormEntryContext.Mode.ENTER && fes.hasEncouterTag() && (fes.getSubmissionActions().getEncountersToCreate() == null || fes.getSubmissionActions().getEncountersToCreate().size() == 0)) { throw new IllegalArgumentException("This form is not going to create an encounter"); } Encounter formEncounter = fes.getContext().getMode() == FormEntryContext.Mode.ENTER ? fes.getSubmissionActions().getEncountersToCreate().get(0) : encounter; // we don't want to lose any time information just because we edited it with a form that only collects date if (fes.getContext().getMode() == FormEntryContext.Mode.EDIT && hasNoTimeComponent(formEncounter.getEncounterDatetime())) { keepTimeComponentOfEncounterIfDateComponentHasNotChanged(fes.getContext().getPreviousEncounterDate(), formEncounter); } // create a visit if necessary // (note that this currently only works in real-time mode) if (createVisit != null && (createVisit) && visit == null) { visit = adtService.ensureActiveVisit(patient, sessionContext.getSessionLocation()); } // attach to the visit if it exists if (visit != null) { try { new EncounterDomainWrapper(formEncounter).attachToVisit(visit); } catch (EncounterDateBeforeVisitStartDateException e) { validationErrors.add(new FormSubmissionError("general-form-error", "Encounter datetime should be after the visit start date")); } catch (EncounterDateAfterVisitStopDateException e) { validationErrors.add(new FormSubmissionError("general-form-error", "Encounter datetime should be before the visit stop date")); } if (validationErrors.size() > 0) { return returnHelper(validationErrors, fes.getContext(), null); } } // Do actual encounter creation/updating fes.applyActions(); request.getSession().setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_INFO_MESSAGE, ui.message(editMode ? "emr.editHtmlForm.successMessage" : "emr.task.enterHtmlForm.successMessage", ui.format(hf.getForm()), ui.format(patient))); request.getSession().setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_TOAST_MESSAGE, "true"); return returnHelper(null, null, formEncounter); }
diff --git a/src/mlparch/XMLPatch.java b/src/mlparch/XMLPatch.java index 13d9141..61ea3ef 100644 --- a/src/mlparch/XMLPatch.java +++ b/src/mlparch/XMLPatch.java @@ -1,624 +1,626 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mlparch; import java.io.ByteArrayInputStream; 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.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.SequenceInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author John Petska */ public class XMLPatch { public int verbosity = 0; public PrintStream stdout = System.out; public void printout(int l, String s) { if (stdout != null && l <= verbosity) stdout.print (s); } public void printlnout(int l, String s) { if (stdout != null && l <= verbosity) stdout.println(s); } public PrintStream stderr = System.err; public void printerr(int l, String s) { if (stderr != null && l <= verbosity) stderr.print (s); } public void printlnerr(int l, String s) { if (stderr != null && l <= verbosity) stderr.println(s); } private final DocumentBuilder docBuilder; private final XPathFactory xpfactory; public static class XMLPDoc { public HashMap<String, String> options; public Document doc; public XMLPDoc(HashMap<String, String> options, Document doc) { this.options = options; this.doc = doc; } } public final HashMap<String, XMLPDoc> docMap = new HashMap<String, XMLPDoc>(); public final HashMap<String, XMLPatchOp> opList = new HashMap<String, XMLPatchOp>(); public void addDefaultOps() { opList.put("print" , new XMLPatchOpPrint(this)); opList.put("=" , new XMLPatchOpSet(this)); opList.put("+=" , new XMLPatchOpAddSet(this)); opList.put("-=" , new XMLPatchOpSubSet(this)); opList.put("*=" , new XMLPatchOpMulSet(this)); opList.put("/=" , new XMLPatchOpDivSet(this)); opList.put("floor" , new XMLPatchOpFloor(this)); opList.put("ceil" , new XMLPatchOpCeil(this)); opList.put("round" , new XMLPatchOpRound(this)); opList.put("sqrt" , new XMLPatchOpSqrt(this)); opList.put("+attr" , new XMLPatchOpAddAttr(this)); opList.put("+elem" , new XMLPatchOpAddElem(this)); opList.put("remove", new XMLPatchOpRemove(this)); } public static class WhitespaceFixerInputStream extends InputStream { public String fixChars = "\""; public String append = " "; public int quotChar = '"'; int appendPos = -1; boolean quot = false; InputStream is; public WhitespaceFixerInputStream(InputStream is) { this.is = is; } @Override public int read() throws IOException { //either dump an append char, or reset to -1. //if we're not appending, do nothing if (appendPos >= 0) if (appendPos >= append.length()) appendPos = -1; else return append.charAt(appendPos++); //read a char... int c = is.read(); //don't modify string literals. if (c == quotChar) quot = !quot; //if it's one of our fix characters, prepare to append if (!quot && fixChars.indexOf(c) >= 0) appendPos = 0; //then write the char return c; } } public static class DummyInputStream extends SequenceInputStream { static byte[] open = "<dummy>".getBytes(); static byte[] close = "</dummy>".getBytes(); public DummyInputStream(InputStream is) { super(Collections.enumeration(Arrays.asList(new InputStream[] { new ByteArrayInputStream(open), is, new ByteArrayInputStream(close), }))); } } public static class DummyOutputStream extends OutputStream { private int state = 0; //state = 0, searching for opening dummy. data is discarded //state = 1, searching for closing dummy, data is written //state = 2, closing dummy matched, data is discarded (never leaves this state) byte[] buffer = new byte[16]; int bpos = 0; OutputStream os; public DummyOutputStream(OutputStream os) { this.os = os; } @Override public void write(int b) throws IOException { byte by = (byte)(0xFF&b); switch (state) { case 0: //search for opening dummy, discarding all data until a match if (by == DummyInputStream.open[bpos]) { buffer[bpos++] = by; if (bpos == DummyInputStream.open.length) { state = 1; bpos = 0; } } else { bpos = 0; } break; case 1: //search for closing dummy, writing any data that doesn't match if (by == DummyInputStream.close[bpos]) { buffer[bpos++] = by; if (bpos == DummyInputStream.close.length) { state = 2; bpos = 0; } } else { os.write(buffer, 0, bpos); os.write(b); bpos = 0; } break; case 2: //done, discard all data break; } } @Override public void flush() throws IOException { os.flush(); } @Override public void close() throws IOException { os.close(); } } public static class XMLQuery { public final Document doc; public final String target; public final String query; public final NodeList result; public final boolean negative; public XMLQuery(Document doc, String target, String query, NodeList result, boolean negative) { this.doc = doc; this.target = target; this.query = query; this.result = result; this.negative = negative; } } public XMLPatch(int verbosity) throws Exception { this.verbosity = verbosity; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); docBuilder = factory.newDocumentBuilder(); xpfactory = XPathFactory.newInstance(); addDefaultOps(); } public Document getDoc(File root, String target, HashMap<String, String> options) throws FileNotFoundException, SAXException, IOException { if (options == null) options = new HashMap<String, String>(1); XMLPDoc doc = docMap.get(target); if (doc == null) { File file = new File(root==null?new File("."):root, target); if (!file.exists() || !file.isFile()) throw new RuntimeException("Couldn't locate target! (\""+file.getPath()+"\")"); InputStream is = new FileInputStream(file); if (Boolean.parseBoolean(options.get("whitespacefix"))) is = new WhitespaceFixerInputStream(is); if (Boolean.parseBoolean(options.get("dummyroot"))) is = new DummyInputStream(is); doc = new XMLPDoc(options, docBuilder.parse(is)); docMap.put(target, doc); } return doc.doc; } public NodeList getNodes(Document doc, String query) throws XPathExpressionException { XPath xpath = xpfactory.newXPath(); NodeList nodes = (NodeList) xpath.evaluate(query, doc, XPathConstants.NODESET); return nodes; } public void applyOp(List<Node> nodes, Element config, XMLPatchOp op) throws XPathExpressionException { for (int i = 0; i < nodes.size(); i++) { Node node = nodes.get(i); try { op.apply(config, node); } catch (Throwable t) { printlnerr(0, "Exception applying op on "+node+": "+t.getClass().getSimpleName()+": "+t.getLocalizedMessage()); } } } public void applyOp(Document doc, String query, Element config, XMLPatchOp op) throws XPathExpressionException { applyOp(new NodeListList(getNodes(doc, query)), config, op); } public void applyPatch(File patchFile, File rootDir) throws Exception { DocumentBuilderFactory patFac = DocumentBuilderFactory.newInstance(); DocumentBuilder patBuilder = patFac.newDocumentBuilder(); Document patchDoc = patBuilder.parse(new FileInputStream(patchFile)); Node n_xmlp = patchDoc.getFirstChild(); if (!n_xmlp.getNodeName().equals("xmlp")) throw new RuntimeException("Root patch node must be named \"xmlp\""); for (Node n_xmlp_node = n_xmlp.getFirstChild(); n_xmlp_node != null; n_xmlp_node = n_xmlp_node.getNextSibling()) { if (n_xmlp_node instanceof Element) { Element e_xmlp_node = (Element) n_xmlp_node; if (n_xmlp_node.getNodeName().equals("patch")) { String patch_name = e_xmlp_node.getAttribute("name"); if (patch_name == null || patch_name.isEmpty()) printlnout(0, "Running anonymous patch..."); else printlnout(0, "Running patch \""+patch_name+"\"..."); ArrayList<XMLQuery> queryList = new ArrayList<XMLQuery>(); patchLoop: for (Node n_xmlp_patch_node = n_xmlp_node.getFirstChild(); n_xmlp_patch_node != null; n_xmlp_patch_node = n_xmlp_patch_node.getNextSibling()) { if (n_xmlp_patch_node instanceof Element) { Element e_xmlp_patch_node = (Element) n_xmlp_patch_node; if (n_xmlp_patch_node.getNodeName().equals("addnodes")) { String p_target = e_xmlp_patch_node.getAttribute("target"); String p_query = e_xmlp_patch_node.getAttribute("query"); if (p_target == null || p_target.isEmpty()) { printlnerr(0, "AddQuery has no target!"); continue; } if (p_query == null || p_query.isEmpty()) { printlnerr(0, "AddQuery has no query!"); continue; } printlnout(2, "Adding nodes with query \""+p_target+"\":\""+p_query+"\"..."); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); - if (!q.negative) { - printlnerr(0, "Warning: tried to add duplicate query!"); - continue patchLoop; - } else { - printlnerr(0, "Warning: cancelling out previous query!"); + if (q.target.equals(p_target) && q.query.equals(p_query)) { + if (q.negative) { + printlnerr(0, "Warning: tried to add duplicate query!"); + continue patchLoop; + } else { + printlnerr(0, "Warning: cancelling out previous query!"); + } } } Document doc = getDoc(rootDir, p_target, null); NodeList nodes = getNodes(doc, p_query); queryList.add(new XMLQuery(doc, p_target, p_query, nodes, false)); } else if (n_xmlp_patch_node.getNodeName().equals("remnodes")) { String p_target = e_xmlp_patch_node.getAttribute("target"); String p_query = e_xmlp_patch_node.getAttribute("query"); if (p_target == null || p_target.isEmpty()) { printlnerr(0, "AddQuery has no target!"); continue; } if (p_query == null || p_query.isEmpty()) { printlnerr(0, "AddQuery has no query!"); continue; } printlnout(2, "Removing nodes with query \""+p_target+"\":\""+p_query+"\"..."); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (q.target.equals(p_target) && q.query.equals(p_query)) { if (q.negative) { printlnerr(0, "Warning: tried to add duplicate query!"); continue patchLoop; } else { printlnerr(0, "Warning: cancelling out previous query!"); } } } Document doc = getDoc(rootDir, p_target, null); NodeList nodes = getNodes(doc, p_query); queryList.add(new XMLQuery(doc, p_target, p_query, nodes, true)); } else if (n_xmlp_patch_node.getNodeName().equals("remquery")) { String p_target = e_xmlp_patch_node.getAttribute("target"); String p_query = e_xmlp_patch_node.getAttribute("query"); if (p_target == null || p_target.isEmpty()) { printlnerr(0, "RemQuery has no target!"); continue; } if (p_query == null || p_query.isEmpty()) { printlnerr(0, "RemQuery has no query!"); continue; } printlnout(2, "Removing query \""+p_target+"\":\""+p_query+"\"..."); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (q.target.equals(p_target) && q.query.equals(p_query)) { queryList.remove(i); break; } } } else if (n_xmlp_patch_node.getNodeName().equals("clearqueries")) { printlnout(2, "Clearing query list..."); queryList.clear(); } else if (n_xmlp_patch_node.getNodeName().equals("op")) { NamedNodeMap n_xmlp_patch_op_attr = n_xmlp_patch_node.getAttributes(); String p_op = e_xmlp_patch_node.getAttribute("id"); if (p_op == null || p_op.isEmpty()) { printlnerr(0, "Op has no id!"); continue; } XMLPatchOp op = opList.get(p_op); if (op == null) { printlnerr(0, "Unrecognized op! (\""+p_op+"\")"); continue; } ArrayList<Node> nodes = new ArrayList<Node>(); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (q.negative) { printlnout(1, "Removing nodes \""+q.target+"\":\""+q.query+"\" from \""+p_op+"\" execution..."); nodes.removeAll(new NodeListList(q.result)); } else { printlnout(1, "Adding nodes \""+q.target+"\":\""+q.query+"\" to \""+p_op+"\" execution..."); nodes.addAll(new NodeListList(q.result)); } } applyOp(nodes, (Element)n_xmlp_patch_node, op); } } } } else if (n_xmlp_node.getNodeName().equals("load")) { NamedNodeMap n_xmlp_node_attr = n_xmlp_node.getAttributes(); Node n = null; String p_target = null; //get target... n = n_xmlp_node_attr.getNamedItem("target"); if (n != null) p_target = n.getNodeValue(); if (p_target == null) { printlnerr(0, "Load has no target!"); continue; } HashMap<String, String> options = new HashMap<String, String>(); for (int i = 0; i < n_xmlp_node_attr.getLength(); i++) { Node item = n_xmlp_node_attr.item(i); if (!item.getNodeName().equals("target")) { options.put(item.getNodeName(), item.getNodeValue()); } } printlnout(0, "Loading \""+p_target+"\" with options... "+options); getDoc(rootDir, p_target, options); } } } } public void writeDocMap(File outDir) throws Exception { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); for (Iterator<Entry<String, XMLPDoc>> iter = docMap.entrySet().iterator(); iter.hasNext();) { Entry i = iter.next(); String path = (String)i.getKey(); XMLPDoc doc = (XMLPDoc)i.getValue(); //initialize StreamResult with File object to save to file File outFile = new File(outDir, path); printlnout(0, "Writing \""+path+"\"..."); OutputStream os = new FileOutputStream(outFile); if (Boolean.parseBoolean(doc.options.get("dummyroot"))) os = new DummyOutputStream(os); StreamResult result = new StreamResult(new OutputStreamWriter(os)); Source source = new DOMSource(doc.doc); transformer.transform(source, result); } } public static String getNameFromType(short type) { switch (type) { case Node.ELEMENT_NODE: return "ELEMENT_NODE"; case Node.ATTRIBUTE_NODE: return "ATTRIBUTE_NODE"; case Node.TEXT_NODE: return "TEXT_NODE"; case Node.CDATA_SECTION_NODE: return "CDATA_SECTION_NODE"; case Node.ENTITY_REFERENCE_NODE: return "ENTITY_REFERENCE_NODE"; case Node.ENTITY_NODE: return "ENTITY_NODE"; case Node.PROCESSING_INSTRUCTION_NODE: return "PROCESSING_INSTRUCTION_NODE"; case Node.COMMENT_NODE: return "COMMENT_NODE"; case Node.DOCUMENT_NODE: return "DOCUMENT_NODE"; case Node.DOCUMENT_TYPE_NODE: return "DOCUMENT_TYPE_NODE"; case Node.DOCUMENT_FRAGMENT_NODE: return "DOCUMENT_FRAGMENT_NODE"; case Node.NOTATION_NODE: return "NOTATION_NODE"; } return "UNKNOWN_NODE"; } public static abstract class XMLPatchOp { public final XMLPatch owner; public XMLPatchOp(XMLPatch owner) { this.owner = owner; } public abstract void apply(Element config, Node target); } public static class XMLPatchOpPrintValue extends XMLPatchOp { public XMLPatchOpPrintValue(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { owner.printlnout(0, target.getNodeName()+"("+getNameFromType(target.getNodeType())+") = "+target.getNodeValue()); } } public static class XMLPatchOpPrint extends XMLPatchOp { public XMLPatchOpPrint(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { owner.printlnout(0, target.toString()); } } public static class XMLPatchOpSet extends XMLPatchOp { public XMLPatchOpSet(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { String value = config.getAttribute("value"); if (value == null || value.isEmpty()) throw new IllegalArgumentException("Expected 'value' attribute!"); String org = target.getNodeValue(); target.setNodeValue(value); owner.printlnout(3, "\""+org+"\" > \""+target.getNodeValue()+"\""); } } public static class XMLPatchOpAddSet extends XMLPatchOp { public XMLPatchOpAddSet(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { String attrS = config.getAttribute("value"); if (attrS == null || attrS.isEmpty()) throw new IllegalArgumentException("Expected 'value' attribute!"); double value = Double.parseDouble(attrS); double org = Double.parseDouble(target.getNodeValue()); target.setNodeValue(Double.toString(org+value)); owner.printlnout(3, "\""+org+"\" > \""+target.getNodeValue()+"\""); } } public static class XMLPatchOpSubSet extends XMLPatchOp { public XMLPatchOpSubSet(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { String attrS = config.getAttribute("value"); if (attrS == null || attrS.isEmpty()) throw new IllegalArgumentException("Expected 'value' attribute!"); double value = Double.parseDouble(attrS); double org = Double.parseDouble(target.getNodeValue()); target.setNodeValue(Double.toString(org-value)); owner.printlnout(3, "\""+org+"\" > \""+target.getNodeValue()+"\""); } } public static class XMLPatchOpMulSet extends XMLPatchOp { public XMLPatchOpMulSet(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { String attrS = config.getAttribute("value"); if (attrS == null || attrS.isEmpty()) throw new IllegalArgumentException("Expected 'value' attribute!"); double value = Double.parseDouble(attrS); double org = Double.parseDouble(target.getNodeValue()); target.setNodeValue(Double.toString(org*value)); owner.printlnout(3, "\""+org+"\" > \""+target.getNodeValue()+"\""); } } public static class XMLPatchOpDivSet extends XMLPatchOp { public XMLPatchOpDivSet(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { String attrS = config.getAttribute("value"); if (attrS == null || attrS.isEmpty()) throw new IllegalArgumentException("Expected 'value' attribute!"); double value = Double.parseDouble(attrS); double org = Double.parseDouble(target.getNodeValue()); target.setNodeValue(Double.toString(org/value)); owner.printlnout(3, "\""+org+"\" > \""+target.getNodeValue()+"\""); } } public static class XMLPatchOpFloor extends XMLPatchOp { public XMLPatchOpFloor(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { boolean direct = false; double sig = 0; String attrS = config.getAttribute("direct"); if (attrS != null && !attrS.isEmpty()) direct = Boolean.parseBoolean(attrS); attrS = config.getAttribute("sig"); if (attrS != null && !attrS.isEmpty()) sig = Double.parseDouble(attrS); double pow = direct ? sig : Math.pow(10, sig); double org = Double.parseDouble(target.getNodeValue()); if (Math.abs(pow-1d)<0.00000001) target.setNodeValue(Integer.toString((int)Math.floor(org))); else target.setNodeValue(Double.toString(Math.floor(org*pow)/pow)); owner.printlnout(3, "\""+org+"\" > \""+target.getNodeValue()+"\""); } } public static class XMLPatchOpCeil extends XMLPatchOp { public XMLPatchOpCeil(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { boolean direct = false; double sig = 0; String attrS = config.getAttribute("direct"); if (attrS != null && !attrS.isEmpty()) direct = Boolean.parseBoolean(attrS); attrS = config.getAttribute("sig"); if (attrS != null && !attrS.isEmpty()) sig = Double.parseDouble(attrS); double pow = direct ? sig : Math.pow(10, sig); double org = Double.parseDouble(target.getNodeValue()); if (Math.abs(pow-1d)<0.00000001) target.setNodeValue(Integer.toString((int)Math.ceil(org))); else target.setNodeValue(Double.toString(Math.ceil(org*pow)/pow)); owner.printlnout(3, "\""+org+"\" > \""+target.getNodeValue()+"\""); } } public static class XMLPatchOpRound extends XMLPatchOp { public XMLPatchOpRound(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { boolean direct = false; double sig = 0; String attrS = config.getAttribute("direct"); if (attrS != null && !attrS.isEmpty()) direct = Boolean.parseBoolean(attrS); attrS = config.getAttribute("sig"); if (attrS != null && !attrS.isEmpty()) sig = Double.parseDouble(attrS); double pow = direct ? sig : Math.pow(10, sig); double org = Double.parseDouble(target.getNodeValue()); if (Math.abs(pow-1d)<0.00000001) target.setNodeValue(Integer.toString((int)Math.round(org))); else target.setNodeValue(Double.toString(Math.round(org*pow)/pow)); owner.printlnout(3, "\""+org+"\" > \""+target.getNodeValue()+"\""); } } public static class XMLPatchOpSqrt extends XMLPatchOp { public XMLPatchOpSqrt(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { double org = Double.parseDouble(target.getNodeValue()); target.setNodeValue(Double.toString(Math.sqrt(org))); owner.printlnout(3, "\""+org+"\" > \""+target.getNodeValue()+"\""); } } public static class XMLPatchOpAddAttr extends XMLPatchOp { public XMLPatchOpAddAttr(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { String name = config.getAttribute("name"); String value = config.getAttribute("value"); if (name == null || name.isEmpty()) throw new IllegalArgumentException("Expected 'name' attribute!"); if (value == null) value = ""; if (!(target instanceof Element)) throw new IllegalArgumentException("Can only add Attributes to Elements!"); Element elem = (Element) target; elem.setAttribute(name, value); owner.printlnout(3, "+attr \""+name+"\" = \""+value+"\""); } } public static class XMLPatchOpAddElem extends XMLPatchOp { public XMLPatchOpAddElem(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { String name = config.getAttribute("name"); String value = config.getAttribute("value"); if (name == null || name.isEmpty()) throw new IllegalArgumentException("Expected 'name' attribute!"); if (value == null) value = ""; Node child = target.appendChild(target.getOwnerDocument().createElement(name)); child.setNodeValue(value); owner.printlnout(3, "+elem \""+name+"\" = \""+value+"\""); } } public static class XMLPatchOpRemove extends XMLPatchOp { public XMLPatchOpRemove(XMLPatch owner) { super(owner); } @Override public void apply(Element config, Node target) { target.getParentNode().removeChild(target); owner.printlnout(3, "removed \""+target.getNodeName()+"\""); } } }
true
true
public void applyPatch(File patchFile, File rootDir) throws Exception { DocumentBuilderFactory patFac = DocumentBuilderFactory.newInstance(); DocumentBuilder patBuilder = patFac.newDocumentBuilder(); Document patchDoc = patBuilder.parse(new FileInputStream(patchFile)); Node n_xmlp = patchDoc.getFirstChild(); if (!n_xmlp.getNodeName().equals("xmlp")) throw new RuntimeException("Root patch node must be named \"xmlp\""); for (Node n_xmlp_node = n_xmlp.getFirstChild(); n_xmlp_node != null; n_xmlp_node = n_xmlp_node.getNextSibling()) { if (n_xmlp_node instanceof Element) { Element e_xmlp_node = (Element) n_xmlp_node; if (n_xmlp_node.getNodeName().equals("patch")) { String patch_name = e_xmlp_node.getAttribute("name"); if (patch_name == null || patch_name.isEmpty()) printlnout(0, "Running anonymous patch..."); else printlnout(0, "Running patch \""+patch_name+"\"..."); ArrayList<XMLQuery> queryList = new ArrayList<XMLQuery>(); patchLoop: for (Node n_xmlp_patch_node = n_xmlp_node.getFirstChild(); n_xmlp_patch_node != null; n_xmlp_patch_node = n_xmlp_patch_node.getNextSibling()) { if (n_xmlp_patch_node instanceof Element) { Element e_xmlp_patch_node = (Element) n_xmlp_patch_node; if (n_xmlp_patch_node.getNodeName().equals("addnodes")) { String p_target = e_xmlp_patch_node.getAttribute("target"); String p_query = e_xmlp_patch_node.getAttribute("query"); if (p_target == null || p_target.isEmpty()) { printlnerr(0, "AddQuery has no target!"); continue; } if (p_query == null || p_query.isEmpty()) { printlnerr(0, "AddQuery has no query!"); continue; } printlnout(2, "Adding nodes with query \""+p_target+"\":\""+p_query+"\"..."); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (!q.negative) { printlnerr(0, "Warning: tried to add duplicate query!"); continue patchLoop; } else { printlnerr(0, "Warning: cancelling out previous query!"); } } Document doc = getDoc(rootDir, p_target, null); NodeList nodes = getNodes(doc, p_query); queryList.add(new XMLQuery(doc, p_target, p_query, nodes, false)); } else if (n_xmlp_patch_node.getNodeName().equals("remnodes")) { String p_target = e_xmlp_patch_node.getAttribute("target"); String p_query = e_xmlp_patch_node.getAttribute("query"); if (p_target == null || p_target.isEmpty()) { printlnerr(0, "AddQuery has no target!"); continue; } if (p_query == null || p_query.isEmpty()) { printlnerr(0, "AddQuery has no query!"); continue; } printlnout(2, "Removing nodes with query \""+p_target+"\":\""+p_query+"\"..."); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (q.target.equals(p_target) && q.query.equals(p_query)) { if (q.negative) { printlnerr(0, "Warning: tried to add duplicate query!"); continue patchLoop; } else { printlnerr(0, "Warning: cancelling out previous query!"); } } } Document doc = getDoc(rootDir, p_target, null); NodeList nodes = getNodes(doc, p_query); queryList.add(new XMLQuery(doc, p_target, p_query, nodes, true)); } else if (n_xmlp_patch_node.getNodeName().equals("remquery")) { String p_target = e_xmlp_patch_node.getAttribute("target"); String p_query = e_xmlp_patch_node.getAttribute("query"); if (p_target == null || p_target.isEmpty()) { printlnerr(0, "RemQuery has no target!"); continue; } if (p_query == null || p_query.isEmpty()) { printlnerr(0, "RemQuery has no query!"); continue; } printlnout(2, "Removing query \""+p_target+"\":\""+p_query+"\"..."); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (q.target.equals(p_target) && q.query.equals(p_query)) { queryList.remove(i); break; } } } else if (n_xmlp_patch_node.getNodeName().equals("clearqueries")) { printlnout(2, "Clearing query list..."); queryList.clear(); } else if (n_xmlp_patch_node.getNodeName().equals("op")) { NamedNodeMap n_xmlp_patch_op_attr = n_xmlp_patch_node.getAttributes(); String p_op = e_xmlp_patch_node.getAttribute("id"); if (p_op == null || p_op.isEmpty()) { printlnerr(0, "Op has no id!"); continue; } XMLPatchOp op = opList.get(p_op); if (op == null) { printlnerr(0, "Unrecognized op! (\""+p_op+"\")"); continue; } ArrayList<Node> nodes = new ArrayList<Node>(); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (q.negative) { printlnout(1, "Removing nodes \""+q.target+"\":\""+q.query+"\" from \""+p_op+"\" execution..."); nodes.removeAll(new NodeListList(q.result)); } else { printlnout(1, "Adding nodes \""+q.target+"\":\""+q.query+"\" to \""+p_op+"\" execution..."); nodes.addAll(new NodeListList(q.result)); } } applyOp(nodes, (Element)n_xmlp_patch_node, op); } } } } else if (n_xmlp_node.getNodeName().equals("load")) { NamedNodeMap n_xmlp_node_attr = n_xmlp_node.getAttributes(); Node n = null; String p_target = null; //get target... n = n_xmlp_node_attr.getNamedItem("target"); if (n != null) p_target = n.getNodeValue(); if (p_target == null) { printlnerr(0, "Load has no target!"); continue; } HashMap<String, String> options = new HashMap<String, String>(); for (int i = 0; i < n_xmlp_node_attr.getLength(); i++) { Node item = n_xmlp_node_attr.item(i); if (!item.getNodeName().equals("target")) { options.put(item.getNodeName(), item.getNodeValue()); } } printlnout(0, "Loading \""+p_target+"\" with options... "+options); getDoc(rootDir, p_target, options); } } } }
public void applyPatch(File patchFile, File rootDir) throws Exception { DocumentBuilderFactory patFac = DocumentBuilderFactory.newInstance(); DocumentBuilder patBuilder = patFac.newDocumentBuilder(); Document patchDoc = patBuilder.parse(new FileInputStream(patchFile)); Node n_xmlp = patchDoc.getFirstChild(); if (!n_xmlp.getNodeName().equals("xmlp")) throw new RuntimeException("Root patch node must be named \"xmlp\""); for (Node n_xmlp_node = n_xmlp.getFirstChild(); n_xmlp_node != null; n_xmlp_node = n_xmlp_node.getNextSibling()) { if (n_xmlp_node instanceof Element) { Element e_xmlp_node = (Element) n_xmlp_node; if (n_xmlp_node.getNodeName().equals("patch")) { String patch_name = e_xmlp_node.getAttribute("name"); if (patch_name == null || patch_name.isEmpty()) printlnout(0, "Running anonymous patch..."); else printlnout(0, "Running patch \""+patch_name+"\"..."); ArrayList<XMLQuery> queryList = new ArrayList<XMLQuery>(); patchLoop: for (Node n_xmlp_patch_node = n_xmlp_node.getFirstChild(); n_xmlp_patch_node != null; n_xmlp_patch_node = n_xmlp_patch_node.getNextSibling()) { if (n_xmlp_patch_node instanceof Element) { Element e_xmlp_patch_node = (Element) n_xmlp_patch_node; if (n_xmlp_patch_node.getNodeName().equals("addnodes")) { String p_target = e_xmlp_patch_node.getAttribute("target"); String p_query = e_xmlp_patch_node.getAttribute("query"); if (p_target == null || p_target.isEmpty()) { printlnerr(0, "AddQuery has no target!"); continue; } if (p_query == null || p_query.isEmpty()) { printlnerr(0, "AddQuery has no query!"); continue; } printlnout(2, "Adding nodes with query \""+p_target+"\":\""+p_query+"\"..."); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (q.target.equals(p_target) && q.query.equals(p_query)) { if (q.negative) { printlnerr(0, "Warning: tried to add duplicate query!"); continue patchLoop; } else { printlnerr(0, "Warning: cancelling out previous query!"); } } } Document doc = getDoc(rootDir, p_target, null); NodeList nodes = getNodes(doc, p_query); queryList.add(new XMLQuery(doc, p_target, p_query, nodes, false)); } else if (n_xmlp_patch_node.getNodeName().equals("remnodes")) { String p_target = e_xmlp_patch_node.getAttribute("target"); String p_query = e_xmlp_patch_node.getAttribute("query"); if (p_target == null || p_target.isEmpty()) { printlnerr(0, "AddQuery has no target!"); continue; } if (p_query == null || p_query.isEmpty()) { printlnerr(0, "AddQuery has no query!"); continue; } printlnout(2, "Removing nodes with query \""+p_target+"\":\""+p_query+"\"..."); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (q.target.equals(p_target) && q.query.equals(p_query)) { if (q.negative) { printlnerr(0, "Warning: tried to add duplicate query!"); continue patchLoop; } else { printlnerr(0, "Warning: cancelling out previous query!"); } } } Document doc = getDoc(rootDir, p_target, null); NodeList nodes = getNodes(doc, p_query); queryList.add(new XMLQuery(doc, p_target, p_query, nodes, true)); } else if (n_xmlp_patch_node.getNodeName().equals("remquery")) { String p_target = e_xmlp_patch_node.getAttribute("target"); String p_query = e_xmlp_patch_node.getAttribute("query"); if (p_target == null || p_target.isEmpty()) { printlnerr(0, "RemQuery has no target!"); continue; } if (p_query == null || p_query.isEmpty()) { printlnerr(0, "RemQuery has no query!"); continue; } printlnout(2, "Removing query \""+p_target+"\":\""+p_query+"\"..."); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (q.target.equals(p_target) && q.query.equals(p_query)) { queryList.remove(i); break; } } } else if (n_xmlp_patch_node.getNodeName().equals("clearqueries")) { printlnout(2, "Clearing query list..."); queryList.clear(); } else if (n_xmlp_patch_node.getNodeName().equals("op")) { NamedNodeMap n_xmlp_patch_op_attr = n_xmlp_patch_node.getAttributes(); String p_op = e_xmlp_patch_node.getAttribute("id"); if (p_op == null || p_op.isEmpty()) { printlnerr(0, "Op has no id!"); continue; } XMLPatchOp op = opList.get(p_op); if (op == null) { printlnerr(0, "Unrecognized op! (\""+p_op+"\")"); continue; } ArrayList<Node> nodes = new ArrayList<Node>(); for (int i = 0; i < queryList.size(); i++) { XMLQuery q = queryList.get(i); if (q.negative) { printlnout(1, "Removing nodes \""+q.target+"\":\""+q.query+"\" from \""+p_op+"\" execution..."); nodes.removeAll(new NodeListList(q.result)); } else { printlnout(1, "Adding nodes \""+q.target+"\":\""+q.query+"\" to \""+p_op+"\" execution..."); nodes.addAll(new NodeListList(q.result)); } } applyOp(nodes, (Element)n_xmlp_patch_node, op); } } } } else if (n_xmlp_node.getNodeName().equals("load")) { NamedNodeMap n_xmlp_node_attr = n_xmlp_node.getAttributes(); Node n = null; String p_target = null; //get target... n = n_xmlp_node_attr.getNamedItem("target"); if (n != null) p_target = n.getNodeValue(); if (p_target == null) { printlnerr(0, "Load has no target!"); continue; } HashMap<String, String> options = new HashMap<String, String>(); for (int i = 0; i < n_xmlp_node_attr.getLength(); i++) { Node item = n_xmlp_node_attr.item(i); if (!item.getNodeName().equals("target")) { options.put(item.getNodeName(), item.getNodeValue()); } } printlnout(0, "Loading \""+p_target+"\" with options... "+options); getDoc(rootDir, p_target, options); } } } }
diff --git a/ThePantry/src/cs169/project/thepantry/RecipeActivity.java b/ThePantry/src/cs169/project/thepantry/RecipeActivity.java index 60bed3d..7246b19 100644 --- a/ThePantry/src/cs169/project/thepantry/RecipeActivity.java +++ b/ThePantry/src/cs169/project/thepantry/RecipeActivity.java @@ -1,374 +1,374 @@ package cs169.project.thepantry; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.loopj.android.image.SmartImageView; import cs169.project.thepantry.ThePantryContract.ShoppingList; public class RecipeActivity extends BasicMenuActivity { Recipe recipe; String type; SmartImageView picture; TextView name; ImageButton star; ImageButton check; LinearLayout ll; LinearLayout ings; static ArrayList<CheckBox> ingChecks; boolean faved; boolean cooked; static DatabaseModel dm; private static final String DATABASE_NAME = "thepantry"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); //Get bundle with recipe information. //Intent i = this.getIntent(); recipe = (Recipe)getIntent().getExtras().getSerializable("result"); type = getIntent().getExtras().getString("type"); //Display recipe picture if there is one. picture = (SmartImageView)findViewById(R.id.recipePic); if (recipe.images != null && recipe.images.hostedLargeUrl != null && isOnline()) { picture.setImageUrl(recipe.images.hostedLargeUrl); picture.setScaleType(ImageView.ScaleType.CENTER_CROP); } //Display recipe name. name = (TextView)findViewById(R.id.recipeName); name.setText(recipe.name); //Render the ingredients list to view. ingChecks = new ArrayList<CheckBox>(); ings = (LinearLayout)findViewById(R.id.ingList); displayIngreds(recipe.ingredientLines); //Render directions to view. //fetch and parse directions aynchronously dm = new DatabaseModel(this, DATABASE_NAME); - if (dm.findItem(ThePantryContract.Recipe.TABLE_NAME, recipe.id) || dm.findItem(ThePantryContract.CookBook.TABLE_NAME, recipe.id)) { + if (dm.findItem(ThePantryContract.Recipe.TABLE_NAME, recipe.id) || dm.findItem(ThePantryContract.CookBook.TABLE_NAME, recipe.id) || recipe.source == null) { displayDirections(recipe.directionLines); } else { new ParseDirectionsTask().execute(recipe.source.sourceRecipeUrl); } Button source = (Button)findViewById(R.id.source); star = (ImageButton)findViewById(R.id.favorite); check = (ImageButton)findViewById(R.id.cooked); //display the source and link to the web page source, open in a webview inside the app if clicked if (type.equals("cookbook")) { source.setVisibility(View.GONE); star.setVisibility(View.GONE); check.setVisibility(View.GONE); } else { if (recipe.source != null) { source.setText("Source: " + recipe.source.sourceDisplayName); source.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { displayWebpage(recipe.source.sourceRecipeUrl); } }); } dm = new DatabaseModel(this, DATABASE_NAME); // check if recipe is in database and get favorite and cooked values true or false faved = dm.isItemChecked(ThePantryContract.Recipe.TABLE_NAME, recipe.id, ThePantryContract.Recipe.FAVORITE); cooked = dm.isItemChecked(ThePantryContract.Recipe.TABLE_NAME, recipe.id, ThePantryContract.Recipe.COOKED); //set favorite button to grayscale or colored image based on state in db //check if recipe in database or if not favorited setStarButton(faved); //set cooked button to grayscale or colored image based on state in db //check if recipe is in db or not cooked setCheckButton(cooked); dm.close(); } } // show all the ingredients in the ings layout public void displayIngreds(List<String> ingreds) { for (String ingred : ingreds) { CheckBox tv = new CheckBox(this); tv.setText(ingred); ings.addView(tv); ingChecks.add(tv); } } // return a string of all checked items public static String getCheckedIngredientsString() { String message = ""; for (CheckBox cb : ingChecks) { String ingred = (String) cb.getText(); if (cb.isChecked()) { // TODO: parse amount and item, check for ingredient and previous amount String[] parsed = IngredientParser.parse(ingred); String amt = parsed[0] + " " + parsed[1]; String ingred_name = parsed[3]; message += "Ingredient: " + ingred_name + ", Amount: " + amt + "\n"; } } return message; } // open the ingredient adding dialog public void openIngDialog(View v) { AddIngredientsDialogFragment dialog = new AddIngredientsDialogFragment(); dialog.context = this; dialog.show(getFragmentManager(), "dialog"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getSupportMenuInflater().inflate(R.menu.recipe, menu); return true; } /** * Set favorite button to correct image either grayscale for not favorited * or color for favorited */ public void setStarButton(boolean faveStatus) { if (faveStatus) { star.setBackgroundResource(R.drawable.star_on); } else { star.setBackgroundResource(R.drawable.star_off); } } /** * Set cooked button to correct image either grayscale for not cooked * or color for cooked */ public void setCheckButton(boolean cookStatus) { if (cookStatus) { check.setBackgroundResource(R.drawable.check_on); } else { check.setBackgroundResource(R.drawable.check_off); } } /** * saves this recipe to the favorites list. * TODO -=--need to add in refreshing the favs fragment adapter */ public void toggleFavorites(View v) { // update recipe table of database so favorited column is yes/no Toast toast; dm = new DatabaseModel(this, DATABASE_NAME); // need to add recipe to database if not already in it dm.addStorage(ThePantryContract.Recipe.TABLE_NAME, recipe); faved = !faved; dm.check(ThePantryContract.Recipe.TABLE_NAME, recipe.id, ThePantryContract.Recipe.FAVORITE, faved); if (faved) { toast = Toast.makeText(this, "This recipe has been added to your favorites!", Toast.LENGTH_SHORT); } else { toast = Toast.makeText(this, "This recipe has been removed from your favorites!", Toast.LENGTH_SHORT); } toast.show(); setStarButton(faved); dm.close(); } /** * marks this recipe as having been cooked before and updates inventory * according to ingredients list. * TODO -=--need to add in refreshing the cooked fragment adapter */ public void toggleCooked(View v) { // update recipe table of database so cooked column is true Toast toast; dm = new DatabaseModel(this, DATABASE_NAME); // need to add recipe if not already in database dm.addStorage(ThePantryContract.Recipe.TABLE_NAME, recipe); cooked = !cooked; dm.check(ThePantryContract.Recipe.TABLE_NAME, recipe.id, ThePantryContract.Recipe.COOKED, cooked); if (cooked) { toast = Toast.makeText(this, "You have cooked this recipe!", Toast.LENGTH_SHORT); } else { toast = Toast.makeText(this, "You haven't cooked this recipe before!", Toast.LENGTH_SHORT); } toast.show(); setCheckButton(cooked); dm.close(); } /** * checks inventory for ingredients and adds missing ingredients to * shopping list */ public static void addToShopping(Context context) { // for each ingredient in list for (CheckBox cb : ingChecks) { String ingred = (String) cb.getText(); if (cb.isChecked()) { // TODO: parse amount and item, check for ingredient and previous amount String[] parsed = IngredientParser.parse(ingred); String amt = parsed[0] + " " + parsed[1]; String ingred_name = parsed[3]; dm = new DatabaseModel(context, DATABASE_NAME); dm.addIngredient(ShoppingList.TABLE_NAME, ingred_name, "Other", amt); dm.close(); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } // display webpage activity with the url public void displayWebpage(String url) { Intent intent = new Intent(getApplicationContext(), DisplayWebpageActivity.class); intent.putExtra("url", url); startActivity(intent); } public void displayDirections(ArrayList<String> directionsList) { if (directionsList != null && directionsList.size() > 0 && !directionsList.get(0).equals("")){ for (int i = 0; i < directionsList.size(); i++) { LinearLayout directionsll = (LinearLayout)findViewById(R.id.dirList); LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View thisDirection = inflater.inflate(R.layout.direction, null); TextView number = (TextView)thisDirection.findViewById(R.id.number); number.setText(i+1+""); TextView directions = (TextView)thisDirection.findViewById(R.id.direction); directions.setText(directionsList.get(i)); directionsll.addView(thisDirection); } } else { LinearLayout directionsll = (LinearLayout)findViewById(R.id.dirList); LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View thisDirection = inflater.inflate(R.layout.direction, null); TextView directions = (TextView)thisDirection.findViewById(R.id.direction); // Change layout for this text directions.setText("Directions currently unavailable"); directionsll.addView(thisDirection); } } /* Class for asynchronously retrieving directions * calls DirectionParser on the recipe url */ public class ParseDirectionsTask extends AsyncTask<String, Void, ArrayList<String>> { FrameLayout mFrameOverlay; @Override protected void onPreExecute() { mFrameOverlay = (FrameLayout)findViewById(R.id.overlay); mFrameOverlay.setVisibility(View.VISIBLE); }; @Override protected ArrayList<String> doInBackground(String... url) { return DirectionParser.getDirections(url[0]); } @Override protected void onPostExecute(ArrayList<String> directionsList) { //store these directions in the recipe database //also store the recipe dm = new DatabaseModel(RecipeActivity.this, DATABASE_NAME); recipe.directionLines = directionsList; boolean success; if (dm.findItem(ThePantryContract.Recipe.TABLE_NAME, recipe.id)){ success = dm.setDirections(ThePantryContract.Recipe.TABLE_NAME, recipe.id, directionsList); }else { success = dm.addStorage(ThePantryContract.Recipe.TABLE_NAME, recipe); } // Do something with success? dm.close(); mFrameOverlay.setVisibility(View.GONE); displayDirections(directionsList); } } /* Class for displaying popup dialog for adding ingredients * */ public static class AddIngredientsDialogFragment extends DialogFragment { Context context; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.dialog_add_ingredients_to_shopping_list) .setMessage(getCheckedIngredientsString()) // TODO: change to editable view .setPositiveButton(R.string.dialog_add_and_return, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { addToShopping(context); } }) .setNeutralButton(R.string.dialog_go_to_shopping, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { addToShopping(context); Intent intent = new Intent(getActivity(), ShoppingListActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }) .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); // Create the AlertDialog object and return it return builder.create(); } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); //Get bundle with recipe information. //Intent i = this.getIntent(); recipe = (Recipe)getIntent().getExtras().getSerializable("result"); type = getIntent().getExtras().getString("type"); //Display recipe picture if there is one. picture = (SmartImageView)findViewById(R.id.recipePic); if (recipe.images != null && recipe.images.hostedLargeUrl != null && isOnline()) { picture.setImageUrl(recipe.images.hostedLargeUrl); picture.setScaleType(ImageView.ScaleType.CENTER_CROP); } //Display recipe name. name = (TextView)findViewById(R.id.recipeName); name.setText(recipe.name); //Render the ingredients list to view. ingChecks = new ArrayList<CheckBox>(); ings = (LinearLayout)findViewById(R.id.ingList); displayIngreds(recipe.ingredientLines); //Render directions to view. //fetch and parse directions aynchronously dm = new DatabaseModel(this, DATABASE_NAME); if (dm.findItem(ThePantryContract.Recipe.TABLE_NAME, recipe.id) || dm.findItem(ThePantryContract.CookBook.TABLE_NAME, recipe.id)) { displayDirections(recipe.directionLines); } else { new ParseDirectionsTask().execute(recipe.source.sourceRecipeUrl); } Button source = (Button)findViewById(R.id.source); star = (ImageButton)findViewById(R.id.favorite); check = (ImageButton)findViewById(R.id.cooked); //display the source and link to the web page source, open in a webview inside the app if clicked if (type.equals("cookbook")) { source.setVisibility(View.GONE); star.setVisibility(View.GONE); check.setVisibility(View.GONE); } else { if (recipe.source != null) { source.setText("Source: " + recipe.source.sourceDisplayName); source.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { displayWebpage(recipe.source.sourceRecipeUrl); } }); } dm = new DatabaseModel(this, DATABASE_NAME); // check if recipe is in database and get favorite and cooked values true or false faved = dm.isItemChecked(ThePantryContract.Recipe.TABLE_NAME, recipe.id, ThePantryContract.Recipe.FAVORITE); cooked = dm.isItemChecked(ThePantryContract.Recipe.TABLE_NAME, recipe.id, ThePantryContract.Recipe.COOKED); //set favorite button to grayscale or colored image based on state in db //check if recipe in database or if not favorited setStarButton(faved); //set cooked button to grayscale or colored image based on state in db //check if recipe is in db or not cooked setCheckButton(cooked); dm.close(); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); //Get bundle with recipe information. //Intent i = this.getIntent(); recipe = (Recipe)getIntent().getExtras().getSerializable("result"); type = getIntent().getExtras().getString("type"); //Display recipe picture if there is one. picture = (SmartImageView)findViewById(R.id.recipePic); if (recipe.images != null && recipe.images.hostedLargeUrl != null && isOnline()) { picture.setImageUrl(recipe.images.hostedLargeUrl); picture.setScaleType(ImageView.ScaleType.CENTER_CROP); } //Display recipe name. name = (TextView)findViewById(R.id.recipeName); name.setText(recipe.name); //Render the ingredients list to view. ingChecks = new ArrayList<CheckBox>(); ings = (LinearLayout)findViewById(R.id.ingList); displayIngreds(recipe.ingredientLines); //Render directions to view. //fetch and parse directions aynchronously dm = new DatabaseModel(this, DATABASE_NAME); if (dm.findItem(ThePantryContract.Recipe.TABLE_NAME, recipe.id) || dm.findItem(ThePantryContract.CookBook.TABLE_NAME, recipe.id) || recipe.source == null) { displayDirections(recipe.directionLines); } else { new ParseDirectionsTask().execute(recipe.source.sourceRecipeUrl); } Button source = (Button)findViewById(R.id.source); star = (ImageButton)findViewById(R.id.favorite); check = (ImageButton)findViewById(R.id.cooked); //display the source and link to the web page source, open in a webview inside the app if clicked if (type.equals("cookbook")) { source.setVisibility(View.GONE); star.setVisibility(View.GONE); check.setVisibility(View.GONE); } else { if (recipe.source != null) { source.setText("Source: " + recipe.source.sourceDisplayName); source.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { displayWebpage(recipe.source.sourceRecipeUrl); } }); } dm = new DatabaseModel(this, DATABASE_NAME); // check if recipe is in database and get favorite and cooked values true or false faved = dm.isItemChecked(ThePantryContract.Recipe.TABLE_NAME, recipe.id, ThePantryContract.Recipe.FAVORITE); cooked = dm.isItemChecked(ThePantryContract.Recipe.TABLE_NAME, recipe.id, ThePantryContract.Recipe.COOKED); //set favorite button to grayscale or colored image based on state in db //check if recipe in database or if not favorited setStarButton(faved); //set cooked button to grayscale or colored image based on state in db //check if recipe is in db or not cooked setCheckButton(cooked); dm.close(); } }
diff --git a/src/soot/jimple/toolkits/callgraph/VirtualCalls.java b/src/soot/jimple/toolkits/callgraph/VirtualCalls.java index 66dfee1c..ce96c8aa 100644 --- a/src/soot/jimple/toolkits/callgraph/VirtualCalls.java +++ b/src/soot/jimple/toolkits/callgraph/VirtualCalls.java @@ -1,142 +1,145 @@ /* Soot - a J*va Optimization Framework * Copyright (C) 2003 Ondrej Lhotak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package soot.jimple.toolkits.callgraph; import soot.*; import soot.jimple.*; import java.util.*; import soot.util.*; import soot.util.queue.*; /** Resolves virtual calls. * @author Ondrej Lhotak */ public final class VirtualCalls { public VirtualCalls( Singletons.Global g ) {} public static VirtualCalls v() { return G.v().VirtualCalls(); } private LargeNumberedMap typeToVtbl = new LargeNumberedMap( Scene.v().getTypeNumberer() ); private SootMethod resolveRefType( RefType t, InstanceInvokeExpr iie, NumberedString subSig, SootMethod container ) { if( iie instanceof SpecialInvokeExpr ) { SootMethod target = iie.getMethod(); /* cf. JVM spec, invokespecial instruction */ if( Scene.v().getOrMakeFastHierarchy() .canStoreType( container.getDeclaringClass().getType(), target.getDeclaringClass().getType() ) && container.getDeclaringClass().getType() != target.getDeclaringClass().getType() && !target.getName().equals( "<init>" ) && subSig != sigClinit ) { t = container.getDeclaringClass().getSuperclass().getType(); } else { return target; } } return resolveNonSpecial( t, iie, container, subSig ); } private SootMethod resolveNonSpecial( RefType t, InstanceInvokeExpr iie, SootMethod container, NumberedString subSig ) { SmallNumberedMap vtbl = (SmallNumberedMap) typeToVtbl.get( t ); if( vtbl == null ) { typeToVtbl.put( t, vtbl = new SmallNumberedMap( Scene.v().getMethodNumberer() ) ); } SootMethod ret = (SootMethod) vtbl.get( subSig ); if( ret != null ) return ret; SootClass cls = ((RefType)t).getSootClass(); if( cls.declaresMethod( subSig ) ) { SootMethod m = cls.getMethod( subSig ); if( m.isConcrete() || m.isNative() ) { ret = cls.getMethod( subSig ); } } else { if( cls.hasSuperclass() ) { ret = resolveNonSpecial( cls.getSuperclass().getType(), iie, container, subSig ); } } vtbl.put( subSig, ret ); return ret; } public void resolve( Type t, InstanceInvokeExpr iie, NumberedString subSig, SootMethod container, ChunkedQueue targets ) { if( iie != null && !Scene.v().getOrMakeFastHierarchy() .canStoreType( t, iie.getBase().getType() ) ) { return; } if( t instanceof ArrayType ) t = RefType.v( "java.lang.Object" ); if( t instanceof RefType ) { SootMethod target = resolveRefType( (RefType) t, iie, subSig, container ); if( target != null ) targets.add( target ); } else if( t instanceof AnySubType ) { + if( iie instanceof SpecialInvokeExpr ) { + targets.add( resolveRefType( null, iie, subSig, container ) ); + return; + } RefType base = ((AnySubType)t).getBase(); resolve( base, iie, subSig, container, targets ); - if( iie instanceof SpecialInvokeExpr ) return; LinkedList worklist = new LinkedList(); HashSet workset = new HashSet(); FastHierarchy fh = Scene.v().getOrMakeFastHierarchy(); SootClass cl = base.getSootClass(); if( workset.add( cl ) ) worklist.add( cl ); while( !worklist.isEmpty() ) { cl = (SootClass) worklist.removeFirst(); if( cl.isInterface() ) { for( Iterator cIt = fh.getAllImplementersOfInterface(cl).iterator(); cIt.hasNext(); ) { final SootClass c = (SootClass) cIt.next(); if( workset.add( c ) ) worklist.add( c ); } } else { resolve( cl.getType(), iie, subSig, container, targets ); for( Iterator cIt = fh.getSubclassesOf( cl ).iterator(); cIt.hasNext(); ) { final SootClass c = (SootClass) cIt.next(); if( workset.add( c ) ) worklist.add( c ); } } } } else if( t instanceof NullType ) { } else { throw new RuntimeException( "oops "+t ); } } public void resolve( Type t, InstanceInvokeExpr iie, SootMethod container, ChunkedQueue targets ) { resolve( t, iie, iie.getMethod().getNumberedSubSignature(), container, targets ); } public void resolveThread( Type t, InstanceInvokeExpr iie, SootMethod container, ChunkedQueue targets ) { if( iie.getMethod().getNumberedSubSignature() != sigStart ) return; if( !Scene.v().getOrMakeFastHierarchy() .canStoreType( t, RefType.v( "java.lang.Runnable" ) ) ) return; resolve( t, iie, sigRun, container, targets ); } public final NumberedString sigClinit = Scene.v().getSubSigNumberer().findOrAdd("void <clinit>()"); public final NumberedString sigStart = Scene.v().getSubSigNumberer().findOrAdd("void start()"); public final NumberedString sigRun = Scene.v().getSubSigNumberer().findOrAdd("void run()"); }
false
true
public void resolve( Type t, InstanceInvokeExpr iie, NumberedString subSig, SootMethod container, ChunkedQueue targets ) { if( iie != null && !Scene.v().getOrMakeFastHierarchy() .canStoreType( t, iie.getBase().getType() ) ) { return; } if( t instanceof ArrayType ) t = RefType.v( "java.lang.Object" ); if( t instanceof RefType ) { SootMethod target = resolveRefType( (RefType) t, iie, subSig, container ); if( target != null ) targets.add( target ); } else if( t instanceof AnySubType ) { RefType base = ((AnySubType)t).getBase(); resolve( base, iie, subSig, container, targets ); if( iie instanceof SpecialInvokeExpr ) return; LinkedList worklist = new LinkedList(); HashSet workset = new HashSet(); FastHierarchy fh = Scene.v().getOrMakeFastHierarchy(); SootClass cl = base.getSootClass(); if( workset.add( cl ) ) worklist.add( cl ); while( !worklist.isEmpty() ) { cl = (SootClass) worklist.removeFirst(); if( cl.isInterface() ) { for( Iterator cIt = fh.getAllImplementersOfInterface(cl).iterator(); cIt.hasNext(); ) { final SootClass c = (SootClass) cIt.next(); if( workset.add( c ) ) worklist.add( c ); } } else { resolve( cl.getType(), iie, subSig, container, targets ); for( Iterator cIt = fh.getSubclassesOf( cl ).iterator(); cIt.hasNext(); ) { final SootClass c = (SootClass) cIt.next(); if( workset.add( c ) ) worklist.add( c ); } } } } else if( t instanceof NullType ) { } else { throw new RuntimeException( "oops "+t ); } }
public void resolve( Type t, InstanceInvokeExpr iie, NumberedString subSig, SootMethod container, ChunkedQueue targets ) { if( iie != null && !Scene.v().getOrMakeFastHierarchy() .canStoreType( t, iie.getBase().getType() ) ) { return; } if( t instanceof ArrayType ) t = RefType.v( "java.lang.Object" ); if( t instanceof RefType ) { SootMethod target = resolveRefType( (RefType) t, iie, subSig, container ); if( target != null ) targets.add( target ); } else if( t instanceof AnySubType ) { if( iie instanceof SpecialInvokeExpr ) { targets.add( resolveRefType( null, iie, subSig, container ) ); return; } RefType base = ((AnySubType)t).getBase(); resolve( base, iie, subSig, container, targets ); LinkedList worklist = new LinkedList(); HashSet workset = new HashSet(); FastHierarchy fh = Scene.v().getOrMakeFastHierarchy(); SootClass cl = base.getSootClass(); if( workset.add( cl ) ) worklist.add( cl ); while( !worklist.isEmpty() ) { cl = (SootClass) worklist.removeFirst(); if( cl.isInterface() ) { for( Iterator cIt = fh.getAllImplementersOfInterface(cl).iterator(); cIt.hasNext(); ) { final SootClass c = (SootClass) cIt.next(); if( workset.add( c ) ) worklist.add( c ); } } else { resolve( cl.getType(), iie, subSig, container, targets ); for( Iterator cIt = fh.getSubclassesOf( cl ).iterator(); cIt.hasNext(); ) { final SootClass c = (SootClass) cIt.next(); if( workset.add( c ) ) worklist.add( c ); } } } } else if( t instanceof NullType ) { } else { throw new RuntimeException( "oops "+t ); } }
diff --git a/vtk-util/src/org/jcae/vtk/AbstractNode.java b/vtk-util/src/org/jcae/vtk/AbstractNode.java index 93917ca6..d75b7d79 100644 --- a/vtk-util/src/org/jcae/vtk/AbstractNode.java +++ b/vtk-util/src/org/jcae/vtk/AbstractNode.java @@ -1,606 +1,606 @@ /* * Project Info: http://jcae.sourceforge.net * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. * * (C) Copyright 2008, by EADS France */ package org.jcae.vtk; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import vtk.vtkActor; import vtk.vtkCellArray; import vtk.vtkFloatArray; import vtk.vtkMapper; import vtk.vtkPainterPolyDataMapper; import vtk.vtkPointData; import vtk.vtkPoints; import vtk.vtkPolyData; import vtk.vtkPolyDataMapper; import vtk.vtkPolyDataNormals; import vtk.vtkProperty; /** * Nodes of scene graph. * The aim of a viewer is of course to display graphical objects. But a scene is * not static, view has to be refreshed when properties change. For instance * when an object is selected, it is highlighted. Color or material may also * be edited by user, and scene has to be rebuild quickly. * * With OpenGL, one can concatenate static objects into so-called display lists, * and compile them so that rendering is very fast. But if an object changes, * display list has to be rebuilt, which can be slow. This must be taken into * account when designing a data structure, otherwise performance can become * very poor. * * The same logic applies to VTK as well. A vtkActor is an object which will * be compiled and can be rendered efficiently. Its geometry is defined by * a vtkMapper, more exactly a vtkPolyDataMapper in our case. It takes some * time to build OpenGL primitives from this geometry, but when this is done, * rendering is very fast when camera moves or vtkActor is highlighted. * It is also possible to change only a subset of properties associated to * geometric data, to highlight only some cells, but this may also take some * time if dataset is very large. * * VTK becomes too slow when there are many actors, but on the other hand * interactive changes become also too slow if too many data are put into * actors. We implemented a tree graph to help merging geometric entities * into single actors. There are two types of nodes: * <ul> * <li>{@link Node}: containers, its children may be Node or LeafNode instances;</li> * <li>{@link LeafNode}: leaf nodes contain geometric data.</li> * </ul> * * This merge is performed only if the Node is set as managing (by using the * {@link #setManager()} method). FIXME: a managing Node can currently contain * either Node or LeafNode instances, but in practice it almost always contains * LeafNode. If we make this a rule, recursive behavior of these nodes will * be much easier to implement and more efficient too. * * This is a general framework, only application developers can know how to * organize their geometrical objects into Node and LeafNode. * * Nodes can be highlighted using the {@link #select} method. A subset of * their underlying geometry can be highlighted using the {@link #setCellSelection} * method, which modifies {@link #selectionActor} actor. * * Nodes can be declared as being not pickable to speed up picking, since non * pickable nodes are ignored. * * You can give customisers to the nodes. This works as follows: if a leaf node * has no customiser it takes the first parent that have one and if nobody have * customiser the DEFAULT customiser is taken. This permits to create a * customiser for the parent node and this will be used for all of its children * (unless if the child has a customiser). Customisers are created to permit * to change and customise VTK objects easily. Actually only color can be * specified for shading of the geometry. If you want to customise the nodes * more you can use the VTK interface but if you merge the leaves in one node * and they have different materials this will cause problems. The solution to * this is that VTK permits to make materials data arrays like color array. * * The node by default take some characteristics of the parent node for example the pickability * and the visibility. * When applying a customiser the actor customisation is refreshed and if we are in a Node, * all the children inherit it. * * @author Julian Ibarz */ public abstract class AbstractNode { private final static Logger LOGGER = Logger.getLogger(AbstractNode.class.getName()); /** Parent node */ protected final Node parent; private final ArrayList<ActorListener> actorListeners = new ArrayList<ActorListener>(); /** Flag to tell if this node is a manager */ private boolean manager; /** Actor of this node, if it is a manager */ protected vtkActor actor; /** Geometry of this actor */ protected vtkPainterPolyDataMapper mapper; protected vtkPolyData data; /** Actor used for selection */ protected vtkActor selectionActor; protected vtkPolyDataMapper selectionMapper; /** Last time this actor had been updated */ protected long lastUpdate; /** Last time data of this actor had been modified */ protected long dataTime; /** Last time this actor had been modified (data, color, visibility) */ protected long modificationTime; /** Last time this node had been selected */ protected long selectionTime; // Useful for debugging private String debugName; protected boolean visible = true; protected boolean selected; protected boolean pickable; public static interface ActorListener { void actorCreated(AbstractNode node, vtkActor actor); void actorDeleted(AbstractNode node, vtkActor actor); } /** * Customise actor when node is not selected. */ public interface ActorCustomiser { void customiseActor(vtkActor actor); } /** * Customise mapper when node is not selected. */ public interface MapperCustomiser { void customiseMapper(vtkMapper mapper); } /** * Default actor customiser, it does nothing. */ public static ActorCustomiser DEFAULT_ACTOR_CUSTOMISER = new ActorCustomiser() { @Override public void customiseActor(vtkActor actor) {} }; /** * Default mapper customiser, it calls vtkMapper.SetResolveCoincidentTopologyToPolygonOffset. */ public static MapperCustomiser DEFAULT_MAPPER_CUSTOMISER = new MapperCustomiser() { @Override public void customiseMapper(vtkMapper mapper) { mapper.SetResolveCoincidentTopologyToPolygonOffset(); mapper.SetResolveCoincidentTopologyPolygonOffsetParameters(Utils.getOffsetFactor(), Utils.getOffsetValue()); } }; /** * Default actor customiser when cells of this node are selected, it does nothing. */ public static ActorCustomiser DEFAULT_SELECTION_ACTOR_CUSTOMISER = new ActorCustomiser() { @Override public void customiseActor(vtkActor actor) {} }; /** * Default mapper customiser when cells of this node are selected, it does nothing. */ public static MapperCustomiser DEFAULT_SELECTION_MAPPER_CUSTOMISER = new MapperCustomiser() { @Override public void customiseMapper(vtkMapper mapper) {} }; protected ActorCustomiser actorCustomiser; protected MapperCustomiser mapperCustomiser; protected ActorCustomiser selectionActorCustomiser; protected MapperCustomiser selectionMapperCustomiser; /** * Constructor. It must not be called directly, only by subclasses. * * @param parent parent node */ protected AbstractNode(Node parent) { this.parent = parent; if(parent != null) { pickable = parent.pickable; visible = parent.visible; } } protected vtkActor createActor() { return new vtkActor(); } public Node getParent() { return parent; } public abstract List<LeafNode> getLeaves(); /** * Set pickable the actor of the node. If the node is not a manager, * it does nothing. * @param pickable */ public void setPickable(boolean pickable) { this.pickable = pickable; if(actor != null) actor.SetPickable(Utils.booleanToInt(pickable)); } public boolean isPickable() { return pickable; } public void addActorListener(ActorListener listener) { actorListeners.add(listener); } public void removeActorListener(ActorListener listener) { actorListeners.remove(listener); } public vtkActor getActor() { return actor; } protected void fireActorCreated(vtkActor actor) { for (ActorListener listener : actorListeners) listener.actorCreated(this, actor); } protected void fireActorDeleted(vtkActor actor) { for (ActorListener listener : actorListeners) listener.actorDeleted(this, actor); } public void setActorCustomiser(ActorCustomiser actorCustomiser) { this.actorCustomiser = actorCustomiser; timeStampModified(); } public void setMapperCustomiser(MapperCustomiser mapperCustomiser) { this.mapperCustomiser = mapperCustomiser; timeStampModified(); } public ActorCustomiser getSelectionActorCustomiser() { if(selectionActorCustomiser != null) return selectionActorCustomiser; else if(parent != null) selectionActorCustomiser = parent.getSelectionActorCustomiser(); if(selectionActorCustomiser == null) selectionActorCustomiser = DEFAULT_SELECTION_ACTOR_CUSTOMISER; return selectionActorCustomiser; } public void setSelectionActorCustomiser(ActorCustomiser selectionActorCustomiser) { this.selectionActorCustomiser = selectionActorCustomiser; timeStampSelected(); } public MapperCustomiser getSelectionMapperCustomiser() { if(selectionMapperCustomiser != null) return selectionMapperCustomiser; if(parent != null) selectionMapperCustomiser = parent.getSelectionMapperCustomiser(); if(selectionMapperCustomiser == null) selectionMapperCustomiser = DEFAULT_SELECTION_MAPPER_CUSTOMISER; return selectionMapperCustomiser; } public void setSelectionMapperCustomiser(MapperCustomiser selectionMapperCustomiser) { this.selectionMapperCustomiser = selectionMapperCustomiser; timeStampSelected(); } public ActorCustomiser getActorCustomiser() { if(actorCustomiser != null) return actorCustomiser; if(parent != null) actorCustomiser = parent.getActorCustomiser(); if(actorCustomiser == null) actorCustomiser = DEFAULT_ACTOR_CUSTOMISER; return actorCustomiser; } public MapperCustomiser getMapperCustomiser() { if(mapperCustomiser != null) return mapperCustomiser; if(parent != null) mapperCustomiser = parent.getMapperCustomiser(); if(mapperCustomiser == null) mapperCustomiser = DEFAULT_MAPPER_CUSTOMISER; return mapperCustomiser; } protected void timeStampData() { dataTime = System.nanoTime(); // When data are modified, actor must be updated timeStampModified(); if (!manager && parent != null) parent.timeStampData(); } protected void timeStampModified() { modificationTime = System.nanoTime(); if (!manager && parent != null) parent.timeStampModified(); } protected void timeStampSelected() { selectionTime = System.nanoTime(); if (!manager && parent != null) parent.timeStampSelected(); } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { if(this.visible == visible) return; this.visible = visible; if(actor != null) actor.SetVisibility(Utils.booleanToInt(visible)); timeStampModified(); // If node is not a manager, its manager have to update // their data. if (!manager && parent != null) parent.timeStampData(); } protected abstract void refresh(); protected void createData(LeafNode.DataProvider dataProvider) { data = new vtkPolyData(); data.SetPoints(Utils.createPoints(dataProvider.getNodes())); vtkCellArray cells = Utils.createCells(dataProvider.getNbrOfVertices(), dataProvider.getVertices()); data.SetVerts(cells); cells=Utils.createCells(dataProvider.getNbrOfLines(), dataProvider.getLines()); data.SetLines(cells); cells=Utils.createCells(dataProvider.getNbrOfPolys(), dataProvider.getPolys()); data.SetPolys(cells); if(LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("Number of points : " + data.GetPoints().GetNumberOfPoints()); LOGGER.finest("Number of vertices : " + data.GetVerts().GetNumberOfCells()); LOGGER.finest("Number of lines : " + data.GetLines().GetNumberOfCells()); LOGGER.finest("Number of polys : " + data.GetPolys().GetNumberOfCells()); LOGGER.finest("vertex coherance : " + Utils.isMeshCoherent(dataProvider.getNodes(), dataProvider.getVertices())); LOGGER.finest("line coherance : " + Utils.isMeshCoherent(dataProvider.getNodes(), dataProvider.getLines())); LOGGER.finest("polys coherance : " + Utils.isMeshCoherent(dataProvider.getNodes(), dataProvider.getPolys())); } if(dataProvider.getNormals() == null) return; // Compute normals that are not given vtkPolyDataNormals algoNormals = new vtkPolyDataNormals(); algoNormals.SetInput(data); algoNormals.SplittingOff(); algoNormals.FlipNormalsOff(); algoNormals.AutoOrientNormalsOff(); algoNormals.ComputePointNormalsOn(); algoNormals.Update(); data = algoNormals.GetOutput(); vtkPointData pointData = data.GetPointData(); vtkFloatArray computedNormals = (vtkFloatArray) pointData.GetNormals(); float[] javaComputedNormals = computedNormals.GetJavaArray(); float[] javaNormals = dataProvider.getNormals(); // If the normals are not computed change them by the normals computed by the meshes - for(int i = 0 ; i < javaComputedNormals.length / 3 ; i += 3) + for(int i = 0 ; i < javaComputedNormals.length ; i+= 3) { if(javaNormals[i] == 0. && javaNormals[i + 1] == 0. && javaNormals[i + 2] == 0.) { javaNormals[i] = javaComputedNormals[i]; javaNormals[i + 1] = javaComputedNormals[i + 1]; javaNormals[i + 2] = javaComputedNormals[i + 2]; } } vtkFloatArray normals = new vtkFloatArray(); normals.SetNumberOfComponents(3); normals.SetJavaArray(javaNormals); pointData.SetNormals(normals); //fireDataModified(data); } protected void deleteData() { if(data != null) { data = null; } if(actor != null) { fireActorDeleted(actor); actor = null; } if(mapper != null) { mapper = null; } } void deleteSelectionActor() { if(selectionActor == null) return; fireActorDeleted(selectionActor); if(selectionActor != null) { selectionActor = null; } if(selectionMapper != null) { selectionMapper = null; } } public void select() { if(selected) return; selected = true; timeStampSelected(); } public void unselect() { if(!selected) return; selected = false; timeStampSelected(); } public boolean isSelected() { return selected; } /** * Declare some cells as being selected. This is called by * {@link Scene#pick(vtk.vtkCanvas, int[], int[])} to store the list * of selected cells in each node, and this result is used by renderer. * * @param cellSelection list of cell ids being selected */ abstract void setCellSelection(PickContext pickContext, int [] cellSelection); abstract void clearCellSelection(); public void setManager(boolean manager) { if(this.manager == manager) return; this.manager = manager; if(!this.manager) deleteData(); timeStampModified(); } public boolean isManager() { return manager; } public void setDebugName(String name) { debugName = name; } @Override public String toString() { StringBuilder sb = new StringBuilder(getClass().getName()+"@"+Integer.toHexString(hashCode())); if (debugName != null) sb.append(" "+debugName); if (manager) sb.append(" manager"); if (selected) sb.append(" selected"); if (actor != null) { sb.append(" actor@"+Integer.toHexString(actor.hashCode())); if (actor.GetVisibility() != 0) sb.append(" visible"); if (actor.GetPickable() != 0) sb.append(" pickable"); } if (selectionActor != null) { sb.append(" selectionActor@"+Integer.toHexString(selectionActor.hashCode())); if (selectionActor.GetVisibility() != 0) sb.append(" visible"); if (selectionActor.GetPickable() != 0) sb.append(" pickable"); } return sb.toString(); } public void setEdgeVisible(boolean b) { if(actor != null) { vtkProperty p = actor.GetProperty(); p.SetEdgeVisibility(Utils.booleanToInt(b)); } } public void setCulling(boolean front, boolean back) { if(actor != null) { vtkProperty p = actor.GetProperty(); p.SetFrontfaceCulling(Utils.booleanToInt(front)); p.SetBackfaceCulling(Utils.booleanToInt(back)); } } }
true
true
protected void createData(LeafNode.DataProvider dataProvider) { data = new vtkPolyData(); data.SetPoints(Utils.createPoints(dataProvider.getNodes())); vtkCellArray cells = Utils.createCells(dataProvider.getNbrOfVertices(), dataProvider.getVertices()); data.SetVerts(cells); cells=Utils.createCells(dataProvider.getNbrOfLines(), dataProvider.getLines()); data.SetLines(cells); cells=Utils.createCells(dataProvider.getNbrOfPolys(), dataProvider.getPolys()); data.SetPolys(cells); if(LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("Number of points : " + data.GetPoints().GetNumberOfPoints()); LOGGER.finest("Number of vertices : " + data.GetVerts().GetNumberOfCells()); LOGGER.finest("Number of lines : " + data.GetLines().GetNumberOfCells()); LOGGER.finest("Number of polys : " + data.GetPolys().GetNumberOfCells()); LOGGER.finest("vertex coherance : " + Utils.isMeshCoherent(dataProvider.getNodes(), dataProvider.getVertices())); LOGGER.finest("line coherance : " + Utils.isMeshCoherent(dataProvider.getNodes(), dataProvider.getLines())); LOGGER.finest("polys coherance : " + Utils.isMeshCoherent(dataProvider.getNodes(), dataProvider.getPolys())); } if(dataProvider.getNormals() == null) return; // Compute normals that are not given vtkPolyDataNormals algoNormals = new vtkPolyDataNormals(); algoNormals.SetInput(data); algoNormals.SplittingOff(); algoNormals.FlipNormalsOff(); algoNormals.AutoOrientNormalsOff(); algoNormals.ComputePointNormalsOn(); algoNormals.Update(); data = algoNormals.GetOutput(); vtkPointData pointData = data.GetPointData(); vtkFloatArray computedNormals = (vtkFloatArray) pointData.GetNormals(); float[] javaComputedNormals = computedNormals.GetJavaArray(); float[] javaNormals = dataProvider.getNormals(); // If the normals are not computed change them by the normals computed by the meshes for(int i = 0 ; i < javaComputedNormals.length / 3 ; i += 3) { if(javaNormals[i] == 0. && javaNormals[i + 1] == 0. && javaNormals[i + 2] == 0.) { javaNormals[i] = javaComputedNormals[i]; javaNormals[i + 1] = javaComputedNormals[i + 1]; javaNormals[i + 2] = javaComputedNormals[i + 2]; } } vtkFloatArray normals = new vtkFloatArray(); normals.SetNumberOfComponents(3); normals.SetJavaArray(javaNormals); pointData.SetNormals(normals); //fireDataModified(data); }
protected void createData(LeafNode.DataProvider dataProvider) { data = new vtkPolyData(); data.SetPoints(Utils.createPoints(dataProvider.getNodes())); vtkCellArray cells = Utils.createCells(dataProvider.getNbrOfVertices(), dataProvider.getVertices()); data.SetVerts(cells); cells=Utils.createCells(dataProvider.getNbrOfLines(), dataProvider.getLines()); data.SetLines(cells); cells=Utils.createCells(dataProvider.getNbrOfPolys(), dataProvider.getPolys()); data.SetPolys(cells); if(LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("Number of points : " + data.GetPoints().GetNumberOfPoints()); LOGGER.finest("Number of vertices : " + data.GetVerts().GetNumberOfCells()); LOGGER.finest("Number of lines : " + data.GetLines().GetNumberOfCells()); LOGGER.finest("Number of polys : " + data.GetPolys().GetNumberOfCells()); LOGGER.finest("vertex coherance : " + Utils.isMeshCoherent(dataProvider.getNodes(), dataProvider.getVertices())); LOGGER.finest("line coherance : " + Utils.isMeshCoherent(dataProvider.getNodes(), dataProvider.getLines())); LOGGER.finest("polys coherance : " + Utils.isMeshCoherent(dataProvider.getNodes(), dataProvider.getPolys())); } if(dataProvider.getNormals() == null) return; // Compute normals that are not given vtkPolyDataNormals algoNormals = new vtkPolyDataNormals(); algoNormals.SetInput(data); algoNormals.SplittingOff(); algoNormals.FlipNormalsOff(); algoNormals.AutoOrientNormalsOff(); algoNormals.ComputePointNormalsOn(); algoNormals.Update(); data = algoNormals.GetOutput(); vtkPointData pointData = data.GetPointData(); vtkFloatArray computedNormals = (vtkFloatArray) pointData.GetNormals(); float[] javaComputedNormals = computedNormals.GetJavaArray(); float[] javaNormals = dataProvider.getNormals(); // If the normals are not computed change them by the normals computed by the meshes for(int i = 0 ; i < javaComputedNormals.length ; i+= 3) { if(javaNormals[i] == 0. && javaNormals[i + 1] == 0. && javaNormals[i + 2] == 0.) { javaNormals[i] = javaComputedNormals[i]; javaNormals[i + 1] = javaComputedNormals[i + 1]; javaNormals[i + 2] = javaComputedNormals[i + 2]; } } vtkFloatArray normals = new vtkFloatArray(); normals.SetNumberOfComponents(3); normals.SetJavaArray(javaNormals); pointData.SetNormals(normals); //fireDataModified(data); }
diff --git a/openxc/src/main/java/com/openxc/VehicleManager.java b/openxc/src/main/java/com/openxc/VehicleManager.java index fd161ed1..e8d80c6f 100644 --- a/openxc/src/main/java/com/openxc/VehicleManager.java +++ b/openxc/src/main/java/com/openxc/VehicleManager.java @@ -1,773 +1,774 @@ package com.openxc; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.openxc.sinks.DataSinkException; import com.openxc.sources.bluetooth.BluetoothVehicleDataSource; import com.openxc.sources.DataSourceException; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.Binder; import android.os.IBinder; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import com.google.common.base.Objects; import com.openxc.measurements.BaseMeasurement; import com.openxc.measurements.Measurement; import com.openxc.measurements.UnrecognizedMeasurementTypeException; import com.openxc.NoValueException; import com.openxc.remote.RawMeasurement; import com.openxc.remote.VehicleServiceException; import com.openxc.remote.VehicleServiceInterface; import com.openxc.sinks.FileRecorderSink; import com.openxc.sinks.MeasurementListenerSink; import com.openxc.sinks.MockedLocationSink; import com.openxc.sinks.UploaderSink; import com.openxc.sinks.VehicleDataSink; import com.openxc.sources.NativeLocationSource; import com.openxc.sources.RemoteListenerSource; import com.openxc.sources.SourceCallback; import com.openxc.sources.VehicleDataSource; import com.openxc.sources.usb.UsbVehicleDataSource; import com.openxc.util.AndroidFileOpener; /** * The VehicleManager is an in-process Android service and the primary entry * point into the OpenXC library. * * An OpenXC application should bind to this service and request vehicle * measurements through it either synchronously or asynchronously. The service * will shut down when no more clients are bound to it. * * Synchronous measurements are obtained by passing the type of the desired * measurement to the get method. Asynchronous measurements are obtained by * defining a Measurement.Listener object and passing it to the service via the * addListener method. * * The sources of data and any post-processing that happens is controlled by * modifying a list of "sources" and "sinks". When a message is received from a * data source, it is passed to any and all registered message "sinks" - these * receivers conform to the {@link com.openxc.sinks.VehicleDataSink}. * There will always be at least one sink that stores the latest messages and * handles passing on data to users of the VehicleManager class. Other possible * sinks include the {@link com.openxc.sinks.FileRecorderSink} which records a * trace of the raw OpenXC measurements to a file and a web streaming sink * (which streams the raw data to a web application). Other possible sources * include the {@link com.openxc.sources.trace.TraceVehicleDataSource} which * reads a previously recorded vehicle data trace file and plays back the * measurements * in real-time. * * One small inconsistency is that if a Bluetooth data source is added, any * calls to set() will be sent to that device. If no Belutooth data source is * in the pipeline, the standard USB device will be used instead. There is * currently no way to modify this behavior. */ public class VehicleManager extends Service implements SourceCallback { public final static String VEHICLE_LOCATION_PROVIDER = MockedLocationSink.VEHICLE_LOCATION_PROVIDER; private final static String TAG = "VehicleManager"; private boolean mIsBound; private Lock mRemoteBoundLock; private Condition mRemoteBoundCondition; private PreferenceListener mPreferenceListener; private SharedPreferences mPreferences; private IBinder mBinder = new VehicleBinder(); private VehicleServiceInterface mRemoteService; private DataPipeline mPipeline; private RemoteListenerSource mRemoteSource; private VehicleDataSink mFileRecorder; private VehicleDataSource mNativeLocationSource; private BluetoothVehicleDataSource mBluetoothSource; private MockedLocationSink mMockedLocationSink; private VehicleDataSink mUploader; private MeasurementListenerSink mNotifier; // The DataPipeline in this class must only have 1 source - the special // RemoteListenerSource that receives measurements from the // VehicleService and propagates them to all of the user-registered // sinks. Any user-registered sources must live in a separate array, // unfortunately, so they don't try to circumvent the VehicleService // and send their values directly to the in-process sinks (otherwise no // other applications could receive updates from that source). For most // applications that might be fine, but since we want to control trace // playback from the Enabler, it needs to be able to inject those into the // RVS. TODO actually, maybe that's the only case. If there are no other // cases where a user application should be able to inject source data for // all other apps to share, we should reconsider this and special case the // trace source. private CopyOnWriteArrayList<VehicleDataSource> mSources; /** * Binder to connect IBinder in a ServiceConnection with the VehicleManager. * * This class is used in the onServiceConnected method of a * ServiceConnection in a client of this service - the IBinder given to the * application can be cast to the VehicleBinder to retrieve the * actual service instance. This is required to actaully call any of its * methods. */ public class VehicleBinder extends Binder { /* * Return this Binder's parent VehicleManager instance. * * @return an instance of VehicleManager. */ public VehicleManager getService() { return VehicleManager.this; } } /** * Block until the VehicleManager is alive and can return measurements. * * Most applications don't need this and don't wait this method, but it can * be useful for testing when you need to make sure you will get a * measurement back from the system. */ public void waitUntilBound() { mRemoteBoundLock.lock(); Log.i(TAG, "Waiting for the VehicleService to bind to " + this); while(!mIsBound) { try { mRemoteBoundCondition.await(); } catch(InterruptedException e) {} } Log.i(TAG, mRemoteService + " is now bound"); mRemoteBoundLock.unlock(); } @Override public void onCreate() { super.onCreate(); Log.i(TAG, "Service starting"); mRemoteBoundLock = new ReentrantLock(); mRemoteBoundCondition = mRemoteBoundLock.newCondition(); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); mPreferenceListener = watchPreferences(mPreferences); mPipeline = new DataPipeline(); initializeDefaultSinks(mPipeline); mSources = new CopyOnWriteArrayList<VehicleDataSource>(); bindRemote(); } private void initializeDefaultSinks(DataPipeline pipeline) { mNotifier = new MeasurementListenerSink(); mMockedLocationSink = new MockedLocationSink(this); pipeline.addSink(mNotifier); pipeline.addSink(mMockedLocationSink); } @Override public void onDestroy() { super.onDestroy(); Log.i(TAG, "Service being destroyed"); if(mPipeline != null) { mPipeline.stop(); } if(mBluetoothSource != null) { mBluetoothSource.close(); } unwatchPreferences(mPreferences, mPreferenceListener); unbindRemote(); } @Override public IBinder onBind(Intent intent) { Log.i(TAG, "Service binding in response to " + intent); bindRemote(); return mBinder; } /** * Retrieve the most current value of a measurement. * * Regardless of if a measurement is available or not, return a * Measurement instance of the specified type. The measurement can be * checked to see if it has a value. * * @param measurementType The class of the requested Measurement * (e.g. VehicleSpeed.class) * @return An instance of the requested Measurement which may or may * not have a value. * @throws UnrecognizedMeasurementTypeException if passed a measurementType * that does not extend Measurement * @throws NoValueException if no value has yet been received for this * measurementType * @see BaseMeasurement */ public Measurement get( Class<? extends Measurement> measurementType) throws UnrecognizedMeasurementTypeException, NoValueException { if(mRemoteService == null) { Log.w(TAG, "Not connected to the VehicleService -- " + "throwing a NoValueException"); throw new NoValueException(); } Log.d(TAG, "Looking up measurement for " + measurementType); try { RawMeasurement rawMeasurement = mRemoteService.get( BaseMeasurement.getIdForClass(measurementType)); return BaseMeasurement.getMeasurementFromRaw(measurementType, rawMeasurement); } catch(RemoteException e) { Log.w(TAG, "Unable to get value from remote vehicle service", e); throw new NoValueException(); } } /** * Send a command back to the vehicle. * * This fails silently if it is unable to connect to the remote vehicle * service. * * @param command The desired command to send to the vehicle. */ public void set(Measurement command) throws UnrecognizedMeasurementTypeException { Log.d(TAG, "Sending command " + command); // TODO measurement should know how to convert itself back to raw... // or maybe we don't even need raw in this case. oh wait, we can't // send templated class over AIDL so we do. RawMeasurement rawCommand = new RawMeasurement(command.getGenericName(), command.getSerializedValue(), command.getSerializedEvent()); // prefer the Bluetooth controller, if connected if(mBluetoothSource != null) { Log.d(TAG, "Sending " + rawCommand + " over Bluetooth to " + mBluetoothSource); mBluetoothSource.set(rawCommand); } else { if(mRemoteService == null) { Log.w(TAG, "Not connected to the VehicleService"); return; } try { mRemoteService.set(rawCommand); } catch(RemoteException e) { Log.w(TAG, "Unable to send command to remote vehicle service", e); } } } /** * Register to receive async updates for a specific Measurement type. * * Use this method to register an object implementing the * Measurement.Listener interface to receive real-time updates * whenever a new value is received for the specified measurementType. * * @param measurementType The class of the Measurement * (e.g. VehicleSpeed.class) the listener was listening for * @param listener An Measurement.Listener instance that was * previously registered with addListener * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional situation * that shouldn't occur. * @throws UnrecognizedMeasurementTypeException if passed a measurementType * not extend Measurement */ public void addListener( Class<? extends Measurement> measurementType, Measurement.Listener listener) throws VehicleServiceException, UnrecognizedMeasurementTypeException { Log.i(TAG, "Adding listener " + listener + " to " + measurementType); mNotifier.register(measurementType, listener); } /** * Reset vehicle service to use only the default vehicle sources. * * The default vehicle data source is USB. If a USB CAN translator is not * connected, there will be no more data. * * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional situation * that shouldn't occur. */ public void initializeDefaultSources() throws VehicleServiceException { Log.i(TAG, "Resetting data sources"); if(mRemoteService != null) { try { mRemoteService.initializeDefaultSources(); } catch(RemoteException e) { throw new VehicleServiceException( "Unable to reset data sources"); } } else { Log.w(TAG, "Can't reset data sources -- " + "not connected to remote service yet"); } } public void clearSources() throws VehicleServiceException { Log.i(TAG, "Clearing all data sources"); if(mRemoteService != null) { try { mRemoteService.clearSources(); } catch(RemoteException e) { throw new VehicleServiceException( "Unable to clear data sources"); } } else { Log.w(TAG, "Can't clear all data sources -- " + "not connected to remote service yet"); } mSources.clear(); } /** * Unregister a previously reigstered Measurement.Listener instance. * * When an application is no longer interested in received measurement * updates (e.g. when it's pausing or exiting) it should unregister all * previously registered listeners to save on CPU. * * @param measurementType The class of the requested Measurement * (e.g. VehicleSpeed.class) * @param listener An object implementing the Measurement.Listener * interface that should be called with any new measurements. * @throws VehicleServiceException if the listener is unable to be * registered with the library internals - an exceptional situation * that shouldn't occur. * @throws UnrecognizedMeasurementTypeException if passed a class that does * not extend Measurement */ public void removeListener(Class<? extends Measurement> measurementType, Measurement.Listener listener) throws VehicleServiceException { Log.i(TAG, "Removing listener " + listener + " from " + measurementType); mNotifier.unregister(measurementType, listener); } /** * Add a new data source to the vehicle service. * * For example, to use the trace data source to playback a trace file, call * the addSource method after binding with VehicleManager: * * service.addSource(new TraceVehicleDataSource( * new URI("/sdcard/openxc/trace.json")))); * * The {@link UsbVehicleDataSource} exists by default with the default USB * device ID. To clear all existing sources, use the {@link #clearSources()} * method. To revert back to the default set of sources, use * {@link #initializeDefaultSources}. * * @param source an instance of a VehicleDataSource */ public void addSource(VehicleDataSource source) { Log.i(TAG, "Adding data source " + source); source.setCallback(this); mSources.add(source); } /** * Return a list of all sources active in the system, suitable for * displaying in a status view. * * This method is soley for being able to peek into the system to see what's * active, which is why it returns strings intead of the actual source * objects. We don't want applications to be able to modify the sources * through this method. * * @return A list of the names and status of all sources. */ public List<String> getSourceSummaries() { ArrayList<String> sources = new ArrayList<String>(); for(VehicleDataSource source : mSources) { sources.add(source.toString()); } for(VehicleDataSource source : mPipeline.getSources()) { sources.add(source.toString()); } if(mRemoteService != null) { try { sources.addAll(mRemoteService.getSourceSummaries()); } catch(RemoteException e) { Log.w(TAG, "Unable to retreive remote source summaries", e); } } return sources; } /** * Return a list of all sinks active in the system. * * The motivation for this method is the same as {@link #getSources}. * * @return A list of the names and status of all sinks. */ public List<String> getSinkSummaries() { ArrayList<String> sinks = new ArrayList<String>(); for(VehicleDataSink sink : mPipeline.getSinks()) { sinks.add(sink.toString()); } if(mRemoteService != null) { try { sinks.addAll(mRemoteService.getSinkSummaries()); } catch(RemoteException e) { Log.w(TAG, "Unable to retreive remote sink summaries", e); } } return sinks; } /** * Remove a previously registered source from the data pipeline. */ public void removeSource(VehicleDataSource source) { if(source != null) { mSources.remove(source); source.stop(); } } /** * Add a new data sink to the vehicle service. * * A data sink added with this method will receive all new measurements as * they arrive from registered data sources. For example, to use the trace * file recorder sink, call the addSink method after binding with * VehicleManager: * * service.addSink(new FileRecorderSink( * new AndroidFileOpener("openxc", this))); * * @param sink an instance of a VehicleDataSink */ public void addSink(VehicleDataSink sink) { Log.i(TAG, "Adding data sink " + sink); mPipeline.addSink(sink); } /** * Remove a previously registered sink from the data pipeline. */ public void removeSink(VehicleDataSink sink) { if(sink != null) { mPipeline.removeSink(sink); sink.stop(); } } /** * Enable or disable uploading of a vehicle trace to a remote web server. * * The URL of the web server to upload the trace to is read from the shared * preferences. * * @param enabled true if uploading should be enabled * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional situation * that shouldn't occur. */ public void setUploadingStatus(boolean enabled) throws VehicleServiceException { Log.i(TAG, "Setting uploading to " + enabled); if(enabled) { String path = mPreferences.getString( getString(R.string.uploading_path_key), null); String error = "Target URL in preferences not valid " + "-- not starting uploading a trace"; if(!UploaderSink.validatePath(path)) { Log.w(TAG, error); } else { try { mUploader = mPipeline.addSink(new UploaderSink(this, path)); } catch(java.net.URISyntaxException e) { Log.w(TAG, error, e); } } } else { mPipeline.removeSink(mUploader); } } /** * Enable or disable receiving vehicle data from a Bluetooth CAN device. * * @param enabled true if bluetooth should be enabled * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional * situation that shouldn't occur. */ public void setBluetoothSourceStatus(boolean enabled) throws VehicleServiceException { Log.i(TAG, "Setting bluetooth data source to " + enabled); if(enabled) { String deviceAddress = mPreferences.getString( getString(R.string.bluetooth_mac_key), null); if(deviceAddress != null) { + removeSource(mBluetoothSource); if(mBluetoothSource != null) { mBluetoothSource.close(); } try { mBluetoothSource = new BluetoothVehicleDataSource(this, deviceAddress); } catch(DataSourceException e) { Log.w(TAG, "Unable to add Bluetooth source", e); return; } addSource(mBluetoothSource); } else { Log.d(TAG, "No Bluetooth device MAC set yet (" + deviceAddress + "), not starting source"); } } else { removeSource(mBluetoothSource); if(mBluetoothSource != null) { mBluetoothSource.close(); } } } /** * Enable or disable recording of a trace file. * * @param enabled true if recording should be enabled * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional * situation that shouldn't occur. */ public void setFileRecordingStatus(boolean enabled) throws VehicleServiceException { Log.i(TAG, "Setting recording to " + enabled); if(enabled) { String directory = mPreferences.getString( getString(R.string.recording_directory_key), null); try { mFileRecorder = mPipeline.addSink(new FileRecorderSink( new AndroidFileOpener(this, directory))); } catch(DataSinkException e) { Log.w(TAG, "Unable to start trace recording", e); } } else { mPipeline.removeSink(mFileRecorder); } } /** * Enable or disable reading GPS from the native Android stack. * * @param enabled true if native GPS should be passed through * @throws VehicleServiceException if native GPS status is unable to be set * - an exceptional situation that shouldn't occur. */ public void setNativeGpsStatus(boolean enabled) throws VehicleServiceException { Log.i(TAG, "Setting native GPS to " + enabled); if(enabled) { mNativeLocationSource = mPipeline.addSource( new NativeLocationSource(this)); } else if(mNativeLocationSource != null) { mPipeline.removeSource(mNativeLocationSource); mNativeLocationSource = null; } } /** * Enable or disable overwriting native GPS measurements with those from the * vehicle. * * @see MockedLocationSink#setOverwritingStatus * * @param enabled true if native GPS should be overwritte. * @throws VehicleServiceException if GPS overwriting status is unable to be * set - an exceptional situation that shouldn't occur. */ public void setNativeGpsOverwriteStatus(boolean enabled) throws VehicleServiceException { Log.i(TAG, "Setting native GPS overwriting to " + enabled); mMockedLocationSink.setOverwritingStatus(enabled); } /** * Read the number of messages received by the vehicle service. * * @throws VehicleServiceException if the listener is unable to be * unregistered with the library internals - an exceptional situation * that shouldn't occur. */ public int getMessageCount() throws VehicleServiceException { if(mRemoteService != null) { try { return mRemoteService.getMessageCount(); } catch(RemoteException e) { throw new VehicleServiceException( "Unable to retrieve message count", e); } } else { throw new VehicleServiceException( "Unable to retrieve message count"); } } @Override public String toString() { return Objects.toStringHelper(this) .add("bound", mIsBound) .toString(); } public void receive(RawMeasurement measurement) { if(mRemoteService != null) { try { mRemoteService.receive(measurement); } catch(RemoteException e) { Log.d(TAG, "Unable to send message to remote service", e); } } } private void unwatchPreferences(SharedPreferences preferences, PreferenceListener listener) { if(preferences != null && listener != null) { preferences.unregisterOnSharedPreferenceChangeListener(listener); } } private PreferenceListener watchPreferences(SharedPreferences preferences) { if(preferences != null) { PreferenceListener listener = new PreferenceListener(preferences); preferences.registerOnSharedPreferenceChangeListener(listener); return listener; } return null; } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { Log.i(TAG, "Bound to VehicleService"); mRemoteService = VehicleServiceInterface.Stub.asInterface( service); mRemoteSource = new RemoteListenerSource(mRemoteService); mPipeline.addSource(mRemoteSource); mPreferenceListener.readStoredPreferences(); mRemoteBoundLock.lock(); mIsBound = true; mRemoteBoundCondition.signal(); mRemoteBoundLock.unlock(); } public void onServiceDisconnected(ComponentName className) { Log.w(TAG, "VehicleService disconnected unexpectedly"); mRemoteService = null; mIsBound = false; mPipeline.removeSource(mRemoteSource); } }; private void bindRemote() { Log.i(TAG, "Binding to VehicleService"); Intent intent = new Intent( VehicleServiceInterface.class.getName()); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } private void unbindRemote() { if(mRemoteBoundLock != null) { mRemoteBoundLock.lock(); } if(mIsBound) { Log.i(TAG, "Unbinding from VehicleService"); unbindService(mConnection); mIsBound = false; } if(mRemoteBoundLock != null) { mRemoteBoundLock.unlock(); } } private class PreferenceListener implements SharedPreferences.OnSharedPreferenceChangeListener { SharedPreferences mPreferences; public PreferenceListener(SharedPreferences preferences) { mPreferences = preferences; } public void readStoredPreferences() { try { setFileRecordingStatus(mPreferences.getBoolean( getString(R.string.recording_checkbox_key), false)); setNativeGpsStatus(mPreferences.getBoolean( getString(R.string.native_gps_checkbox_key), false)); setNativeGpsOverwriteStatus(mPreferences.getBoolean( getString(R.string.gps_overwrite_checkbox_key), false)); setUploadingStatus(mPreferences.getBoolean( getString(R.string.uploading_checkbox_key), false)); setBluetoothSourceStatus(mPreferences.getBoolean( getString(R.string.bluetooth_checkbox_key), false)); } catch(VehicleServiceException e) { Log.w(TAG, "Unable to initialize vehicle service with stored " + "preferences", e); } } public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { try { if(key.equals(getString(R.string.recording_checkbox_key))) { setFileRecordingStatus(preferences.getBoolean(key, false)); } else if(key.equals(getString(R.string.native_gps_checkbox_key))) { setNativeGpsStatus(preferences.getBoolean(key, false)); } else if(key.equals(getString(R.string.gps_overwrite_checkbox_key))) { setNativeGpsOverwriteStatus(preferences.getBoolean(key, false)); } else if(key.equals(getString(R.string.uploading_checkbox_key))) { setUploadingStatus(preferences.getBoolean(key, false)); } else if(key.equals(getString(R.string.bluetooth_checkbox_key)) || key.equals(getString(R.string.bluetooth_mac_key))) { setBluetoothSourceStatus(preferences.getBoolean( getString(R.string.bluetooth_checkbox_key), false)); } } catch(VehicleServiceException e) { Log.w(TAG, "Unable to update vehicle service when preference \"" + key + "\" changed", e); } } } }
true
true
public void setBluetoothSourceStatus(boolean enabled) throws VehicleServiceException { Log.i(TAG, "Setting bluetooth data source to " + enabled); if(enabled) { String deviceAddress = mPreferences.getString( getString(R.string.bluetooth_mac_key), null); if(deviceAddress != null) { if(mBluetoothSource != null) { mBluetoothSource.close(); } try { mBluetoothSource = new BluetoothVehicleDataSource(this, deviceAddress); } catch(DataSourceException e) { Log.w(TAG, "Unable to add Bluetooth source", e); return; } addSource(mBluetoothSource); } else { Log.d(TAG, "No Bluetooth device MAC set yet (" + deviceAddress + "), not starting source"); } } else { removeSource(mBluetoothSource); if(mBluetoothSource != null) { mBluetoothSource.close(); } } }
public void setBluetoothSourceStatus(boolean enabled) throws VehicleServiceException { Log.i(TAG, "Setting bluetooth data source to " + enabled); if(enabled) { String deviceAddress = mPreferences.getString( getString(R.string.bluetooth_mac_key), null); if(deviceAddress != null) { removeSource(mBluetoothSource); if(mBluetoothSource != null) { mBluetoothSource.close(); } try { mBluetoothSource = new BluetoothVehicleDataSource(this, deviceAddress); } catch(DataSourceException e) { Log.w(TAG, "Unable to add Bluetooth source", e); return; } addSource(mBluetoothSource); } else { Log.d(TAG, "No Bluetooth device MAC set yet (" + deviceAddress + "), not starting source"); } } else { removeSource(mBluetoothSource); if(mBluetoothSource != null) { mBluetoothSource.close(); } } }
diff --git a/src/main/java/org/elasticsearch/plugins/PluginManager.java b/src/main/java/org/elasticsearch/plugins/PluginManager.java index 2a5b9704232..8874eb695c1 100644 --- a/src/main/java/org/elasticsearch/plugins/PluginManager.java +++ b/src/main/java/org/elasticsearch/plugins/PluginManager.java @@ -1,439 +1,439 @@ /* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.plugins; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.http.client.HttpDownloadHelper; import org.elasticsearch.common.io.FileSystemUtils; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.node.internal.InternalSettingsPerparer; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import static org.elasticsearch.common.settings.ImmutableSettings.Builder.EMPTY_SETTINGS; /** * */ public class PluginManager { public static final class ACTION { public static final int NONE = 0; public static final int INSTALL = 1; public static final int REMOVE = 2; public static final int LIST = 3; } private final Environment environment; private String url; public PluginManager(Environment environment, String url) { this.environment = environment; this.url = url; TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } public void downloadAndExtract(String name, boolean verbose) throws IOException { HttpDownloadHelper downloadHelper = new HttpDownloadHelper(); if (!environment.pluginsFile().canWrite()) { System.out.println(); throw new IOException("plugin directory " + environment.pluginsFile() + " is read only"); } File pluginFile = new File(environment.pluginsFile(), name + ".zip"); // first, try directly from the URL provided boolean downloaded = false; if (url != null) { URL pluginUrl = new URL(url); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (IOException e) { // ignore if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } } // now, try as a path name... String filterZipName = null; if (!downloaded) { if (name.indexOf('/') != -1) { // github repo String[] elements = name.split("/"); String userName = elements[0]; String repoName = elements[1]; String version = null; if (elements.length > 2) { version = elements[2]; } - filterZipName = userName + "-" + repoName; + filterZipName = repoName; // the installation file should not include the userName, just the repoName name = repoName; if (name.startsWith("elasticsearch-")) { // remove elasticsearch- prefix name = name.substring("elasticsearch-".length()); } else if (name.startsWith("es-")) { // remove es- prefix name = name.substring("es-".length()); } // update the plugin file name to reflect the extracted name pluginFile = new File(environment.pluginsFile(), name + ".zip"); if (version != null) { URL pluginUrl = new URL("http://download.elasticsearch.org/" + userName + "/" + repoName + "/" + repoName + "-" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e) { if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } if (!downloaded) { // try maven, see if its there... (both central and sonatype) pluginUrl = new URL("http://search.maven.org/remotecontent?filepath=" + userName.replace('.', '/') + "/" + repoName + "/" + version + "/" + repoName + "-" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e) { if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } if (!downloaded) { pluginUrl = new URL("https://oss.sonatype.org/service/local/repositories/releases/content/" + userName.replace('.', '/') + "/" + repoName + "/" + version + "/" + repoName + "-" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e) { if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } } } if (!downloaded) { // try it as a site plugin tagged pluginUrl = new URL("https://github.com/" + userName + "/" + repoName + "/archive/v" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "... (assuming site plugin)"); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e1) { // ignore if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e1)); } } } } else { // assume site plugin, download master.... URL pluginUrl = new URL("https://github.com/" + userName + "/" + repoName + "/archive/master.zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "... (assuming site plugin)"); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e2) { // ignore if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e2)); } } } } } if (!downloaded) { throw new IOException("failed to download out of all possible locations..., use -verbose to get detailed information"); } // extract the plugin File extractLocation = new File(environment.pluginsFile(), name); if (extractLocation.exists()) { throw new IOException("plugin directory " + extractLocation.getAbsolutePath() + " already exists. To update the plugin, uninstall it first using -remove " + name + " command"); } ZipFile zipFile = null; try { zipFile = new ZipFile(pluginFile); Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); if (zipEntry.isDirectory()) { continue; } - String zipName = zipEntry.getName().replace('\\', '/'); + String zipEntryName = zipEntry.getName().replace('\\', '/'); if (filterZipName != null) { - if (zipName.startsWith(filterZipName)) { - zipName = zipName.substring(zipName.indexOf('/')); + if (zipEntryName.startsWith(filterZipName)) { + zipEntryName = zipEntryName.substring(zipEntryName.indexOf('/')); } } - File target = new File(extractLocation, zipName); + File target = new File(extractLocation, zipEntryName); FileSystemUtils.mkdirs(target.getParentFile()); Streams.copy(zipFile.getInputStream(zipEntry), new FileOutputStream(target)); } System.out.println("Installed " + name + " into " + extractLocation.getAbsolutePath()); } catch (Exception e) { System.err.println("failed to extract plugin [" + pluginFile + "]: " + ExceptionsHelper.detailedMessage(e)); return; } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // ignore } } pluginFile.delete(); } if (FileSystemUtils.hasExtensions(extractLocation, ".java")) { System.out.println("Plugin installation assumed to be site plugin, but contains source code, aborting installation..."); FileSystemUtils.deleteRecursively(extractLocation); return; } File binFile = new File(extractLocation, "bin"); if (binFile.exists() && binFile.isDirectory()) { File toLocation = new File(new File(environment.homeFile(), "bin"), name); System.out.println("Found bin, moving to " + toLocation.getAbsolutePath()); FileSystemUtils.deleteRecursively(toLocation); binFile.renameTo(toLocation); System.out.println("Installed " + name + " into " + toLocation.getAbsolutePath()); } // try and identify the plugin type, see if it has no .class or .jar files in it // so its probably a _site, and it it does not have a _site in it, move everything to _site if (!new File(extractLocation, "_site").exists()) { if (!FileSystemUtils.hasExtensions(extractLocation, ".class", ".jar")) { System.out.println("Identified as a _site plugin, moving to _site structure ..."); File site = new File(extractLocation, "_site"); File tmpLocation = new File(environment.pluginsFile(), name + ".tmp"); extractLocation.renameTo(tmpLocation); FileSystemUtils.mkdirs(extractLocation); tmpLocation.renameTo(site); System.out.println("Installed " + name + " into " + site.getAbsolutePath()); } } } public void removePlugin(String name) throws IOException { File pluginToDelete = new File(environment.pluginsFile(), name); if (pluginToDelete.exists()) { FileSystemUtils.deleteRecursively(pluginToDelete, true); } pluginToDelete = new File(environment.pluginsFile(), name + ".zip"); if (pluginToDelete.exists()) { pluginToDelete.delete(); } File binLocation = new File(new File(environment.homeFile(), "bin"), name); if (binLocation.exists()) { FileSystemUtils.deleteRecursively(binLocation); } } public void listInstalledPlugins() { File[] plugins = environment.pluginsFile().listFiles(); System.out.println("Installed plugins:"); if (plugins == null || plugins.length == 0) { System.out.println(" - No plugin detected in " + environment.pluginsFile().getAbsolutePath()); } else { for (int i = 0; i < plugins.length; i++) { System.out.println(" - " + plugins[i].getName()); } } } private static final int EXIT_CODE_OK = 0; private static final int EXIT_CODE_CMD_USAGE = 64; private static final int EXIT_CODE_IO_ERROR = 74; private static final int EXIT_CODE_ERROR = 70; public static void main(String[] args) { Tuple<Settings, Environment> initialSettings = InternalSettingsPerparer.prepareSettings(EMPTY_SETTINGS, true); if (!initialSettings.v2().pluginsFile().exists()) { FileSystemUtils.mkdirs(initialSettings.v2().pluginsFile()); } String url = null; boolean verbose = false; String pluginName = null; int action = ACTION.NONE; if (args.length < 1) { displayHelp(null); } try { for (int c = 0; c < args.length; c++) { String command = args[c]; if ("-u".equals(command) || "--url".equals(command) // Deprecated commands || "url".equals(command) || "-url".equals(command)) { url = args[++c]; } else if ("-v".equals(command) || "--v".equals(command) || "verbose".equals(command) || "-verbose".equals(command)) { verbose = true; } else if (command.equals("-i") || command.equals("--install") // Deprecated commands || command.equals("install") || command.equals("-install")) { pluginName = args[++c]; action = ACTION.INSTALL; } else if (command.equals("-r") || command.equals("--remove") // Deprecated commands || command.equals("remove") || command.equals("-remove")) { pluginName = args[++c]; action = ACTION.REMOVE; } else if (command.equals("-l") || command.equals("--list")) { action = ACTION.LIST; } else if (command.equals("-h") || command.equals("--help")) { displayHelp(null); } else { displayHelp("Command [" + args[c] + "] unknown."); // Unknown command. We break... System.exit(EXIT_CODE_CMD_USAGE); } } } catch (Throwable e) { displayHelp("Error while parsing options: " + e.getClass().getSimpleName() + ": " + e.getMessage()); System.exit(EXIT_CODE_CMD_USAGE); } if (action > ACTION.NONE) { int exitCode = EXIT_CODE_ERROR; // we fail unless it's reset PluginManager pluginManager = new PluginManager(initialSettings.v2(), url); switch (action) { case ACTION.INSTALL: try { System.out.println("-> Installing " + pluginName + "..."); pluginManager.downloadAndExtract(pluginName, verbose); exitCode = EXIT_CODE_OK; } catch (IOException e) { exitCode = EXIT_CODE_IO_ERROR; System.out.println("Failed to install " + pluginName + ", reason: " + e.getMessage()); } catch (Throwable e) { exitCode = EXIT_CODE_ERROR; displayHelp("Error while installing plugin, reason: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } break; case ACTION.REMOVE: try { System.out.println("-> Removing " + pluginName + " "); pluginManager.removePlugin(pluginName); exitCode = EXIT_CODE_OK; } catch (IOException e) { exitCode = EXIT_CODE_IO_ERROR; System.out.println("Failed to remove " + pluginName + ", reason: " + e.getMessage()); } catch (Throwable e) { exitCode = EXIT_CODE_ERROR; displayHelp("Error while removing plugin, reason: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } break; case ACTION.LIST: try { pluginManager.listInstalledPlugins(); exitCode = EXIT_CODE_OK; } catch (Throwable e) { displayHelp("Error while listing plugins, reason: " + e.getClass().getSimpleName() + ": " + e.getMessage()); } break; default: System.out.println("Unknown Action [" + action + "]"); exitCode = EXIT_CODE_ERROR; } System.exit(exitCode); // exit here! } } private static void displayHelp(String message) { System.out.println("Usage:"); System.out.println(" -u, --url [plugin location] : Set exact URL to download the plugin from"); System.out.println(" -i, --install [plugin name] : Downloads and installs listed plugins [*]"); System.out.println(" -r, --remove [plugin name] : Removes listed plugins"); System.out.println(" -l, --list : List installed plugins"); System.out.println(" -v, --verbose : Prints verbose messages"); System.out.println(" -h, --help : Prints this help message"); System.out.println(); System.out.println(" [*] Plugin name could be:"); System.out.println(" elasticsearch/plugin/version for official elasticsearch plugins (download from download.elasticsearch.org)"); System.out.println(" groupId/artifactId/version for community plugins (download from maven central or oss sonatype)"); System.out.println(" username/repository for site plugins (download from github master)"); if (message != null) { System.out.println(); System.out.println("Message:"); System.out.println(" " + message); } } }
false
true
public void downloadAndExtract(String name, boolean verbose) throws IOException { HttpDownloadHelper downloadHelper = new HttpDownloadHelper(); if (!environment.pluginsFile().canWrite()) { System.out.println(); throw new IOException("plugin directory " + environment.pluginsFile() + " is read only"); } File pluginFile = new File(environment.pluginsFile(), name + ".zip"); // first, try directly from the URL provided boolean downloaded = false; if (url != null) { URL pluginUrl = new URL(url); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (IOException e) { // ignore if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } } // now, try as a path name... String filterZipName = null; if (!downloaded) { if (name.indexOf('/') != -1) { // github repo String[] elements = name.split("/"); String userName = elements[0]; String repoName = elements[1]; String version = null; if (elements.length > 2) { version = elements[2]; } filterZipName = userName + "-" + repoName; // the installation file should not include the userName, just the repoName name = repoName; if (name.startsWith("elasticsearch-")) { // remove elasticsearch- prefix name = name.substring("elasticsearch-".length()); } else if (name.startsWith("es-")) { // remove es- prefix name = name.substring("es-".length()); } // update the plugin file name to reflect the extracted name pluginFile = new File(environment.pluginsFile(), name + ".zip"); if (version != null) { URL pluginUrl = new URL("http://download.elasticsearch.org/" + userName + "/" + repoName + "/" + repoName + "-" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e) { if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } if (!downloaded) { // try maven, see if its there... (both central and sonatype) pluginUrl = new URL("http://search.maven.org/remotecontent?filepath=" + userName.replace('.', '/') + "/" + repoName + "/" + version + "/" + repoName + "-" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e) { if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } if (!downloaded) { pluginUrl = new URL("https://oss.sonatype.org/service/local/repositories/releases/content/" + userName.replace('.', '/') + "/" + repoName + "/" + version + "/" + repoName + "-" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e) { if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } } } if (!downloaded) { // try it as a site plugin tagged pluginUrl = new URL("https://github.com/" + userName + "/" + repoName + "/archive/v" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "... (assuming site plugin)"); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e1) { // ignore if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e1)); } } } } else { // assume site plugin, download master.... URL pluginUrl = new URL("https://github.com/" + userName + "/" + repoName + "/archive/master.zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "... (assuming site plugin)"); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e2) { // ignore if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e2)); } } } } } if (!downloaded) { throw new IOException("failed to download out of all possible locations..., use -verbose to get detailed information"); } // extract the plugin File extractLocation = new File(environment.pluginsFile(), name); if (extractLocation.exists()) { throw new IOException("plugin directory " + extractLocation.getAbsolutePath() + " already exists. To update the plugin, uninstall it first using -remove " + name + " command"); } ZipFile zipFile = null; try { zipFile = new ZipFile(pluginFile); Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); if (zipEntry.isDirectory()) { continue; } String zipName = zipEntry.getName().replace('\\', '/'); if (filterZipName != null) { if (zipName.startsWith(filterZipName)) { zipName = zipName.substring(zipName.indexOf('/')); } } File target = new File(extractLocation, zipName); FileSystemUtils.mkdirs(target.getParentFile()); Streams.copy(zipFile.getInputStream(zipEntry), new FileOutputStream(target)); } System.out.println("Installed " + name + " into " + extractLocation.getAbsolutePath()); } catch (Exception e) { System.err.println("failed to extract plugin [" + pluginFile + "]: " + ExceptionsHelper.detailedMessage(e)); return; } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // ignore } } pluginFile.delete(); } if (FileSystemUtils.hasExtensions(extractLocation, ".java")) { System.out.println("Plugin installation assumed to be site plugin, but contains source code, aborting installation..."); FileSystemUtils.deleteRecursively(extractLocation); return; } File binFile = new File(extractLocation, "bin"); if (binFile.exists() && binFile.isDirectory()) { File toLocation = new File(new File(environment.homeFile(), "bin"), name); System.out.println("Found bin, moving to " + toLocation.getAbsolutePath()); FileSystemUtils.deleteRecursively(toLocation); binFile.renameTo(toLocation); System.out.println("Installed " + name + " into " + toLocation.getAbsolutePath()); } // try and identify the plugin type, see if it has no .class or .jar files in it // so its probably a _site, and it it does not have a _site in it, move everything to _site if (!new File(extractLocation, "_site").exists()) { if (!FileSystemUtils.hasExtensions(extractLocation, ".class", ".jar")) { System.out.println("Identified as a _site plugin, moving to _site structure ..."); File site = new File(extractLocation, "_site"); File tmpLocation = new File(environment.pluginsFile(), name + ".tmp"); extractLocation.renameTo(tmpLocation); FileSystemUtils.mkdirs(extractLocation); tmpLocation.renameTo(site); System.out.println("Installed " + name + " into " + site.getAbsolutePath()); } } }
public void downloadAndExtract(String name, boolean verbose) throws IOException { HttpDownloadHelper downloadHelper = new HttpDownloadHelper(); if (!environment.pluginsFile().canWrite()) { System.out.println(); throw new IOException("plugin directory " + environment.pluginsFile() + " is read only"); } File pluginFile = new File(environment.pluginsFile(), name + ".zip"); // first, try directly from the URL provided boolean downloaded = false; if (url != null) { URL pluginUrl = new URL(url); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (IOException e) { // ignore if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } } // now, try as a path name... String filterZipName = null; if (!downloaded) { if (name.indexOf('/') != -1) { // github repo String[] elements = name.split("/"); String userName = elements[0]; String repoName = elements[1]; String version = null; if (elements.length > 2) { version = elements[2]; } filterZipName = repoName; // the installation file should not include the userName, just the repoName name = repoName; if (name.startsWith("elasticsearch-")) { // remove elasticsearch- prefix name = name.substring("elasticsearch-".length()); } else if (name.startsWith("es-")) { // remove es- prefix name = name.substring("es-".length()); } // update the plugin file name to reflect the extracted name pluginFile = new File(environment.pluginsFile(), name + ".zip"); if (version != null) { URL pluginUrl = new URL("http://download.elasticsearch.org/" + userName + "/" + repoName + "/" + repoName + "-" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e) { if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } if (!downloaded) { // try maven, see if its there... (both central and sonatype) pluginUrl = new URL("http://search.maven.org/remotecontent?filepath=" + userName.replace('.', '/') + "/" + repoName + "/" + version + "/" + repoName + "-" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e) { if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } if (!downloaded) { pluginUrl = new URL("https://oss.sonatype.org/service/local/repositories/releases/content/" + userName.replace('.', '/') + "/" + repoName + "/" + version + "/" + repoName + "-" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "..."); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e) { if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e)); } } } } if (!downloaded) { // try it as a site plugin tagged pluginUrl = new URL("https://github.com/" + userName + "/" + repoName + "/archive/v" + version + ".zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "... (assuming site plugin)"); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e1) { // ignore if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e1)); } } } } else { // assume site plugin, download master.... URL pluginUrl = new URL("https://github.com/" + userName + "/" + repoName + "/archive/master.zip"); System.out.println("Trying " + pluginUrl.toExternalForm() + "... (assuming site plugin)"); try { downloadHelper.download(pluginUrl, pluginFile, new HttpDownloadHelper.VerboseProgress(System.out)); downloaded = true; } catch (Exception e2) { // ignore if (verbose) { System.out.println("Failed: " + ExceptionsHelper.detailedMessage(e2)); } } } } } if (!downloaded) { throw new IOException("failed to download out of all possible locations..., use -verbose to get detailed information"); } // extract the plugin File extractLocation = new File(environment.pluginsFile(), name); if (extractLocation.exists()) { throw new IOException("plugin directory " + extractLocation.getAbsolutePath() + " already exists. To update the plugin, uninstall it first using -remove " + name + " command"); } ZipFile zipFile = null; try { zipFile = new ZipFile(pluginFile); Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); while (zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); if (zipEntry.isDirectory()) { continue; } String zipEntryName = zipEntry.getName().replace('\\', '/'); if (filterZipName != null) { if (zipEntryName.startsWith(filterZipName)) { zipEntryName = zipEntryName.substring(zipEntryName.indexOf('/')); } } File target = new File(extractLocation, zipEntryName); FileSystemUtils.mkdirs(target.getParentFile()); Streams.copy(zipFile.getInputStream(zipEntry), new FileOutputStream(target)); } System.out.println("Installed " + name + " into " + extractLocation.getAbsolutePath()); } catch (Exception e) { System.err.println("failed to extract plugin [" + pluginFile + "]: " + ExceptionsHelper.detailedMessage(e)); return; } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { // ignore } } pluginFile.delete(); } if (FileSystemUtils.hasExtensions(extractLocation, ".java")) { System.out.println("Plugin installation assumed to be site plugin, but contains source code, aborting installation..."); FileSystemUtils.deleteRecursively(extractLocation); return; } File binFile = new File(extractLocation, "bin"); if (binFile.exists() && binFile.isDirectory()) { File toLocation = new File(new File(environment.homeFile(), "bin"), name); System.out.println("Found bin, moving to " + toLocation.getAbsolutePath()); FileSystemUtils.deleteRecursively(toLocation); binFile.renameTo(toLocation); System.out.println("Installed " + name + " into " + toLocation.getAbsolutePath()); } // try and identify the plugin type, see if it has no .class or .jar files in it // so its probably a _site, and it it does not have a _site in it, move everything to _site if (!new File(extractLocation, "_site").exists()) { if (!FileSystemUtils.hasExtensions(extractLocation, ".class", ".jar")) { System.out.println("Identified as a _site plugin, moving to _site structure ..."); File site = new File(extractLocation, "_site"); File tmpLocation = new File(environment.pluginsFile(), name + ".tmp"); extractLocation.renameTo(tmpLocation); FileSystemUtils.mkdirs(extractLocation); tmpLocation.renameTo(site); System.out.println("Installed " + name + " into " + site.getAbsolutePath()); } } }
diff --git a/src/main/java/org/pircbotx/DccChat.java b/src/main/java/org/pircbotx/DccChat.java index 53d311c..95d82f2 100644 --- a/src/main/java/org/pircbotx/DccChat.java +++ b/src/main/java/org/pircbotx/DccChat.java @@ -1,193 +1,197 @@ /** * Copyright (C) 2010 Leon Blakey <lord.quackstar at gmail.com> * * This file is part of PircBotX. * * PircBotX 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. * * PircBotX 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 PircBotX. If not, see <http://www.gnu.org/licenses/>. */ package org.pircbotx; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Arrays; import lombok.Getter; /** * This class is used to allow the bot to interact with a DCC Chat session. * * @since PircBot 0.9c * @author Origionally by: * <a href="http://www.jibble.org/">Paul James Mutton</a> for <a href="http://www.jibble.org/pircbot.php">PircBot</a> * <p>Forked and Maintained by in <a href="http://pircbotx.googlecode.com">PircBotX</a>: * Leon Blakey <lord.quackstar at gmail.com> */ public class DccChat { private PircBotX bot; @Getter private User user; private BufferedReader reader; private BufferedWriter writer; private Socket socket; private boolean acceptable; @Getter private InetAddress address; private int port = 0; /** * This constructor is used when we are accepting a DCC CHAT request * from somebody. It attempts to connect to the client that issued the * request. * * @param bot An instance of the underlying PircBotX. * @param sourceNick The nick of the sender. * @param address The address to connect to. * @param port The port number to connect to. * * @throws IOException If the connection cannot be made. */ protected DccChat(PircBotX bot, User source, BigInteger address, int port) { + byte[] addressBytes = address.toByteArray(); try { this.bot = bot; - //If there aren't enough bytes, pad with 0 byte - byte[] addressBytes = address.toByteArray(); - if(addressBytes.length < 4) { + //If there aren't enough bytes, pad with 0 byte + if (addressBytes.length == 5) + //Has signum, strip it + addressBytes = Arrays.copyOfRange(addressBytes, 1, 5); + else if (addressBytes.length < 4) { + System.out.println("Not enough bytes, padding!!"); byte[] newAddressBytes = new byte[4]; newAddressBytes[3] = addressBytes[0]; - newAddressBytes[2] = (addressBytes.length > 1) ? addressBytes[1] : (byte)0; - newAddressBytes[1] = (addressBytes.length > 2) ? addressBytes[2] : (byte)0; - newAddressBytes[0] = (addressBytes.length > 3) ? addressBytes[3] : (byte)0; + newAddressBytes[2] = (addressBytes.length > 1) ? addressBytes[1] : (byte) 0; + newAddressBytes[1] = (addressBytes.length > 2) ? addressBytes[2] : (byte) 0; + newAddressBytes[0] = (addressBytes.length > 3) ? addressBytes[3] : (byte) 0; addressBytes = newAddressBytes; } this.address = InetAddress.getByAddress(addressBytes); this.port = port; this.user = source; acceptable = true; } catch (UnknownHostException ex) { - throw new RuntimeException("Can't get InetAdrress version of int IP address " + address, ex); + throw new RuntimeException("Can't get InetAdrress version of int IP address " + address + " (bytes: " + Arrays.toString(addressBytes) + ")", ex); } } /** * This constructor is used after we have issued a DCC CHAT request to * somebody. If the client accepts the chat request, then the socket we * obtain is passed to this constructor. * * @param bot An instance of the underlying PircBotX. * @param sourceNick The nick of the user we are sending the request to. * @param socket The socket which will be used for the DCC CHAT session. * * @throws IOException If the socket cannot be read from. */ protected DccChat(PircBotX bot, User source, Socket socket) throws IOException { this.bot = bot; this.user = source; this.socket = socket; reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); acceptable = false; } /** * Accept this DccChat connection. * * @since PircBot 1.2.0 * */ public synchronized void accept() throws IOException { if (!acceptable) throw new IOException("Connection already created"); acceptable = false; socket = new Socket(address, port); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } /** * Reads the next line of text from the client at the other end of our DCC Chat * connection. This method blocks until something can be returned. * If the connection has closed, null is returned. * * @return The next line of text from the client. Returns null if the * connection has closed normally. * * @throws IOException If an I/O error occurs. */ public String readLine() throws IOException { if (acceptable) throw new IOException("You must call the accept() method of the DccChat request before you can use it."); return reader.readLine(); } /** * Sends a line of text to the client at the other end of our DCC Chat * connection. * * @param line The line of text to be sent. This should not include * linefeed characters. * * @throws IOException If an I/O error occurs. */ public void sendLine(String line) throws IOException { if (acceptable) throw new IOException("You must call the accept() method of the DccChat request before you can use it."); // No need for synchronization here really... writer.write(line + "\r\n"); writer.flush(); } /** * Closes the DCC Chat connection. * * @throws IOException If an I/O error occurs. */ public void close() throws IOException { if (acceptable) throw new IOException("You must call the accept() method of the DccChat request before you can use it."); socket.close(); } /** * Returns the BufferedReader used by this DCC Chat. * * @return the BufferedReader used by this DCC Chat. */ public BufferedReader getBufferedReader() { return reader; } /** * Returns the BufferedReader used by this DCC Chat. * * @return the BufferedReader used by this DCC Chat. */ public BufferedWriter getBufferedWriter() { return writer; } /** * Returns the raw Socket used by this DCC Chat. * * @return the raw Socket used by this DCC Chat. */ public Socket getSocket() { return socket; } }
false
true
protected DccChat(PircBotX bot, User source, BigInteger address, int port) { try { this.bot = bot; //If there aren't enough bytes, pad with 0 byte byte[] addressBytes = address.toByteArray(); if(addressBytes.length < 4) { byte[] newAddressBytes = new byte[4]; newAddressBytes[3] = addressBytes[0]; newAddressBytes[2] = (addressBytes.length > 1) ? addressBytes[1] : (byte)0; newAddressBytes[1] = (addressBytes.length > 2) ? addressBytes[2] : (byte)0; newAddressBytes[0] = (addressBytes.length > 3) ? addressBytes[3] : (byte)0; addressBytes = newAddressBytes; } this.address = InetAddress.getByAddress(addressBytes); this.port = port; this.user = source; acceptable = true; } catch (UnknownHostException ex) { throw new RuntimeException("Can't get InetAdrress version of int IP address " + address, ex); } }
protected DccChat(PircBotX bot, User source, BigInteger address, int port) { byte[] addressBytes = address.toByteArray(); try { this.bot = bot; //If there aren't enough bytes, pad with 0 byte if (addressBytes.length == 5) //Has signum, strip it addressBytes = Arrays.copyOfRange(addressBytes, 1, 5); else if (addressBytes.length < 4) { System.out.println("Not enough bytes, padding!!"); byte[] newAddressBytes = new byte[4]; newAddressBytes[3] = addressBytes[0]; newAddressBytes[2] = (addressBytes.length > 1) ? addressBytes[1] : (byte) 0; newAddressBytes[1] = (addressBytes.length > 2) ? addressBytes[2] : (byte) 0; newAddressBytes[0] = (addressBytes.length > 3) ? addressBytes[3] : (byte) 0; addressBytes = newAddressBytes; } this.address = InetAddress.getByAddress(addressBytes); this.port = port; this.user = source; acceptable = true; } catch (UnknownHostException ex) { throw new RuntimeException("Can't get InetAdrress version of int IP address " + address + " (bytes: " + Arrays.toString(addressBytes) + ")", ex); } }
diff --git a/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/TokenResolverGenerator.java b/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/TokenResolverGenerator.java index 96f77eb9f..63de111ed 100644 --- a/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/TokenResolverGenerator.java +++ b/Core/SDK/org.emftext.sdk.codegen.resource/src/org/emftext/sdk/codegen/resource/generators/TokenResolverGenerator.java @@ -1,188 +1,184 @@ /******************************************************************************* * Copyright (c) 2006-2012 * Software Technology Group, Dresden University of Technology * DevBoost GmbH, Berlin, Amtsgericht Charlottenburg, HRB 140026 * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Software Technology Group - TU Dresden, Germany; * DevBoost GmbH - Berlin, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.codegen.resource.generators; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_OBJECT; import static org.emftext.sdk.codegen.resource.generators.IClassNameConstants.E_STRUCTURAL_FEATURE; import org.emftext.sdk.codegen.annotations.SyntaxDependent; import org.emftext.sdk.codegen.composites.JavaComposite; import org.emftext.sdk.codegen.composites.StringComposite; import org.emftext.sdk.codegen.resource.GeneratorUtil; import org.emftext.sdk.codegen.resource.TextResourceArtifacts; import org.emftext.sdk.codegen.resource.TokenResolverParameters; import org.emftext.sdk.codegen.util.NameUtil; import org.emftext.sdk.concretesyntax.CompleteTokenDefinition; import org.emftext.sdk.concretesyntax.ConcreteSyntax; import org.emftext.sdk.concretesyntax.QuotedTokenDefinition; import org.emftext.sdk.util.StringUtil; /** * A TokenResolverGenerator generates a single TokenResolver for a given TokenDefinition. * * For a definition with prefix and suffix it generates code which removes these * strings from the beginning and the end of a lexem and then passes the manipulated * lexem to the default token resolver. In the deresolvement the conversion from * object to string is also delegated to the default resolver. * Finally the deresolved String will be decorated by pre- and suffixes again. * * @author Sven Karol ([email protected]) */ @SyntaxDependent public class TokenResolverGenerator extends JavaBaseGenerator<TokenResolverParameters> { private final GeneratorUtil generatorUtil = new GeneratorUtil(); private final NameUtil nameUtil = new NameUtil(); private CompleteTokenDefinition definition; public void generateJavaContents(JavaComposite sc) { setTokenDefinition(getParameters().getDefinition()); sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); ConcreteSyntax syntax = getContext().getConcreteSyntax(); sc.add("public class " + nameUtil.getTokenResolverClassName(syntax, definition) + " implements " + iTokenResolverClassName + " {"); sc.addLineBreak(); // do not generate a resolver for imported tokens boolean isImportedToken = definition.isImported(syntax); if (isImportedToken) { String importedTokenResolverClassName = nameUtil.getQualifiedTokenResolverClassName(syntax, definition, true); - sc.addComment( - "If this line does not compile, the imported language plug-ins were generated before EMFText 1.4.0. " + - "To resolve the compilation error remove the argument from the constructor call." - ); - sc.add("private " + importedTokenResolverClassName + " importedResolver = new " + importedTokenResolverClassName + "(true);"); + sc.add("private " + importedTokenResolverClassName + " importedResolver = new " + importedTokenResolverClassName + "();"); sc.addLineBreak(); generateDeResolveMethod2(sc); generateResolveMethod2(sc); generatorUtil.addSetOptionsMethod(sc, "importedResolver.setOptions(options);", null); } else { sc.add("private " + defaultTokenResolverClassName + " defaultTokenResolver = new " + defaultTokenResolverClassName + "(true);"); sc.addLineBreak(); generateDeResolveMethod1(sc); generateResolveMethod1(sc); generatorUtil.addSetOptionsMethod(sc, "defaultTokenResolver.setOptions(options);", null); } sc.add("}"); } private void generateDeResolveMethod1(JavaComposite sc) { String prefix = getPrefix(); String suffix = getSuffix(); String escapeCharacter = getEscapeCharacter(); String javaSourcePrefix = escape(prefix); String javaSourceSuffix = escape(suffix); String javaSourceEscapeCharacter = escape(escapeCharacter); sc.add("public String deResolve(Object value, " + E_STRUCTURAL_FEATURE + " feature, " + E_OBJECT + " container) {"); sc.addComment("By default token de-resolving is delegated to the DefaultTokenResolver."); sc.add("String result = defaultTokenResolver.deResolve(value, feature, container, " + javaSourcePrefix + ", " + javaSourceSuffix + ", " + javaSourceEscapeCharacter + ");"); sc.add("return result;"); sc.add("}"); sc.addLineBreak(); } private void generateDeResolveMethod2(StringComposite sc) { sc.add("public String deResolve(Object value, " + E_STRUCTURAL_FEATURE + " feature, " + E_OBJECT + " container) {"); sc.add("String result = importedResolver.deResolve(value, feature, container);"); sc.add("return result;"); sc.add("}"); sc.addLineBreak(); } private void generateResolveMethod1(JavaComposite sc) { String prefix = getPrefix(); String suffix = getSuffix(); String escapeCharacter = getEscapeCharacter(); String javaSourcePrefix = escape(prefix); String javaSourceSuffix = escape(suffix); String javaSourceEscapeCharacter = escape(escapeCharacter); sc.add("public void resolve(String lexem, " + E_STRUCTURAL_FEATURE + " feature, " + iTokenResolveResultClassName + " result) {"); sc.addComment("By default token resolving is delegated to the DefaultTokenResolver."); sc.add("defaultTokenResolver.resolve(lexem, feature, result, " + javaSourcePrefix + ", " + javaSourceSuffix + ", " + javaSourceEscapeCharacter + ");"); sc.add("}"); sc.addLineBreak(); } private String escape(String prefix) { String javaSourcePrefix = StringUtil.escapeToJavaString(prefix); if (javaSourcePrefix != null) { javaSourcePrefix = "\"" + javaSourcePrefix + "\""; } return javaSourcePrefix; } private void generateResolveMethod2(StringComposite sc) { ConcreteSyntax syntax = getContext().getConcreteSyntax(); ConcreteSyntax containingSyntax = definition.getContainingSyntax(syntax); String importedTokenResolveResultClassName = getContext().getQualifiedClassName(TextResourceArtifacts.I_TOKEN_RESOLVE_RESULT, containingSyntax); sc.add("public void resolve(String lexem, " + E_STRUCTURAL_FEATURE + " feature, final " + iTokenResolveResultClassName + " result) {"); sc.add("importedResolver.resolve(lexem, feature, new " + importedTokenResolveResultClassName + "() {"); sc.add("public String getErrorMessage() {"); sc.add("return result.getErrorMessage();"); sc.add("}"); sc.addLineBreak(); sc.add("public Object getResolvedToken() {"); sc.add("return result.getResolvedToken();"); sc.add("}"); sc.addLineBreak(); sc.add("public void setErrorMessage(String message) {"); sc.add("result.setErrorMessage(message);"); sc.add("}"); sc.addLineBreak(); sc.add("public void setResolvedToken(Object resolvedToken) {"); sc.add("result.setResolvedToken(resolvedToken);"); sc.add("}"); sc.addLineBreak(); sc.add("});"); sc.add("}"); sc.addLineBreak(); } private String getPrefix() { String prefix = null; if (definition instanceof QuotedTokenDefinition) { prefix = ((QuotedTokenDefinition) definition).getPrefix(); } return prefix; } private String getSuffix() { String suffix = null; if (definition instanceof QuotedTokenDefinition) { suffix = ((QuotedTokenDefinition) definition).getSuffix(); } return suffix; } private String getEscapeCharacter() { String suffix = null; if (definition instanceof QuotedTokenDefinition) { suffix = ((QuotedTokenDefinition) definition).getEscapeCharacter(); } return suffix; } private void setTokenDefinition(CompleteTokenDefinition tokenDefinition) { this.definition = tokenDefinition; } }
true
true
public void generateJavaContents(JavaComposite sc) { setTokenDefinition(getParameters().getDefinition()); sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); ConcreteSyntax syntax = getContext().getConcreteSyntax(); sc.add("public class " + nameUtil.getTokenResolverClassName(syntax, definition) + " implements " + iTokenResolverClassName + " {"); sc.addLineBreak(); // do not generate a resolver for imported tokens boolean isImportedToken = definition.isImported(syntax); if (isImportedToken) { String importedTokenResolverClassName = nameUtil.getQualifiedTokenResolverClassName(syntax, definition, true); sc.addComment( "If this line does not compile, the imported language plug-ins were generated before EMFText 1.4.0. " + "To resolve the compilation error remove the argument from the constructor call." ); sc.add("private " + importedTokenResolverClassName + " importedResolver = new " + importedTokenResolverClassName + "(true);"); sc.addLineBreak(); generateDeResolveMethod2(sc); generateResolveMethod2(sc); generatorUtil.addSetOptionsMethod(sc, "importedResolver.setOptions(options);", null); } else { sc.add("private " + defaultTokenResolverClassName + " defaultTokenResolver = new " + defaultTokenResolverClassName + "(true);"); sc.addLineBreak(); generateDeResolveMethod1(sc); generateResolveMethod1(sc); generatorUtil.addSetOptionsMethod(sc, "defaultTokenResolver.setOptions(options);", null); } sc.add("}"); }
public void generateJavaContents(JavaComposite sc) { setTokenDefinition(getParameters().getDefinition()); sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); ConcreteSyntax syntax = getContext().getConcreteSyntax(); sc.add("public class " + nameUtil.getTokenResolverClassName(syntax, definition) + " implements " + iTokenResolverClassName + " {"); sc.addLineBreak(); // do not generate a resolver for imported tokens boolean isImportedToken = definition.isImported(syntax); if (isImportedToken) { String importedTokenResolverClassName = nameUtil.getQualifiedTokenResolverClassName(syntax, definition, true); sc.add("private " + importedTokenResolverClassName + " importedResolver = new " + importedTokenResolverClassName + "();"); sc.addLineBreak(); generateDeResolveMethod2(sc); generateResolveMethod2(sc); generatorUtil.addSetOptionsMethod(sc, "importedResolver.setOptions(options);", null); } else { sc.add("private " + defaultTokenResolverClassName + " defaultTokenResolver = new " + defaultTokenResolverClassName + "(true);"); sc.addLineBreak(); generateDeResolveMethod1(sc); generateResolveMethod1(sc); generatorUtil.addSetOptionsMethod(sc, "defaultTokenResolver.setOptions(options);", null); } sc.add("}"); }
diff --git a/java/gov/nist/javax/sip/message/SIPRequest.java b/java/gov/nist/javax/sip/message/SIPRequest.java index 3136383..25304c2 100644 --- a/java/gov/nist/javax/sip/message/SIPRequest.java +++ b/java/gov/nist/javax/sip/message/SIPRequest.java @@ -1,1207 +1,1211 @@ /* * Conditions Of Use * * This software was developed by employees of the National Institute of * Standards and Technology (NIST), an agency of the Federal Government. * Pursuant to title 15 Untied States Code Section 105, works of NIST * employees are not subject to copyright protection in the United States * and are considered to be in the public domain. As a result, a formal * license is not needed to use the software. * * This software is provided by NIST as a service and is expressly * provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT * AND DATA ACCURACY. NIST does not warrant or make any representations * regarding the use of the software or the results thereof, including but * not limited to the correctness, accuracy, reliability or usefulness of * the software. * * Permission to use this software is contingent upon your acceptance * of the terms of this agreement * * . * */ /******************************************************************************* * Product of NIST/ITL Advanced Networking Technologies Division (ANTD) * *******************************************************************************/ package gov.nist.javax.sip.message; import gov.nist.javax.sip.address.*; import gov.nist.core.*; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.Set; import java.io.UnsupportedEncodingException; import java.util.Iterator; import javax.sip.address.URI; import javax.sip.message.*; import java.text.ParseException; import javax.sip.*; import javax.sip.header.*; import gov.nist.javax.sip.header.*; import gov.nist.javax.sip.stack.SIPTransactionStack; /* * Acknowledgements: Mark Bednarek made a few fixes to this code. Jeff Keyser added two methods * that create responses and generate cancel requests from incoming orignial requests without the * additional overhead of encoding and decoding messages. Bruno Konik noticed an extraneous * newline added to the end of the buffer when encoding it. Incorporates a bug report from Andreas * Bystrom. Szabo Barna noticed a contact in a cancel request - this is a pointless header for * cancel. Antonis Kyardis contributed bug fixes. Jeroen van Bemmel noted that method names are * case sensitive, should use equals() in getting CannonicalName * */ /** * The SIP Request structure. * * @version 1.2 $Revision: 1.52 $ $Date: 2009/12/16 14:58:40 $ * @since 1.1 * * @author M. Ranganathan <br/> * * * */ public final class SIPRequest extends SIPMessage implements javax.sip.message.Request, RequestExt { private static final long serialVersionUID = 3360720013577322927L; private static final String DEFAULT_USER = "ip"; private static final String DEFAULT_TRANSPORT = "udp"; private transient Object transactionPointer; private RequestLine requestLine; private transient Object messageChannel; private transient Object inviteTransaction; // The original invite request for a // given cancel request /** * Set of target refresh methods, currently: INVITE, UPDATE, SUBSCRIBE, NOTIFY, REFER * * A target refresh request and its response MUST have a Contact */ private static final Set<String> targetRefreshMethods = new HashSet<String>(); /* * A table that maps a name string to its cannonical constant. This is used to speed up * parsing of messages .equals reduces to == if we use the constant value. */ private static final Hashtable<String, String> nameTable = new Hashtable<String, String>(); private static void putName(String name) { nameTable.put(name, name); } static { targetRefreshMethods.add(Request.INVITE); targetRefreshMethods.add(Request.UPDATE); targetRefreshMethods.add(Request.SUBSCRIBE); targetRefreshMethods.add(Request.NOTIFY); targetRefreshMethods.add(Request.REFER); putName(Request.INVITE); putName(Request.BYE); putName(Request.CANCEL); putName(Request.ACK); putName(Request.PRACK); putName(Request.INFO); putName(Request.MESSAGE); putName(Request.NOTIFY); putName(Request.OPTIONS); putName(Request.PRACK); putName(Request.PUBLISH); putName(Request.REFER); putName(Request.REGISTER); putName(Request.SUBSCRIBE); putName(Request.UPDATE); } /** * @return true iff the method is a target refresh */ public static boolean isTargetRefresh(String ucaseMethod) { return targetRefreshMethods.contains(ucaseMethod); } /** * @return true iff the method is a dialog creating method */ public static boolean isDialogCreating(String ucaseMethod) { return SIPTransactionStack.isDialogCreated(ucaseMethod); } /** * Set to standard constants to speed up processing. this makes equals comparisons run much * faster in the stack because then it is just identity comparision. Character by char * comparison is not required. The method returns the String CONSTANT corresponding to the * String name. * */ public static String getCannonicalName(String method) { if (nameTable.containsKey(method)) return (String) nameTable.get(method); else return method; } /** * Get the Request Line of the SIPRequest. * * @return the request line of the SIP Request. */ public RequestLine getRequestLine() { return requestLine; } /** * Set the request line of the SIP Request. * * @param requestLine is the request line to set in the SIP Request. */ public void setRequestLine(RequestLine requestLine) { this.requestLine = requestLine; } /** * Constructor. */ public SIPRequest() { super(); } /** * Convert to a formatted string for pretty printing. Note that the encode method converts * this into a sip message that is suitable for transmission. Note hack here if you want to * convert the nice curly brackets into some grotesque XML tag. * * @return a string which can be used to examine the message contents. * */ public String debugDump() { String superstring = super.debugDump(); stringRepresentation = ""; sprint(SIPRequest.class.getName()); sprint("{"); if (requestLine != null) sprint(requestLine.debugDump()); sprint(superstring); sprint("}"); return stringRepresentation; } /** * Check header for constraints. (1) Invite options and bye requests can only have SIP URIs in * the contact headers. (2) Request must have cseq, to and from and via headers. (3) Method in * request URI must match that in CSEQ. */ public void checkHeaders() throws ParseException { String prefix = "Missing a required header : "; /* Check for required headers */ if (getCSeq() == null) { throw new ParseException(prefix + CSeqHeader.NAME, 0); } if (getTo() == null) { throw new ParseException(prefix + ToHeader.NAME, 0); } if (this.callIdHeader == null || this.callIdHeader.getCallId() == null || callIdHeader.getCallId().equals("")) { throw new ParseException(prefix + CallIdHeader.NAME, 0); } if (getFrom() == null) { throw new ParseException(prefix + FromHeader.NAME, 0); } if (getViaHeaders() == null) { throw new ParseException(prefix + ViaHeader.NAME, 0); } + // BEGIN android-deleted + /* if (getMaxForwards() == null) { throw new ParseException(prefix + MaxForwardsHeader.NAME, 0); } + */ + // END android-deleted if (getTopmostVia() == null) throw new ParseException("No via header in request! ", 0); if (getMethod().equals(Request.NOTIFY)) { if (getHeader(SubscriptionStateHeader.NAME) == null) throw new ParseException(prefix + SubscriptionStateHeader.NAME, 0); if (getHeader(EventHeader.NAME) == null) throw new ParseException(prefix + EventHeader.NAME, 0); } else if (getMethod().equals(Request.PUBLISH)) { /* * For determining the type of the published event state, the EPA MUST include a * single Event header field in PUBLISH requests. The value of this header field * indicates the event package for which this request is publishing event state. */ if (getHeader(EventHeader.NAME) == null) throw new ParseException(prefix + EventHeader.NAME, 0); } /* * RFC 3261 8.1.1.8 The Contact header field MUST be present and contain exactly one SIP * or SIPS URI in any request that can result in the establishment of a dialog. For the * methods defined in this specification, that includes only the INVITE request. For these * requests, the scope of the Contact is global. That is, the Contact header field value * contains the URI at which the UA would like to receive requests, and this URI MUST be * valid even if used in subsequent requests outside of any dialogs. * * If the Request-URI or top Route header field value contains a SIPS URI, the Contact * header field MUST contain a SIPS URI as well. */ if (requestLine.getMethod().equals(Request.INVITE) || requestLine.getMethod().equals(Request.SUBSCRIBE) || requestLine.getMethod().equals(Request.REFER)) { if (this.getContactHeader() == null) { // Make sure this is not a target refresh. If this is a target // refresh its ok not to have a contact header. Otherwise // contact header is mandatory. if (this.getToTag() == null) throw new ParseException(prefix + ContactHeader.NAME, 0); } if (requestLine.getUri() instanceof SipUri) { String scheme = ((SipUri) requestLine.getUri()).getScheme(); if ("sips".equalsIgnoreCase(scheme)) { SipUri sipUri = (SipUri) this.getContactHeader().getAddress().getURI(); if (!sipUri.getScheme().equals("sips")) { throw new ParseException("Scheme for contact should be sips:" + sipUri, 0); } } } } /* * Contact header is mandatory for a SIP INVITE request. */ if (this.getContactHeader() == null && (this.getMethod().equals(Request.INVITE) || this.getMethod().equals(Request.REFER) || this.getMethod().equals( Request.SUBSCRIBE))) { throw new ParseException("Contact Header is Mandatory for a SIP INVITE", 0); } if (requestLine != null && requestLine.getMethod() != null && getCSeq().getMethod() != null && requestLine.getMethod().compareTo(getCSeq().getMethod()) != 0) { throw new ParseException("CSEQ method mismatch with Request-Line ", 0); } } /** * Set the default values in the request URI if necessary. */ protected void setDefaults() { // The request line may be unparseable (set to null by the // exception handler. if (requestLine == null) return; String method = requestLine.getMethod(); // The requestLine may be malformed! if (method == null) return; GenericURI u = requestLine.getUri(); if (u == null) return; if (method.compareTo(Request.REGISTER) == 0 || method.compareTo(Request.INVITE) == 0) { if (u instanceof SipUri) { SipUri sipUri = (SipUri) u; sipUri.setUserParam(DEFAULT_USER); try { sipUri.setTransportParam(DEFAULT_TRANSPORT); } catch (ParseException ex) { } } } } /** * Patch up the request line as necessary. */ protected void setRequestLineDefaults() { String method = requestLine.getMethod(); if (method == null) { CSeq cseq = (CSeq) this.getCSeq(); if (cseq != null) { method = getCannonicalName(cseq.getMethod()); requestLine.setMethod(method); } } } /** * A conveniance function to access the Request URI. * * @return the requestURI if it exists. */ public javax.sip.address.URI getRequestURI() { if (this.requestLine == null) return null; else return (javax.sip.address.URI) this.requestLine.getUri(); } /** * Sets the RequestURI of Request. The Request-URI is a SIP or SIPS URI or a general URI. It * indicates the user or service to which this request is being addressed. SIP elements MAY * support Request-URIs with schemes other than "sip" and "sips", for example the "tel" URI * scheme. SIP elements MAY translate non-SIP URIs using any mechanism at their disposal, * resulting in SIP URI, SIPS URI, or some other scheme. * * @param uri the new Request URI of this request message */ public void setRequestURI(URI uri) { if ( uri == null ) { throw new NullPointerException("Null request URI"); } if (this.requestLine == null) { this.requestLine = new RequestLine(); } this.requestLine.setUri((GenericURI) uri); this.nullRequest = false; } /** * Set the method. * * @param method is the method to set. * @throws IllegalArgumentException if the method is null */ public void setMethod(String method) { if (method == null) throw new IllegalArgumentException("null method"); if (this.requestLine == null) { this.requestLine = new RequestLine(); } // Set to standard constants to speed up processing. // this makes equals compares run much faster in the // stack because then it is just identity comparision String meth = getCannonicalName(method); this.requestLine.setMethod(meth); if (this.cSeqHeader != null) { try { this.cSeqHeader.setMethod(meth); } catch (ParseException e) { } } } /** * Get the method from the request line. * * @return the method from the request line if the method exits and null if the request line * or the method does not exist. */ public String getMethod() { if (requestLine == null) return null; else return requestLine.getMethod(); } /** * Encode the SIP Request as a string. * * @return an encoded String containing the encoded SIP Message. */ public String encode() { String retval; if (requestLine != null) { this.setRequestLineDefaults(); retval = requestLine.encode() + super.encode(); } else if (this.isNullRequest()) { retval = "\r\n\r\n"; } else { retval = super.encode(); } return retval; } /** * Encode only the headers and not the content. */ public String encodeMessage() { String retval; if (requestLine != null) { this.setRequestLineDefaults(); retval = requestLine.encode() + super.encodeSIPHeaders(); } else if (this.isNullRequest()) { retval = "\r\n\r\n"; } else retval = super.encodeSIPHeaders(); return retval; } /** * ALias for encode above. */ public String toString() { return this.encode(); } /** * Make a clone (deep copy) of this object. You can use this if you want to modify a request * while preserving the original * * @return a deep copy of this object. */ public Object clone() { SIPRequest retval = (SIPRequest) super.clone(); // Do not copy over the tx pointer -- this is only for internal // tracking. retval.transactionPointer = null; if (this.requestLine != null) retval.requestLine = (RequestLine) this.requestLine.clone(); return retval; } /** * Compare for equality. * * @param other object to compare ourselves with. */ public boolean equals(Object other) { if (!this.getClass().equals(other.getClass())) return false; SIPRequest that = (SIPRequest) other; return requestLine.equals(that.requestLine) && super.equals(other); } /** * Get the message as a linked list of strings. Use this if you want to iterate through the * message. * * @return a linked list containing the request line and headers encoded as strings. */ public LinkedList getMessageAsEncodedStrings() { LinkedList retval = super.getMessageAsEncodedStrings(); if (requestLine != null) { this.setRequestLineDefaults(); retval.addFirst(requestLine.encode()); } return retval; } /** * Match with a template. You can use this if you want to match incoming messages with a * pattern and do something when you find a match. This is useful for building filters/pattern * matching responders etc. * * @param matchObj object to match ourselves with (null matches wildcard) * */ public boolean match(Object matchObj) { if (matchObj == null) return true; else if (!matchObj.getClass().equals(this.getClass())) return false; else if (matchObj == this) return true; SIPRequest that = (SIPRequest) matchObj; RequestLine rline = that.requestLine; if (this.requestLine == null && rline != null) return false; else if (this.requestLine == rline) return super.match(matchObj); return requestLine.match(that.requestLine) && super.match(matchObj); } /** * Get a dialog identifier. Generates a string that can be used as a dialog identifier. * * @param isServer is set to true if this is the UAS and set to false if this is the UAC */ public String getDialogId(boolean isServer) { CallID cid = (CallID) this.getCallId(); StringBuffer retval = new StringBuffer(cid.getCallId()); From from = (From) this.getFrom(); To to = (To) this.getTo(); if (!isServer) { // retval.append(COLON).append(from.getUserAtHostPort()); if (from.getTag() != null) { retval.append(COLON); retval.append(from.getTag()); } // retval.append(COLON).append(to.getUserAtHostPort()); if (to.getTag() != null) { retval.append(COLON); retval.append(to.getTag()); } } else { // retval.append(COLON).append(to.getUserAtHostPort()); if (to.getTag() != null) { retval.append(COLON); retval.append(to.getTag()); } // retval.append(COLON).append(from.getUserAtHostPort()); if (from.getTag() != null) { retval.append(COLON); retval.append(from.getTag()); } } return retval.toString().toLowerCase(); } /** * Get a dialog id given the remote tag. */ public String getDialogId(boolean isServer, String toTag) { From from = (From) this.getFrom(); CallID cid = (CallID) this.getCallId(); StringBuffer retval = new StringBuffer(cid.getCallId()); if (!isServer) { // retval.append(COLON).append(from.getUserAtHostPort()); if (from.getTag() != null) { retval.append(COLON); retval.append(from.getTag()); } // retval.append(COLON).append(to.getUserAtHostPort()); if (toTag != null) { retval.append(COLON); retval.append(toTag); } } else { // retval.append(COLON).append(to.getUserAtHostPort()); if (toTag != null) { retval.append(COLON); retval.append(toTag); } // retval.append(COLON).append(from.getUserAtHostPort()); if (from.getTag() != null) { retval.append(COLON); retval.append(from.getTag()); } } return retval.toString().toLowerCase(); } /** * Encode this into a byte array. This is used when the body has been set as a binary array * and you want to encode the body as a byte array for transmission. * * @return a byte array containing the SIPRequest encoded as a byte array. */ public byte[] encodeAsBytes(String transport) { if (this.isNullRequest()) { // Encoding a null message for keepalive. return "\r\n\r\n".getBytes(); } else if ( this.requestLine == null ) { return new byte[0]; } byte[] rlbytes = null; if (requestLine != null) { try { rlbytes = requestLine.encode().getBytes("UTF-8"); } catch (UnsupportedEncodingException ex) { InternalErrorHandler.handleException(ex); } } byte[] superbytes = super.encodeAsBytes(transport); byte[] retval = new byte[rlbytes.length + superbytes.length]; System.arraycopy(rlbytes, 0, retval, 0, rlbytes.length); System.arraycopy(superbytes, 0, retval, rlbytes.length, superbytes.length); return retval; } /** * Creates a default SIPResponse message for this request. Note You must add the necessary * tags to outgoing responses if need be. For efficiency, this method does not clone the * incoming request. If you want to modify the outgoing response, be sure to clone the * incoming request as the headers are shared and any modification to the headers of the * outgoing response will result in a modification of the incoming request. Tag fields are * just copied from the incoming request. Contact headers are removed from the incoming * request. Added by Jeff Keyser. * * @param statusCode Status code for the response. Reason phrase is generated. * * @return A SIPResponse with the status and reason supplied, and a copy of all the original * headers from this request. */ public SIPResponse createResponse(int statusCode) { String reasonPhrase = SIPResponse.getReasonPhrase(statusCode); return this.createResponse(statusCode, reasonPhrase); } /** * Creates a default SIPResponse message for this request. Note You must add the necessary * tags to outgoing responses if need be. For efficiency, this method does not clone the * incoming request. If you want to modify the outgoing response, be sure to clone the * incoming request as the headers are shared and any modification to the headers of the * outgoing response will result in a modification of the incoming request. Tag fields are * just copied from the incoming request. Contact headers are removed from the incoming * request. Added by Jeff Keyser. Route headers are not added to the response. * * @param statusCode Status code for the response. * @param reasonPhrase Reason phrase for this response. * * @return A SIPResponse with the status and reason supplied, and a copy of all the original * headers from this request except the ones that are not supposed to be part of the * response . */ public SIPResponse createResponse(int statusCode, String reasonPhrase) { SIPResponse newResponse; Iterator headerIterator; SIPHeader nextHeader; newResponse = new SIPResponse(); try { newResponse.setStatusCode(statusCode); } catch (ParseException ex) { throw new IllegalArgumentException("Bad code " + statusCode); } if (reasonPhrase != null) newResponse.setReasonPhrase(reasonPhrase); else newResponse.setReasonPhrase(SIPResponse.getReasonPhrase(statusCode)); headerIterator = getHeaders(); while (headerIterator.hasNext()) { nextHeader = (SIPHeader) headerIterator.next(); if (nextHeader instanceof From || nextHeader instanceof To || nextHeader instanceof ViaList || nextHeader instanceof CallID || (nextHeader instanceof RecordRouteList && mustCopyRR(statusCode)) || nextHeader instanceof CSeq // We just copy TimeStamp for all headers (not just 100). || nextHeader instanceof TimeStamp) { try { newResponse.attachHeader((SIPHeader) nextHeader.clone(), false); } catch (SIPDuplicateHeaderException e) { e.printStackTrace(); } } } if (MessageFactoryImpl.getDefaultServerHeader() != null) { newResponse.setHeader(MessageFactoryImpl.getDefaultServerHeader()); } if (newResponse.getStatusCode() == 100) { // Trying is never supposed to have the tag parameter set. newResponse.getTo().removeParameter("tag"); } ServerHeader server = MessageFactoryImpl.getDefaultServerHeader(); if (server != null) { newResponse.setHeader(server); } return newResponse; } // Helper method for createResponse, to avoid copying Record-Route unless needed private final boolean mustCopyRR( int code ) { // Only for 1xx-2xx, not for 100 or errors if ( code>100 && code<300 ) { return isDialogCreating( this.getMethod() ) && getToTag() == null; } else return false; } /** * Creates a default SIPResquest message that would cancel this request. Note that tag * assignment and removal of is left to the caller (we use whatever tags are present in the * original request). * * @return A CANCEL SIPRequest constructed according to RFC3261 section 9.1 * * @throws SipException * @throws ParseException */ public SIPRequest createCancelRequest() throws SipException { // see RFC3261 9.1 // A CANCEL request SHOULD NOT be sent to cancel a request other than // INVITE if (!this.getMethod().equals(Request.INVITE)) throw new SipException("Attempt to create CANCEL for " + this.getMethod()); /* * The following procedures are used to construct a CANCEL request. The Request-URI, * Call-ID, To, the numeric part of CSeq, and From header fields in the CANCEL request * MUST be identical to those in the request being cancelled, including tags. A CANCEL * constructed by a client MUST have only a single Via header field value matching the top * Via value in the request being cancelled. Using the same values for these header fields * allows the CANCEL to be matched with the request it cancels (Section 9.2 indicates how * such matching occurs). However, the method part of the CSeq header field MUST have a * value of CANCEL. This allows it to be identified and processed as a transaction in its * own right (See Section 17). */ SIPRequest cancel = new SIPRequest(); cancel.setRequestLine((RequestLine) this.requestLine.clone()); cancel.setMethod(Request.CANCEL); cancel.setHeader((Header) this.callIdHeader.clone()); cancel.setHeader((Header) this.toHeader.clone()); cancel.setHeader((Header) cSeqHeader.clone()); try { cancel.getCSeq().setMethod(Request.CANCEL); } catch (ParseException e) { e.printStackTrace(); // should not happen } cancel.setHeader((Header) this.fromHeader.clone()); cancel.addFirst((Header) this.getTopmostVia().clone()); cancel.setHeader((Header) this.maxForwardsHeader.clone()); /* * If the request being cancelled contains a Route header field, the CANCEL request MUST * include that Route header field's values. */ if (this.getRouteHeaders() != null) { cancel.setHeader((SIPHeaderList< ? >) this.getRouteHeaders().clone()); } if (MessageFactoryImpl.getDefaultUserAgentHeader() != null) { cancel.setHeader(MessageFactoryImpl.getDefaultUserAgentHeader()); } return cancel; } /** * Creates a default ACK SIPRequest message for this original request. Note that the * defaultACK SIPRequest does not include the content of the original SIPRequest. If * responseToHeader is null then the toHeader of this request is used to construct the ACK. * Note that tag fields are just copied from the original SIP Request. Added by Jeff Keyser. * * @param responseToHeader To header to use for this request. * * @return A SIPRequest with an ACK method. */ public SIPRequest createAckRequest(To responseToHeader) { SIPRequest newRequest; Iterator headerIterator; SIPHeader nextHeader; newRequest = new SIPRequest(); newRequest.setRequestLine((RequestLine) this.requestLine.clone()); newRequest.setMethod(Request.ACK); headerIterator = getHeaders(); while (headerIterator.hasNext()) { nextHeader = (SIPHeader) headerIterator.next(); if (nextHeader instanceof RouteList) { // Ack and cancel do not get ROUTE headers. // Route header for ACK is assigned by the // Dialog if necessary. continue; } else if (nextHeader instanceof ProxyAuthorization) { // Remove proxy auth header. // Assigned by the Dialog if necessary. continue; } else if (nextHeader instanceof ContentLength) { // Adding content is responsibility of user. nextHeader = (SIPHeader) nextHeader.clone(); try { ((ContentLength) nextHeader).setContentLength(0); } catch (InvalidArgumentException e) { } } else if (nextHeader instanceof ContentType) { // Content type header is removed since // content length is 0. continue; } else if (nextHeader instanceof CSeq) { // The CSeq header field in the // ACK MUST contain the same value for the // sequence number as was present in the // original request, but the method parameter // MUST be equal to "ACK". CSeq cseq = (CSeq) nextHeader.clone(); try { cseq.setMethod(Request.ACK); } catch (ParseException e) { } nextHeader = cseq; } else if (nextHeader instanceof To) { if (responseToHeader != null) { nextHeader = responseToHeader; } else { nextHeader = (SIPHeader) nextHeader.clone(); } } else if (nextHeader instanceof ContactList || nextHeader instanceof Expires) { // CONTACT header does not apply for ACK requests. continue; } else if (nextHeader instanceof ViaList) { // Bug reported by Gianluca Martinello // The ACK MUST contain a single Via header field, // and this MUST be equal to the top Via header // field of the original // request. nextHeader = (SIPHeader) ((ViaList) nextHeader).getFirst().clone(); } else { nextHeader = (SIPHeader) nextHeader.clone(); } try { newRequest.attachHeader(nextHeader, false); } catch (SIPDuplicateHeaderException e) { e.printStackTrace(); } } if (MessageFactoryImpl.getDefaultUserAgentHeader() != null) { newRequest.setHeader(MessageFactoryImpl.getDefaultUserAgentHeader()); } return newRequest; } /** * Creates an ACK for non-2xx responses according to RFC3261 17.1.1.3 * * @return A SIPRequest with an ACK method. * @throws SipException * @throws NullPointerException * @throws ParseException * * @author jvb */ public final SIPRequest createErrorAck(To responseToHeader) throws SipException, ParseException { /* * The ACK request constructed by the client transaction MUST contain values for the * Call-ID, From, and Request-URI that are equal to the values of those header fields in * the request passed to the transport by the client transaction (call this the "original * request"). The To header field in the ACK MUST equal the To header field in the * response being acknowledged, and therefore will usually differ from the To header field * in the original request by the addition of the tag parameter. The ACK MUST contain a * single Via header field, and this MUST be equal to the top Via header field of the * original request. The CSeq header field in the ACK MUST contain the same value for the * sequence number as was present in the original request, but the method parameter MUST * be equal to "ACK". */ SIPRequest newRequest = new SIPRequest(); newRequest.setRequestLine((RequestLine) this.requestLine.clone()); newRequest.setMethod(Request.ACK); newRequest.setHeader((Header) this.callIdHeader.clone()); newRequest.setHeader((Header) this.maxForwardsHeader.clone()); // ISSUE // 130 // fix newRequest.setHeader((Header) this.fromHeader.clone()); newRequest.setHeader((Header) responseToHeader.clone()); newRequest.addFirst((Header) this.getTopmostVia().clone()); newRequest.setHeader((Header) cSeqHeader.clone()); newRequest.getCSeq().setMethod(Request.ACK); /* * If the INVITE request whose response is being acknowledged had Route header fields, * those header fields MUST appear in the ACK. This is to ensure that the ACK can be * routed properly through any downstream stateless proxies. */ if (this.getRouteHeaders() != null) { newRequest.setHeader((SIPHeaderList) this.getRouteHeaders().clone()); } if (MessageFactoryImpl.getDefaultUserAgentHeader() != null) { newRequest.setHeader(MessageFactoryImpl.getDefaultUserAgentHeader()); } return newRequest; } /** * Create a new default SIPRequest from the original request. Warning: the newly created * SIPRequest, shares the headers of this request but we generate any new headers that we need * to modify so the original request is umodified. However, if you modify the shared headers * after this request is created, then the newly created request will also be modified. If you * want to modify the original request without affecting the returned Request make sure you * clone it before calling this method. * * Only required headers are copied. * <ul> * <li> Contact headers are not included in the newly created request. Setting the appropriate * sequence number is the responsibility of the caller. </li> * <li> RouteList is not copied for ACK and CANCEL </li> * <li> Note that we DO NOT copy the body of the argument into the returned header. We do not * copy the content type header from the original request either. These have to be added * seperately and the content length has to be correctly set if necessary the content length * is set to 0 in the returned header. </li> * <li>Contact List is not copied from the original request.</li> * <li>RecordRoute List is not included from original request. </li> * <li>Via header is not included from the original request. </li> * </ul> * * @param requestLine is the new request line. * * @param switchHeaders is a boolean flag that causes to and from headers to switch (set this * to true if you are the server of the transaction and are generating a BYE request). * If the headers are switched, we generate new From and To headers otherwise we just * use the incoming headers. * * @return a new Default SIP Request which has the requestLine specified. * */ public SIPRequest createSIPRequest(RequestLine requestLine, boolean switchHeaders) { SIPRequest newRequest = new SIPRequest(); newRequest.requestLine = requestLine; Iterator<SIPHeader> headerIterator = this.getHeaders(); while (headerIterator.hasNext()) { SIPHeader nextHeader = (SIPHeader) headerIterator.next(); // For BYE and cancel set the CSeq header to the // appropriate method. if (nextHeader instanceof CSeq) { CSeq newCseq = (CSeq) nextHeader.clone(); nextHeader = newCseq; try { newCseq.setMethod(requestLine.getMethod()); } catch (ParseException e) { } } else if (nextHeader instanceof ViaList) { Via via = (Via) (((ViaList) nextHeader).getFirst().clone()); via.removeParameter("branch"); nextHeader = via; // Cancel and ACK preserve the branch ID. } else if (nextHeader instanceof To) { To to = (To) nextHeader; if (switchHeaders) { nextHeader = new From(to); ((From) nextHeader).removeTag(); } else { nextHeader = (SIPHeader) to.clone(); ((To) nextHeader).removeTag(); } } else if (nextHeader instanceof From) { From from = (From) nextHeader; if (switchHeaders) { nextHeader = new To(from); ((To) nextHeader).removeTag(); } else { nextHeader = (SIPHeader) from.clone(); ((From) nextHeader).removeTag(); } } else if (nextHeader instanceof ContentLength) { ContentLength cl = (ContentLength) nextHeader.clone(); try { cl.setContentLength(0); } catch (InvalidArgumentException e) { } nextHeader = cl; } else if (!(nextHeader instanceof CallID) && !(nextHeader instanceof MaxForwards)) { // Route is kept by dialog. // RR is added by the caller. // Contact is added by the Caller // Any extension headers must be added // by the caller. continue; } try { newRequest.attachHeader(nextHeader, false); } catch (SIPDuplicateHeaderException e) { e.printStackTrace(); } } if (MessageFactoryImpl.getDefaultUserAgentHeader() != null) { newRequest.setHeader(MessageFactoryImpl.getDefaultUserAgentHeader()); } return newRequest; } /** * Create a BYE request from this request. * * @param switchHeaders is a boolean flag that causes from and isServerTransaction to headers * to be swapped. Set this to true if you are the server of the dialog and are * generating a BYE request for the dialog. * @return a new default BYE request. */ public SIPRequest createBYERequest(boolean switchHeaders) { RequestLine requestLine = (RequestLine) this.requestLine.clone(); requestLine.setMethod("BYE"); return this.createSIPRequest(requestLine, switchHeaders); } /** * Create an ACK request from this request. This is suitable for generating an ACK for an * INVITE client transaction. * * @return an ACK request that is generated from this request. */ public SIPRequest createACKRequest() { RequestLine requestLine = (RequestLine) this.requestLine.clone(); requestLine.setMethod(Request.ACK); return this.createSIPRequest(requestLine, false); } /** * Get the host from the topmost via header. * * @return the string representation of the host from the topmost via header. */ public String getViaHost() { Via via = (Via) this.getViaHeaders().getFirst(); return via.getHost(); } /** * Get the port from the topmost via header. * * @return the port from the topmost via header (5060 if there is no port indicated). */ public int getViaPort() { Via via = (Via) this.getViaHeaders().getFirst(); if (via.hasPort()) return via.getPort(); else return 5060; } /** * Get the first line encoded. * * @return a string containing the encoded request line. */ public String getFirstLine() { if (requestLine == null) return null; else return this.requestLine.encode(); } /** * Set the sip version. * * @param sipVersion the sip version to set. */ public void setSIPVersion(String sipVersion) throws ParseException { if (sipVersion == null || !sipVersion.equalsIgnoreCase("SIP/2.0")) throw new ParseException("sipVersion", 0); this.requestLine.setSipVersion(sipVersion); } /** * Get the SIP version. * * @return the SIP version from the request line. */ public String getSIPVersion() { return this.requestLine.getSipVersion(); } /** * Book keeping method to return the current tx for the request if one exists. * * @return the assigned tx. */ public Object getTransaction() { // Return an opaque pointer to the transaction object. // This is for consistency checking and quick lookup. return this.transactionPointer; } /** * Book keeping field to set the current tx for the request. * * @param transaction */ public void setTransaction(Object transaction) { this.transactionPointer = transaction; } /** * Book keeping method to get the messasge channel for the request. * * @return the message channel for the request. */ public Object getMessageChannel() { // return opaque ptr to the message chanel on // which the message was recieved. For consistency // checking and lookup. return this.messageChannel; } /** * Set the message channel for the request ( bookkeeping field ). * * @param messageChannel */ public void setMessageChannel(Object messageChannel) { this.messageChannel = messageChannel; } /** * Generates an Id for checking potentially merged requests. * * @return String to check for merged requests */ public String getMergeId() { /* * generate an identifier from the From tag, Call-ID, and CSeq */ String fromTag = this.getFromTag(); String cseq = this.cSeqHeader.toString(); String callId = this.callIdHeader.getCallId(); /* NOTE : The RFC does NOT specify you need to include a Request URI * This is added here for the case of Back to Back User Agents. */ String requestUri = this.getRequestURI().toString(); if (fromTag != null) { return new StringBuffer().append(requestUri).append(":").append(fromTag).append(":").append(cseq).append(":") .append(callId).toString(); } else return null; } /** * @param inviteTransaction the inviteTransaction to set */ public void setInviteTransaction(Object inviteTransaction) { this.inviteTransaction = inviteTransaction; } /** * @return the inviteTransaction */ public Object getInviteTransaction() { return inviteTransaction; } }
false
true
public void checkHeaders() throws ParseException { String prefix = "Missing a required header : "; /* Check for required headers */ if (getCSeq() == null) { throw new ParseException(prefix + CSeqHeader.NAME, 0); } if (getTo() == null) { throw new ParseException(prefix + ToHeader.NAME, 0); } if (this.callIdHeader == null || this.callIdHeader.getCallId() == null || callIdHeader.getCallId().equals("")) { throw new ParseException(prefix + CallIdHeader.NAME, 0); } if (getFrom() == null) { throw new ParseException(prefix + FromHeader.NAME, 0); } if (getViaHeaders() == null) { throw new ParseException(prefix + ViaHeader.NAME, 0); } if (getMaxForwards() == null) { throw new ParseException(prefix + MaxForwardsHeader.NAME, 0); } if (getTopmostVia() == null) throw new ParseException("No via header in request! ", 0); if (getMethod().equals(Request.NOTIFY)) { if (getHeader(SubscriptionStateHeader.NAME) == null) throw new ParseException(prefix + SubscriptionStateHeader.NAME, 0); if (getHeader(EventHeader.NAME) == null) throw new ParseException(prefix + EventHeader.NAME, 0); } else if (getMethod().equals(Request.PUBLISH)) { /* * For determining the type of the published event state, the EPA MUST include a * single Event header field in PUBLISH requests. The value of this header field * indicates the event package for which this request is publishing event state. */ if (getHeader(EventHeader.NAME) == null) throw new ParseException(prefix + EventHeader.NAME, 0); } /* * RFC 3261 8.1.1.8 The Contact header field MUST be present and contain exactly one SIP * or SIPS URI in any request that can result in the establishment of a dialog. For the * methods defined in this specification, that includes only the INVITE request. For these * requests, the scope of the Contact is global. That is, the Contact header field value * contains the URI at which the UA would like to receive requests, and this URI MUST be * valid even if used in subsequent requests outside of any dialogs. * * If the Request-URI or top Route header field value contains a SIPS URI, the Contact * header field MUST contain a SIPS URI as well. */ if (requestLine.getMethod().equals(Request.INVITE) || requestLine.getMethod().equals(Request.SUBSCRIBE) || requestLine.getMethod().equals(Request.REFER)) { if (this.getContactHeader() == null) { // Make sure this is not a target refresh. If this is a target // refresh its ok not to have a contact header. Otherwise // contact header is mandatory. if (this.getToTag() == null) throw new ParseException(prefix + ContactHeader.NAME, 0); } if (requestLine.getUri() instanceof SipUri) { String scheme = ((SipUri) requestLine.getUri()).getScheme(); if ("sips".equalsIgnoreCase(scheme)) { SipUri sipUri = (SipUri) this.getContactHeader().getAddress().getURI(); if (!sipUri.getScheme().equals("sips")) { throw new ParseException("Scheme for contact should be sips:" + sipUri, 0); } } } } /* * Contact header is mandatory for a SIP INVITE request. */ if (this.getContactHeader() == null && (this.getMethod().equals(Request.INVITE) || this.getMethod().equals(Request.REFER) || this.getMethod().equals( Request.SUBSCRIBE))) { throw new ParseException("Contact Header is Mandatory for a SIP INVITE", 0); } if (requestLine != null && requestLine.getMethod() != null && getCSeq().getMethod() != null && requestLine.getMethod().compareTo(getCSeq().getMethod()) != 0) { throw new ParseException("CSEQ method mismatch with Request-Line ", 0); } }
public void checkHeaders() throws ParseException { String prefix = "Missing a required header : "; /* Check for required headers */ if (getCSeq() == null) { throw new ParseException(prefix + CSeqHeader.NAME, 0); } if (getTo() == null) { throw new ParseException(prefix + ToHeader.NAME, 0); } if (this.callIdHeader == null || this.callIdHeader.getCallId() == null || callIdHeader.getCallId().equals("")) { throw new ParseException(prefix + CallIdHeader.NAME, 0); } if (getFrom() == null) { throw new ParseException(prefix + FromHeader.NAME, 0); } if (getViaHeaders() == null) { throw new ParseException(prefix + ViaHeader.NAME, 0); } // BEGIN android-deleted /* if (getMaxForwards() == null) { throw new ParseException(prefix + MaxForwardsHeader.NAME, 0); } */ // END android-deleted if (getTopmostVia() == null) throw new ParseException("No via header in request! ", 0); if (getMethod().equals(Request.NOTIFY)) { if (getHeader(SubscriptionStateHeader.NAME) == null) throw new ParseException(prefix + SubscriptionStateHeader.NAME, 0); if (getHeader(EventHeader.NAME) == null) throw new ParseException(prefix + EventHeader.NAME, 0); } else if (getMethod().equals(Request.PUBLISH)) { /* * For determining the type of the published event state, the EPA MUST include a * single Event header field in PUBLISH requests. The value of this header field * indicates the event package for which this request is publishing event state. */ if (getHeader(EventHeader.NAME) == null) throw new ParseException(prefix + EventHeader.NAME, 0); } /* * RFC 3261 8.1.1.8 The Contact header field MUST be present and contain exactly one SIP * or SIPS URI in any request that can result in the establishment of a dialog. For the * methods defined in this specification, that includes only the INVITE request. For these * requests, the scope of the Contact is global. That is, the Contact header field value * contains the URI at which the UA would like to receive requests, and this URI MUST be * valid even if used in subsequent requests outside of any dialogs. * * If the Request-URI or top Route header field value contains a SIPS URI, the Contact * header field MUST contain a SIPS URI as well. */ if (requestLine.getMethod().equals(Request.INVITE) || requestLine.getMethod().equals(Request.SUBSCRIBE) || requestLine.getMethod().equals(Request.REFER)) { if (this.getContactHeader() == null) { // Make sure this is not a target refresh. If this is a target // refresh its ok not to have a contact header. Otherwise // contact header is mandatory. if (this.getToTag() == null) throw new ParseException(prefix + ContactHeader.NAME, 0); } if (requestLine.getUri() instanceof SipUri) { String scheme = ((SipUri) requestLine.getUri()).getScheme(); if ("sips".equalsIgnoreCase(scheme)) { SipUri sipUri = (SipUri) this.getContactHeader().getAddress().getURI(); if (!sipUri.getScheme().equals("sips")) { throw new ParseException("Scheme for contact should be sips:" + sipUri, 0); } } } } /* * Contact header is mandatory for a SIP INVITE request. */ if (this.getContactHeader() == null && (this.getMethod().equals(Request.INVITE) || this.getMethod().equals(Request.REFER) || this.getMethod().equals( Request.SUBSCRIBE))) { throw new ParseException("Contact Header is Mandatory for a SIP INVITE", 0); } if (requestLine != null && requestLine.getMethod() != null && getCSeq().getMethod() != null && requestLine.getMethod().compareTo(getCSeq().getMethod()) != 0) { throw new ParseException("CSEQ method mismatch with Request-Line ", 0); } }
diff --git a/bitvunit-core/src/main/java/de/codescape/bitvunit/util/Assert.java b/bitvunit-core/src/main/java/de/codescape/bitvunit/util/Assert.java index 8356fd1..eeb4303 100644 --- a/bitvunit-core/src/main/java/de/codescape/bitvunit/util/Assert.java +++ b/bitvunit-core/src/main/java/de/codescape/bitvunit/util/Assert.java @@ -1,73 +1,74 @@ package de.codescape.bitvunit.util; /** * Utility class with reusable assertions. * * @author Stefan Glase * @since 0.5 */ public final class Assert { private Assert() { throw new UnsupportedOperationException("Utility class should not be instantiated."); } /** * Verifies that the given object is not <code>null</code> and throws an <code>IllegalArgumentException</code> with * a default message otherwise. * * @param object object that should be checked */ public static void notNull(Object object) { notNull("Parameter may not be null.", object); } /** * Verifies that the given list of objects does not contain a single element that is <code>null</code> and throws an * <code>IllegalArgumentException</code> with a default message otherwise. * * @param objects objects that should be checked */ public static void notNull(Object... objects) { + notNull((Object) objects); for (Object object : objects) { notNull(object); } } /** * Verifies that the given object is not <code>null</code> and throws an <code>IllegalArgumentException</code> with * the given message otherwise. * * @param message message that should be included in case of an error * @param object object that should be checked */ public static void notNull(String message, Object object) { if (object == null) { throw new IllegalArgumentException(message); } } /** * Verifies that the given string is neither <code>null</code> nor empty and throws an * <code>IllegalArgumentException</code> with a default message otherwise. * * @param string string that should be checked */ public static void notEmpty(String string) { notEmpty("Parameter may not be null or empty.", string); } /** * Verifies that the given string is neither <code>null</code> nor empty and throws an * <code>IllegalArgumentException</code> with the given message otherwise. * * @param message message that should be included in case of an error * @param string string that should be checked */ public static void notEmpty(String message, String string) { if (string == null || string.trim().isEmpty()) { throw new IllegalArgumentException(message); } } }
true
true
public static void notNull(Object... objects) { for (Object object : objects) { notNull(object); } }
public static void notNull(Object... objects) { notNull((Object) objects); for (Object object : objects) { notNull(object); } }
diff --git a/src/cli/src/main/java/org/geogit/cli/porcelain/Merge.java b/src/cli/src/main/java/org/geogit/cli/porcelain/Merge.java index 3c4df3e2..fec44b91 100644 --- a/src/cli/src/main/java/org/geogit/cli/porcelain/Merge.java +++ b/src/cli/src/main/java/org/geogit/cli/porcelain/Merge.java @@ -1,150 +1,150 @@ /* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.cli.porcelain; import java.io.IOException; import java.util.Iterator; import java.util.List; import jline.console.ConsoleReader; import org.fusesource.jansi.Ansi; import org.fusesource.jansi.Ansi.Color; import org.geogit.api.GeoGIT; import org.geogit.api.ObjectId; import org.geogit.api.Ref; import org.geogit.api.RevCommit; import org.geogit.api.plumbing.RefParse; import org.geogit.api.plumbing.RevParse; import org.geogit.api.plumbing.diff.DiffEntry; import org.geogit.api.porcelain.DiffOp; import org.geogit.api.porcelain.MergeOp; import org.geogit.api.porcelain.MergeOp.MergeReport; import org.geogit.api.porcelain.NothingToCommitException; import org.geogit.api.porcelain.ResetOp; import org.geogit.api.porcelain.ResetOp.ResetMode; import org.geogit.cli.AbstractCommand; import org.geogit.cli.CLICommand; import org.geogit.cli.CommandFailedException; import org.geogit.cli.GeogitCLI; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.common.base.Optional; import com.google.common.base.Suppliers; import com.google.common.collect.Lists; /** * Incorporates changes from the named commits (since the time their histories diverged from the * current branch) into the current branch. * <p> * CLI proxy for {@link MergeOp} * <p> * Usage: * <ul> * <li> {@code geogit merge [-m <msg>] [--ours] [--theirs] <commitish>...} * </ul> * * @see MergeOp */ @Parameters(commandNames = "merge", commandDescription = "Merge two or more histories into one") public class Merge extends AbstractCommand implements CLICommand { @Parameter(names = "-m", description = "Commit message") private String message; @Parameter(names = "--ours", description = "Use 'ours' strategy") private boolean ours; @Parameter(names = "--theirs", description = "Use 'theirs' strategy") private boolean theirs; @Parameter(names = "--no-commit", description = "Do not perform a commit after merging") private boolean noCommit; @Parameter(names = "--abort", description = "Aborts the current merge") private boolean abort; @Parameter(description = "<commitish>...") private List<String> commits = Lists.newArrayList(); /** * Executes the merge command using the provided options. */ @Override public void runInternal(GeogitCLI cli) throws IOException { checkParameter(commits.size() > 0, "No commits provided to merge."); ConsoleReader console = cli.getConsole(); final GeoGIT geogit = cli.getGeogit(); Ansi ansi = newAnsi(console.getTerminal()); if (abort) { Optional<Ref> ref = geogit.command(RefParse.class).setName(Ref.ORIG_HEAD).call(); if (!ref.isPresent()) { throw new CommandFailedException("There is no merge to abort <ORIG_HEAD missing>."); } geogit.command(ResetOp.class).setMode(ResetMode.HARD) - .setCommit(Suppliers.ofInstance(ref.get().getObjectId())); + .setCommit(Suppliers.ofInstance(ref.get().getObjectId())).call(); console.println("Merge aborted successfully."); return; } RevCommit commit; try { MergeOp merge = geogit.command(MergeOp.class); merge.setOurs(ours).setTheirs(theirs).setNoCommit(noCommit); merge.setMessage(message).setProgressListener(cli.getProgressListener()); for (String commitish : commits) { Optional<ObjectId> commitId; commitId = geogit.command(RevParse.class).setRefSpec(commitish).call(); checkParameter(commitId.isPresent(), "Commit not found '%s'", commitish); merge.addCommit(Suppliers.ofInstance(commitId.get())); } MergeReport report = merge.call(); commit = report.getMergeCommit(); } catch (RuntimeException e) { if (e instanceof NothingToCommitException || e instanceof IllegalArgumentException || e instanceof IllegalStateException) { throw new CommandFailedException(e.getMessage(), e); } throw e; } final ObjectId parentId = commit.parentN(0).or(ObjectId.NULL); console.println("[" + commit.getId() + "] " + commit.getMessage()); console.print("Committed, counting objects..."); Iterator<DiffEntry> diff = geogit.command(DiffOp.class).setOldVersion(parentId) .setNewVersion(commit.getId()).call(); int adds = 0, deletes = 0, changes = 0; DiffEntry diffEntry; while (diff.hasNext()) { diffEntry = diff.next(); switch (diffEntry.changeType()) { case ADDED: ++adds; break; case REMOVED: ++deletes; break; case MODIFIED: ++changes; break; } } ansi.fg(Color.GREEN).a(adds).reset().a(" features added, ").fg(Color.YELLOW).a(changes) .reset().a(" changed, ").fg(Color.RED).a(deletes).reset().a(" deleted.").reset() .newline(); console.print(ansi.toString()); } }
true
true
public void runInternal(GeogitCLI cli) throws IOException { checkParameter(commits.size() > 0, "No commits provided to merge."); ConsoleReader console = cli.getConsole(); final GeoGIT geogit = cli.getGeogit(); Ansi ansi = newAnsi(console.getTerminal()); if (abort) { Optional<Ref> ref = geogit.command(RefParse.class).setName(Ref.ORIG_HEAD).call(); if (!ref.isPresent()) { throw new CommandFailedException("There is no merge to abort <ORIG_HEAD missing>."); } geogit.command(ResetOp.class).setMode(ResetMode.HARD) .setCommit(Suppliers.ofInstance(ref.get().getObjectId())); console.println("Merge aborted successfully."); return; } RevCommit commit; try { MergeOp merge = geogit.command(MergeOp.class); merge.setOurs(ours).setTheirs(theirs).setNoCommit(noCommit); merge.setMessage(message).setProgressListener(cli.getProgressListener()); for (String commitish : commits) { Optional<ObjectId> commitId; commitId = geogit.command(RevParse.class).setRefSpec(commitish).call(); checkParameter(commitId.isPresent(), "Commit not found '%s'", commitish); merge.addCommit(Suppliers.ofInstance(commitId.get())); } MergeReport report = merge.call(); commit = report.getMergeCommit(); } catch (RuntimeException e) { if (e instanceof NothingToCommitException || e instanceof IllegalArgumentException || e instanceof IllegalStateException) { throw new CommandFailedException(e.getMessage(), e); } throw e; } final ObjectId parentId = commit.parentN(0).or(ObjectId.NULL); console.println("[" + commit.getId() + "] " + commit.getMessage()); console.print("Committed, counting objects..."); Iterator<DiffEntry> diff = geogit.command(DiffOp.class).setOldVersion(parentId) .setNewVersion(commit.getId()).call(); int adds = 0, deletes = 0, changes = 0; DiffEntry diffEntry; while (diff.hasNext()) { diffEntry = diff.next(); switch (diffEntry.changeType()) { case ADDED: ++adds; break; case REMOVED: ++deletes; break; case MODIFIED: ++changes; break; } } ansi.fg(Color.GREEN).a(adds).reset().a(" features added, ").fg(Color.YELLOW).a(changes) .reset().a(" changed, ").fg(Color.RED).a(deletes).reset().a(" deleted.").reset() .newline(); console.print(ansi.toString()); }
public void runInternal(GeogitCLI cli) throws IOException { checkParameter(commits.size() > 0, "No commits provided to merge."); ConsoleReader console = cli.getConsole(); final GeoGIT geogit = cli.getGeogit(); Ansi ansi = newAnsi(console.getTerminal()); if (abort) { Optional<Ref> ref = geogit.command(RefParse.class).setName(Ref.ORIG_HEAD).call(); if (!ref.isPresent()) { throw new CommandFailedException("There is no merge to abort <ORIG_HEAD missing>."); } geogit.command(ResetOp.class).setMode(ResetMode.HARD) .setCommit(Suppliers.ofInstance(ref.get().getObjectId())).call(); console.println("Merge aborted successfully."); return; } RevCommit commit; try { MergeOp merge = geogit.command(MergeOp.class); merge.setOurs(ours).setTheirs(theirs).setNoCommit(noCommit); merge.setMessage(message).setProgressListener(cli.getProgressListener()); for (String commitish : commits) { Optional<ObjectId> commitId; commitId = geogit.command(RevParse.class).setRefSpec(commitish).call(); checkParameter(commitId.isPresent(), "Commit not found '%s'", commitish); merge.addCommit(Suppliers.ofInstance(commitId.get())); } MergeReport report = merge.call(); commit = report.getMergeCommit(); } catch (RuntimeException e) { if (e instanceof NothingToCommitException || e instanceof IllegalArgumentException || e instanceof IllegalStateException) { throw new CommandFailedException(e.getMessage(), e); } throw e; } final ObjectId parentId = commit.parentN(0).or(ObjectId.NULL); console.println("[" + commit.getId() + "] " + commit.getMessage()); console.print("Committed, counting objects..."); Iterator<DiffEntry> diff = geogit.command(DiffOp.class).setOldVersion(parentId) .setNewVersion(commit.getId()).call(); int adds = 0, deletes = 0, changes = 0; DiffEntry diffEntry; while (diff.hasNext()) { diffEntry = diff.next(); switch (diffEntry.changeType()) { case ADDED: ++adds; break; case REMOVED: ++deletes; break; case MODIFIED: ++changes; break; } } ansi.fg(Color.GREEN).a(adds).reset().a(" features added, ").fg(Color.YELLOW).a(changes) .reset().a(" changed, ").fg(Color.RED).a(deletes).reset().a(" deleted.").reset() .newline(); console.print(ansi.toString()); }
diff --git a/org.caltoopia.frontend/src/org/caltoopia/codegen/printer/CBuildFuncDeclaration.java b/org.caltoopia.frontend/src/org/caltoopia/codegen/printer/CBuildFuncDeclaration.java index 235a55b..087a860 100644 --- a/org.caltoopia.frontend/src/org/caltoopia/codegen/printer/CBuildFuncDeclaration.java +++ b/org.caltoopia.frontend/src/org/caltoopia/codegen/printer/CBuildFuncDeclaration.java @@ -1,124 +1,124 @@ /* * Copyright (c) Ericsson AB, 2013 * All rights reserved. * * License terms: * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of the copyright holder nor the names * of its contributors may be used to endorse or promote * products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.caltoopia.codegen.printer; import java.util.Iterator; import org.caltoopia.ast2ir.Util; import org.caltoopia.codegen.CEnvironment; import org.caltoopia.codegen.CodegenError; import org.caltoopia.codegen.UtilIR; import org.caltoopia.codegen.printer.CBuildVarDeclaration.varCB; import org.caltoopia.codegen.transformer.IrTransformer; import org.caltoopia.codegen.transformer.TransUtil; import org.caltoopia.codegen.transformer.analysis.IrVariableAnnotation.VarType; import org.caltoopia.ir.LambdaExpression; import org.caltoopia.ir.ProcExpression; import org.caltoopia.ir.Type; import org.caltoopia.ir.TypeActor; import org.caltoopia.ir.TypeLambda; import org.caltoopia.ir.Variable; import org.caltoopia.ir.util.IrSwitch; import org.eclipse.emf.ecore.EObject; public class CBuildFuncDeclaration extends IrSwitch<Boolean> { String funcStr=""; Variable variable; boolean header = false; CEnvironment cenv = null; public CBuildFuncDeclaration(Variable variable, CEnvironment cenv, boolean header) { funcStr=""; this.header = header; this.variable = variable; this.cenv = cenv; } public String toStr() { Boolean res = doSwitch(variable); if(!res) { CodegenError.err("Func declaration builder", funcStr); } return funcStr; } private void enter(EObject obj) {} private void leave() {} public Boolean caseVariable(Variable variable) { LambdaExpression lambda = (LambdaExpression) variable.getInitValue(); Type type = ((TypeLambda)lambda.getType()).getOutputType(); funcStr = new CBuildTypeName(type, new CPrintUtil.listStarCB()).toStr() + " "; String thisStr = TransUtil.getNamespaceAnnotation(variable); funcStr += thisStr + "__"; funcStr += CPrintUtil.validCName(variable.getName()) + "("; - VarType varType = VarType.valueOf(TransUtil.getAnnotationArg(type, IrTransformer.VARIABLE_ANNOTATION, "VarType")); + VarType varType = VarType.valueOf(TransUtil.getAnnotationArg(variable, IrTransformer.VARIABLE_ANNOTATION, "VarType")); if(varType == VarType.actorFunc) { funcStr += ("ActorInstance_" + thisStr + "* thisActor"); if(!lambda.getParameters().isEmpty()) funcStr += (", "); } for(Iterator<Variable> i = lambda.getParameters().iterator();i.hasNext();) { Variable p = i.next(); //FIXME must fix so that it can handle params funcStr += new CBuildVarDeclaration(p,cenv,false).toStr(); if (i.hasNext()) funcStr += ", "; } funcStr += (")"); if(header) { funcStr += (";\n"); } else { if(lambda.getBody() instanceof ProcExpression) { //Expression have been expanded to nameless proc to get a block //doSwitch(((ProcExpression)lambda.getBody()).getBody()); funcStr += "/* Here body statements should be printed */\n"; } else { funcStr += ("{\n"); funcStr += ("\treturn "); funcStr += new CBuildExpression(lambda.getBody(),cenv).toStr(); funcStr += (";\n"); funcStr += ("}\n"); } } return true; } }
true
true
public Boolean caseVariable(Variable variable) { LambdaExpression lambda = (LambdaExpression) variable.getInitValue(); Type type = ((TypeLambda)lambda.getType()).getOutputType(); funcStr = new CBuildTypeName(type, new CPrintUtil.listStarCB()).toStr() + " "; String thisStr = TransUtil.getNamespaceAnnotation(variable); funcStr += thisStr + "__"; funcStr += CPrintUtil.validCName(variable.getName()) + "("; VarType varType = VarType.valueOf(TransUtil.getAnnotationArg(type, IrTransformer.VARIABLE_ANNOTATION, "VarType")); if(varType == VarType.actorFunc) { funcStr += ("ActorInstance_" + thisStr + "* thisActor"); if(!lambda.getParameters().isEmpty()) funcStr += (", "); } for(Iterator<Variable> i = lambda.getParameters().iterator();i.hasNext();) { Variable p = i.next(); //FIXME must fix so that it can handle params funcStr += new CBuildVarDeclaration(p,cenv,false).toStr(); if (i.hasNext()) funcStr += ", "; } funcStr += (")"); if(header) { funcStr += (";\n"); } else { if(lambda.getBody() instanceof ProcExpression) { //Expression have been expanded to nameless proc to get a block //doSwitch(((ProcExpression)lambda.getBody()).getBody()); funcStr += "/* Here body statements should be printed */\n"; } else { funcStr += ("{\n"); funcStr += ("\treturn "); funcStr += new CBuildExpression(lambda.getBody(),cenv).toStr(); funcStr += (";\n"); funcStr += ("}\n"); } } return true; }
public Boolean caseVariable(Variable variable) { LambdaExpression lambda = (LambdaExpression) variable.getInitValue(); Type type = ((TypeLambda)lambda.getType()).getOutputType(); funcStr = new CBuildTypeName(type, new CPrintUtil.listStarCB()).toStr() + " "; String thisStr = TransUtil.getNamespaceAnnotation(variable); funcStr += thisStr + "__"; funcStr += CPrintUtil.validCName(variable.getName()) + "("; VarType varType = VarType.valueOf(TransUtil.getAnnotationArg(variable, IrTransformer.VARIABLE_ANNOTATION, "VarType")); if(varType == VarType.actorFunc) { funcStr += ("ActorInstance_" + thisStr + "* thisActor"); if(!lambda.getParameters().isEmpty()) funcStr += (", "); } for(Iterator<Variable> i = lambda.getParameters().iterator();i.hasNext();) { Variable p = i.next(); //FIXME must fix so that it can handle params funcStr += new CBuildVarDeclaration(p,cenv,false).toStr(); if (i.hasNext()) funcStr += ", "; } funcStr += (")"); if(header) { funcStr += (";\n"); } else { if(lambda.getBody() instanceof ProcExpression) { //Expression have been expanded to nameless proc to get a block //doSwitch(((ProcExpression)lambda.getBody()).getBody()); funcStr += "/* Here body statements should be printed */\n"; } else { funcStr += ("{\n"); funcStr += ("\treturn "); funcStr += new CBuildExpression(lambda.getBody(),cenv).toStr(); funcStr += (";\n"); funcStr += ("}\n"); } } return true; }
diff --git a/src/com/android/settings/TextToSpeechSettings.java b/src/com/android/settings/TextToSpeechSettings.java index 84b14a191..04287beb2 100644 --- a/src/com/android/settings/TextToSpeechSettings.java +++ b/src/com/android/settings/TextToSpeechSettings.java @@ -1,740 +1,756 @@ /* * Copyright (C) 2009 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.settings; import static android.provider.Settings.Secure.TTS_USE_DEFAULTS; import static android.provider.Settings.Secure.TTS_DEFAULT_RATE; import static android.provider.Settings.Secure.TTS_DEFAULT_LANG; import static android.provider.Settings.Secure.TTS_DEFAULT_COUNTRY; import static android.provider.Settings.Secure.TTS_DEFAULT_VARIANT; import static android.provider.Settings.Secure.TTS_DEFAULT_SYNTH; import static android.provider.Settings.Secure.TTS_ENABLED_PLUGINS; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceScreen; import android.preference.CheckBoxPreference; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.speech.tts.TextToSpeech; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; public class TextToSpeechSettings extends PreferenceActivity implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener, TextToSpeech.OnInitListener { private static final String TAG = "TextToSpeechSettings"; private static final String SYSTEM_TTS = "com.svox.pico"; private static final String KEY_TTS_PLAY_EXAMPLE = "tts_play_example"; private static final String KEY_TTS_INSTALL_DATA = "tts_install_data"; private static final String KEY_TTS_USE_DEFAULT = "toggle_use_default_tts_settings"; private static final String KEY_TTS_DEFAULT_RATE = "tts_default_rate"; private static final String KEY_TTS_DEFAULT_LANG = "tts_default_lang"; private static final String KEY_TTS_DEFAULT_COUNTRY = "tts_default_country"; private static final String KEY_TTS_DEFAULT_VARIANT = "tts_default_variant"; private static final String KEY_TTS_DEFAULT_SYNTH = "tts_default_synth"; private static final String KEY_PLUGIN_ENABLED_PREFIX = "ENABLED_"; private static final String KEY_PLUGIN_SETTINGS_PREFIX = "SETTINGS_"; // TODO move default Locale values to TextToSpeech.Engine private static final String DEFAULT_LANG_VAL = "eng"; private static final String DEFAULT_COUNTRY_VAL = "USA"; private static final String DEFAULT_VARIANT_VAL = ""; private static final String LOCALE_DELIMITER = "-"; private static final String FALLBACK_TTS_DEFAULT_SYNTH = TextToSpeech.Engine.DEFAULT_SYNTH; private Preference mPlayExample = null; private Preference mInstallData = null; private CheckBoxPreference mUseDefaultPref = null; private ListPreference mDefaultRatePref = null; private ListPreference mDefaultLocPref = null; private ListPreference mDefaultSynthPref = null; private String mDefaultLanguage = null; private String mDefaultCountry = null; private String mDefaultLocVariant = null; private String mDefaultEng = ""; private int mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE; // Array of strings used to demonstrate TTS in the different languages. private String[] mDemoStrings; // Index of the current string to use for the demo. private int mDemoStringIndex = 0; private boolean mEnableDemo = false; private boolean mVoicesMissing = false; private TextToSpeech mTts = null; private boolean mTtsStarted = false; /** * Request code (arbitrary value) for voice data check through * startActivityForResult. */ private static final int VOICE_DATA_INTEGRITY_CHECK = 1977; private static final int GET_SAMPLE_TEXT = 1983; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.tts_settings); addEngineSpecificSettings(); mDemoStrings = getResources().getStringArray(R.array.tts_demo_strings); setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM); mEnableDemo = false; mTtsStarted = false; Locale currentLocale = Locale.getDefault(); mDefaultLanguage = currentLocale.getISO3Language(); mDefaultCountry = currentLocale.getISO3Country(); mDefaultLocVariant = currentLocale.getVariant(); mTts = new TextToSpeech(this, this); } @Override protected void onStart() { super.onStart(); if (mTtsStarted){ // whenever we return to this screen, we don't know the state of the // system, so we have to recheck that we can play the demo, or it must be disabled. // TODO make the TTS service listen to "changes in the system", i.e. sd card un/mount initClickers(); updateWidgetState(); checkVoiceData(); } } @Override protected void onDestroy() { super.onDestroy(); if (mTts != null) { mTts.shutdown(); } } @Override protected void onPause() { super.onPause(); if ((mDefaultRatePref != null) && (mDefaultRatePref.getDialog() != null)) { mDefaultRatePref.getDialog().dismiss(); } if ((mDefaultLocPref != null) && (mDefaultLocPref.getDialog() != null)) { mDefaultLocPref.getDialog().dismiss(); } if ((mDefaultSynthPref != null) && (mDefaultSynthPref.getDialog() != null)) { mDefaultSynthPref.getDialog().dismiss(); } } private void addEngineSpecificSettings() { PreferenceGroup enginesCategory = (PreferenceGroup) findPreference("tts_engines_section"); Intent intent = new Intent("android.intent.action.START_TTS_ENGINE"); ResolveInfo[] enginesArray = new ResolveInfo[0]; PackageManager pm = getPackageManager(); enginesArray = pm.queryIntentActivities(intent, 0).toArray(enginesArray); for (int i = 0; i < enginesArray.length; i++) { String prefKey = ""; final String pluginPackageName = enginesArray[i].activityInfo.packageName; if (!enginesArray[i].activityInfo.packageName.equals(SYSTEM_TTS)) { CheckBoxPreference chkbxPref = new CheckBoxPreference(this); prefKey = KEY_PLUGIN_ENABLED_PREFIX + pluginPackageName; chkbxPref.setKey(prefKey); chkbxPref.setTitle(enginesArray[i].loadLabel(pm)); enginesCategory.addPreference(chkbxPref); } if (pluginHasSettings(pluginPackageName)) { Preference pref = new Preference(this); prefKey = KEY_PLUGIN_SETTINGS_PREFIX + pluginPackageName; pref.setKey(prefKey); pref.setTitle(enginesArray[i].loadLabel(pm)); CharSequence settingsLabel = getResources().getString( R.string.tts_engine_name_settings, enginesArray[i].loadLabel(pm)); pref.setSummary(settingsLabel); pref.setOnPreferenceClickListener(new OnPreferenceClickListener(){ public boolean onPreferenceClick(Preference preference){ Intent i = new Intent(); i.setClassName(pluginPackageName, pluginPackageName + ".EngineSettings"); startActivity(i); return true; } }); enginesCategory.addPreference(pref); } } } private boolean pluginHasSettings(String pluginPackageName) { PackageManager pm = getPackageManager(); Intent i = new Intent(); i.setClassName(pluginPackageName, pluginPackageName + ".EngineSettings"); if (pm.resolveActivity(i, PackageManager.MATCH_DEFAULT_ONLY) != null){ return true; } return false; } private void initClickers() { mPlayExample = findPreference(KEY_TTS_PLAY_EXAMPLE); mPlayExample.setOnPreferenceClickListener(this); mInstallData = findPreference(KEY_TTS_INSTALL_DATA); mInstallData.setOnPreferenceClickListener(this); } private void initDefaultSettings() { ContentResolver resolver = getContentResolver(); // Find the default TTS values in the settings, initialize and store the // settings if they are not found. // "Use Defaults" int useDefault = 0; mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT); try { useDefault = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS); } catch (SettingNotFoundException e) { // "use default" setting not found, initialize it useDefault = TextToSpeech.Engine.USE_DEFAULTS; Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, useDefault); } mUseDefaultPref.setChecked(useDefault == 1); mUseDefaultPref.setOnPreferenceChangeListener(this); // Default synthesis engine mDefaultSynthPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_SYNTH); loadEngines(); mDefaultSynthPref.setOnPreferenceChangeListener(this); String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH); if (engine == null) { // TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech engine = FALLBACK_TTS_DEFAULT_SYNTH; Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine); } mDefaultEng = engine; // Default rate mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE); try { mDefaultRate = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE); } catch (SettingNotFoundException e) { // default rate setting not found, initialize it mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE; Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, mDefaultRate); } mDefaultRatePref.setValue(String.valueOf(mDefaultRate)); mDefaultRatePref.setOnPreferenceChangeListener(this); // Default language / country / variant : these three values map to a single ListPref // representing the matching Locale mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG); initDefaultLang(); mDefaultLocPref.setOnPreferenceChangeListener(this); } /** * Ask the current default engine to launch the matching CHECK_TTS_DATA activity * to check the required TTS files are properly installed. */ private void checkVoiceData() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK); } } } /** * Ask the current default engine to launch the matching INSTALL_TTS_DATA activity * so the required TTS files are properly installed. */ private void installVoiceData() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); intent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivity(intent); } } } /** * Ask the current default engine to return a string of sample text to be * spoken to the user. */ private void getSampleText() { PackageManager pm = getPackageManager(); Intent intent = new Intent(); // TODO (clchen): Replace Intent string with the actual // Intent defined in the list of platform Intents. intent.setAction("android.speech.tts.engine.GET_SAMPLE_TEXT"); intent.putExtra("language", mDefaultLanguage); intent.putExtra("country", mDefaultCountry); intent.putExtra("variant", mDefaultLocVariant); List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0); // query only the package that matches that of the default engine for (int i = 0; i < resolveInfos.size(); i++) { ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo; if (mDefaultEng.equals(currentActivityInfo.packageName)) { intent.setClassName(mDefaultEng, currentActivityInfo.name); this.startActivityForResult(intent, GET_SAMPLE_TEXT); } } } /** * Called when the TTS engine is initialized. */ public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { mEnableDemo = true; if (mDefaultLanguage == null) { mDefaultLanguage = Locale.getDefault().getISO3Language(); } if (mDefaultCountry == null) { mDefaultCountry = Locale.getDefault().getISO3Country(); } if (mDefaultLocVariant == null) { mDefaultLocVariant = new String(); } mTts.setLanguage(new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); mTts.setSpeechRate((float)(mDefaultRate/100.0f)); initDefaultSettings(); initClickers(); updateWidgetState(); checkVoiceData(); mTtsStarted = true; Log.v(TAG, "TTS engine for settings screen initialized."); } else { Log.v(TAG, "TTS engine for settings screen failed to initialize successfully."); mEnableDemo = false; } updateWidgetState(); } /** * Called when voice data integrity check returns */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_DATA_INTEGRITY_CHECK) { if (data == null){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } ArrayList<String> available = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES); ArrayList<String> unavailable = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES); if ((available == null) || (unavailable == null)){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } if (available.size() > 0){ if (mTts == null) { mTts = new TextToSpeech(this, this); } ListPreference ttsLanguagePref = (ListPreference) findPreference("tts_default_lang"); CharSequence[] entries = new CharSequence[available.size()]; CharSequence[] entryValues = new CharSequence[available.size()]; - for (int i=0; i<available.size(); i++){ + int selectedLanguageIndex = -1; + String selectedLanguagePref = mDefaultLanguage; + if (mDefaultCountry.length() > 0) { + selectedLanguagePref = selectedLanguagePref + LOCALE_DELIMITER + + mDefaultCountry; + } + if (mDefaultLocVariant.length() > 0) { + selectedLanguagePref = selectedLanguagePref + LOCALE_DELIMITER + + mDefaultLocVariant; + } + for (int i = 0; i < available.size(); i++){ String[] langCountryVariant = available.get(i).split("-"); Locale loc = null; if (langCountryVariant.length == 1){ loc = new Locale(langCountryVariant[0]); } else if (langCountryVariant.length == 2){ loc = new Locale(langCountryVariant[0], langCountryVariant[1]); } else if (langCountryVariant.length == 3){ loc = new Locale(langCountryVariant[0], langCountryVariant[1], langCountryVariant[2]); } if (loc != null){ entries[i] = loc.getDisplayName(); entryValues[i] = available.get(i); + if (entryValues[i].equals(selectedLanguagePref)){ + selectedLanguageIndex = i; + } } } ttsLanguagePref.setEntries(entries); ttsLanguagePref.setEntryValues(entryValues); + if (selectedLanguageIndex > -1) { + ttsLanguagePref.setValueIndex(selectedLanguageIndex); + } mEnableDemo = true; // Make sure that the default language can be used. int languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); if (languageResult < TextToSpeech.LANG_AVAILABLE){ Locale currentLocale = Locale.getDefault(); mDefaultLanguage = currentLocale.getISO3Language(); mDefaultCountry = currentLocale.getISO3Country(); mDefaultLocVariant = currentLocale.getVariant(); languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); // If the default Locale isn't supported, just choose the first available // language so that there is at least something. if (languageResult < TextToSpeech.LANG_AVAILABLE){ parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString()); mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); } ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); } } else { mEnableDemo = false; } if (unavailable.size() > 0){ mVoicesMissing = true; } else { mVoicesMissing = false; } updateWidgetState(); } else if (requestCode == GET_SAMPLE_TEXT) { if (resultCode == TextToSpeech.LANG_AVAILABLE) { String sample = getString(R.string.tts_demo); if ((data != null) && (data.getStringExtra("sampleText") != null)) { sample = data.getStringExtra("sampleText"); } if (mTts != null) { mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null); } } else { // TODO: Display an error here to the user. Log.e(TAG, "Did not have a sample string for the requested language"); } } } public boolean onPreferenceChange(Preference preference, Object objValue) { if (KEY_TTS_USE_DEFAULT.equals(preference.getKey())) { // "Use Defaults" int value = (Boolean)objValue ? 1 : 0; Settings.Secure.putInt(getContentResolver(), TTS_USE_DEFAULTS, value); Log.i(TAG, "TTS use default settings is "+objValue.toString()); } else if (KEY_TTS_DEFAULT_RATE.equals(preference.getKey())) { // Default rate mDefaultRate = Integer.parseInt((String) objValue); try { Settings.Secure.putInt(getContentResolver(), TTS_DEFAULT_RATE, mDefaultRate); if (mTts != null) { mTts.setSpeechRate((float)(mDefaultRate/100.0f)); } Log.i(TAG, "TTS default rate is " + mDefaultRate); } catch (NumberFormatException e) { Log.e(TAG, "could not persist default TTS rate setting", e); } } else if (KEY_TTS_DEFAULT_LANG.equals(preference.getKey())) { // Default locale ContentResolver resolver = getContentResolver(); parseLocaleInfo((String) objValue); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); Log.v(TAG, "TTS default lang/country/variant set to " + mDefaultLanguage + "/" + mDefaultCountry + "/" + mDefaultLocVariant); if (mTts != null) { mTts.setLanguage(new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); } int newIndex = mDefaultLocPref.findIndexOfValue((String)objValue); Log.v("Settings", " selected is " + newIndex); mDemoStringIndex = newIndex > -1 ? newIndex : 0; } else if (KEY_TTS_DEFAULT_SYNTH.equals(preference.getKey())) { mDefaultEng = objValue.toString(); Settings.Secure.putString(getContentResolver(), TTS_DEFAULT_SYNTH, mDefaultEng); if (mTts != null) { mTts.setEngineByPackageName(mDefaultEng); mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); checkVoiceData(); } Log.v("Settings", "The default synth is: " + objValue.toString()); } return true; } /** * Called when mPlayExample or mInstallData is clicked */ public boolean onPreferenceClick(Preference preference) { if (preference == mPlayExample) { // Get the sample text from the TTS engine; onActivityResult will do // the actual speaking getSampleText(); return true; } if (preference == mInstallData) { installVoiceData(); // quit this activity so it needs to be restarted after installation of the voice data finish(); return true; } return false; } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (Utils.isMonkeyRunning()) { return false; } if (preference instanceof CheckBoxPreference) { final CheckBoxPreference chkPref = (CheckBoxPreference) preference; if (!chkPref.getKey().equals(KEY_TTS_USE_DEFAULT)){ if (chkPref.isChecked()) { chkPref.setChecked(false); AlertDialog d = (new AlertDialog.Builder(this)) .setTitle(android.R.string.dialog_alert_title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(getString(R.string.tts_engine_security_warning, chkPref.getTitle())) .setCancelable(true) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { chkPref.setChecked(true); loadEngines(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .create(); d.show(); } else { loadEngines(); } return true; } } return false; } private void updateWidgetState() { mPlayExample.setEnabled(mEnableDemo); mUseDefaultPref.setEnabled(mEnableDemo); mDefaultRatePref.setEnabled(mEnableDemo); mDefaultLocPref.setEnabled(mEnableDemo); mInstallData.setEnabled(mVoicesMissing); } private void parseLocaleInfo(String locale) { StringTokenizer tokenizer = new StringTokenizer(locale, LOCALE_DELIMITER); mDefaultLanguage = ""; mDefaultCountry = ""; mDefaultLocVariant = ""; if (tokenizer.hasMoreTokens()) { mDefaultLanguage = tokenizer.nextToken().trim(); } if (tokenizer.hasMoreTokens()) { mDefaultCountry = tokenizer.nextToken().trim(); } if (tokenizer.hasMoreTokens()) { mDefaultLocVariant = tokenizer.nextToken().trim(); } } /** * Initialize the default language in the UI and in the preferences. * After this method has been invoked, the default language is a supported Locale. */ private void initDefaultLang() { // if there isn't already a default language preference if (!hasLangPref()) { // if the current Locale is supported if (isCurrentLocSupported()) { // then use the current Locale as the default language useCurrentLocAsDefault(); } else { // otherwise use a default supported Locale as the default language useSupportedLocAsDefault(); } } // Update the language preference list with the default language and the matching // demo string (at this stage there is a default language pref) ContentResolver resolver = getContentResolver(); mDefaultLanguage = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG); mDefaultCountry = Settings.Secure.getString(resolver, TTS_DEFAULT_COUNTRY); mDefaultLocVariant = Settings.Secure.getString(resolver, TTS_DEFAULT_VARIANT); // update the demo string mDemoStringIndex = mDefaultLocPref.findIndexOfValue(mDefaultLanguage + LOCALE_DELIMITER + mDefaultCountry); if (mDemoStringIndex > -1){ mDefaultLocPref.setValueIndex(mDemoStringIndex); } } /** * (helper function for initDefaultLang() ) * Returns whether there is a default language in the TTS settings. */ private boolean hasLangPref() { String language = Settings.Secure.getString(getContentResolver(), TTS_DEFAULT_LANG); return (language != null); } /** * (helper function for initDefaultLang() ) * Returns whether the current Locale is supported by this Settings screen */ private boolean isCurrentLocSupported() { String currentLocID = Locale.getDefault().getISO3Language() + LOCALE_DELIMITER + Locale.getDefault().getISO3Country(); return (mDefaultLocPref.findIndexOfValue(currentLocID) > -1); } /** * (helper function for initDefaultLang() ) * Sets the default language in TTS settings to be the current Locale. * This should only be used after checking that the current Locale is supported. */ private void useCurrentLocAsDefault() { Locale currentLocale = Locale.getDefault(); ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, currentLocale.getISO3Language()); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, currentLocale.getISO3Country()); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, currentLocale.getVariant()); } /** * (helper function for initDefaultLang() ) * Sets the default language in TTS settings to be one known to be supported */ private void useSupportedLocAsDefault() { ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, DEFAULT_LANG_VAL); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, DEFAULT_COUNTRY_VAL); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, DEFAULT_VARIANT_VAL); } private void loadEngines() { mDefaultSynthPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_SYNTH); // TODO (clchen): Try to see if it is possible to be more efficient here // and not search for plugins again. Intent intent = new Intent("android.intent.action.START_TTS_ENGINE"); ResolveInfo[] enginesArray = new ResolveInfo[0]; PackageManager pm = getPackageManager(); enginesArray = pm.queryIntentActivities(intent, 0).toArray(enginesArray); ArrayList<CharSequence> entries = new ArrayList<CharSequence>(); ArrayList<CharSequence> values = new ArrayList<CharSequence>(); String enabledEngines = ""; for (int i = 0; i < enginesArray.length; i++) { String pluginPackageName = enginesArray[i].activityInfo.packageName; if (pluginPackageName.equals(SYSTEM_TTS)) { entries.add(enginesArray[i].loadLabel(pm)); values.add(pluginPackageName); } else { CheckBoxPreference pref = (CheckBoxPreference) findPreference( KEY_PLUGIN_ENABLED_PREFIX + pluginPackageName); if ((pref != null) && pref.isChecked()){ entries.add(enginesArray[i].loadLabel(pm)); values.add(pluginPackageName); enabledEngines = enabledEngines + pluginPackageName + " "; } } } ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_ENABLED_PLUGINS, enabledEngines); CharSequence entriesArray[] = new CharSequence[entries.size()]; CharSequence valuesArray[] = new CharSequence[values.size()]; mDefaultSynthPref.setEntries(entries.toArray(entriesArray)); mDefaultSynthPref.setEntryValues(values.toArray(valuesArray)); // Set the selected engine based on the saved preference String selectedEngine = Settings.Secure.getString(getContentResolver(), TTS_DEFAULT_SYNTH); int selectedEngineIndex = mDefaultSynthPref.findIndexOfValue(selectedEngine); if (selectedEngineIndex == -1){ selectedEngineIndex = mDefaultSynthPref.findIndexOfValue(SYSTEM_TTS); } mDefaultSynthPref.setValueIndex(selectedEngineIndex); } }
false
true
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_DATA_INTEGRITY_CHECK) { if (data == null){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } ArrayList<String> available = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES); ArrayList<String> unavailable = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES); if ((available == null) || (unavailable == null)){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } if (available.size() > 0){ if (mTts == null) { mTts = new TextToSpeech(this, this); } ListPreference ttsLanguagePref = (ListPreference) findPreference("tts_default_lang"); CharSequence[] entries = new CharSequence[available.size()]; CharSequence[] entryValues = new CharSequence[available.size()]; for (int i=0; i<available.size(); i++){ String[] langCountryVariant = available.get(i).split("-"); Locale loc = null; if (langCountryVariant.length == 1){ loc = new Locale(langCountryVariant[0]); } else if (langCountryVariant.length == 2){ loc = new Locale(langCountryVariant[0], langCountryVariant[1]); } else if (langCountryVariant.length == 3){ loc = new Locale(langCountryVariant[0], langCountryVariant[1], langCountryVariant[2]); } if (loc != null){ entries[i] = loc.getDisplayName(); entryValues[i] = available.get(i); } } ttsLanguagePref.setEntries(entries); ttsLanguagePref.setEntryValues(entryValues); mEnableDemo = true; // Make sure that the default language can be used. int languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); if (languageResult < TextToSpeech.LANG_AVAILABLE){ Locale currentLocale = Locale.getDefault(); mDefaultLanguage = currentLocale.getISO3Language(); mDefaultCountry = currentLocale.getISO3Country(); mDefaultLocVariant = currentLocale.getVariant(); languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); // If the default Locale isn't supported, just choose the first available // language so that there is at least something. if (languageResult < TextToSpeech.LANG_AVAILABLE){ parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString()); mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); } ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); } } else { mEnableDemo = false; } if (unavailable.size() > 0){ mVoicesMissing = true; } else { mVoicesMissing = false; } updateWidgetState(); } else if (requestCode == GET_SAMPLE_TEXT) { if (resultCode == TextToSpeech.LANG_AVAILABLE) { String sample = getString(R.string.tts_demo); if ((data != null) && (data.getStringExtra("sampleText") != null)) { sample = data.getStringExtra("sampleText"); } if (mTts != null) { mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null); } } else { // TODO: Display an error here to the user. Log.e(TAG, "Did not have a sample string for the requested language"); } } }
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_DATA_INTEGRITY_CHECK) { if (data == null){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } ArrayList<String> available = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES); ArrayList<String> unavailable = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES); if ((available == null) || (unavailable == null)){ // The CHECK_TTS_DATA activity for the plugin did not run properly; // disable the preview and install controls and return. mEnableDemo = false; mVoicesMissing = false; updateWidgetState(); return; } if (available.size() > 0){ if (mTts == null) { mTts = new TextToSpeech(this, this); } ListPreference ttsLanguagePref = (ListPreference) findPreference("tts_default_lang"); CharSequence[] entries = new CharSequence[available.size()]; CharSequence[] entryValues = new CharSequence[available.size()]; int selectedLanguageIndex = -1; String selectedLanguagePref = mDefaultLanguage; if (mDefaultCountry.length() > 0) { selectedLanguagePref = selectedLanguagePref + LOCALE_DELIMITER + mDefaultCountry; } if (mDefaultLocVariant.length() > 0) { selectedLanguagePref = selectedLanguagePref + LOCALE_DELIMITER + mDefaultLocVariant; } for (int i = 0; i < available.size(); i++){ String[] langCountryVariant = available.get(i).split("-"); Locale loc = null; if (langCountryVariant.length == 1){ loc = new Locale(langCountryVariant[0]); } else if (langCountryVariant.length == 2){ loc = new Locale(langCountryVariant[0], langCountryVariant[1]); } else if (langCountryVariant.length == 3){ loc = new Locale(langCountryVariant[0], langCountryVariant[1], langCountryVariant[2]); } if (loc != null){ entries[i] = loc.getDisplayName(); entryValues[i] = available.get(i); if (entryValues[i].equals(selectedLanguagePref)){ selectedLanguageIndex = i; } } } ttsLanguagePref.setEntries(entries); ttsLanguagePref.setEntryValues(entryValues); if (selectedLanguageIndex > -1) { ttsLanguagePref.setValueIndex(selectedLanguageIndex); } mEnableDemo = true; // Make sure that the default language can be used. int languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); if (languageResult < TextToSpeech.LANG_AVAILABLE){ Locale currentLocale = Locale.getDefault(); mDefaultLanguage = currentLocale.getISO3Language(); mDefaultCountry = currentLocale.getISO3Country(); mDefaultLocVariant = currentLocale.getVariant(); languageResult = mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); // If the default Locale isn't supported, just choose the first available // language so that there is at least something. if (languageResult < TextToSpeech.LANG_AVAILABLE){ parseLocaleInfo(ttsLanguagePref.getEntryValues()[0].toString()); mTts.setLanguage( new Locale(mDefaultLanguage, mDefaultCountry, mDefaultLocVariant)); } ContentResolver resolver = getContentResolver(); Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage); Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry); Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant); } } else { mEnableDemo = false; } if (unavailable.size() > 0){ mVoicesMissing = true; } else { mVoicesMissing = false; } updateWidgetState(); } else if (requestCode == GET_SAMPLE_TEXT) { if (resultCode == TextToSpeech.LANG_AVAILABLE) { String sample = getString(R.string.tts_demo); if ((data != null) && (data.getStringExtra("sampleText") != null)) { sample = data.getStringExtra("sampleText"); } if (mTts != null) { mTts.speak(sample, TextToSpeech.QUEUE_FLUSH, null); } } else { // TODO: Display an error here to the user. Log.e(TAG, "Did not have a sample string for the requested language"); } } }
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/Notification.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/Notification.java index c66f8a635..42ce1ade1 100644 --- a/src/com/itmill/toolkit/terminal/gwt/client/ui/Notification.java +++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/Notification.java @@ -1,276 +1,276 @@ /* @ITMillApache2LicenseForJavaFiles@ */ package com.itmill.toolkit.terminal.gwt.client.ui; import java.util.ArrayList; import java.util.EventObject; import java.util.Iterator; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Element; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Widget; public class Notification extends ToolkitOverlay { public static final int CENTERED = 1; public static final int CENTERED_TOP = 2; public static final int CENTERED_BOTTOM = 3; public static final int TOP_LEFT = 4; public static final int TOP_RIGHT = 5; public static final int BOTTOM_LEFT = 6; public static final int BOTTOM_RIGHT = 7; public static final int DELAY_FOREVER = -1; public static final int DELAY_NONE = 0; private static final String STYLENAME = "i-Notification"; private static final int mouseMoveThreshold = 7; private static final int Z_INDEX_BASE = 20000; private int startOpacity = 90; private int fadeMsec = 400; private int delayMsec = 1000; private Timer fader; private Timer delay; private int x = -1; private int y = -1; private String temporaryStyle; private ArrayList listeners; public Notification() { setStylePrimaryName(STYLENAME); sinkEvents(Event.ONCLICK); DOM.setStyleAttribute(getElement(), "zIndex", "" + Z_INDEX_BASE); } public Notification(int delayMsec) { this(); this.delayMsec = delayMsec; } public Notification(int delayMsec, int fadeMsec, int startOpacity) { this(delayMsec); this.fadeMsec = fadeMsec; this.startOpacity = startOpacity; } public void startDelay() { DOM.removeEventPreview(this); if (delayMsec > 0) { delay = new Timer() { public void run() { fade(); } }; delay.scheduleRepeating(delayMsec); } else if (delayMsec == 0) { fade(); } } public void show() { show(CENTERED); } public void show(String style) { show(CENTERED, style); } public void show(int position) { show(position, null); } public void show(Widget widget, int position, String style) { setWidget(widget); show(position, style); } public void show(String html, int position, String style) { setWidget(new HTML(html)); show(position, style); } public void show(int position, String style) { setOpacity(getElement(), startOpacity); if (style != null) { temporaryStyle = style; addStyleName(style); } super.show(); setPosition(position); } public void hide() { DOM.removeEventPreview(this); cancelDelay(); cancelFade(); if (temporaryStyle != null) { removeStyleName(temporaryStyle); temporaryStyle = null; } super.hide(); fireEvent(new HideEvent(this)); } public void fade() { DOM.removeEventPreview(this); cancelDelay(); fader = new Timer() { int opacity = startOpacity; public void run() { opacity -= 5; setOpacity(getElement(), opacity); if (opacity <= 0) { cancel(); hide(); } } }; final int msec = fadeMsec / (startOpacity / 5); fader.scheduleRepeating(msec); } public void setPosition(int position) { final Element el = getElement(); - DOM.setStyleAttribute(el, "top", null); - DOM.setStyleAttribute(el, "left", null); - DOM.setStyleAttribute(el, "bottom", null); - DOM.setStyleAttribute(el, "right", null); + DOM.setStyleAttribute(el, "top", ""); + DOM.setStyleAttribute(el, "left", ""); + DOM.setStyleAttribute(el, "bottom", ""); + DOM.setStyleAttribute(el, "right", ""); switch (position) { case TOP_LEFT: DOM.setStyleAttribute(el, "top", "0px"); DOM.setStyleAttribute(el, "left", "0px"); break; case TOP_RIGHT: DOM.setStyleAttribute(el, "top", "0px"); DOM.setStyleAttribute(el, "right", "0px"); break; case BOTTOM_RIGHT: DOM.setStyleAttribute(el, "position", "absolute"); DOM.setStyleAttribute(el, "bottom", "0px"); DOM.setStyleAttribute(el, "right", "0px"); break; case BOTTOM_LEFT: DOM.setStyleAttribute(el, "bottom", "0px"); DOM.setStyleAttribute(el, "left", "0px"); break; case CENTERED_TOP: center(); DOM.setStyleAttribute(el, "top", "0px"); break; case CENTERED_BOTTOM: center(); - DOM.setStyleAttribute(el, "top", null); + DOM.setStyleAttribute(el, "top", ""); DOM.setStyleAttribute(el, "bottom", "0px"); break; default: case CENTERED: center(); break; } } private void cancelFade() { if (fader != null) { fader.cancel(); fader = null; } } private void cancelDelay() { if (delay != null) { delay.cancel(); delay = null; } } private void setOpacity(Element el, int opacity) { DOM.setStyleAttribute(el, "opacity", "" + (opacity / 100.0)); DOM.setStyleAttribute(el, "filter", "Alpha(opacity=" + opacity + ")"); } public void onBrowserEvent(Event event) { DOM.removeEventPreview(this); if (fader == null) { fade(); } } public boolean onEventPreview(Event event) { int type = DOM.eventGetType(event); // "modal" if (delayMsec == -1) { if (type == Event.ONCLICK && DOM .isOrHasChild(getElement(), DOM .eventGetTarget(event))) { fade(); } return false; } // default switch (type) { case Event.ONMOUSEMOVE: if (x < 0) { x = DOM.eventGetClientX(event); y = DOM.eventGetClientY(event); } else if (Math.abs(DOM.eventGetClientX(event) - x) > mouseMoveThreshold || Math.abs(DOM.eventGetClientY(event) - y) > mouseMoveThreshold) { startDelay(); } break; case Event.ONCLICK: case Event.ONDBLCLICK: case Event.KEYEVENTS: case Event.ONSCROLL: default: startDelay(); } return true; } public void addEventListener(EventListener listener) { if (listeners == null) { listeners = new ArrayList(); } listeners.add(listener); } public void removeEventListener(EventListener listener) { if (listeners == null) { return; } listeners.remove(listener); } private void fireEvent(HideEvent event) { if (listeners != null) { for (Iterator it = listeners.iterator(); it.hasNext();) { EventListener l = (EventListener) it.next(); l.notificationHidden(event); } } } public class HideEvent extends EventObject { public HideEvent(Object source) { super(source); } } public interface EventListener extends java.util.EventListener { public void notificationHidden(HideEvent event); } }
false
true
public void setPosition(int position) { final Element el = getElement(); DOM.setStyleAttribute(el, "top", null); DOM.setStyleAttribute(el, "left", null); DOM.setStyleAttribute(el, "bottom", null); DOM.setStyleAttribute(el, "right", null); switch (position) { case TOP_LEFT: DOM.setStyleAttribute(el, "top", "0px"); DOM.setStyleAttribute(el, "left", "0px"); break; case TOP_RIGHT: DOM.setStyleAttribute(el, "top", "0px"); DOM.setStyleAttribute(el, "right", "0px"); break; case BOTTOM_RIGHT: DOM.setStyleAttribute(el, "position", "absolute"); DOM.setStyleAttribute(el, "bottom", "0px"); DOM.setStyleAttribute(el, "right", "0px"); break; case BOTTOM_LEFT: DOM.setStyleAttribute(el, "bottom", "0px"); DOM.setStyleAttribute(el, "left", "0px"); break; case CENTERED_TOP: center(); DOM.setStyleAttribute(el, "top", "0px"); break; case CENTERED_BOTTOM: center(); DOM.setStyleAttribute(el, "top", null); DOM.setStyleAttribute(el, "bottom", "0px"); break; default: case CENTERED: center(); break; } }
public void setPosition(int position) { final Element el = getElement(); DOM.setStyleAttribute(el, "top", ""); DOM.setStyleAttribute(el, "left", ""); DOM.setStyleAttribute(el, "bottom", ""); DOM.setStyleAttribute(el, "right", ""); switch (position) { case TOP_LEFT: DOM.setStyleAttribute(el, "top", "0px"); DOM.setStyleAttribute(el, "left", "0px"); break; case TOP_RIGHT: DOM.setStyleAttribute(el, "top", "0px"); DOM.setStyleAttribute(el, "right", "0px"); break; case BOTTOM_RIGHT: DOM.setStyleAttribute(el, "position", "absolute"); DOM.setStyleAttribute(el, "bottom", "0px"); DOM.setStyleAttribute(el, "right", "0px"); break; case BOTTOM_LEFT: DOM.setStyleAttribute(el, "bottom", "0px"); DOM.setStyleAttribute(el, "left", "0px"); break; case CENTERED_TOP: center(); DOM.setStyleAttribute(el, "top", "0px"); break; case CENTERED_BOTTOM: center(); DOM.setStyleAttribute(el, "top", ""); DOM.setStyleAttribute(el, "bottom", "0px"); break; default: case CENTERED: center(); break; } }
diff --git a/common/src/net/myrrix/common/io/IOUtils.java b/common/src/net/myrrix/common/io/IOUtils.java index b1d8b6b..e9d5d9c 100644 --- a/common/src/net/myrrix/common/io/IOUtils.java +++ b/common/src/net/myrrix/common/io/IOUtils.java @@ -1,123 +1,126 @@ /* * Copyright Myrrix 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 net.myrrix.common.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayDeque; import java.util.Deque; import java.util.zip.DeflaterInputStream; import java.util.zip.GZIPInputStream; import java.util.zip.ZipInputStream; import com.google.common.io.ByteStreams; import com.google.common.io.Closeables; /** * Simple utility methods related to I/O. * * @author Sean Owen */ public final class IOUtils { private IOUtils() { } /** * Attempts to recursively delete a directory. This may not work across symlinks. * * @param dir directory to delete along with contents * @return {@code true} if all files and dirs were deleted successfully */ public static boolean deleteRecursively(File dir) { + if (dir == null) { + return false; + } Deque<File> stack = new ArrayDeque<File>(); stack.push(dir); boolean result = true; while (!stack.isEmpty()) { File topElement = stack.peek(); if (topElement.isDirectory()) { File[] directoryContents = topElement.listFiles(); if (directoryContents != null && directoryContents.length > 0) { for (File fileOrSubDirectory : directoryContents) { stack.push(fileOrSubDirectory); } } else { result = result && stack.pop().delete(); } } else { result = result && stack.pop().delete(); } } return result; } /** * Opens an {@link InputStream} to the file. If it appears to be compressed, because its file name ends in * ".gz" or ".zip" or ".deflate", then it will be decompressed accordingly * * @param file file, possibly compressed, to open * @return {@link InputStream} on uncompressed contents * @throws IOException if the stream can't be opened or is invalid or can't be read */ public static InputStream openMaybeDecompressing(File file) throws IOException { String name = file.getName(); InputStream in = new FileInputStream(file); if (name.endsWith(".gz")) { return new GZIPInputStream(in); } if (name.endsWith(".zip")) { return new ZipInputStream(in); } if (name.endsWith(".deflate")) { return new DeflaterInputStream(in); } return in; } /** * @param in stream to read and copy * @param file file to write stream's contents to * @throws IOException if the stream can't be read or the file can't be written */ public static void copyStreamToFile(InputStream in, File file) throws IOException { FileOutputStream out = new FileOutputStream(file); try { ByteStreams.copy(in, out); } finally { out.close(); } } /** * @param url URL whose contents are to be read and copied * @param file file to write contents to * @throws IOException if the URL can't be read or the file can't be written */ public static void copyURLToFile(URL url, File file) throws IOException { InputStream in = url.openStream(); try { copyStreamToFile(in, file); } finally { Closeables.closeQuietly(in); } } }
true
true
public static boolean deleteRecursively(File dir) { Deque<File> stack = new ArrayDeque<File>(); stack.push(dir); boolean result = true; while (!stack.isEmpty()) { File topElement = stack.peek(); if (topElement.isDirectory()) { File[] directoryContents = topElement.listFiles(); if (directoryContents != null && directoryContents.length > 0) { for (File fileOrSubDirectory : directoryContents) { stack.push(fileOrSubDirectory); } } else { result = result && stack.pop().delete(); } } else { result = result && stack.pop().delete(); } } return result; }
public static boolean deleteRecursively(File dir) { if (dir == null) { return false; } Deque<File> stack = new ArrayDeque<File>(); stack.push(dir); boolean result = true; while (!stack.isEmpty()) { File topElement = stack.peek(); if (topElement.isDirectory()) { File[] directoryContents = topElement.listFiles(); if (directoryContents != null && directoryContents.length > 0) { for (File fileOrSubDirectory : directoryContents) { stack.push(fileOrSubDirectory); } } else { result = result && stack.pop().delete(); } } else { result = result && stack.pop().delete(); } } return result; }
diff --git a/org.eclipse.virgo.web.enterprise.appdeployer/src/main/java/org/eclipse/virgo/web/enterprise/openejb/deployer/VirgoDeploymentLoader.java b/org.eclipse.virgo.web.enterprise.appdeployer/src/main/java/org/eclipse/virgo/web/enterprise/openejb/deployer/VirgoDeploymentLoader.java index c2e36bc..82741e8 100755 --- a/org.eclipse.virgo.web.enterprise.appdeployer/src/main/java/org/eclipse/virgo/web/enterprise/openejb/deployer/VirgoDeploymentLoader.java +++ b/org.eclipse.virgo.web.enterprise.appdeployer/src/main/java/org/eclipse/virgo/web/enterprise/openejb/deployer/VirgoDeploymentLoader.java @@ -1,85 +1,94 @@ /******************************************************************************* * Copyright (c) 2012 SAP AG * 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: * SAP AG - initial contribution *******************************************************************************/ package org.eclipse.virgo.web.enterprise.openejb.deployer; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.Map; import java.util.TreeMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.openejb.OpenEJBException; import org.apache.openejb.config.AppModule; import org.apache.openejb.config.DeploymentLoader; /** * * The purpose of this class is to enable proper recognition of packed web apps that use EJBs during deployment * <p /> * */ public class VirgoDeploymentLoader extends DeploymentLoader { private static final String VIRGO_ROOT_APPLICATION_RESERVED_MODULE_ID = "virgoRootApplicationReservedModuleID"; private final String webContextPath; public VirgoDeploymentLoader(String webContextPath) { super(); this.webContextPath = webContextPath; } @Override public AppModule load(File arg0) throws OpenEJBException { //Sets the web context path as the moduleId, leaving the original logic unchanged AppModule result = super.load(arg0); result.setModuleId(createModuleIDFromWebContextPath()); return result; } private String createModuleIDFromWebContextPath() { if (this.webContextPath.equals("")) { return VIRGO_ROOT_APPLICATION_RESERVED_MODULE_ID; } // remove the slash at the beginning of each webContextPath return this.webContextPath.substring(1); } @Override protected String getContextRoot() { return webContextPath; } @Override protected Map<String, URL> getWebDescriptors(File warFile) throws IOException { //Fixes a bug in OpenEjb that prevents recognising web modules when deploying packed web apps Map<String, URL> descriptors = new TreeMap<String, URL>(); if (warFile.isFile()) { URL jarURL = new URL("jar", "", -1, warFile.toURI().toURL() + "!/"); + JarFile jarFile = null; try { - JarFile jarFile = new JarFile(warFile); + jarFile = new JarFile(warFile); for (JarEntry entry : Collections.list(jarFile.entries())) { String entryName = entry.getName(); if (!entry.isDirectory() && entryName.startsWith("WEB-INF/") && entryName.indexOf('/', "WEB-INF".length()) > 0) { descriptors.put(entryName, new URL(jarURL, entry.getName())); } } } catch (IOException e) { // most likely an invalid jar file + } finally { + try { + if (jarFile != null) { + jarFile.close(); + } + } catch (IOException e) { + // do nothing + } } } descriptors.putAll(super.getWebDescriptors(warFile)); return descriptors; } }
false
true
protected Map<String, URL> getWebDescriptors(File warFile) throws IOException { //Fixes a bug in OpenEjb that prevents recognising web modules when deploying packed web apps Map<String, URL> descriptors = new TreeMap<String, URL>(); if (warFile.isFile()) { URL jarURL = new URL("jar", "", -1, warFile.toURI().toURL() + "!/"); try { JarFile jarFile = new JarFile(warFile); for (JarEntry entry : Collections.list(jarFile.entries())) { String entryName = entry.getName(); if (!entry.isDirectory() && entryName.startsWith("WEB-INF/") && entryName.indexOf('/', "WEB-INF".length()) > 0) { descriptors.put(entryName, new URL(jarURL, entry.getName())); } } } catch (IOException e) { // most likely an invalid jar file } } descriptors.putAll(super.getWebDescriptors(warFile)); return descriptors; }
protected Map<String, URL> getWebDescriptors(File warFile) throws IOException { //Fixes a bug in OpenEjb that prevents recognising web modules when deploying packed web apps Map<String, URL> descriptors = new TreeMap<String, URL>(); if (warFile.isFile()) { URL jarURL = new URL("jar", "", -1, warFile.toURI().toURL() + "!/"); JarFile jarFile = null; try { jarFile = new JarFile(warFile); for (JarEntry entry : Collections.list(jarFile.entries())) { String entryName = entry.getName(); if (!entry.isDirectory() && entryName.startsWith("WEB-INF/") && entryName.indexOf('/', "WEB-INF".length()) > 0) { descriptors.put(entryName, new URL(jarURL, entry.getName())); } } } catch (IOException e) { // most likely an invalid jar file } finally { try { if (jarFile != null) { jarFile.close(); } } catch (IOException e) { // do nothing } } } descriptors.putAll(super.getWebDescriptors(warFile)); return descriptors; }
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/architecture/impl/ArchitectureFactoryImpl.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/architecture/impl/ArchitectureFactoryImpl.java index 8a8b8764b..67890b66a 100644 --- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/architecture/impl/ArchitectureFactoryImpl.java +++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/tta/architecture/impl/ArchitectureFactoryImpl.java @@ -1,1227 +1,1227 @@ /* * Copyright (c) 2011, IRISA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of IRISA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package net.sf.orcc.backends.tta.architecture.impl; import java.util.Map; import net.sf.orcc.backends.tta.architecture.AddressSpace; import net.sf.orcc.backends.tta.architecture.ArchitectureFactory; import net.sf.orcc.backends.tta.architecture.ArchitecturePackage; import net.sf.orcc.backends.tta.architecture.Bridge; import net.sf.orcc.backends.tta.architecture.Bus; import net.sf.orcc.backends.tta.architecture.Design; import net.sf.orcc.backends.tta.architecture.Element; import net.sf.orcc.backends.tta.architecture.ExprBinary; import net.sf.orcc.backends.tta.architecture.ExprFalse; import net.sf.orcc.backends.tta.architecture.ExprTrue; import net.sf.orcc.backends.tta.architecture.ExprUnary; import net.sf.orcc.backends.tta.architecture.Extension; import net.sf.orcc.backends.tta.architecture.FunctionUnit; import net.sf.orcc.backends.tta.architecture.GlobalControlUnit; import net.sf.orcc.backends.tta.architecture.Guard; import net.sf.orcc.backends.tta.architecture.HwFifo; import net.sf.orcc.backends.tta.architecture.Implementation; import net.sf.orcc.backends.tta.architecture.OpBinary; import net.sf.orcc.backends.tta.architecture.OpUnary; import net.sf.orcc.backends.tta.architecture.Operation; import net.sf.orcc.backends.tta.architecture.Port; import net.sf.orcc.backends.tta.architecture.Processor; import net.sf.orcc.backends.tta.architecture.Reads; import net.sf.orcc.backends.tta.architecture.RegisterFile; import net.sf.orcc.backends.tta.architecture.Resource; import net.sf.orcc.backends.tta.architecture.Segment; import net.sf.orcc.backends.tta.architecture.ShortImmediate; import net.sf.orcc.backends.tta.architecture.Socket; import net.sf.orcc.backends.tta.architecture.SocketType; import net.sf.orcc.backends.tta.architecture.Term; import net.sf.orcc.backends.tta.architecture.TermBool; import net.sf.orcc.backends.tta.architecture.TermUnit; import net.sf.orcc.backends.tta.architecture.Writes; import net.sf.orcc.util.EcoreHelper; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EDataType; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.impl.EFactoryImpl; import org.eclipse.emf.ecore.plugin.EcorePlugin; /** * <!-- begin-user-doc --> An implementation of the model <b>Factory</b>. <!-- * end-user-doc --> * @generated */ public class ArchitectureFactoryImpl extends EFactoryImpl implements ArchitectureFactory { /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @deprecated * @generated */ @Deprecated public static ArchitecturePackage getPackage() { return ArchitecturePackage.eINSTANCE; } /** * Creates the default factory implementation. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @generated */ public static ArchitectureFactory init() { try { ArchitectureFactory theArchitectureFactory = (ArchitectureFactory) EPackage.Registry.INSTANCE .getEFactory("http://orcc.sf.net/backends/tta/architecture/TTA_architecture"); if (theArchitectureFactory != null) { return theArchitectureFactory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new ArchitectureFactoryImpl(); } /** * Creates an instance of the factory. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @generated */ public ArchitectureFactoryImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String convertExtensionToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String convertOpBinaryToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String convertOpUnaryToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String convertSocketTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public String convertToString(EDataType eDataType, Object instanceValue) { switch (eDataType.getClassifierID()) { case ArchitecturePackage.SOCKET_TYPE: return convertSocketTypeToString(eDataType, instanceValue); case ArchitecturePackage.EXTENSION: return convertExtensionToString(eDataType, instanceValue); case ArchitecturePackage.OP_UNARY: return convertOpUnaryToString(eDataType, instanceValue); case ArchitecturePackage.OP_BINARY: return convertOpBinaryToString(eDataType, instanceValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Design createDesign() { DesignImpl design = new DesignImpl(); return design; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public HwFifo createHwFifo() { HwFifoImpl hwFifo = new HwFifoImpl(); return hwFifo; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Processor createProcessor() { ProcessorImpl processor = new ProcessorImpl(); return processor; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public EObject create(EClass eClass) { switch (eClass.getClassifierID()) { case ArchitecturePackage.DESIGN: return createDesign(); case ArchitecturePackage.HW_FIFO: return createHwFifo(); case ArchitecturePackage.PROCESSOR: return createProcessor(); case ArchitecturePackage.BUS: return createBus(); case ArchitecturePackage.BRIDGE: return createBridge(); case ArchitecturePackage.SEGMENT: return createSegment(); case ArchitecturePackage.GLOBAL_CONTROL_UNIT: return createGlobalControlUnit(); case ArchitecturePackage.FUNCTION_UNIT: return createFunctionUnit(); case ArchitecturePackage.REGISTER_FILE: return createRegisterFile(); case ArchitecturePackage.PORT: return createPort(); case ArchitecturePackage.SOCKET: return createSocket(); case ArchitecturePackage.OPERATION: return createOperation(); case ArchitecturePackage.ADDRESS_SPACE: return createAddressSpace(); case ArchitecturePackage.READS: return createReads(); case ArchitecturePackage.WRITES: return createWrites(); case ArchitecturePackage.RESOURCE: return createResource(); case ArchitecturePackage.SHORT_IMMEDIATE: return createShortImmediate(); case ArchitecturePackage.EXPR_UNARY: return createExprUnary(); case ArchitecturePackage.EXPR_BINARY: return createExprBinary(); case ArchitecturePackage.EXPR_TRUE: return createExprTrue(); case ArchitecturePackage.EXPR_FALSE: return createExprFalse(); case ArchitecturePackage.TERM_BOOL: return createTermBool(); case ArchitecturePackage.TERM_UNIT: return createTermUnit(); case ArchitecturePackage.IMPLEMENTATION: return createImplementation(); case ArchitecturePackage.PORT_TO_INDEX_MAP_ENTRY: return (EObject) createPortToIndexMapEntry(); default: throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public AddressSpace createAddressSpace() { AddressSpaceImpl addressSpace = new AddressSpaceImpl(); return addressSpace; } @Override public AddressSpace createAddressSpace(String name, int width, int minAddress, int maxAddress) { AddressSpaceImpl addressSpace = new AddressSpaceImpl(); addressSpace.setName(name); addressSpace.setWidth(width); addressSpace.setMinAddress(minAddress); addressSpace.setMaxAddress(maxAddress); return addressSpace; } @Override public FunctionUnit createAluUnit(Processor tta, String name) { FunctionUnitImpl functionUnit = new FunctionUnitImpl(); functionUnit.setName(name); // Sockets EList<Segment> segments = getAllSegments(tta.getBuses()); Socket i1 = createInputSocket(name + "_i1", segments); Socket i2 = createInputSocket(name + "_i2", segments); Socket o1 = createOutputSocket(name + "_o1", segments); // Port Port in1t = createPort("in1t", 32, true, true); Port in2 = createPort("in2", 32, false, false); Port out1 = createPort("out1", 32, false, false); in1t.connect(i1); in2.connect(i2); out1.connect(o1); functionUnit.getPorts().add(in1t); functionUnit.getPorts().add(in2); functionUnit.getPorts().add(out1); // Implementation Implementation aluImpl = createImplementation("asic_130nm_1.5V.hdb", 375); functionUnit.setImplementation(aluImpl); tta.getHardwareDatabase().add(aluImpl); // Operations (Shift operations use inverse binding) String[] oneInputOps = { "sxqw", "sxhw" }; String[] twoInputOps = { "add", "and", "eq", "gt", "gtu", "ior", "sub", "xor" }; String[] shiftOps = { "shl", "shr", "shru" }; for (String operation : oneInputOps) { functionUnit.getOperations().add( createOperationDefault(operation, in1t, out1)); } for (String operation : twoInputOps) { functionUnit.getOperations().add( createOperationDefault(operation, in1t, in2, out1)); } for (String operation : shiftOps) { functionUnit.getOperations().add( createOperationDefault(operation, in2, in1t, out1)); } return functionUnit; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Bridge createBridge() { BridgeImpl bridge = new BridgeImpl(); return bridge; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Bus createBus() { BusImpl bus = new BusImpl(); return bus; } @Override public Bus createBus(int index, int width) { BusImpl bus = new BusImpl(); bus.setName("Bus" + index); bus.setWidth(width); return bus; } @Override public Bus createBusDefault(int index, int width) { Bus bus = createBus(index, width); bus.getSegments().add(createSegment("segment0")); bus.setShortImmediate(createShortImmediate(width, Extension.ZERO)); return bus; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public ExprBinary createExprBinary() { ExprBinaryImpl exprBinary = new ExprBinaryImpl(); return exprBinary; } @Override public ExprBinary createExprBinary(OpBinary op, ExprUnary e1, ExprUnary e2) { ExprBinaryImpl exprBinary = new ExprBinaryImpl(); exprBinary.setE1(e1); exprBinary.setE2(e2); exprBinary.setOperator(op); return exprBinary; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public ExprFalse createExprFalse() { ExprFalseImpl exprFalse = new ExprFalseImpl(); return exprFalse; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public ExprTrue createExprTrue() { ExprTrueImpl exprTrue = new ExprTrueImpl(); return exprTrue; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public ExprUnary createExprUnary() { ExprUnaryImpl exprUnary = new ExprUnaryImpl(); return exprUnary; } @Override public ExprUnary createExprUnary(boolean isInverted, Term term) { ExprUnaryImpl exprUnary = new ExprUnaryImpl(); if (isInverted) { exprUnary.setOperator(OpUnary.INVERTED); } else { exprUnary.setOperator(OpUnary.SIMPLE); } exprUnary.setTerm(term); return exprUnary; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Extension createExtensionFromString(EDataType eDataType, String initialValue) { Extension result = Extension.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public Object createFromString(EDataType eDataType, String initialValue) { switch (eDataType.getClassifierID()) { case ArchitecturePackage.SOCKET_TYPE: return createSocketTypeFromString(eDataType, initialValue); case ArchitecturePackage.EXTENSION: return createExtensionFromString(eDataType, initialValue); case ArchitecturePackage.OP_UNARY: return createOpUnaryFromString(eDataType, initialValue); case ArchitecturePackage.OP_BINARY: return createOpBinaryFromString(eDataType, initialValue); default: throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public FunctionUnit createFunctionUnit() { FunctionUnitImpl functionUnit = new FunctionUnitImpl(); return functionUnit; } @Override public FunctionUnit createFunctionUnit(Processor tta, String name, Implementation implementation) { FunctionUnitImpl functionUnit = new FunctionUnitImpl(); functionUnit.setName(name); // Sockets EList<Segment> segments = getAllSegments(tta.getBuses()); Socket i1 = createInputSocket(name + "_i1", segments); Socket i2 = createInputSocket(name + "_i2", segments); Socket o1 = createOutputSocket(name + "_o1", segments); // Port Port in1t = createPort("in1t", 32, true, true); Port in2 = createPort("in2", 32, false, false); Port out1 = createPort("out1", 32, false, false); in1t.connect(i1); in2.connect(i2); out1.connect(o1); functionUnit.getPorts().add(in1t); functionUnit.getPorts().add(in2); functionUnit.getPorts().add(out1); // Implementation functionUnit.setImplementation(implementation); return functionUnit; } @Override public FunctionUnit createFunctionUnit(Processor tta, String name, String[] operations1, String[] operations2, Implementation implementation) { FunctionUnit functionUnit = createFunctionUnit(tta, name, implementation); EList<Port> ports = functionUnit.getPorts(); // Operations if (operations1 != null) { for (String operation : operations1) { functionUnit.getOperations().add( createOperationDefault(operation, ports.get(0), ports.get(2))); } } if (operations2 != null) { for (String operation : operations2) { functionUnit.getOperations().add( createOperationDefault(operation, ports.get(0), ports.get(1), ports.get(2))); } } return functionUnit; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public GlobalControlUnit createGlobalControlUnit() { GlobalControlUnitImpl globalControlUnit = new GlobalControlUnitImpl(); return globalControlUnit; } @Override public GlobalControlUnit createGlobalControlUnit(int delaySlots, int guardLatency) { GlobalControlUnitImpl globalControlUnit = new GlobalControlUnitImpl(); globalControlUnit.setDelaySlots(delaySlots); globalControlUnit.setGuardLatency(guardLatency); return globalControlUnit; } @Override public GlobalControlUnit createGlobalControlUnitDefault(Processor tta) { GlobalControlUnit gcu = createGlobalControlUnit(3, 1); gcu.setAddressSpace(tta.getProgram()); // Sockets EList<Segment> segments = getAllSegments(tta.getBuses()); Socket gcu_i1 = createInputSocket("gcu_i1", segments); Socket gcu_i2 = createInputSocket("gcu_i2", segments); Socket gcu_o1 = createOutputSocket("gcu_o1", segments); // Ports Port pc = createPort("pc", 32, true, true); pc.connect(gcu_i1); Port ra = createPort("ra", 32, false, false); ra.connect(gcu_i2); ra.connect(gcu_o1); gcu.setReturnAddress(ra); gcu.getPorts().add(pc); // Control operations gcu.getOperations().add(createOperationCtrl("jump", pc)); gcu.getOperations().add(createOperationCtrl("call", pc)); return gcu; } @Override public EList<Guard> createGuardsDefault(RegisterFile register) { EList<Guard> guards = new BasicEList<Guard>(); guards.add(createExprTrue()); guards.add(createExprUnary(false, createTermBool(register, 0))); guards.add(createExprUnary(true, createTermBool(register, 0))); guards.add(createExprUnary(false, createTermBool(register, 1))); guards.add(createExprUnary(true, createTermBool(register, 1))); return guards; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Implementation createImplementation() { ImplementationImpl implementation = new ImplementationImpl(); return implementation; } public Implementation createImplementation(String hdbFile, int id) { ImplementationImpl implementation = new ImplementationImpl(); implementation.setHdbFile(hdbFile); implementation.setId(id); return implementation; } @Override public Socket createInputSocket(String name, EList<Segment> segments) { Socket socket = createSocket(name, segments); socket.setType(SocketType.INPUT); return socket; } @Override public FunctionUnit createLSU(Processor tta, Implementation implementation) { FunctionUnit LSU = createFunctionUnit(tta, "LSU", implementation); // Operations EList<Port> ports = LSU.getPorts(); String[] loadOperations = { "ldw", "ldq", "ldh", "ldqu", "ldhu" }; for (String loadOperation : loadOperations) { LSU.getOperations().add( createOperationLoad(loadOperation, ports.get(0), ports.get(2))); } String[] storeOperations = { "stw", "stq", "sth" }; for (String storeOperation : storeOperations) { LSU.getOperations().add( createOperationStore(storeOperation, ports.get(0), ports.get(1))); } LSU.setAddressSpace(tta.getData()); return LSU; } @Override public FunctionUnit createMultiplier(Processor tta, Implementation implementation) { FunctionUnit multiplier = createFunctionUnit(tta, "Mul", implementation); multiplier.getOperations().add( createOperationMul("mul", multiplier.getPorts().get(0), multiplier.getPorts().get(1), multiplier.getPorts() .get(2))); multiplier.setAddressSpace(tta.getData()); return multiplier; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public OpBinary createOpBinaryFromString(EDataType eDataType, String initialValue) { OpBinary result = OpBinary.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Operation createOperation() { OperationImpl operation = new OperationImpl(); return operation; } @Override public Operation createOperation(String name) { OperationImpl operation = new OperationImpl(); operation.setName(name); return operation; } @Override public Operation createOperationCtrl(String name, Port port) { Operation operation = new OperationImpl(); operation.setName(name); operation.setControl(true); operation.getPipeline().add(createReads(port, 0, 1)); operation.getPortToIndexMap().put(port, 1); return operation; } private Operation createOperationDefault(String name, Port port1, int startCycle1, int cycle1, boolean isReads1, Port port2, int startCycle2, int cycle2, boolean isReads2) { Operation operation = createOperation(name); operation.setControl(false); Element element1, element2; if (isReads1) { element1 = createReads(port1, startCycle1, cycle1); } else { element1 = createWrites(port1, startCycle1, cycle1); } if (isReads2) { element2 = createReads(port2, startCycle2, cycle2); } else { element2 = createWrites(port2, startCycle2, cycle2); } operation.getPipeline().add(element1); operation.getPipeline().add(element2); return operation; } private Operation createOperationDefault(String name, Port in1, Port out1) { Operation operation = createOperation(name); operation.setControl(false); operation.getPipeline().add(createReads(in1, 0, 1)); operation.getPipeline().add(createWrites(out1, 0, 1)); return operation; } private Operation createOperationDefault(String name, Port in1, Port in2, Port out1) { Operation operation = createOperation(name); operation.setControl(false); operation.getPipeline().add(createReads(in1, 0, 1)); operation.getPipeline().add(createReads(in2, 0, 1)); operation.getPipeline().add(createWrites(out1, 0, 1)); return operation; } @SuppressWarnings("unused") private Operation createOperationIn(Port in, Port out) { Operation operation = createOperation("cal_stream_in_read"); operation.setControl(false); operation.getPipeline().add(createResource("res0", 0, 3)); operation.getPipeline().add(createReads(in, 0, 1)); operation.getPipeline().add(createWrites(out, 1, 1)); return operation; } private Operation createOperationInV2(Port in1, Port out) { Operation operation = createOperation("cal_stream_in_read"); operation.setControl(false); operation.getPipeline().add(createResource("res0", 0, 2)); operation.getPipeline().add(createReads(in1, 0, 1)); operation.getPipeline().add(createWrites(out, 0, 1)); return operation; } @SuppressWarnings("unused") private Operation createOperationInPeek(Port in, Port out) { Operation operation = createOperation("cal_stream_in_peek"); operation.setControl(false); operation.getPipeline().add(createResource("res0", 0, 3)); operation.getPipeline().add(createReads(in, 0, 1)); operation.getPipeline().add(createWrites(out, 1, 1)); return operation; } private Operation createOperationInPeekV2(Port in1, Port out) { Operation operation = createOperation("cal_stream_in_peek"); operation.setControl(false); operation.getPipeline().add(createResource("res0", 0, 2)); operation.getPipeline().add(createReads(in1, 0, 1)); operation.getPipeline().add(createWrites(out, 0, 1)); return operation; } @SuppressWarnings("unused") private Operation createOperationInStatus(Port in, Port out) { Operation operation = createOperation("cal_stream_in_status"); operation.setControl(false); operation.getPipeline().add(createReads(in, 0, 1)); operation.getPipeline().add(createWrites(out, 1, 1)); return operation; } private Operation createOperationInStatusV2(Port in1, Port out) { Operation operation = createOperation("cal_stream_in_status"); operation.setControl(false); operation.getPipeline().add(createResource("res0", 0, 2)); operation.getPipeline().add(createReads(in1, 0, 1)); operation.getPipeline().add(createWrites(out, 0, 1)); return operation; } private Operation createOperationLoad(String name, Port in, Port out) { return createOperationDefault(name, in, 0, 1, true, out, 2, 1, false); } private Operation createOperationMul(String name, Port in1, Port in2, Port out) { Operation operation = createOperation(name); operation.setControl(false); operation.getPipeline().add(createReads(in1, 0, 1)); operation.getPipeline().add(createReads(in2, 0, 1)); operation.getPipeline().add(createWrites(out, 1, 1)); return operation; } @SuppressWarnings("unused") private Operation createOperationOut(Port in, Port out) { Operation operation = createOperation("cal_stream_out_write"); operation.setControl(false); operation.getPipeline().add(createResource("res0", 0, 3)); operation.getPipeline().add(createReads(in, 0, 1)); return operation; } private Operation createOperationOutV2(Port in1, Port in2) { Operation operation = createOperation("cal_stream_out_write"); operation.setControl(false); operation.getPipeline().add(createResource("res0", 0, 2)); operation.getPipeline().add(createReads(in1, 0, 1)); operation.getPipeline().add(createReads(in2, 0, 1)); return operation; } @SuppressWarnings("unused") private Operation createOperationOutStatus(Port in, Port out) { Operation operation = createOperation("cal_stream_out_status"); operation.setControl(false); operation.getPipeline().add(createReads(in, 0, 1)); operation.getPipeline().add(createWrites(out, 1, 1)); return operation; } private Operation createOperationOutStatusV2(Port in1, Port out) { Operation operation = createOperation("cal_stream_out_status"); operation.setControl(false); operation.getPipeline().add(createResource("res0", 0, 2)); operation.getPipeline().add(createReads(in1, 0, 1)); operation.getPipeline().add(createWrites(out, 0, 1)); return operation; } private Operation createOperationStore(String name, Port in1, Port in2) { return createOperationDefault(name, in1, 0, 1, true, in2, 0, 1, true); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public OpUnary createOpUnaryFromString(EDataType eDataType, String initialValue) { OpUnary result = OpUnary.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } @Override public Socket createOutputSocket(String name, EList<Segment> segments) { Socket socket = createSocket(name, segments); socket.setType(SocketType.OUTPUT); return socket; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Port createPort() { PortImpl port = new PortImpl(); return port; } @Override public Port createPort(String name) { PortImpl port = new PortImpl(); port.setName(name); return port; } @Override public Port createPort(String name, int width, boolean isOpcodeSelector, boolean isTrigger) { Port port = createPort(name); port.setWidth(width); port.setOpcodeSelector(isOpcodeSelector); port.setTrigger(isTrigger); return port; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Map.Entry<Port, Integer> createPortToIndexMapEntry() { PortToIndexMapEntryImpl portToIndexMapEntry = new PortToIndexMapEntryImpl(); return portToIndexMapEntry; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Reads createReads() { ReadsImpl reads = new ReadsImpl(); return reads; } @Override public Reads createReads(Port port, int startCycle, int cycle) { ReadsImpl reads = new ReadsImpl(); reads.setPort(port); reads.setStartCycle(startCycle); reads.setCycles(cycle); return reads; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public RegisterFile createRegisterFile() { RegisterFileImpl registerFile = new RegisterFileImpl(); return registerFile; } @Override public RegisterFile createRegisterFile(String name, int size, int width, int maxReads, int maxWrites, Implementation implementation) { RegisterFileImpl registerFile = new RegisterFileImpl(); registerFile.setName(name); registerFile.setSize(size); registerFile.setWidth(width); registerFile.setMaxReads(maxReads); registerFile.setMaxWrites(maxWrites); registerFile.setImplementation(implementation); return registerFile; } @Override public RegisterFile createRegisterFileDefault(Processor tta, String name, int size, int width, Implementation implementation) { RegisterFile registerFile = createRegisterFile(name, size, width, 1, 1, implementation); // Sockets EList<Segment> segments = getAllSegments(tta.getBuses()); Socket i1 = createInputSocket(name + "_i1", segments); Socket o1 = createOutputSocket(name + "_o1", segments); // Ports Port wr = createPort("wr"); wr.connect(o1); Port rd = createPort("rd"); rd.connect(i1); registerFile.getPorts().add(wr); registerFile.getPorts().add(rd); return registerFile; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Resource createResource() { ResourceImpl resource = new ResourceImpl(); return resource; } @Override public Resource createResource(String name, int startCycle, int cycles) { ResourceImpl resource = new ResourceImpl(); resource.setName(name); resource.setStartCycle(startCycle); resource.setCycles(cycles); return resource; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Segment createSegment() { SegmentImpl segment = new SegmentImpl(); return segment; } @Override public Segment createSegment(String name) { SegmentImpl segment = new SegmentImpl(); segment.setName(name); return segment; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public ShortImmediate createShortImmediate() { ShortImmediateImpl shortImmediate = new ShortImmediateImpl(); return shortImmediate; } @Override public ShortImmediate createShortImmediate(int width, Extension extension) { ShortImmediateImpl shortImmediate = new ShortImmediateImpl(); shortImmediate.setWidth(width); shortImmediate.setExtension(extension); return shortImmediate; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Socket createSocket() { SocketImpl socket = new SocketImpl(); return socket; } @Override public Socket createSocket(String name, EList<Segment> segments) { SocketImpl socket = new SocketImpl(); socket.setName(name); socket.getConnectedSegments().addAll(segments); EcoreHelper.getContainerOfType(segments.get(0), Processor.class) .getSockets().add(socket); return socket; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public SocketType createSocketTypeFromString(EDataType eDataType, String initialValue) { SocketType result = SocketType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; } @Override public FunctionUnit createStreamInput(Processor tta, int index) { FunctionUnitImpl functionUnit = new FunctionUnitImpl(); String name = "STREAM_IN_" + index; functionUnit.setName(name); // Sockets EList<Segment> segments = getAllSegments(tta.getBuses()); Socket i1 = createInputSocket(name + "_i1", segments); Socket o1 = createOutputSocket(name + "_o1", segments); // Port Port in1t = createPort("in1t", 32, true, true); Port out1 = createPort("out1", 32, false, false); in1t.connect(i1); out1.connect(o1); functionUnit.getPorts().add(in1t); functionUnit.getPorts().add(out1); // Operations functionUnit.getOperations().add(createOperationInV2(in1t, out1)); functionUnit.getOperations().add(createOperationInPeekV2(in1t, out1)); functionUnit.getOperations().add(createOperationInStatusV2(in1t, out1)); // Implementation Implementation streamImpl = createImplementation("stream_units.hdb", 1); functionUnit.setImplementation(streamImpl); tta.getHardwareDatabase().add(streamImpl); return functionUnit; } @Override public FunctionUnit createStreamOutput(Processor tta, int index) { FunctionUnitImpl functionUnit = new FunctionUnitImpl(); String name = "STREAM_OUT_" + index; functionUnit.setName(name); // Sockets EList<Segment> segments = getAllSegments(tta.getBuses()); Socket i1 = createInputSocket(name + "_i1", segments); Socket i2 = createInputSocket(name + "_i2", segments); Socket o1 = createOutputSocket(name + "_o1", segments); // Port Port in1t = createPort("in1t", 32, true, true); Port in2 = createPort("in2", 32, false, false); Port out1 = createPort("out1", 32, false, false); in1t.connect(i1); in2.connect(i2); out1.connect(o1); functionUnit.getPorts().add(in1t); functionUnit.getPorts().add(in2); functionUnit.getPorts().add(out1); // Operations functionUnit.getOperations().add(createOperationOutV2(in1t, in2)); functionUnit.getOperations() .add(createOperationOutStatusV2(in1t, out1)); // Implementation Implementation streamImpl = createImplementation("stream_units.hdb", 2); functionUnit.setImplementation(streamImpl); tta.getHardwareDatabase().add(streamImpl); return functionUnit; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public TermBool createTermBool() { TermBoolImpl termBool = new TermBoolImpl(); return termBool; } @Override public TermBool createTermBool(RegisterFile register, int index) { TermBoolImpl termBool = new TermBoolImpl(); termBool.setRegister(register); termBool.setIndex(index); return termBool; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public TermUnit createTermUnit() { TermUnitImpl termUnit = new TermUnitImpl(); return termUnit; } @Override public TermUnit createTermUnit(FunctionUnit unit, Port port) { TermUnitImpl termUnit = new TermUnitImpl(); termUnit.setFunctionUnit(unit); termUnit.setPort(port); return termUnit; } @Override public Processor createProcessor(String name, int busNb, int registerNb, int aluNb, int inputNb, int outputNb, int ramSize) { Processor tta = createProcessor(); tta.setName(name); // Address spaces tta.setData(createAddressSpace("data", 8, 0, - quantizeUp(ramSize / 8 + 256))); + quantizeUp(ramSize / 8 + 512))); tta.setProgram(createAddressSpace("instructions", 8, 0, 60000)); // Buses for (int i = 0; i < busNb; i++) { Bus bus = createBusDefault(i, 32); tta.getBuses().add(bus); } // Global Control Unit tta.setGcu(createGlobalControlUnitDefault(tta)); // Register files Implementation registerImpl = createImplementation( "asic_130nm_1.5V.hdb", 96); RegisterFile bool = createRegisterFileDefault(tta, "BOOL", 2, 1, registerImpl); tta.getRegisterFiles().add(bool); for (int i = 0; i < registerNb; i++) { RegisterFile rf = createRegisterFileDefault(tta, "RF_" + i, 12, 32, registerImpl); tta.getRegisterFiles().add(rf); } tta.getHardwareDatabase().add(registerImpl); // Guards for (Bus bus : tta.getBuses()) { bus.getGuards().addAll(createGuardsDefault(bool)); } // Functional units EList<FunctionUnit> units = tta.getFunctionUnits(); // * ALU for (int i = 0; i < aluNb; i++) { FunctionUnit alu = createAluUnit(tta, "ALU_" + i); units.add(alu); } // * LSU Implementation lsuImpl = createImplementation("stratixII.hdb", 2); units.add(createLSU(tta, lsuImpl)); tta.getHardwareDatabase().add(lsuImpl); // * Mul Implementation mulImpl = createImplementation("asic_130nm_1.5V.hdb", 88); units.add(createMultiplier(tta, mulImpl)); tta.getHardwareDatabase().add(mulImpl); // * And-ior-xor Implementation logicImpl = createImplementation("asic_130nm_1.5V.hdb", 22); String[] aixOperations2 = { "and", "ior", "xor" }; units.add(createFunctionUnit(tta, "And_ior_xor", null, aixOperations2, logicImpl)); tta.getHardwareDatabase().add(logicImpl); // * Stream-units for (int i = 0; i < inputNb; i++) { tta.getFunctionUnits().add(createStreamInput(tta, i)); } for (int i = 0; i < outputNb; i++) { tta.getFunctionUnits().add(createStreamOutput(tta, i)); } return tta; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public Writes createWrites() { WritesImpl writes = new WritesImpl(); return writes; } @Override public Writes createWrites(Port port, int startCycle, int cycle) { WritesImpl writes = new WritesImpl(); writes.setPort(port); writes.setStartCycle(startCycle); writes.setCycles(cycle); return writes; } private EList<Segment> getAllSegments(EList<Bus> buses) { EList<Segment> segments = new BasicEList<Segment>(); for (Bus bus : buses) { segments.addAll(bus.getSegments()); } return segments; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public ArchitecturePackage getArchitecturePackage() { return (ArchitecturePackage) getEPackage(); } /** * Round up to next power of 2 for example 30000 -> 32768 * * @param value * the value to round up * @return the next power of 2 after the value */ private int quantizeUp(int value) { double tmp = Math.log(value) / Math.log(2.0); return (int) (Math.pow(2, (Math.floor(tmp) + 1.0)) - 1.0); } } // ArchitectureFactoryImpl
true
true
public Processor createProcessor(String name, int busNb, int registerNb, int aluNb, int inputNb, int outputNb, int ramSize) { Processor tta = createProcessor(); tta.setName(name); // Address spaces tta.setData(createAddressSpace("data", 8, 0, quantizeUp(ramSize / 8 + 256))); tta.setProgram(createAddressSpace("instructions", 8, 0, 60000)); // Buses for (int i = 0; i < busNb; i++) { Bus bus = createBusDefault(i, 32); tta.getBuses().add(bus); } // Global Control Unit tta.setGcu(createGlobalControlUnitDefault(tta)); // Register files Implementation registerImpl = createImplementation( "asic_130nm_1.5V.hdb", 96); RegisterFile bool = createRegisterFileDefault(tta, "BOOL", 2, 1, registerImpl); tta.getRegisterFiles().add(bool); for (int i = 0; i < registerNb; i++) { RegisterFile rf = createRegisterFileDefault(tta, "RF_" + i, 12, 32, registerImpl); tta.getRegisterFiles().add(rf); } tta.getHardwareDatabase().add(registerImpl); // Guards for (Bus bus : tta.getBuses()) { bus.getGuards().addAll(createGuardsDefault(bool)); } // Functional units EList<FunctionUnit> units = tta.getFunctionUnits(); // * ALU for (int i = 0; i < aluNb; i++) { FunctionUnit alu = createAluUnit(tta, "ALU_" + i); units.add(alu); } // * LSU Implementation lsuImpl = createImplementation("stratixII.hdb", 2); units.add(createLSU(tta, lsuImpl)); tta.getHardwareDatabase().add(lsuImpl); // * Mul Implementation mulImpl = createImplementation("asic_130nm_1.5V.hdb", 88); units.add(createMultiplier(tta, mulImpl)); tta.getHardwareDatabase().add(mulImpl); // * And-ior-xor Implementation logicImpl = createImplementation("asic_130nm_1.5V.hdb", 22); String[] aixOperations2 = { "and", "ior", "xor" }; units.add(createFunctionUnit(tta, "And_ior_xor", null, aixOperations2, logicImpl)); tta.getHardwareDatabase().add(logicImpl); // * Stream-units for (int i = 0; i < inputNb; i++) { tta.getFunctionUnits().add(createStreamInput(tta, i)); } for (int i = 0; i < outputNb; i++) { tta.getFunctionUnits().add(createStreamOutput(tta, i)); } return tta; }
public Processor createProcessor(String name, int busNb, int registerNb, int aluNb, int inputNb, int outputNb, int ramSize) { Processor tta = createProcessor(); tta.setName(name); // Address spaces tta.setData(createAddressSpace("data", 8, 0, quantizeUp(ramSize / 8 + 512))); tta.setProgram(createAddressSpace("instructions", 8, 0, 60000)); // Buses for (int i = 0; i < busNb; i++) { Bus bus = createBusDefault(i, 32); tta.getBuses().add(bus); } // Global Control Unit tta.setGcu(createGlobalControlUnitDefault(tta)); // Register files Implementation registerImpl = createImplementation( "asic_130nm_1.5V.hdb", 96); RegisterFile bool = createRegisterFileDefault(tta, "BOOL", 2, 1, registerImpl); tta.getRegisterFiles().add(bool); for (int i = 0; i < registerNb; i++) { RegisterFile rf = createRegisterFileDefault(tta, "RF_" + i, 12, 32, registerImpl); tta.getRegisterFiles().add(rf); } tta.getHardwareDatabase().add(registerImpl); // Guards for (Bus bus : tta.getBuses()) { bus.getGuards().addAll(createGuardsDefault(bool)); } // Functional units EList<FunctionUnit> units = tta.getFunctionUnits(); // * ALU for (int i = 0; i < aluNb; i++) { FunctionUnit alu = createAluUnit(tta, "ALU_" + i); units.add(alu); } // * LSU Implementation lsuImpl = createImplementation("stratixII.hdb", 2); units.add(createLSU(tta, lsuImpl)); tta.getHardwareDatabase().add(lsuImpl); // * Mul Implementation mulImpl = createImplementation("asic_130nm_1.5V.hdb", 88); units.add(createMultiplier(tta, mulImpl)); tta.getHardwareDatabase().add(mulImpl); // * And-ior-xor Implementation logicImpl = createImplementation("asic_130nm_1.5V.hdb", 22); String[] aixOperations2 = { "and", "ior", "xor" }; units.add(createFunctionUnit(tta, "And_ior_xor", null, aixOperations2, logicImpl)); tta.getHardwareDatabase().add(logicImpl); // * Stream-units for (int i = 0; i < inputNb; i++) { tta.getFunctionUnits().add(createStreamInput(tta, i)); } for (int i = 0; i < outputNb; i++) { tta.getFunctionUnits().add(createStreamOutput(tta, i)); } return tta; }
diff --git a/project/project-et-web/src/main/java/cz/muni/fi/pv243/et/controller/ReceiptController.java b/project/project-et-web/src/main/java/cz/muni/fi/pv243/et/controller/ReceiptController.java index d14eece..f60fd5a 100644 --- a/project/project-et-web/src/main/java/cz/muni/fi/pv243/et/controller/ReceiptController.java +++ b/project/project-et-web/src/main/java/cz/muni/fi/pv243/et/controller/ReceiptController.java @@ -1,126 +1,128 @@ package cz.muni.fi.pv243.et.controller; import cz.muni.fi.pv243.et.data.PersonListProducer; import cz.muni.fi.pv243.et.data.ReceiptListProducer; import cz.muni.fi.pv243.et.data.ReceiptRepository; import cz.muni.fi.pv243.et.model.Person; import cz.muni.fi.pv243.et.model.PersonWrapper; import cz.muni.fi.pv243.et.model.Receipt; import cz.muni.fi.pv243.et.service.ReceiptService; import cz.muni.fi.pv243.et.util.CurrentPerson; import org.apache.commons.io.FilenameUtils; import org.apache.myfaces.custom.fileupload.UploadedFile; import org.picketlink.Identity; import javax.enterprise.inject.Model; import javax.enterprise.inject.Produces; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import javax.validation.constraints.NotNull; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.Date; @Model public class ReceiptController { @Inject private ReceiptService receiptService; @Inject private ReceiptModel receiptModel; @NotNull private UploadedFile uploadedFile; @Inject private Identity identity; @Inject private FacesContext facesContext; @Inject @CurrentPerson private PersonWrapper currentPerson; @Produces @Named("allReceipts") public Collection<Receipt> getAllReceipts() { return receiptService.findAll(); } @Produces @Named("currentUserReceipts") public Collection<Receipt> getCurrentUserReceipts() { Person currentPerson = identity.getUser().<Person>getAttribute("person").getValue(); return receiptService.findForPerson(currentPerson); } public String saveReceipt() throws IOException { Receipt r = receiptModel.getReceipt(); String fileName = FilenameUtils.getName(uploadedFile.getName()); byte[] bytes = uploadedFile.getBytes(); r.setDocumentName(fileName); r.setDocument(bytes); if (r.getId() == null) { r.setImportDate(new Date()); r.setImportedBy(currentPerson.getPerson()); } receiptService.save(r); +// String url = FacesContext.getCurrentInstance().getViewRoot().getViewId(); +// return "/secured/receipts?faces-redirect=true&backurl=" + url; return "/secured/receipts?faces-redirect=true"; } public String editReceipt(Long id) { Receipt r = receiptService.get(id); receiptModel.setReceipt(r); return "/secured/editReceipt"; } public String createReceipt() { receiptModel.setReceipt(new Receipt()); return "/secured/createReceipt"; } public String removeReceipt(Long id) { receiptModel.setReceipt(null); receiptService.remove(receiptService.get(id)); return "/secured/receipts?faces-redirect=true"; } public void showFile(Long receiptId) throws IOException { Receipt r = receiptService.get(receiptId); FacesContext fc = FacesContext.getCurrentInstance(); ExternalContext ec = fc.getExternalContext(); ec.responseReset(); ec.setResponseContentType(ec.getMimeType(r.getDocumentName())); ec.setResponseContentLength(r.getDocument().length); ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + r.getDocumentName() + "\""); OutputStream stream = ec.getResponseOutputStream(); stream.write(r.getDocument()); fc.responseComplete(); } public UploadedFile getUploadedFile() { return uploadedFile; } public void setUploadedFile(UploadedFile uploadedFile) { this.uploadedFile = uploadedFile; } }
true
true
public String saveReceipt() throws IOException { Receipt r = receiptModel.getReceipt(); String fileName = FilenameUtils.getName(uploadedFile.getName()); byte[] bytes = uploadedFile.getBytes(); r.setDocumentName(fileName); r.setDocument(bytes); if (r.getId() == null) { r.setImportDate(new Date()); r.setImportedBy(currentPerson.getPerson()); } receiptService.save(r); return "/secured/receipts?faces-redirect=true"; }
public String saveReceipt() throws IOException { Receipt r = receiptModel.getReceipt(); String fileName = FilenameUtils.getName(uploadedFile.getName()); byte[] bytes = uploadedFile.getBytes(); r.setDocumentName(fileName); r.setDocument(bytes); if (r.getId() == null) { r.setImportDate(new Date()); r.setImportedBy(currentPerson.getPerson()); } receiptService.save(r); // String url = FacesContext.getCurrentInstance().getViewRoot().getViewId(); // return "/secured/receipts?faces-redirect=true&backurl=" + url; return "/secured/receipts?faces-redirect=true"; }
diff --git a/src/org/apache/xerces/impl/xs/XSLoaderImpl.java b/src/org/apache/xerces/impl/xs/XSLoaderImpl.java index 9bf0ac40..01611869 100644 --- a/src/org/apache/xerces/impl/xs/XSLoaderImpl.java +++ b/src/org/apache/xerces/impl/xs/XSLoaderImpl.java @@ -1,325 +1,325 @@ /* * Copyright 2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.impl.xs; import org.apache.xerces.dom3.DOMConfiguration; import org.apache.xerces.dom3.DOMStringList; import org.apache.xerces.impl.xs.XMLSchemaLoader; import org.apache.xerces.impl.xs.util.XSGrammarPool; import org.apache.xerces.xni.grammars.Grammar; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.grammars.XSGrammar; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xs.LSInputList; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSLoader; import org.apache.xerces.xs.XSModel; import org.apache.xerces.xs.XSNamedMap; import org.apache.xerces.xs.XSObjectList; import org.apache.xerces.xs.XSTypeDefinition; import org.w3c.dom.DOMException; import org.w3c.dom.ls.LSInput; /** * <p>An implementation of XSLoader which wraps XMLSchemaLoader.</p> * * @xerces.internal * * @author Michael Glavassevich, IBM * * @version $Id$ */ public final class XSLoaderImpl implements XSLoader, DOMConfiguration { /** * Grammar pool. Need this to prevent us from * getting two grammars from the same namespace. */ private final XSGrammarPool fGrammarPool = new XSGrammarMerger(); /** Schema loader. **/ private final XMLSchemaLoader fSchemaLoader = new XMLSchemaLoader(); /** * No-args constructor. */ public XSLoaderImpl() { fSchemaLoader.setProperty(XMLSchemaLoader.XMLGRAMMAR_POOL, fGrammarPool); } /** * The configuration of a document. It maintains a table of recognized * parameters. Using the configuration, it is possible to change the * behavior of the load methods. The configuration may support the * setting of and the retrieval of the following non-boolean parameters * defined on the <code>DOMConfiguration</code> interface: * <code>error-handler</code> (<code>DOMErrorHandler</code>) and * <code>resource-resolver</code> (<code>LSResourceResolver</code>). * <br> The following list of boolean parameters is defined: * <dl> * <dt> * <code>"validate"</code></dt> * <dd> * <dl> * <dt><code>true</code></dt> * <dd>[required] (default) Validate an XML * Schema during loading. If validation errors are found, the error * handler is notified. </dd> * <dt><code>false</code></dt> * <dd>[optional] Do not * report errors during the loading of an XML Schema document. </dd> * </dl></dd> * </dl> */ public DOMConfiguration getConfig() { return this; } /** * Parses the content of XML Schema documents specified as the list of URI * references. If the URI contains a fragment identifier, the behavior * is not defined by this specification. * @param uri The list of URI locations. * @return An XSModel representing the schema documents. */ public XSModel loadURIList(StringList uriList) { int length = uriList.getLength(); if (length == 0) { return null; } try { fGrammarPool.clear(); for (int i = 0; i < length; ++i) { fSchemaLoader.loadGrammar(new XMLInputSource(null, uriList.item(i), null)); } return fGrammarPool.toXSModel(); } catch (Exception e) { fSchemaLoader.reportDOMFatalError(e); return null; } } /** * Parses the content of XML Schema documents specified as a list of * <code>LSInput</code>s. * @param is The list of <code>LSInput</code>s from which the XML * Schema documents are to be read. * @return An XSModel representing the schema documents. */ public XSModel loadInputList(LSInputList is) { final int length = is.getLength(); if (length == 0) { return null; } try { fGrammarPool.clear(); for (int i = 0; i < length; ++i) { fSchemaLoader.loadGrammar(fSchemaLoader.dom2xmlInputSource(is.item(i))); } return fGrammarPool.toXSModel(); } catch (Exception e) { fSchemaLoader.reportDOMFatalError(e); return null; } } /** * Parse an XML Schema document from a location identified by a URI * reference. If the URI contains a fragment identifier, the behavior is * not defined by this specification. * @param uri The location of the XML Schema document to be read. * @return An XSModel representing this schema. */ public XSModel loadURI(String uri) { try { fGrammarPool.clear(); return ((XSGrammar) fSchemaLoader.loadGrammar(new XMLInputSource(null, uri, null))).toXSModel(); } catch (Exception e){ fSchemaLoader.reportDOMFatalError(e); return null; } } /** * Parse an XML Schema document from a resource identified by a * <code>LSInput</code> . * @param is The <code>DOMInputSource</code> from which the source * document is to be read. * @return An XSModel representing this schema. */ public XSModel load(LSInput is) { try { fGrammarPool.clear(); return ((XSGrammar) fSchemaLoader.loadGrammar(fSchemaLoader.dom2xmlInputSource(is))).toXSModel(); } catch (Exception e) { fSchemaLoader.reportDOMFatalError(e); return null; } } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#setParameter(java.lang.String, java.lang.Object) */ public void setParameter(String name, Object value) throws DOMException { fSchemaLoader.setParameter(name, value); } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#getParameter(java.lang.String) */ public Object getParameter(String name) throws DOMException { return fSchemaLoader.getParameter(name); } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#canSetParameter(java.lang.String, java.lang.Object) */ public boolean canSetParameter(String name, Object value) { return fSchemaLoader.canSetParameter(name, value); } /* (non-Javadoc) * @see org.apache.xerces.dom3.DOMConfiguration#getParameterNames() */ public DOMStringList getParameterNames() { return fSchemaLoader.getParameterNames(); } /** * Grammar pool which merges grammars from the same namespace into one. This eliminates * duplicate named components. It doesn't ensure that the grammar is consistent, however * this no worse than than the behaviour of XMLSchemaLoader alone when used as an XSLoader. */ private static final class XSGrammarMerger extends XSGrammarPool { public XSGrammarMerger () {} public void putGrammar(Grammar grammar) { SchemaGrammar cachedGrammar = toSchemaGrammar(super.getGrammar(grammar.getGrammarDescription())); if (cachedGrammar != null) { SchemaGrammar newGrammar = toSchemaGrammar(grammar); if (newGrammar != null) { mergeSchemaGrammars(cachedGrammar, newGrammar); } } else { super.putGrammar(grammar); } } private SchemaGrammar toSchemaGrammar (Grammar grammar) { return (grammar instanceof SchemaGrammar) ? (SchemaGrammar) grammar : null; } private void mergeSchemaGrammars(SchemaGrammar cachedGrammar, SchemaGrammar newGrammar) { /** Add new top-level element declarations. **/ XSNamedMap map = newGrammar.getComponents(XSConstants.ELEMENT_DECLARATION); int length = map.getLength(); for (int i = 0; i < length; ++i) { XSElementDecl decl = (XSElementDecl) map.item(i); - if (cachedGrammar.getElementDeclaration(decl.getName()) == null) { + if (cachedGrammar.getGlobalElementDecl(decl.getName()) == null) { cachedGrammar.addGlobalElementDecl(decl); } } /** Add new top-level attribute declarations. **/ map = newGrammar.getComponents(XSConstants.ATTRIBUTE_DECLARATION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSAttributeDecl decl = (XSAttributeDecl) map.item(i); - if (cachedGrammar.getAttributeDeclaration(decl.getName()) == null) { + if (cachedGrammar.getGlobalAttributeDecl(decl.getName()) == null) { cachedGrammar.addGlobalAttributeDecl(decl); } } /** Add new top-level type definitions. **/ map = newGrammar.getComponents(XSConstants.TYPE_DEFINITION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSTypeDefinition decl = (XSTypeDefinition) map.item(i); if (cachedGrammar.getGlobalTypeDecl(decl.getName()) == null) { cachedGrammar.addGlobalTypeDecl(decl); } } /** Add new top-level attribute group definitions. **/ map = newGrammar.getComponents(XSConstants.ATTRIBUTE_GROUP); length = map.getLength(); for (int i = 0; i < length; ++i) { XSAttributeGroupDecl decl = (XSAttributeGroupDecl) map.item(i); - if (cachedGrammar.getAttributeDeclaration(decl.getName()) == null) { + if (cachedGrammar.getGlobalAttributeGroupDecl(decl.getName()) == null) { cachedGrammar.addGlobalAttributeGroupDecl(decl); } } /** Add new top-level model group definitions. **/ map = newGrammar.getComponents(XSConstants.MODEL_GROUP); length = map.getLength(); for (int i = 0; i < length; ++i) { XSGroupDecl decl = (XSGroupDecl) map.item(i); if (cachedGrammar.getGlobalGroupDecl(decl.getName()) == null) { cachedGrammar.addGlobalGroupDecl(decl); } } /** Add new top-level notation declarations. **/ map = newGrammar.getComponents(XSConstants.NOTATION_DECLARATION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSNotationDecl decl = (XSNotationDecl) map.item(i); if (cachedGrammar.getGlobalNotationDecl(decl.getName()) == null) { cachedGrammar.addGlobalNotationDecl(decl); } } /** * Add all annotations. Since these components are not named it's * possible we'll add duplicate components. There isn't much we can * do. It's no worse than XMLSchemaLoader when used as an XSLoader. */ XSObjectList annotations = newGrammar.getAnnotations(); length = annotations.getLength(); for (int i = 0; i < length; ++i) { cachedGrammar.addAnnotation((XSAnnotationImpl) annotations.item(i)); } } public boolean containsGrammar(XMLGrammarDescription desc) { return false; } public Grammar getGrammar(XMLGrammarDescription desc) { return null; } public Grammar retrieveGrammar(XMLGrammarDescription desc) { return null; } public Grammar [] retrieveInitialGrammarSet (String grammarType) { return new Grammar[0]; } } }
false
true
private void mergeSchemaGrammars(SchemaGrammar cachedGrammar, SchemaGrammar newGrammar) { /** Add new top-level element declarations. **/ XSNamedMap map = newGrammar.getComponents(XSConstants.ELEMENT_DECLARATION); int length = map.getLength(); for (int i = 0; i < length; ++i) { XSElementDecl decl = (XSElementDecl) map.item(i); if (cachedGrammar.getElementDeclaration(decl.getName()) == null) { cachedGrammar.addGlobalElementDecl(decl); } } /** Add new top-level attribute declarations. **/ map = newGrammar.getComponents(XSConstants.ATTRIBUTE_DECLARATION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSAttributeDecl decl = (XSAttributeDecl) map.item(i); if (cachedGrammar.getAttributeDeclaration(decl.getName()) == null) { cachedGrammar.addGlobalAttributeDecl(decl); } } /** Add new top-level type definitions. **/ map = newGrammar.getComponents(XSConstants.TYPE_DEFINITION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSTypeDefinition decl = (XSTypeDefinition) map.item(i); if (cachedGrammar.getGlobalTypeDecl(decl.getName()) == null) { cachedGrammar.addGlobalTypeDecl(decl); } } /** Add new top-level attribute group definitions. **/ map = newGrammar.getComponents(XSConstants.ATTRIBUTE_GROUP); length = map.getLength(); for (int i = 0; i < length; ++i) { XSAttributeGroupDecl decl = (XSAttributeGroupDecl) map.item(i); if (cachedGrammar.getAttributeDeclaration(decl.getName()) == null) { cachedGrammar.addGlobalAttributeGroupDecl(decl); } } /** Add new top-level model group definitions. **/ map = newGrammar.getComponents(XSConstants.MODEL_GROUP); length = map.getLength(); for (int i = 0; i < length; ++i) { XSGroupDecl decl = (XSGroupDecl) map.item(i); if (cachedGrammar.getGlobalGroupDecl(decl.getName()) == null) { cachedGrammar.addGlobalGroupDecl(decl); } } /** Add new top-level notation declarations. **/ map = newGrammar.getComponents(XSConstants.NOTATION_DECLARATION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSNotationDecl decl = (XSNotationDecl) map.item(i); if (cachedGrammar.getGlobalNotationDecl(decl.getName()) == null) { cachedGrammar.addGlobalNotationDecl(decl); } } /** * Add all annotations. Since these components are not named it's * possible we'll add duplicate components. There isn't much we can * do. It's no worse than XMLSchemaLoader when used as an XSLoader. */ XSObjectList annotations = newGrammar.getAnnotations(); length = annotations.getLength(); for (int i = 0; i < length; ++i) { cachedGrammar.addAnnotation((XSAnnotationImpl) annotations.item(i)); } }
private void mergeSchemaGrammars(SchemaGrammar cachedGrammar, SchemaGrammar newGrammar) { /** Add new top-level element declarations. **/ XSNamedMap map = newGrammar.getComponents(XSConstants.ELEMENT_DECLARATION); int length = map.getLength(); for (int i = 0; i < length; ++i) { XSElementDecl decl = (XSElementDecl) map.item(i); if (cachedGrammar.getGlobalElementDecl(decl.getName()) == null) { cachedGrammar.addGlobalElementDecl(decl); } } /** Add new top-level attribute declarations. **/ map = newGrammar.getComponents(XSConstants.ATTRIBUTE_DECLARATION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSAttributeDecl decl = (XSAttributeDecl) map.item(i); if (cachedGrammar.getGlobalAttributeDecl(decl.getName()) == null) { cachedGrammar.addGlobalAttributeDecl(decl); } } /** Add new top-level type definitions. **/ map = newGrammar.getComponents(XSConstants.TYPE_DEFINITION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSTypeDefinition decl = (XSTypeDefinition) map.item(i); if (cachedGrammar.getGlobalTypeDecl(decl.getName()) == null) { cachedGrammar.addGlobalTypeDecl(decl); } } /** Add new top-level attribute group definitions. **/ map = newGrammar.getComponents(XSConstants.ATTRIBUTE_GROUP); length = map.getLength(); for (int i = 0; i < length; ++i) { XSAttributeGroupDecl decl = (XSAttributeGroupDecl) map.item(i); if (cachedGrammar.getGlobalAttributeGroupDecl(decl.getName()) == null) { cachedGrammar.addGlobalAttributeGroupDecl(decl); } } /** Add new top-level model group definitions. **/ map = newGrammar.getComponents(XSConstants.MODEL_GROUP); length = map.getLength(); for (int i = 0; i < length; ++i) { XSGroupDecl decl = (XSGroupDecl) map.item(i); if (cachedGrammar.getGlobalGroupDecl(decl.getName()) == null) { cachedGrammar.addGlobalGroupDecl(decl); } } /** Add new top-level notation declarations. **/ map = newGrammar.getComponents(XSConstants.NOTATION_DECLARATION); length = map.getLength(); for (int i = 0; i < length; ++i) { XSNotationDecl decl = (XSNotationDecl) map.item(i); if (cachedGrammar.getGlobalNotationDecl(decl.getName()) == null) { cachedGrammar.addGlobalNotationDecl(decl); } } /** * Add all annotations. Since these components are not named it's * possible we'll add duplicate components. There isn't much we can * do. It's no worse than XMLSchemaLoader when used as an XSLoader. */ XSObjectList annotations = newGrammar.getAnnotations(); length = annotations.getLength(); for (int i = 0; i < length; ++i) { cachedGrammar.addAnnotation((XSAnnotationImpl) annotations.item(i)); } }
diff --git a/editor/java/org/sugarj/builder/MarkingProcessingListener.java b/editor/java/org/sugarj/builder/MarkingProcessingListener.java index dc826ed..b95a2ca 100644 --- a/editor/java/org/sugarj/builder/MarkingProcessingListener.java +++ b/editor/java/org/sugarj/builder/MarkingProcessingListener.java @@ -1,69 +1,71 @@ package org.sugarj.builder; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.spoofax.jsglr_layout.shared.BadTokenException; import org.sugarj.driver.Result; import org.sugarj.common.path.RelativeSourceLocationPath; import org.sugarj.util.ProcessingListener; /** * @author seba */ public class MarkingProcessingListener implements ProcessingListener { private IProject project; public MarkingProcessingListener(IProject project) { this.project = project; } private IResource getResource(RelativeSourceLocationPath sourceFile) throws JavaModelException { if (!sourceFile.getAbsolutePath().startsWith(project.getLocation().toString())) return null; try { for (IPackageFragmentRoot frag : JavaCore.create(project).getAllPackageFragmentRoots()) if (frag.getKind() == IPackageFragmentRoot.K_SOURCE) { IResource resource = project.findMember(frag.getPath().makeRelativeTo(project.getFullPath()).append(sourceFile.getRelativePath())); if (resource != null) return resource; } } catch (JavaModelException e) { } return null; } @Override public void processingStarts(RelativeSourceLocationPath sourceFile) { try { IResource resource = getResource(sourceFile); if (resource != null) resource.deleteMarkers(IMarker.MARKER, true, IResource.DEPTH_INFINITE); } catch (CoreException e) { } } @Override public void processingDone(Result result) { try { IResource resource = getResource(result.getSourceFile()); + if (resource == null) + return; for (String error : result.getCollectedErrors()) { IMarker marker = resource.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.MESSAGE, "compilation failed: " + error); } for (BadTokenException error : result.getParseErrors()) { IMarker marker = resource.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.MESSAGE, "parsing failed: " + error.getLocalizedMessage()); } } catch (CoreException e) { } } }
true
true
public void processingDone(Result result) { try { IResource resource = getResource(result.getSourceFile()); for (String error : result.getCollectedErrors()) { IMarker marker = resource.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.MESSAGE, "compilation failed: " + error); } for (BadTokenException error : result.getParseErrors()) { IMarker marker = resource.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.MESSAGE, "parsing failed: " + error.getLocalizedMessage()); } } catch (CoreException e) { } }
public void processingDone(Result result) { try { IResource resource = getResource(result.getSourceFile()); if (resource == null) return; for (String error : result.getCollectedErrors()) { IMarker marker = resource.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.MESSAGE, "compilation failed: " + error); } for (BadTokenException error : result.getParseErrors()) { IMarker marker = resource.createMarker(IMarker.PROBLEM); marker.setAttribute(IMarker.MESSAGE, "parsing failed: " + error.getLocalizedMessage()); } } catch (CoreException e) { } }
diff --git a/src/be/ibridge/kettle/trans/step/textfileoutput/TextFileOutputDialog.java b/src/be/ibridge/kettle/trans/step/textfileoutput/TextFileOutputDialog.java index 0ec35141..25da7779 100644 --- a/src/be/ibridge/kettle/trans/step/textfileoutput/TextFileOutputDialog.java +++ b/src/be/ibridge/kettle/trans/step/textfileoutput/TextFileOutputDialog.java @@ -1,1196 +1,1209 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ /* * Created on 18-mei-2003 * */ package be.ibridge.kettle.trans.step.textfileoutput; import java.nio.charset.Charset; import java.util.ArrayList; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.FocusListener; 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.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; 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 be.ibridge.kettle.core.ColumnInfo; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Props; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.dialog.EnterSelectionDialog; import be.ibridge.kettle.core.dialog.ErrorDialog; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.core.widget.TableView; import be.ibridge.kettle.core.widget.TextVar; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStepDialog; import be.ibridge.kettle.trans.step.BaseStepMeta; import be.ibridge.kettle.trans.step.StepDialogInterface; public class TextFileOutputDialog extends BaseStepDialog implements StepDialogInterface { private CTabFolder wTabFolder; private FormData fdTabFolder; private CTabItem wFileTab, wContentTab, wFieldsTab; private FormData fdFileComp, fdContentComp, fdFieldsComp; private Label wlFilename; private Button wbFilename; private TextVar wFilename; private FormData fdlFilename, fdbFilename, fdFilename; private Label wlFileIsCommand; private Button wFileIsCommand; private FormData fdlFileIsCommand, fdFileIsCommand; private Label wlExtension; private Text wExtension; private FormData fdlExtension, fdExtension; private Label wlAddStepnr; private Button wAddStepnr; private FormData fdlAddStepnr, fdAddStepnr; private Label wlAddPartnr; private Button wAddPartnr; private FormData fdlAddPartnr, fdAddPartnr; private Label wlAddDate; private Button wAddDate; private FormData fdlAddDate, fdAddDate; private Label wlAddTime; private Button wAddTime; private FormData fdlAddTime, fdAddTime; private Button wbShowFiles; private FormData fdbShowFiles; private Label wlAppend; private Button wAppend; private FormData fdlAppend, fdAppend; private Label wlSeparator; private Button wbSeparator; private Text wSeparator; private FormData fdlSeparator, fdbSeparator, fdSeparator; private Label wlEnclosure; private Text wEnclosure; private FormData fdlEnclosure, fdEnclosure; private Label wlEndedLine; private Text wEndedLine; private FormData fdlEndedLine, fdEndedLine; private Label wlEnclForced; private Button wEnclForced; private FormData fdlEnclForced, fdEnclForced; private Label wlHeader; private Button wHeader; private FormData fdlHeader, fdHeader; private Label wlFooter; private Button wFooter; private FormData fdlFooter, fdFooter; private Label wlFormat; private CCombo wFormat; private FormData fdlFormat, fdFormat; private Label wlCompression; private CCombo wCompression; private FormData fdlCompression, fdCompression; private Label wlEncoding; private CCombo wEncoding; private FormData fdlEncoding, fdEncoding; private Label wlPad; private Button wPad; private FormData fdlPad, fdPad; private Label wlFastDump; private Button wFastDump; private FormData fdlFastDump, fdFastDump; private Label wlSplitEvery; private Text wSplitEvery; private FormData fdlSplitEvery, fdSplitEvery; private TableView wFields; private FormData fdFields; private TextFileOutputMeta input; private Button wMinWidth; private Listener lsMinWidth; private boolean gotEncodings = false; public TextFileOutputDialog(Shell parent, Object in, TransMeta transMeta, String sname) { super(parent, (BaseStepMeta)in, transMeta, sname); input=(TextFileOutputMeta)in; } public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN); props.setLook(shell); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { input.setChanged(); } }; changed = input.hasChanged(); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(Messages.getString("TextFileOutputDialog.DialogTitle")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Stepname line wlStepname=new Label(shell, SWT.RIGHT); wlStepname.setText(Messages.getString("System.Label.StepName")); props.setLook(wlStepname); fdlStepname=new FormData(); fdlStepname.left = new FormAttachment(0, 0); fdlStepname.top = new FormAttachment(0, margin); fdlStepname.right = new FormAttachment(middle, -margin); wlStepname.setLayoutData(fdlStepname); wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wStepname.setText(stepname); props.setLook(wStepname); wStepname.addModifyListener(lsMod); fdStepname=new FormData(); fdStepname.left = new FormAttachment(middle, 0); fdStepname.top = new FormAttachment(0, margin); fdStepname.right= new FormAttachment(100, 0); wStepname.setLayoutData(fdStepname); wTabFolder = new CTabFolder(shell, SWT.BORDER); props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB); ////////////////////////// // START OF FILE TAB/// /// wFileTab=new CTabItem(wTabFolder, SWT.NONE); wFileTab.setText(Messages.getString("TextFileOutputDialog.FileTab.TabTitle")); Composite wFileComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wFileComp); FormLayout fileLayout = new FormLayout(); fileLayout.marginWidth = 3; fileLayout.marginHeight = 3; wFileComp.setLayout(fileLayout); // Filename line wlFilename=new Label(wFileComp, SWT.RIGHT); wlFilename.setText(Messages.getString("TextFileOutputDialog.Filename.Label")); props.setLook(wlFilename); fdlFilename=new FormData(); fdlFilename.left = new FormAttachment(0, 0); fdlFilename.top = new FormAttachment(0, margin); fdlFilename.right= new FormAttachment(middle, -margin); wlFilename.setLayoutData(fdlFilename); wbFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER); props.setLook(wbFilename); wbFilename.setText(Messages.getString("System.Button.Browse")); fdbFilename=new FormData(); fdbFilename.right= new FormAttachment(100, 0); fdbFilename.top = new FormAttachment(0, 0); wbFilename.setLayoutData(fdbFilename); wFilename=new TextVar(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wFilename); wFilename.addModifyListener(lsMod); fdFilename=new FormData(); fdFilename.left = new FormAttachment(middle, 0); fdFilename.top = new FormAttachment(0, margin); fdFilename.right= new FormAttachment(wbFilename, -margin); wFilename.setLayoutData(fdFilename); // Run this as a command instead? wlFileIsCommand=new Label(wFileComp, SWT.RIGHT); wlFileIsCommand.setText(Messages.getString("TextFileOutputDialog.FileIsCommand.Label")); props.setLook(wlFileIsCommand); fdlFileIsCommand=new FormData(); fdlFileIsCommand.left = new FormAttachment(0, 0); fdlFileIsCommand.top = new FormAttachment(wFilename, margin); fdlFileIsCommand.right= new FormAttachment(middle, -margin); wlFileIsCommand.setLayoutData(fdlFileIsCommand); wFileIsCommand=new Button(wFileComp, SWT.CHECK); props.setLook(wFileIsCommand); fdFileIsCommand=new FormData(); fdFileIsCommand.left = new FormAttachment(middle, 0); fdFileIsCommand.top = new FormAttachment(wFilename, margin); fdFileIsCommand.right= new FormAttachment(100, 0); wFileIsCommand.setLayoutData(fdFileIsCommand); wFileIsCommand.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); // Extension line wlExtension=new Label(wFileComp, SWT.RIGHT); wlExtension.setText(Messages.getString("System.Label.Extension")); props.setLook(wlExtension); fdlExtension=new FormData(); fdlExtension.left = new FormAttachment(0, 0); fdlExtension.top = new FormAttachment(wFileIsCommand, margin); fdlExtension.right= new FormAttachment(middle, -margin); wlExtension.setLayoutData(fdlExtension); wExtension=new Text(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wExtension.setText(""); props.setLook(wExtension); wExtension.addModifyListener(lsMod); fdExtension=new FormData(); fdExtension.left = new FormAttachment(middle, 0); fdExtension.top = new FormAttachment(wFileIsCommand, margin); fdExtension.right= new FormAttachment(100, 0); wExtension.setLayoutData(fdExtension); // Create multi-part file? wlAddStepnr=new Label(wFileComp, SWT.RIGHT); wlAddStepnr.setText(Messages.getString("TextFileOutputDialog.AddStepnr.Label")); props.setLook(wlAddStepnr); fdlAddStepnr=new FormData(); fdlAddStepnr.left = new FormAttachment(0, 0); fdlAddStepnr.top = new FormAttachment(wExtension, margin); fdlAddStepnr.right= new FormAttachment(middle, -margin); wlAddStepnr.setLayoutData(fdlAddStepnr); wAddStepnr=new Button(wFileComp, SWT.CHECK); props.setLook(wAddStepnr); fdAddStepnr=new FormData(); fdAddStepnr.left = new FormAttachment(middle, 0); fdAddStepnr.top = new FormAttachment(wExtension, margin); fdAddStepnr.right= new FormAttachment(100, 0); wAddStepnr.setLayoutData(fdAddStepnr); wAddStepnr.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); // Create multi-part file? wlAddPartnr=new Label(wFileComp, SWT.RIGHT); wlAddPartnr.setText(Messages.getString("TextFileOutputDialog.AddPartnr.Label")); props.setLook(wlAddPartnr); fdlAddPartnr=new FormData(); fdlAddPartnr.left = new FormAttachment(0, 0); fdlAddPartnr.top = new FormAttachment(wAddStepnr, margin); fdlAddPartnr.right= new FormAttachment(middle, -margin); wlAddPartnr.setLayoutData(fdlAddPartnr); wAddPartnr=new Button(wFileComp, SWT.CHECK); props.setLook(wAddPartnr); fdAddPartnr=new FormData(); fdAddPartnr.left = new FormAttachment(middle, 0); fdAddPartnr.top = new FormAttachment(wAddStepnr, margin); fdAddPartnr.right= new FormAttachment(100, 0); wAddPartnr.setLayoutData(fdAddPartnr); wAddPartnr.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); // Create multi-part file? wlAddDate=new Label(wFileComp, SWT.RIGHT); wlAddDate.setText(Messages.getString("TextFileOutputDialog.AddDate.Label")); props.setLook(wlAddDate); fdlAddDate=new FormData(); fdlAddDate.left = new FormAttachment(0, 0); fdlAddDate.top = new FormAttachment(wAddPartnr, margin); fdlAddDate.right= new FormAttachment(middle, -margin); wlAddDate.setLayoutData(fdlAddDate); wAddDate=new Button(wFileComp, SWT.CHECK); props.setLook(wAddDate); fdAddDate=new FormData(); fdAddDate.left = new FormAttachment(middle, 0); fdAddDate.top = new FormAttachment(wAddPartnr, margin); fdAddDate.right= new FormAttachment(100, 0); wAddDate.setLayoutData(fdAddDate); wAddDate.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); // System.out.println("wAddDate.getSelection()="+wAddDate.getSelection()); } } ); // Create multi-part file? wlAddTime=new Label(wFileComp, SWT.RIGHT); wlAddTime.setText(Messages.getString("TextFileOutputDialog.AddTime.Label")); props.setLook(wlAddTime); fdlAddTime=new FormData(); fdlAddTime.left = new FormAttachment(0, 0); fdlAddTime.top = new FormAttachment(wAddDate, margin); fdlAddTime.right= new FormAttachment(middle, -margin); wlAddTime.setLayoutData(fdlAddTime); wAddTime=new Button(wFileComp, SWT.CHECK); props.setLook(wAddTime); fdAddTime=new FormData(); fdAddTime.left = new FormAttachment(middle, 0); fdAddTime.top = new FormAttachment(wAddDate, margin); fdAddTime.right= new FormAttachment(100, 0); wAddTime.setLayoutData(fdAddTime); wAddTime.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wbShowFiles=new Button(wFileComp, SWT.PUSH| SWT.CENTER); props.setLook(wbShowFiles); wbShowFiles.setText(Messages.getString("TextFileOutputDialog.ShowFiles.Button")); fdbShowFiles=new FormData(); fdbShowFiles.left = new FormAttachment(middle, 0); fdbShowFiles.top = new FormAttachment(wAddTime, margin*2); wbShowFiles.setLayoutData(fdbShowFiles); wbShowFiles.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { TextFileOutputMeta tfoi = new TextFileOutputMeta(); getInfo(tfoi); String files[] = tfoi.getFiles(); if (files!=null && files.length>0) { EnterSelectionDialog esd = new EnterSelectionDialog(shell, files, Messages.getString("TextFileOutputDialog.SelectOutputFiles.DialogTitle"), Messages.getString("TextFileOutputDialog.SelectOutputFiles.DialogMessage")); esd.setViewOnly(); esd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("TextFileOutputDialog.NoFilesFound.DialogMessage")); mb.setText(Messages.getString("System.DialogTitle.Error")); mb.open(); } } } ); fdFileComp=new FormData(); fdFileComp.left = new FormAttachment(0, 0); fdFileComp.top = new FormAttachment(0, 0); fdFileComp.right = new FormAttachment(100, 0); fdFileComp.bottom= new FormAttachment(100, 0); wFileComp.setLayoutData(fdFileComp); wFileComp.layout(); wFileTab.setControl(wFileComp); ///////////////////////////////////////////////////////////// /// END OF FILE TAB ///////////////////////////////////////////////////////////// ////////////////////////// // START OF CONTENT TAB/// /// wContentTab=new CTabItem(wTabFolder, SWT.NONE); wContentTab.setText(Messages.getString("TextFileOutputDialog.ContentTab.TabTitle")); FormLayout contentLayout = new FormLayout (); contentLayout.marginWidth = 3; contentLayout.marginHeight = 3; Composite wContentComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wContentComp); wContentComp.setLayout(contentLayout); // Append to end of file? wlAppend=new Label(wContentComp, SWT.RIGHT); wlAppend.setText(Messages.getString("TextFileOutputDialog.Append.Label")); props.setLook(wlAppend); fdlAppend=new FormData(); fdlAppend.left = new FormAttachment(0, 0); fdlAppend.top = new FormAttachment(0, 0); fdlAppend.right= new FormAttachment(middle, -margin); wlAppend.setLayoutData(fdlAppend); wAppend=new Button(wContentComp, SWT.CHECK); props.setLook(wAppend); fdAppend=new FormData(); fdAppend.left = new FormAttachment(middle, 0); fdAppend.top = new FormAttachment(0, 0); fdAppend.right= new FormAttachment(100, 0); wAppend.setLayoutData(fdAppend); wAppend.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlSeparator=new Label(wContentComp, SWT.RIGHT); wlSeparator.setText(Messages.getString("TextFileOutputDialog.Separator.Label")); props.setLook(wlSeparator); fdlSeparator=new FormData(); fdlSeparator.left = new FormAttachment(0, 0); fdlSeparator.top = new FormAttachment(wAppend, margin); fdlSeparator.right= new FormAttachment(middle, -margin); wlSeparator.setLayoutData(fdlSeparator); wbSeparator=new Button(wContentComp, SWT.PUSH| SWT.CENTER); props.setLook(wbSeparator); wbSeparator.setText(Messages.getString("TextFileOutputDialog.Separator.Button")); fdbSeparator=new FormData(); fdbSeparator.right= new FormAttachment(100, 0); fdbSeparator.top = new FormAttachment(wAppend, 0); wbSeparator.setLayoutData(fdbSeparator); wbSeparator.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent se) { wSeparator.insert("\t"); } } ); wSeparator=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wSeparator); wSeparator.addModifyListener(lsMod); fdSeparator=new FormData(); fdSeparator.left = new FormAttachment(middle, 0); fdSeparator.top = new FormAttachment(wAppend, margin); fdSeparator.right= new FormAttachment(wbSeparator, -margin); wSeparator.setLayoutData(fdSeparator); // Enclosure line... wlEnclosure=new Label(wContentComp, SWT.RIGHT); wlEnclosure.setText(Messages.getString("TextFileOutputDialog.Enclosure.Label")); props.setLook(wlEnclosure); fdlEnclosure=new FormData(); fdlEnclosure.left = new FormAttachment(0, 0); fdlEnclosure.top = new FormAttachment(wSeparator, margin); fdlEnclosure.right= new FormAttachment(middle, -margin); wlEnclosure.setLayoutData(fdlEnclosure); wEnclosure=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wEnclosure); wEnclosure.addModifyListener(lsMod); fdEnclosure=new FormData(); fdEnclosure.left = new FormAttachment(middle, 0); fdEnclosure.top = new FormAttachment(wSeparator, margin); fdEnclosure.right= new FormAttachment(100, 0); wEnclosure.setLayoutData(fdEnclosure); wlEnclForced=new Label(wContentComp, SWT.RIGHT); wlEnclForced.setText(Messages.getString("TextFileOutputDialog.EnclForced.Label")); props.setLook(wlEnclForced); fdlEnclForced=new FormData(); fdlEnclForced.left = new FormAttachment(0, 0); fdlEnclForced.top = new FormAttachment(wEnclosure, margin); fdlEnclForced.right= new FormAttachment(middle, -margin); wlEnclForced.setLayoutData(fdlEnclForced); wEnclForced=new Button(wContentComp, SWT.CHECK ); props.setLook(wEnclForced); fdEnclForced=new FormData(); fdEnclForced.left = new FormAttachment(middle, 0); fdEnclForced.top = new FormAttachment(wEnclosure, margin); fdEnclForced.right= new FormAttachment(100, 0); wEnclForced.setLayoutData(fdEnclForced); wEnclForced.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlHeader=new Label(wContentComp, SWT.RIGHT); wlHeader.setText(Messages.getString("TextFileOutputDialog.Header.Label")); props.setLook(wlHeader); fdlHeader=new FormData(); fdlHeader.left = new FormAttachment(0, 0); fdlHeader.top = new FormAttachment(wEnclForced, margin); fdlHeader.right= new FormAttachment(middle, -margin); wlHeader.setLayoutData(fdlHeader); wHeader=new Button(wContentComp, SWT.CHECK ); props.setLook(wHeader); fdHeader=new FormData(); fdHeader.left = new FormAttachment(middle, 0); fdHeader.top = new FormAttachment(wEnclForced, margin); fdHeader.right= new FormAttachment(100, 0); wHeader.setLayoutData(fdHeader); wHeader.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlFooter=new Label(wContentComp, SWT.RIGHT); wlFooter.setText(Messages.getString("TextFileOutputDialog.Footer.Label")); props.setLook(wlFooter); fdlFooter=new FormData(); fdlFooter.left = new FormAttachment(0, 0); fdlFooter.top = new FormAttachment(wHeader, margin); fdlFooter.right= new FormAttachment(middle, -margin); wlFooter.setLayoutData(fdlFooter); wFooter=new Button(wContentComp, SWT.CHECK ); props.setLook(wFooter); fdFooter=new FormData(); fdFooter.left = new FormAttachment(middle, 0); fdFooter.top = new FormAttachment(wHeader, margin); fdFooter.right= new FormAttachment(100, 0); wFooter.setLayoutData(fdFooter); wFooter.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlFormat=new Label(wContentComp, SWT.RIGHT); wlFormat.setText(Messages.getString("TextFileOutputDialog.Format.Label")); props.setLook(wlFormat); fdlFormat=new FormData(); fdlFormat.left = new FormAttachment(0, 0); fdlFormat.top = new FormAttachment(wFooter, margin); fdlFormat.right= new FormAttachment(middle, -margin); wlFormat.setLayoutData(fdlFormat); wFormat=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY); wFormat.setText(Messages.getString("TextFileOutputDialog.Format.Label")); props.setLook(wFormat); wFormat.add("DOS"); wFormat.add("Unix"); wFormat.select(0); wFormat.addModifyListener(lsMod); fdFormat=new FormData(); fdFormat.left = new FormAttachment(middle, 0); fdFormat.top = new FormAttachment(wFooter, margin); fdFormat.right= new FormAttachment(100, 0); wFormat.setLayoutData(fdFormat); wlCompression=new Label(wContentComp, SWT.RIGHT); wlCompression.setText(Messages.getString("TextFileOutputDialog.Compression.Label")); props.setLook(wlCompression); fdlCompression=new FormData(); fdlCompression.left = new FormAttachment(0, 0); fdlCompression.top = new FormAttachment(wFormat, margin); fdlCompression.right= new FormAttachment(middle, -margin); wlCompression.setLayoutData(fdlCompression); wCompression=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY); wCompression.setText(Messages.getString("TextFileOutputDialog.Compression.Label")); props.setLook(wCompression); wCompression.setItems(TextFileOutputMeta.fileCompressionTypeCodes); wCompression.addModifyListener(lsMod); fdCompression=new FormData(); fdCompression.left = new FormAttachment(middle, 0); fdCompression.top = new FormAttachment(wFormat, margin); fdCompression.right= new FormAttachment(100, 0); wCompression.setLayoutData(fdCompression); wlEncoding=new Label(wContentComp, SWT.RIGHT); wlEncoding.setText(Messages.getString("TextFileOutputDialog.Encoding.Label")); props.setLook(wlEncoding); fdlEncoding=new FormData(); fdlEncoding.left = new FormAttachment(0, 0); fdlEncoding.top = new FormAttachment(wCompression, margin); fdlEncoding.right= new FormAttachment(middle, -margin); wlEncoding.setLayoutData(fdlEncoding); wEncoding=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY); wEncoding.setEditable(true); props.setLook(wEncoding); wEncoding.addModifyListener(lsMod); fdEncoding=new FormData(); fdEncoding.left = new FormAttachment(middle, 0); fdEncoding.top = new FormAttachment(wCompression, margin); fdEncoding.right= new FormAttachment(100, 0); wEncoding.setLayoutData(fdEncoding); wEncoding.addFocusListener(new FocusListener() { public void focusLost(org.eclipse.swt.events.FocusEvent e) { } public void focusGained(org.eclipse.swt.events.FocusEvent e) { Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(busy); setEncodings(); shell.setCursor(null); busy.dispose(); } } ); wlPad=new Label(wContentComp, SWT.RIGHT); wlPad.setText(Messages.getString("TextFileOutputDialog.Pad.Label")); props.setLook(wlPad); fdlPad=new FormData(); fdlPad.left = new FormAttachment(0, 0); fdlPad.top = new FormAttachment(wEncoding, margin); fdlPad.right= new FormAttachment(middle, -margin); wlPad.setLayoutData(fdlPad); wPad=new Button(wContentComp, SWT.CHECK ); props.setLook(wPad); fdPad=new FormData(); fdPad.left = new FormAttachment(middle, 0); fdPad.top = new FormAttachment(wEncoding, margin); fdPad.right= new FormAttachment(100, 0); wPad.setLayoutData(fdPad); wPad.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlFastDump=new Label(wContentComp, SWT.RIGHT); wlFastDump.setText(Messages.getString("TextFileOutputDialog.FastDump.Label")); props.setLook(wlFastDump); fdlFastDump=new FormData(); fdlFastDump.left = new FormAttachment(0, 0); fdlFastDump.top = new FormAttachment(wPad, margin); fdlFastDump.right= new FormAttachment(middle, -margin); wlFastDump.setLayoutData(fdlFastDump); wFastDump=new Button(wContentComp, SWT.CHECK ); props.setLook(wFastDump); fdFastDump=new FormData(); fdFastDump.left = new FormAttachment(middle, 0); fdFastDump.top = new FormAttachment(wPad, margin); fdFastDump.right= new FormAttachment(100, 0); wFastDump.setLayoutData(fdFastDump); wFastDump.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlSplitEvery=new Label(wContentComp, SWT.RIGHT); wlSplitEvery.setText(Messages.getString("TextFileOutputDialog.SplitEvery.Label")); props.setLook(wlSplitEvery); fdlSplitEvery=new FormData(); fdlSplitEvery.left = new FormAttachment(0, 0); fdlSplitEvery.top = new FormAttachment(wFastDump, margin); fdlSplitEvery.right= new FormAttachment(middle, -margin); wlSplitEvery.setLayoutData(fdlSplitEvery); wSplitEvery=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wSplitEvery); wSplitEvery.addModifyListener(lsMod); fdSplitEvery=new FormData(); fdSplitEvery.left = new FormAttachment(middle, 0); fdSplitEvery.top = new FormAttachment(wFastDump, margin); fdSplitEvery.right= new FormAttachment(100, 0); wSplitEvery.setLayoutData(fdSplitEvery); //Bruise: wlEndedLine=new Label(wContentComp, SWT.RIGHT); wlEndedLine.setText(Messages.getString("TextFileOutputDialog.EndedLine.Label")); props.setLook(wlEndedLine); fdlEndedLine=new FormData(); fdlEndedLine.left = new FormAttachment(0, 0); fdlEndedLine.top = new FormAttachment(wSplitEvery, margin); fdlEndedLine.right= new FormAttachment(middle, -margin); wlEndedLine.setLayoutData(fdlEndedLine); wEndedLine=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wEndedLine); wEndedLine.addModifyListener(lsMod); fdEndedLine=new FormData(); fdEndedLine.left = new FormAttachment(middle, 0); fdEndedLine.top = new FormAttachment(wSplitEvery, margin); fdEndedLine.right= new FormAttachment(100, 0); wEndedLine.setLayoutData(fdEndedLine); fdContentComp = new FormData(); fdContentComp.left = new FormAttachment(0, 0); fdContentComp.top = new FormAttachment(0, 0); fdContentComp.right = new FormAttachment(100, 0); fdContentComp.bottom= new FormAttachment(100, 0); wContentComp.setLayoutData(fdContentComp); wContentComp.layout(); wContentTab.setControl(wContentComp); ///////////////////////////////////////////////////////////// /// END OF CONTENT TAB ///////////////////////////////////////////////////////////// // Fields tab... // wFieldsTab = new CTabItem(wTabFolder, SWT.NONE); wFieldsTab.setText(Messages.getString("TextFileOutputDialog.FieldsTab.TabTitle")); FormLayout fieldsLayout = new FormLayout (); fieldsLayout.marginWidth = Const.FORM_MARGIN; fieldsLayout.marginHeight = Const.FORM_MARGIN; Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE); wFieldsComp.setLayout(fieldsLayout); props.setLook(wFieldsComp); wGet=new Button(wFieldsComp, SWT.PUSH); wGet.setText(Messages.getString("System.Button.GetFields")); wGet.setToolTipText(Messages.getString("System.Tooltip.GetFields")); wMinWidth =new Button(wFieldsComp, SWT.PUSH); wMinWidth.setText(Messages.getString("TextFileOutputDialog.MinWidth.Button")); wMinWidth.setToolTipText(Messages.getString("TextFileOutputDialog.MinWidth.Tooltip")); setButtonPositions(new Button[] { wGet, wMinWidth}, margin, null); final int FieldsCols=9; final int FieldsRows=input.getOutputFields().length; // Prepare a list of possible formats... String dats[] = Const.dateFormats; String nums[] = Const.numberFormats; int totsize = dats.length + nums.length; String formats[] = new String[totsize]; for (int x=0;x<dats.length;x++) formats[x] = dats[x]; for (int x=0;x<nums.length;x++) formats[dats.length+x] = nums[x]; ColumnInfo[] colinf=new ColumnInfo[FieldsCols]; colinf[0]=new ColumnInfo(Messages.getString("TextFileOutputDialog.NameColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[1]=new ColumnInfo(Messages.getString("TextFileOutputDialog.TypeColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, Value.getTypes() ); colinf[2]=new ColumnInfo(Messages.getString("TextFileOutputDialog.FormatColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, formats); colinf[3]=new ColumnInfo(Messages.getString("TextFileOutputDialog.LengthColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[4]=new ColumnInfo(Messages.getString("TextFileOutputDialog.PrecisionColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[5]=new ColumnInfo(Messages.getString("TextFileOutputDialog.CurrencyColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[6]=new ColumnInfo(Messages.getString("TextFileOutputDialog.DecimalColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[7]=new ColumnInfo(Messages.getString("TextFileOutputDialog.GroupColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[8]=new ColumnInfo(Messages.getString("TextFileOutputDialog.NullColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); wFields=new TableView(wFieldsComp, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props ); fdFields=new FormData(); fdFields.left = new FormAttachment(0, 0); fdFields.top = new FormAttachment(0, 0); fdFields.right = new FormAttachment(100, 0); fdFields.bottom= new FormAttachment(wGet, -margin); wFields.setLayoutData(fdFields); fdFieldsComp=new FormData(); fdFieldsComp.left = new FormAttachment(0, 0); fdFieldsComp.top = new FormAttachment(0, 0); fdFieldsComp.right = new FormAttachment(100, 0); fdFieldsComp.bottom= new FormAttachment(100, 0); wFieldsComp.setLayoutData(fdFieldsComp); wFieldsComp.layout(); wFieldsTab.setControl(wFieldsComp); fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment(0, 0); fdTabFolder.top = new FormAttachment(wStepname, margin); fdTabFolder.right = new FormAttachment(100, 0); fdTabFolder.bottom= new FormAttachment(100, -50); wTabFolder.setLayoutData(fdTabFolder); wOK=new Button(shell, SWT.PUSH); wOK.setText(Messages.getString("System.Button.OK")); wCancel=new Button(shell, SWT.PUSH); wCancel.setText(Messages.getString("System.Button.Cancel")); setButtonPositions(new Button[] { wOK, wCancel }, margin, wTabFolder); // Add listeners lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; lsGet = new Listener() { public void handleEvent(Event e) { get(); } }; lsMinWidth = new Listener() { public void handleEvent(Event e) { setMinimalWidth(); } }; lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; wOK.addListener (SWT.Selection, lsOK ); wGet.addListener (SWT.Selection, lsGet ); wMinWidth.addListener (SWT.Selection, lsMinWidth ); wCancel.addListener(SWT.Selection, lsCancel); lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wStepname.addSelectionListener( lsDef ); wFilename.addSelectionListener( lsDef ); wSeparator.addSelectionListener( lsDef ); // Whenever something changes, set the tooltip to the expanded version: wFilename.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wFilename.setToolTipText(StringUtil.environmentSubstitute( wFilename.getText() ) ); } } ); wbFilename.addSelectionListener ( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setFilterExtensions(new String[] {"*.txt", "*.csv", "*"}); if (wFilename.getText()!=null) { dialog.setFileName(StringUtil.environmentSubstitute(wFilename.getText())); } dialog.setFilterNames(new String[] {Messages.getString("System.FileType.TextFiles"), Messages.getString("System.FileType.CSVFiles"), Messages.getString("System.FileType.AllFiles")}); if (dialog.open()!=null) { - wFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName()); + String extension = wExtension.getText(); + if ( extension != null && dialog.getFileName() != null && + dialog.getFileName().endsWith("." + extension) ) + { + // The extension is filled in and matches the end + // of the selected file => Strip off the extension. + String fileName = dialog.getFileName(); + wFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+ + fileName.substring(0, fileName.length() - (extension.length()+1))); + } + else + { + wFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName()); + } } } } ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } ); lsResize = new Listener() { public void handleEvent(Event event) { Point size = shell.getSize(); wFields.setSize(size.x-10, size.y-50); wFields.table.setSize(size.x-10, size.y-50); wFields.redraw(); } }; shell.addListener(SWT.Resize, lsResize); wTabFolder.setSelection(0); // Set the shell size, based upon previous time... setSize(); getData(); input.setChanged(changed); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return stepname; } private void setEncodings() { // Encoding of the text file: if (!gotEncodings) { gotEncodings = true; wEncoding.removeAll(); ArrayList values = new ArrayList(Charset.availableCharsets().values()); for (int i=0;i<values.size();i++) { Charset charSet = (Charset)values.get(i); wEncoding.add( charSet.displayName() ); } // Now select the default! String defEncoding = Const.getEnvironmentVariable("file.encoding", "UTF-8"); int idx = Const.indexOfString(defEncoding, wEncoding.getItems() ); if (idx>=0) wEncoding.select( idx ); } } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { if (input.getFileName() != null) wFilename.setText(input.getFileName()); wFileIsCommand.setSelection(input.isFileAsCommand()); if (input.getExtension() != null) wExtension.setText(input.getExtension()); if (input.getSeparator() !=null) wSeparator.setText(input.getSeparator()); if (input.getEnclosure() !=null) wEnclosure.setText(input.getEnclosure()); if (input.getFileFormat()!=null) wFormat.setText(input.getFileFormat()); if (input.getFileCompression()!=null) wCompression.setText(input.getFileCompression()); if (input.getEncoding() !=null) wEncoding.setText(input.getEncoding()); if (input.getEndedLine() !=null) wEndedLine.setText(input.getEndedLine()); wSplitEvery.setText(""+input.getSplitEvery()); wEnclForced.setSelection(input.isEnclosureForced()); wHeader.setSelection(input.isHeaderEnabled()); wFooter.setSelection(input.isFooterEnabled()); wAddDate.setSelection(input.isDateInFilename()); wAddTime.setSelection(input.isTimeInFilename()); wAppend.setSelection(input.isFileAppended()); wAddStepnr.setSelection(input.isStepNrInFilename()); wAddPartnr.setSelection(input.isPartNrInFilename()); wPad.setSelection(input.isPadded()); wFastDump.setSelection(input.isFastDump()); log.logDebug(toString(), "getting fields info..."); for (int i=0;i<input.getOutputFields().length;i++) { TextFileField field = input.getOutputFields()[i]; TableItem item = wFields.table.getItem(i); if (field.getName()!=null) item.setText(1, field.getName()); item.setText(2, field.getTypeDesc()); if (field.getFormat()!=null) item.setText(3, field.getFormat()); if (field.getLength()!=-1) item.setText(4, ""+field.getLength()); if (field.getPrecision()!=-1) item.setText(5, ""+field.getPrecision()); if (field.getCurrencySymbol()!=null) item.setText(6, field.getCurrencySymbol()); if (field.getDecimalSymbol()!=null) item.setText(7, field.getDecimalSymbol()); if (field.getGroupingSymbol()!=null) item.setText(8, field.getGroupingSymbol()); if (field.getNullString()!=null) item.setText(9, field.getNullString()); } wFields.optWidth(true); wStepname.selectAll(); } private void cancel() { stepname=null; input.setChanged(backupChanged); dispose(); } private void getInfo(TextFileOutputMeta tfoi) { tfoi.setFileName( wFilename.getText() ); tfoi.setFileAsCommand( wFileIsCommand.getSelection() ); tfoi.setFileFormat( wFormat.getText() ); tfoi.setFileCompression( wCompression.getText() ); tfoi.setEncoding( wEncoding.getText() ); tfoi.setSeparator( wSeparator.getText() ); tfoi.setEnclosure( wEnclosure.getText() ); tfoi.setExtension( wExtension.getText() ); tfoi.setSplitEvery( Const.toInt(wSplitEvery.getText(), 0) ); tfoi.setEndedLine( wEndedLine.getText() ); tfoi.setEnclosureForced( wEnclForced.getSelection() ); tfoi.setHeaderEnabled( wHeader.getSelection() ); tfoi.setFooterEnabled( wFooter.getSelection() ); tfoi.setFileAppended( wAppend.getSelection() ); tfoi.setStepNrInFilename( wAddStepnr.getSelection() ); tfoi.setPartNrInFilename( wAddPartnr.getSelection() ); tfoi.setDateInFilename( wAddDate.getSelection() ); tfoi.setTimeInFilename( wAddTime.getSelection() ); tfoi.setPadded( wPad.getSelection() ); tfoi.setFastDump( wFastDump.getSelection() ); int i; //Table table = wFields.table; int nrfields = wFields.nrNonEmpty(); tfoi.allocate(nrfields); for (i=0;i<nrfields;i++) { TextFileField field = new TextFileField(); TableItem item = wFields.getNonEmpty(i); field.setName( item.getText(1) ); field.setType( item.getText(2) ); field.setFormat( item.getText(3) ); field.setLength( Const.toInt(item.getText(4), -1) ); field.setPrecision( Const.toInt(item.getText(5), -1) ); field.setCurrencySymbol( item.getText(6) ); field.setDecimalSymbol( item.getText(7) ); field.setGroupingSymbol( item.getText(8) ); field.setNullString( item.getText(9) ); tfoi.getOutputFields()[i] = field; } } private void ok() { stepname = wStepname.getText(); // return value getInfo(input); dispose(); } private void get() { try { Row r = transMeta.getPrevStepFields(stepname); if (r!=null) { Table table=wFields.table; int count=table.getItemCount(); for (int i=0;i<r.size();i++) { Value v = r.getValue(i); TableItem ti = new TableItem(table, SWT.NONE); ti.setText(0, ""+(count+i+1)); ti.setText(1, v.getName()); ti.setText(2, v.getTypeDesc()); if (v.isNumber()) { if (v.getLength()>0) { int le=v.getLength(); int pr=v.getPrecision(); if (v.getPrecision()<=0) { pr=0; } String mask=""; for (int m=0;m<le-pr;m++) { mask+="0"; } if (pr>0) mask+="."; for (int m=0;m<pr;m++) { mask+="0"; } ti.setText(3, mask); } } ti.setText(4, ""+v.getLength()); ti.setText(5, ""+v.getPrecision()); } wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); } } catch(KettleException ke) { new ErrorDialog(shell, Messages.getString("System.Dialog.GetFieldsFailed.Title"), Messages.getString("System.Dialog.GetFieldsFailed.Message"), ke); } } /** * Sets the output width to minimal width... * */ public void setMinimalWidth() { for (int i=0;i<wFields.nrNonEmpty();i++) { TableItem item = wFields.getNonEmpty(i); item.setText(4, ""); item.setText(5, ""); int type = Value.getType(item.getText(2)); switch(type) { case Value.VALUE_TYPE_STRING: item.setText(3, ""); break; case Value.VALUE_TYPE_INTEGER: item.setText(3, "0"); break; case Value.VALUE_TYPE_NUMBER: item.setText(3, "0.#####"); break; case Value.VALUE_TYPE_DATE: break; default: break; } } wFields.optWidth(true); } public String toString() { return this.getClass().getName(); } }
true
true
public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN); props.setLook(shell); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { input.setChanged(); } }; changed = input.hasChanged(); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(Messages.getString("TextFileOutputDialog.DialogTitle")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Stepname line wlStepname=new Label(shell, SWT.RIGHT); wlStepname.setText(Messages.getString("System.Label.StepName")); props.setLook(wlStepname); fdlStepname=new FormData(); fdlStepname.left = new FormAttachment(0, 0); fdlStepname.top = new FormAttachment(0, margin); fdlStepname.right = new FormAttachment(middle, -margin); wlStepname.setLayoutData(fdlStepname); wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wStepname.setText(stepname); props.setLook(wStepname); wStepname.addModifyListener(lsMod); fdStepname=new FormData(); fdStepname.left = new FormAttachment(middle, 0); fdStepname.top = new FormAttachment(0, margin); fdStepname.right= new FormAttachment(100, 0); wStepname.setLayoutData(fdStepname); wTabFolder = new CTabFolder(shell, SWT.BORDER); props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB); ////////////////////////// // START OF FILE TAB/// /// wFileTab=new CTabItem(wTabFolder, SWT.NONE); wFileTab.setText(Messages.getString("TextFileOutputDialog.FileTab.TabTitle")); Composite wFileComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wFileComp); FormLayout fileLayout = new FormLayout(); fileLayout.marginWidth = 3; fileLayout.marginHeight = 3; wFileComp.setLayout(fileLayout); // Filename line wlFilename=new Label(wFileComp, SWT.RIGHT); wlFilename.setText(Messages.getString("TextFileOutputDialog.Filename.Label")); props.setLook(wlFilename); fdlFilename=new FormData(); fdlFilename.left = new FormAttachment(0, 0); fdlFilename.top = new FormAttachment(0, margin); fdlFilename.right= new FormAttachment(middle, -margin); wlFilename.setLayoutData(fdlFilename); wbFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER); props.setLook(wbFilename); wbFilename.setText(Messages.getString("System.Button.Browse")); fdbFilename=new FormData(); fdbFilename.right= new FormAttachment(100, 0); fdbFilename.top = new FormAttachment(0, 0); wbFilename.setLayoutData(fdbFilename); wFilename=new TextVar(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wFilename); wFilename.addModifyListener(lsMod); fdFilename=new FormData(); fdFilename.left = new FormAttachment(middle, 0); fdFilename.top = new FormAttachment(0, margin); fdFilename.right= new FormAttachment(wbFilename, -margin); wFilename.setLayoutData(fdFilename); // Run this as a command instead? wlFileIsCommand=new Label(wFileComp, SWT.RIGHT); wlFileIsCommand.setText(Messages.getString("TextFileOutputDialog.FileIsCommand.Label")); props.setLook(wlFileIsCommand); fdlFileIsCommand=new FormData(); fdlFileIsCommand.left = new FormAttachment(0, 0); fdlFileIsCommand.top = new FormAttachment(wFilename, margin); fdlFileIsCommand.right= new FormAttachment(middle, -margin); wlFileIsCommand.setLayoutData(fdlFileIsCommand); wFileIsCommand=new Button(wFileComp, SWT.CHECK); props.setLook(wFileIsCommand); fdFileIsCommand=new FormData(); fdFileIsCommand.left = new FormAttachment(middle, 0); fdFileIsCommand.top = new FormAttachment(wFilename, margin); fdFileIsCommand.right= new FormAttachment(100, 0); wFileIsCommand.setLayoutData(fdFileIsCommand); wFileIsCommand.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); // Extension line wlExtension=new Label(wFileComp, SWT.RIGHT); wlExtension.setText(Messages.getString("System.Label.Extension")); props.setLook(wlExtension); fdlExtension=new FormData(); fdlExtension.left = new FormAttachment(0, 0); fdlExtension.top = new FormAttachment(wFileIsCommand, margin); fdlExtension.right= new FormAttachment(middle, -margin); wlExtension.setLayoutData(fdlExtension); wExtension=new Text(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wExtension.setText(""); props.setLook(wExtension); wExtension.addModifyListener(lsMod); fdExtension=new FormData(); fdExtension.left = new FormAttachment(middle, 0); fdExtension.top = new FormAttachment(wFileIsCommand, margin); fdExtension.right= new FormAttachment(100, 0); wExtension.setLayoutData(fdExtension); // Create multi-part file? wlAddStepnr=new Label(wFileComp, SWT.RIGHT); wlAddStepnr.setText(Messages.getString("TextFileOutputDialog.AddStepnr.Label")); props.setLook(wlAddStepnr); fdlAddStepnr=new FormData(); fdlAddStepnr.left = new FormAttachment(0, 0); fdlAddStepnr.top = new FormAttachment(wExtension, margin); fdlAddStepnr.right= new FormAttachment(middle, -margin); wlAddStepnr.setLayoutData(fdlAddStepnr); wAddStepnr=new Button(wFileComp, SWT.CHECK); props.setLook(wAddStepnr); fdAddStepnr=new FormData(); fdAddStepnr.left = new FormAttachment(middle, 0); fdAddStepnr.top = new FormAttachment(wExtension, margin); fdAddStepnr.right= new FormAttachment(100, 0); wAddStepnr.setLayoutData(fdAddStepnr); wAddStepnr.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); // Create multi-part file? wlAddPartnr=new Label(wFileComp, SWT.RIGHT); wlAddPartnr.setText(Messages.getString("TextFileOutputDialog.AddPartnr.Label")); props.setLook(wlAddPartnr); fdlAddPartnr=new FormData(); fdlAddPartnr.left = new FormAttachment(0, 0); fdlAddPartnr.top = new FormAttachment(wAddStepnr, margin); fdlAddPartnr.right= new FormAttachment(middle, -margin); wlAddPartnr.setLayoutData(fdlAddPartnr); wAddPartnr=new Button(wFileComp, SWT.CHECK); props.setLook(wAddPartnr); fdAddPartnr=new FormData(); fdAddPartnr.left = new FormAttachment(middle, 0); fdAddPartnr.top = new FormAttachment(wAddStepnr, margin); fdAddPartnr.right= new FormAttachment(100, 0); wAddPartnr.setLayoutData(fdAddPartnr); wAddPartnr.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); // Create multi-part file? wlAddDate=new Label(wFileComp, SWT.RIGHT); wlAddDate.setText(Messages.getString("TextFileOutputDialog.AddDate.Label")); props.setLook(wlAddDate); fdlAddDate=new FormData(); fdlAddDate.left = new FormAttachment(0, 0); fdlAddDate.top = new FormAttachment(wAddPartnr, margin); fdlAddDate.right= new FormAttachment(middle, -margin); wlAddDate.setLayoutData(fdlAddDate); wAddDate=new Button(wFileComp, SWT.CHECK); props.setLook(wAddDate); fdAddDate=new FormData(); fdAddDate.left = new FormAttachment(middle, 0); fdAddDate.top = new FormAttachment(wAddPartnr, margin); fdAddDate.right= new FormAttachment(100, 0); wAddDate.setLayoutData(fdAddDate); wAddDate.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); // System.out.println("wAddDate.getSelection()="+wAddDate.getSelection()); } } ); // Create multi-part file? wlAddTime=new Label(wFileComp, SWT.RIGHT); wlAddTime.setText(Messages.getString("TextFileOutputDialog.AddTime.Label")); props.setLook(wlAddTime); fdlAddTime=new FormData(); fdlAddTime.left = new FormAttachment(0, 0); fdlAddTime.top = new FormAttachment(wAddDate, margin); fdlAddTime.right= new FormAttachment(middle, -margin); wlAddTime.setLayoutData(fdlAddTime); wAddTime=new Button(wFileComp, SWT.CHECK); props.setLook(wAddTime); fdAddTime=new FormData(); fdAddTime.left = new FormAttachment(middle, 0); fdAddTime.top = new FormAttachment(wAddDate, margin); fdAddTime.right= new FormAttachment(100, 0); wAddTime.setLayoutData(fdAddTime); wAddTime.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wbShowFiles=new Button(wFileComp, SWT.PUSH| SWT.CENTER); props.setLook(wbShowFiles); wbShowFiles.setText(Messages.getString("TextFileOutputDialog.ShowFiles.Button")); fdbShowFiles=new FormData(); fdbShowFiles.left = new FormAttachment(middle, 0); fdbShowFiles.top = new FormAttachment(wAddTime, margin*2); wbShowFiles.setLayoutData(fdbShowFiles); wbShowFiles.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { TextFileOutputMeta tfoi = new TextFileOutputMeta(); getInfo(tfoi); String files[] = tfoi.getFiles(); if (files!=null && files.length>0) { EnterSelectionDialog esd = new EnterSelectionDialog(shell, files, Messages.getString("TextFileOutputDialog.SelectOutputFiles.DialogTitle"), Messages.getString("TextFileOutputDialog.SelectOutputFiles.DialogMessage")); esd.setViewOnly(); esd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("TextFileOutputDialog.NoFilesFound.DialogMessage")); mb.setText(Messages.getString("System.DialogTitle.Error")); mb.open(); } } } ); fdFileComp=new FormData(); fdFileComp.left = new FormAttachment(0, 0); fdFileComp.top = new FormAttachment(0, 0); fdFileComp.right = new FormAttachment(100, 0); fdFileComp.bottom= new FormAttachment(100, 0); wFileComp.setLayoutData(fdFileComp); wFileComp.layout(); wFileTab.setControl(wFileComp); ///////////////////////////////////////////////////////////// /// END OF FILE TAB ///////////////////////////////////////////////////////////// ////////////////////////// // START OF CONTENT TAB/// /// wContentTab=new CTabItem(wTabFolder, SWT.NONE); wContentTab.setText(Messages.getString("TextFileOutputDialog.ContentTab.TabTitle")); FormLayout contentLayout = new FormLayout (); contentLayout.marginWidth = 3; contentLayout.marginHeight = 3; Composite wContentComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wContentComp); wContentComp.setLayout(contentLayout); // Append to end of file? wlAppend=new Label(wContentComp, SWT.RIGHT); wlAppend.setText(Messages.getString("TextFileOutputDialog.Append.Label")); props.setLook(wlAppend); fdlAppend=new FormData(); fdlAppend.left = new FormAttachment(0, 0); fdlAppend.top = new FormAttachment(0, 0); fdlAppend.right= new FormAttachment(middle, -margin); wlAppend.setLayoutData(fdlAppend); wAppend=new Button(wContentComp, SWT.CHECK); props.setLook(wAppend); fdAppend=new FormData(); fdAppend.left = new FormAttachment(middle, 0); fdAppend.top = new FormAttachment(0, 0); fdAppend.right= new FormAttachment(100, 0); wAppend.setLayoutData(fdAppend); wAppend.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlSeparator=new Label(wContentComp, SWT.RIGHT); wlSeparator.setText(Messages.getString("TextFileOutputDialog.Separator.Label")); props.setLook(wlSeparator); fdlSeparator=new FormData(); fdlSeparator.left = new FormAttachment(0, 0); fdlSeparator.top = new FormAttachment(wAppend, margin); fdlSeparator.right= new FormAttachment(middle, -margin); wlSeparator.setLayoutData(fdlSeparator); wbSeparator=new Button(wContentComp, SWT.PUSH| SWT.CENTER); props.setLook(wbSeparator); wbSeparator.setText(Messages.getString("TextFileOutputDialog.Separator.Button")); fdbSeparator=new FormData(); fdbSeparator.right= new FormAttachment(100, 0); fdbSeparator.top = new FormAttachment(wAppend, 0); wbSeparator.setLayoutData(fdbSeparator); wbSeparator.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent se) { wSeparator.insert("\t"); } } ); wSeparator=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wSeparator); wSeparator.addModifyListener(lsMod); fdSeparator=new FormData(); fdSeparator.left = new FormAttachment(middle, 0); fdSeparator.top = new FormAttachment(wAppend, margin); fdSeparator.right= new FormAttachment(wbSeparator, -margin); wSeparator.setLayoutData(fdSeparator); // Enclosure line... wlEnclosure=new Label(wContentComp, SWT.RIGHT); wlEnclosure.setText(Messages.getString("TextFileOutputDialog.Enclosure.Label")); props.setLook(wlEnclosure); fdlEnclosure=new FormData(); fdlEnclosure.left = new FormAttachment(0, 0); fdlEnclosure.top = new FormAttachment(wSeparator, margin); fdlEnclosure.right= new FormAttachment(middle, -margin); wlEnclosure.setLayoutData(fdlEnclosure); wEnclosure=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wEnclosure); wEnclosure.addModifyListener(lsMod); fdEnclosure=new FormData(); fdEnclosure.left = new FormAttachment(middle, 0); fdEnclosure.top = new FormAttachment(wSeparator, margin); fdEnclosure.right= new FormAttachment(100, 0); wEnclosure.setLayoutData(fdEnclosure); wlEnclForced=new Label(wContentComp, SWT.RIGHT); wlEnclForced.setText(Messages.getString("TextFileOutputDialog.EnclForced.Label")); props.setLook(wlEnclForced); fdlEnclForced=new FormData(); fdlEnclForced.left = new FormAttachment(0, 0); fdlEnclForced.top = new FormAttachment(wEnclosure, margin); fdlEnclForced.right= new FormAttachment(middle, -margin); wlEnclForced.setLayoutData(fdlEnclForced); wEnclForced=new Button(wContentComp, SWT.CHECK ); props.setLook(wEnclForced); fdEnclForced=new FormData(); fdEnclForced.left = new FormAttachment(middle, 0); fdEnclForced.top = new FormAttachment(wEnclosure, margin); fdEnclForced.right= new FormAttachment(100, 0); wEnclForced.setLayoutData(fdEnclForced); wEnclForced.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlHeader=new Label(wContentComp, SWT.RIGHT); wlHeader.setText(Messages.getString("TextFileOutputDialog.Header.Label")); props.setLook(wlHeader); fdlHeader=new FormData(); fdlHeader.left = new FormAttachment(0, 0); fdlHeader.top = new FormAttachment(wEnclForced, margin); fdlHeader.right= new FormAttachment(middle, -margin); wlHeader.setLayoutData(fdlHeader); wHeader=new Button(wContentComp, SWT.CHECK ); props.setLook(wHeader); fdHeader=new FormData(); fdHeader.left = new FormAttachment(middle, 0); fdHeader.top = new FormAttachment(wEnclForced, margin); fdHeader.right= new FormAttachment(100, 0); wHeader.setLayoutData(fdHeader); wHeader.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlFooter=new Label(wContentComp, SWT.RIGHT); wlFooter.setText(Messages.getString("TextFileOutputDialog.Footer.Label")); props.setLook(wlFooter); fdlFooter=new FormData(); fdlFooter.left = new FormAttachment(0, 0); fdlFooter.top = new FormAttachment(wHeader, margin); fdlFooter.right= new FormAttachment(middle, -margin); wlFooter.setLayoutData(fdlFooter); wFooter=new Button(wContentComp, SWT.CHECK ); props.setLook(wFooter); fdFooter=new FormData(); fdFooter.left = new FormAttachment(middle, 0); fdFooter.top = new FormAttachment(wHeader, margin); fdFooter.right= new FormAttachment(100, 0); wFooter.setLayoutData(fdFooter); wFooter.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlFormat=new Label(wContentComp, SWT.RIGHT); wlFormat.setText(Messages.getString("TextFileOutputDialog.Format.Label")); props.setLook(wlFormat); fdlFormat=new FormData(); fdlFormat.left = new FormAttachment(0, 0); fdlFormat.top = new FormAttachment(wFooter, margin); fdlFormat.right= new FormAttachment(middle, -margin); wlFormat.setLayoutData(fdlFormat); wFormat=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY); wFormat.setText(Messages.getString("TextFileOutputDialog.Format.Label")); props.setLook(wFormat); wFormat.add("DOS"); wFormat.add("Unix"); wFormat.select(0); wFormat.addModifyListener(lsMod); fdFormat=new FormData(); fdFormat.left = new FormAttachment(middle, 0); fdFormat.top = new FormAttachment(wFooter, margin); fdFormat.right= new FormAttachment(100, 0); wFormat.setLayoutData(fdFormat); wlCompression=new Label(wContentComp, SWT.RIGHT); wlCompression.setText(Messages.getString("TextFileOutputDialog.Compression.Label")); props.setLook(wlCompression); fdlCompression=new FormData(); fdlCompression.left = new FormAttachment(0, 0); fdlCompression.top = new FormAttachment(wFormat, margin); fdlCompression.right= new FormAttachment(middle, -margin); wlCompression.setLayoutData(fdlCompression); wCompression=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY); wCompression.setText(Messages.getString("TextFileOutputDialog.Compression.Label")); props.setLook(wCompression); wCompression.setItems(TextFileOutputMeta.fileCompressionTypeCodes); wCompression.addModifyListener(lsMod); fdCompression=new FormData(); fdCompression.left = new FormAttachment(middle, 0); fdCompression.top = new FormAttachment(wFormat, margin); fdCompression.right= new FormAttachment(100, 0); wCompression.setLayoutData(fdCompression); wlEncoding=new Label(wContentComp, SWT.RIGHT); wlEncoding.setText(Messages.getString("TextFileOutputDialog.Encoding.Label")); props.setLook(wlEncoding); fdlEncoding=new FormData(); fdlEncoding.left = new FormAttachment(0, 0); fdlEncoding.top = new FormAttachment(wCompression, margin); fdlEncoding.right= new FormAttachment(middle, -margin); wlEncoding.setLayoutData(fdlEncoding); wEncoding=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY); wEncoding.setEditable(true); props.setLook(wEncoding); wEncoding.addModifyListener(lsMod); fdEncoding=new FormData(); fdEncoding.left = new FormAttachment(middle, 0); fdEncoding.top = new FormAttachment(wCompression, margin); fdEncoding.right= new FormAttachment(100, 0); wEncoding.setLayoutData(fdEncoding); wEncoding.addFocusListener(new FocusListener() { public void focusLost(org.eclipse.swt.events.FocusEvent e) { } public void focusGained(org.eclipse.swt.events.FocusEvent e) { Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(busy); setEncodings(); shell.setCursor(null); busy.dispose(); } } ); wlPad=new Label(wContentComp, SWT.RIGHT); wlPad.setText(Messages.getString("TextFileOutputDialog.Pad.Label")); props.setLook(wlPad); fdlPad=new FormData(); fdlPad.left = new FormAttachment(0, 0); fdlPad.top = new FormAttachment(wEncoding, margin); fdlPad.right= new FormAttachment(middle, -margin); wlPad.setLayoutData(fdlPad); wPad=new Button(wContentComp, SWT.CHECK ); props.setLook(wPad); fdPad=new FormData(); fdPad.left = new FormAttachment(middle, 0); fdPad.top = new FormAttachment(wEncoding, margin); fdPad.right= new FormAttachment(100, 0); wPad.setLayoutData(fdPad); wPad.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlFastDump=new Label(wContentComp, SWT.RIGHT); wlFastDump.setText(Messages.getString("TextFileOutputDialog.FastDump.Label")); props.setLook(wlFastDump); fdlFastDump=new FormData(); fdlFastDump.left = new FormAttachment(0, 0); fdlFastDump.top = new FormAttachment(wPad, margin); fdlFastDump.right= new FormAttachment(middle, -margin); wlFastDump.setLayoutData(fdlFastDump); wFastDump=new Button(wContentComp, SWT.CHECK ); props.setLook(wFastDump); fdFastDump=new FormData(); fdFastDump.left = new FormAttachment(middle, 0); fdFastDump.top = new FormAttachment(wPad, margin); fdFastDump.right= new FormAttachment(100, 0); wFastDump.setLayoutData(fdFastDump); wFastDump.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlSplitEvery=new Label(wContentComp, SWT.RIGHT); wlSplitEvery.setText(Messages.getString("TextFileOutputDialog.SplitEvery.Label")); props.setLook(wlSplitEvery); fdlSplitEvery=new FormData(); fdlSplitEvery.left = new FormAttachment(0, 0); fdlSplitEvery.top = new FormAttachment(wFastDump, margin); fdlSplitEvery.right= new FormAttachment(middle, -margin); wlSplitEvery.setLayoutData(fdlSplitEvery); wSplitEvery=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wSplitEvery); wSplitEvery.addModifyListener(lsMod); fdSplitEvery=new FormData(); fdSplitEvery.left = new FormAttachment(middle, 0); fdSplitEvery.top = new FormAttachment(wFastDump, margin); fdSplitEvery.right= new FormAttachment(100, 0); wSplitEvery.setLayoutData(fdSplitEvery); //Bruise: wlEndedLine=new Label(wContentComp, SWT.RIGHT); wlEndedLine.setText(Messages.getString("TextFileOutputDialog.EndedLine.Label")); props.setLook(wlEndedLine); fdlEndedLine=new FormData(); fdlEndedLine.left = new FormAttachment(0, 0); fdlEndedLine.top = new FormAttachment(wSplitEvery, margin); fdlEndedLine.right= new FormAttachment(middle, -margin); wlEndedLine.setLayoutData(fdlEndedLine); wEndedLine=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wEndedLine); wEndedLine.addModifyListener(lsMod); fdEndedLine=new FormData(); fdEndedLine.left = new FormAttachment(middle, 0); fdEndedLine.top = new FormAttachment(wSplitEvery, margin); fdEndedLine.right= new FormAttachment(100, 0); wEndedLine.setLayoutData(fdEndedLine); fdContentComp = new FormData(); fdContentComp.left = new FormAttachment(0, 0); fdContentComp.top = new FormAttachment(0, 0); fdContentComp.right = new FormAttachment(100, 0); fdContentComp.bottom= new FormAttachment(100, 0); wContentComp.setLayoutData(fdContentComp); wContentComp.layout(); wContentTab.setControl(wContentComp); ///////////////////////////////////////////////////////////// /// END OF CONTENT TAB ///////////////////////////////////////////////////////////// // Fields tab... // wFieldsTab = new CTabItem(wTabFolder, SWT.NONE); wFieldsTab.setText(Messages.getString("TextFileOutputDialog.FieldsTab.TabTitle")); FormLayout fieldsLayout = new FormLayout (); fieldsLayout.marginWidth = Const.FORM_MARGIN; fieldsLayout.marginHeight = Const.FORM_MARGIN; Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE); wFieldsComp.setLayout(fieldsLayout); props.setLook(wFieldsComp); wGet=new Button(wFieldsComp, SWT.PUSH); wGet.setText(Messages.getString("System.Button.GetFields")); wGet.setToolTipText(Messages.getString("System.Tooltip.GetFields")); wMinWidth =new Button(wFieldsComp, SWT.PUSH); wMinWidth.setText(Messages.getString("TextFileOutputDialog.MinWidth.Button")); wMinWidth.setToolTipText(Messages.getString("TextFileOutputDialog.MinWidth.Tooltip")); setButtonPositions(new Button[] { wGet, wMinWidth}, margin, null); final int FieldsCols=9; final int FieldsRows=input.getOutputFields().length; // Prepare a list of possible formats... String dats[] = Const.dateFormats; String nums[] = Const.numberFormats; int totsize = dats.length + nums.length; String formats[] = new String[totsize]; for (int x=0;x<dats.length;x++) formats[x] = dats[x]; for (int x=0;x<nums.length;x++) formats[dats.length+x] = nums[x]; ColumnInfo[] colinf=new ColumnInfo[FieldsCols]; colinf[0]=new ColumnInfo(Messages.getString("TextFileOutputDialog.NameColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[1]=new ColumnInfo(Messages.getString("TextFileOutputDialog.TypeColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, Value.getTypes() ); colinf[2]=new ColumnInfo(Messages.getString("TextFileOutputDialog.FormatColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, formats); colinf[3]=new ColumnInfo(Messages.getString("TextFileOutputDialog.LengthColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[4]=new ColumnInfo(Messages.getString("TextFileOutputDialog.PrecisionColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[5]=new ColumnInfo(Messages.getString("TextFileOutputDialog.CurrencyColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[6]=new ColumnInfo(Messages.getString("TextFileOutputDialog.DecimalColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[7]=new ColumnInfo(Messages.getString("TextFileOutputDialog.GroupColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[8]=new ColumnInfo(Messages.getString("TextFileOutputDialog.NullColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); wFields=new TableView(wFieldsComp, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props ); fdFields=new FormData(); fdFields.left = new FormAttachment(0, 0); fdFields.top = new FormAttachment(0, 0); fdFields.right = new FormAttachment(100, 0); fdFields.bottom= new FormAttachment(wGet, -margin); wFields.setLayoutData(fdFields); fdFieldsComp=new FormData(); fdFieldsComp.left = new FormAttachment(0, 0); fdFieldsComp.top = new FormAttachment(0, 0); fdFieldsComp.right = new FormAttachment(100, 0); fdFieldsComp.bottom= new FormAttachment(100, 0); wFieldsComp.setLayoutData(fdFieldsComp); wFieldsComp.layout(); wFieldsTab.setControl(wFieldsComp); fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment(0, 0); fdTabFolder.top = new FormAttachment(wStepname, margin); fdTabFolder.right = new FormAttachment(100, 0); fdTabFolder.bottom= new FormAttachment(100, -50); wTabFolder.setLayoutData(fdTabFolder); wOK=new Button(shell, SWT.PUSH); wOK.setText(Messages.getString("System.Button.OK")); wCancel=new Button(shell, SWT.PUSH); wCancel.setText(Messages.getString("System.Button.Cancel")); setButtonPositions(new Button[] { wOK, wCancel }, margin, wTabFolder); // Add listeners lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; lsGet = new Listener() { public void handleEvent(Event e) { get(); } }; lsMinWidth = new Listener() { public void handleEvent(Event e) { setMinimalWidth(); } }; lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; wOK.addListener (SWT.Selection, lsOK ); wGet.addListener (SWT.Selection, lsGet ); wMinWidth.addListener (SWT.Selection, lsMinWidth ); wCancel.addListener(SWT.Selection, lsCancel); lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wStepname.addSelectionListener( lsDef ); wFilename.addSelectionListener( lsDef ); wSeparator.addSelectionListener( lsDef ); // Whenever something changes, set the tooltip to the expanded version: wFilename.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wFilename.setToolTipText(StringUtil.environmentSubstitute( wFilename.getText() ) ); } } ); wbFilename.addSelectionListener ( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setFilterExtensions(new String[] {"*.txt", "*.csv", "*"}); if (wFilename.getText()!=null) { dialog.setFileName(StringUtil.environmentSubstitute(wFilename.getText())); } dialog.setFilterNames(new String[] {Messages.getString("System.FileType.TextFiles"), Messages.getString("System.FileType.CSVFiles"), Messages.getString("System.FileType.AllFiles")}); if (dialog.open()!=null) { wFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName()); } } } ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } ); lsResize = new Listener() { public void handleEvent(Event event) { Point size = shell.getSize(); wFields.setSize(size.x-10, size.y-50); wFields.table.setSize(size.x-10, size.y-50); wFields.redraw(); } }; shell.addListener(SWT.Resize, lsResize); wTabFolder.setSelection(0); // Set the shell size, based upon previous time... setSize(); getData(); input.setChanged(changed); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return stepname; }
public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN); props.setLook(shell); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { input.setChanged(); } }; changed = input.hasChanged(); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(Messages.getString("TextFileOutputDialog.DialogTitle")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Stepname line wlStepname=new Label(shell, SWT.RIGHT); wlStepname.setText(Messages.getString("System.Label.StepName")); props.setLook(wlStepname); fdlStepname=new FormData(); fdlStepname.left = new FormAttachment(0, 0); fdlStepname.top = new FormAttachment(0, margin); fdlStepname.right = new FormAttachment(middle, -margin); wlStepname.setLayoutData(fdlStepname); wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wStepname.setText(stepname); props.setLook(wStepname); wStepname.addModifyListener(lsMod); fdStepname=new FormData(); fdStepname.left = new FormAttachment(middle, 0); fdStepname.top = new FormAttachment(0, margin); fdStepname.right= new FormAttachment(100, 0); wStepname.setLayoutData(fdStepname); wTabFolder = new CTabFolder(shell, SWT.BORDER); props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB); ////////////////////////// // START OF FILE TAB/// /// wFileTab=new CTabItem(wTabFolder, SWT.NONE); wFileTab.setText(Messages.getString("TextFileOutputDialog.FileTab.TabTitle")); Composite wFileComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wFileComp); FormLayout fileLayout = new FormLayout(); fileLayout.marginWidth = 3; fileLayout.marginHeight = 3; wFileComp.setLayout(fileLayout); // Filename line wlFilename=new Label(wFileComp, SWT.RIGHT); wlFilename.setText(Messages.getString("TextFileOutputDialog.Filename.Label")); props.setLook(wlFilename); fdlFilename=new FormData(); fdlFilename.left = new FormAttachment(0, 0); fdlFilename.top = new FormAttachment(0, margin); fdlFilename.right= new FormAttachment(middle, -margin); wlFilename.setLayoutData(fdlFilename); wbFilename=new Button(wFileComp, SWT.PUSH| SWT.CENTER); props.setLook(wbFilename); wbFilename.setText(Messages.getString("System.Button.Browse")); fdbFilename=new FormData(); fdbFilename.right= new FormAttachment(100, 0); fdbFilename.top = new FormAttachment(0, 0); wbFilename.setLayoutData(fdbFilename); wFilename=new TextVar(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wFilename); wFilename.addModifyListener(lsMod); fdFilename=new FormData(); fdFilename.left = new FormAttachment(middle, 0); fdFilename.top = new FormAttachment(0, margin); fdFilename.right= new FormAttachment(wbFilename, -margin); wFilename.setLayoutData(fdFilename); // Run this as a command instead? wlFileIsCommand=new Label(wFileComp, SWT.RIGHT); wlFileIsCommand.setText(Messages.getString("TextFileOutputDialog.FileIsCommand.Label")); props.setLook(wlFileIsCommand); fdlFileIsCommand=new FormData(); fdlFileIsCommand.left = new FormAttachment(0, 0); fdlFileIsCommand.top = new FormAttachment(wFilename, margin); fdlFileIsCommand.right= new FormAttachment(middle, -margin); wlFileIsCommand.setLayoutData(fdlFileIsCommand); wFileIsCommand=new Button(wFileComp, SWT.CHECK); props.setLook(wFileIsCommand); fdFileIsCommand=new FormData(); fdFileIsCommand.left = new FormAttachment(middle, 0); fdFileIsCommand.top = new FormAttachment(wFilename, margin); fdFileIsCommand.right= new FormAttachment(100, 0); wFileIsCommand.setLayoutData(fdFileIsCommand); wFileIsCommand.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); // Extension line wlExtension=new Label(wFileComp, SWT.RIGHT); wlExtension.setText(Messages.getString("System.Label.Extension")); props.setLook(wlExtension); fdlExtension=new FormData(); fdlExtension.left = new FormAttachment(0, 0); fdlExtension.top = new FormAttachment(wFileIsCommand, margin); fdlExtension.right= new FormAttachment(middle, -margin); wlExtension.setLayoutData(fdlExtension); wExtension=new Text(wFileComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wExtension.setText(""); props.setLook(wExtension); wExtension.addModifyListener(lsMod); fdExtension=new FormData(); fdExtension.left = new FormAttachment(middle, 0); fdExtension.top = new FormAttachment(wFileIsCommand, margin); fdExtension.right= new FormAttachment(100, 0); wExtension.setLayoutData(fdExtension); // Create multi-part file? wlAddStepnr=new Label(wFileComp, SWT.RIGHT); wlAddStepnr.setText(Messages.getString("TextFileOutputDialog.AddStepnr.Label")); props.setLook(wlAddStepnr); fdlAddStepnr=new FormData(); fdlAddStepnr.left = new FormAttachment(0, 0); fdlAddStepnr.top = new FormAttachment(wExtension, margin); fdlAddStepnr.right= new FormAttachment(middle, -margin); wlAddStepnr.setLayoutData(fdlAddStepnr); wAddStepnr=new Button(wFileComp, SWT.CHECK); props.setLook(wAddStepnr); fdAddStepnr=new FormData(); fdAddStepnr.left = new FormAttachment(middle, 0); fdAddStepnr.top = new FormAttachment(wExtension, margin); fdAddStepnr.right= new FormAttachment(100, 0); wAddStepnr.setLayoutData(fdAddStepnr); wAddStepnr.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); // Create multi-part file? wlAddPartnr=new Label(wFileComp, SWT.RIGHT); wlAddPartnr.setText(Messages.getString("TextFileOutputDialog.AddPartnr.Label")); props.setLook(wlAddPartnr); fdlAddPartnr=new FormData(); fdlAddPartnr.left = new FormAttachment(0, 0); fdlAddPartnr.top = new FormAttachment(wAddStepnr, margin); fdlAddPartnr.right= new FormAttachment(middle, -margin); wlAddPartnr.setLayoutData(fdlAddPartnr); wAddPartnr=new Button(wFileComp, SWT.CHECK); props.setLook(wAddPartnr); fdAddPartnr=new FormData(); fdAddPartnr.left = new FormAttachment(middle, 0); fdAddPartnr.top = new FormAttachment(wAddStepnr, margin); fdAddPartnr.right= new FormAttachment(100, 0); wAddPartnr.setLayoutData(fdAddPartnr); wAddPartnr.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); // Create multi-part file? wlAddDate=new Label(wFileComp, SWT.RIGHT); wlAddDate.setText(Messages.getString("TextFileOutputDialog.AddDate.Label")); props.setLook(wlAddDate); fdlAddDate=new FormData(); fdlAddDate.left = new FormAttachment(0, 0); fdlAddDate.top = new FormAttachment(wAddPartnr, margin); fdlAddDate.right= new FormAttachment(middle, -margin); wlAddDate.setLayoutData(fdlAddDate); wAddDate=new Button(wFileComp, SWT.CHECK); props.setLook(wAddDate); fdAddDate=new FormData(); fdAddDate.left = new FormAttachment(middle, 0); fdAddDate.top = new FormAttachment(wAddPartnr, margin); fdAddDate.right= new FormAttachment(100, 0); wAddDate.setLayoutData(fdAddDate); wAddDate.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); // System.out.println("wAddDate.getSelection()="+wAddDate.getSelection()); } } ); // Create multi-part file? wlAddTime=new Label(wFileComp, SWT.RIGHT); wlAddTime.setText(Messages.getString("TextFileOutputDialog.AddTime.Label")); props.setLook(wlAddTime); fdlAddTime=new FormData(); fdlAddTime.left = new FormAttachment(0, 0); fdlAddTime.top = new FormAttachment(wAddDate, margin); fdlAddTime.right= new FormAttachment(middle, -margin); wlAddTime.setLayoutData(fdlAddTime); wAddTime=new Button(wFileComp, SWT.CHECK); props.setLook(wAddTime); fdAddTime=new FormData(); fdAddTime.left = new FormAttachment(middle, 0); fdAddTime.top = new FormAttachment(wAddDate, margin); fdAddTime.right= new FormAttachment(100, 0); wAddTime.setLayoutData(fdAddTime); wAddTime.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wbShowFiles=new Button(wFileComp, SWT.PUSH| SWT.CENTER); props.setLook(wbShowFiles); wbShowFiles.setText(Messages.getString("TextFileOutputDialog.ShowFiles.Button")); fdbShowFiles=new FormData(); fdbShowFiles.left = new FormAttachment(middle, 0); fdbShowFiles.top = new FormAttachment(wAddTime, margin*2); wbShowFiles.setLayoutData(fdbShowFiles); wbShowFiles.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { TextFileOutputMeta tfoi = new TextFileOutputMeta(); getInfo(tfoi); String files[] = tfoi.getFiles(); if (files!=null && files.length>0) { EnterSelectionDialog esd = new EnterSelectionDialog(shell, files, Messages.getString("TextFileOutputDialog.SelectOutputFiles.DialogTitle"), Messages.getString("TextFileOutputDialog.SelectOutputFiles.DialogMessage")); esd.setViewOnly(); esd.open(); } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setMessage(Messages.getString("TextFileOutputDialog.NoFilesFound.DialogMessage")); mb.setText(Messages.getString("System.DialogTitle.Error")); mb.open(); } } } ); fdFileComp=new FormData(); fdFileComp.left = new FormAttachment(0, 0); fdFileComp.top = new FormAttachment(0, 0); fdFileComp.right = new FormAttachment(100, 0); fdFileComp.bottom= new FormAttachment(100, 0); wFileComp.setLayoutData(fdFileComp); wFileComp.layout(); wFileTab.setControl(wFileComp); ///////////////////////////////////////////////////////////// /// END OF FILE TAB ///////////////////////////////////////////////////////////// ////////////////////////// // START OF CONTENT TAB/// /// wContentTab=new CTabItem(wTabFolder, SWT.NONE); wContentTab.setText(Messages.getString("TextFileOutputDialog.ContentTab.TabTitle")); FormLayout contentLayout = new FormLayout (); contentLayout.marginWidth = 3; contentLayout.marginHeight = 3; Composite wContentComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wContentComp); wContentComp.setLayout(contentLayout); // Append to end of file? wlAppend=new Label(wContentComp, SWT.RIGHT); wlAppend.setText(Messages.getString("TextFileOutputDialog.Append.Label")); props.setLook(wlAppend); fdlAppend=new FormData(); fdlAppend.left = new FormAttachment(0, 0); fdlAppend.top = new FormAttachment(0, 0); fdlAppend.right= new FormAttachment(middle, -margin); wlAppend.setLayoutData(fdlAppend); wAppend=new Button(wContentComp, SWT.CHECK); props.setLook(wAppend); fdAppend=new FormData(); fdAppend.left = new FormAttachment(middle, 0); fdAppend.top = new FormAttachment(0, 0); fdAppend.right= new FormAttachment(100, 0); wAppend.setLayoutData(fdAppend); wAppend.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlSeparator=new Label(wContentComp, SWT.RIGHT); wlSeparator.setText(Messages.getString("TextFileOutputDialog.Separator.Label")); props.setLook(wlSeparator); fdlSeparator=new FormData(); fdlSeparator.left = new FormAttachment(0, 0); fdlSeparator.top = new FormAttachment(wAppend, margin); fdlSeparator.right= new FormAttachment(middle, -margin); wlSeparator.setLayoutData(fdlSeparator); wbSeparator=new Button(wContentComp, SWT.PUSH| SWT.CENTER); props.setLook(wbSeparator); wbSeparator.setText(Messages.getString("TextFileOutputDialog.Separator.Button")); fdbSeparator=new FormData(); fdbSeparator.right= new FormAttachment(100, 0); fdbSeparator.top = new FormAttachment(wAppend, 0); wbSeparator.setLayoutData(fdbSeparator); wbSeparator.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent se) { wSeparator.insert("\t"); } } ); wSeparator=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wSeparator); wSeparator.addModifyListener(lsMod); fdSeparator=new FormData(); fdSeparator.left = new FormAttachment(middle, 0); fdSeparator.top = new FormAttachment(wAppend, margin); fdSeparator.right= new FormAttachment(wbSeparator, -margin); wSeparator.setLayoutData(fdSeparator); // Enclosure line... wlEnclosure=new Label(wContentComp, SWT.RIGHT); wlEnclosure.setText(Messages.getString("TextFileOutputDialog.Enclosure.Label")); props.setLook(wlEnclosure); fdlEnclosure=new FormData(); fdlEnclosure.left = new FormAttachment(0, 0); fdlEnclosure.top = new FormAttachment(wSeparator, margin); fdlEnclosure.right= new FormAttachment(middle, -margin); wlEnclosure.setLayoutData(fdlEnclosure); wEnclosure=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wEnclosure); wEnclosure.addModifyListener(lsMod); fdEnclosure=new FormData(); fdEnclosure.left = new FormAttachment(middle, 0); fdEnclosure.top = new FormAttachment(wSeparator, margin); fdEnclosure.right= new FormAttachment(100, 0); wEnclosure.setLayoutData(fdEnclosure); wlEnclForced=new Label(wContentComp, SWT.RIGHT); wlEnclForced.setText(Messages.getString("TextFileOutputDialog.EnclForced.Label")); props.setLook(wlEnclForced); fdlEnclForced=new FormData(); fdlEnclForced.left = new FormAttachment(0, 0); fdlEnclForced.top = new FormAttachment(wEnclosure, margin); fdlEnclForced.right= new FormAttachment(middle, -margin); wlEnclForced.setLayoutData(fdlEnclForced); wEnclForced=new Button(wContentComp, SWT.CHECK ); props.setLook(wEnclForced); fdEnclForced=new FormData(); fdEnclForced.left = new FormAttachment(middle, 0); fdEnclForced.top = new FormAttachment(wEnclosure, margin); fdEnclForced.right= new FormAttachment(100, 0); wEnclForced.setLayoutData(fdEnclForced); wEnclForced.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlHeader=new Label(wContentComp, SWT.RIGHT); wlHeader.setText(Messages.getString("TextFileOutputDialog.Header.Label")); props.setLook(wlHeader); fdlHeader=new FormData(); fdlHeader.left = new FormAttachment(0, 0); fdlHeader.top = new FormAttachment(wEnclForced, margin); fdlHeader.right= new FormAttachment(middle, -margin); wlHeader.setLayoutData(fdlHeader); wHeader=new Button(wContentComp, SWT.CHECK ); props.setLook(wHeader); fdHeader=new FormData(); fdHeader.left = new FormAttachment(middle, 0); fdHeader.top = new FormAttachment(wEnclForced, margin); fdHeader.right= new FormAttachment(100, 0); wHeader.setLayoutData(fdHeader); wHeader.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlFooter=new Label(wContentComp, SWT.RIGHT); wlFooter.setText(Messages.getString("TextFileOutputDialog.Footer.Label")); props.setLook(wlFooter); fdlFooter=new FormData(); fdlFooter.left = new FormAttachment(0, 0); fdlFooter.top = new FormAttachment(wHeader, margin); fdlFooter.right= new FormAttachment(middle, -margin); wlFooter.setLayoutData(fdlFooter); wFooter=new Button(wContentComp, SWT.CHECK ); props.setLook(wFooter); fdFooter=new FormData(); fdFooter.left = new FormAttachment(middle, 0); fdFooter.top = new FormAttachment(wHeader, margin); fdFooter.right= new FormAttachment(100, 0); wFooter.setLayoutData(fdFooter); wFooter.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlFormat=new Label(wContentComp, SWT.RIGHT); wlFormat.setText(Messages.getString("TextFileOutputDialog.Format.Label")); props.setLook(wlFormat); fdlFormat=new FormData(); fdlFormat.left = new FormAttachment(0, 0); fdlFormat.top = new FormAttachment(wFooter, margin); fdlFormat.right= new FormAttachment(middle, -margin); wlFormat.setLayoutData(fdlFormat); wFormat=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY); wFormat.setText(Messages.getString("TextFileOutputDialog.Format.Label")); props.setLook(wFormat); wFormat.add("DOS"); wFormat.add("Unix"); wFormat.select(0); wFormat.addModifyListener(lsMod); fdFormat=new FormData(); fdFormat.left = new FormAttachment(middle, 0); fdFormat.top = new FormAttachment(wFooter, margin); fdFormat.right= new FormAttachment(100, 0); wFormat.setLayoutData(fdFormat); wlCompression=new Label(wContentComp, SWT.RIGHT); wlCompression.setText(Messages.getString("TextFileOutputDialog.Compression.Label")); props.setLook(wlCompression); fdlCompression=new FormData(); fdlCompression.left = new FormAttachment(0, 0); fdlCompression.top = new FormAttachment(wFormat, margin); fdlCompression.right= new FormAttachment(middle, -margin); wlCompression.setLayoutData(fdlCompression); wCompression=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY); wCompression.setText(Messages.getString("TextFileOutputDialog.Compression.Label")); props.setLook(wCompression); wCompression.setItems(TextFileOutputMeta.fileCompressionTypeCodes); wCompression.addModifyListener(lsMod); fdCompression=new FormData(); fdCompression.left = new FormAttachment(middle, 0); fdCompression.top = new FormAttachment(wFormat, margin); fdCompression.right= new FormAttachment(100, 0); wCompression.setLayoutData(fdCompression); wlEncoding=new Label(wContentComp, SWT.RIGHT); wlEncoding.setText(Messages.getString("TextFileOutputDialog.Encoding.Label")); props.setLook(wlEncoding); fdlEncoding=new FormData(); fdlEncoding.left = new FormAttachment(0, 0); fdlEncoding.top = new FormAttachment(wCompression, margin); fdlEncoding.right= new FormAttachment(middle, -margin); wlEncoding.setLayoutData(fdlEncoding); wEncoding=new CCombo(wContentComp, SWT.BORDER | SWT.READ_ONLY); wEncoding.setEditable(true); props.setLook(wEncoding); wEncoding.addModifyListener(lsMod); fdEncoding=new FormData(); fdEncoding.left = new FormAttachment(middle, 0); fdEncoding.top = new FormAttachment(wCompression, margin); fdEncoding.right= new FormAttachment(100, 0); wEncoding.setLayoutData(fdEncoding); wEncoding.addFocusListener(new FocusListener() { public void focusLost(org.eclipse.swt.events.FocusEvent e) { } public void focusGained(org.eclipse.swt.events.FocusEvent e) { Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(busy); setEncodings(); shell.setCursor(null); busy.dispose(); } } ); wlPad=new Label(wContentComp, SWT.RIGHT); wlPad.setText(Messages.getString("TextFileOutputDialog.Pad.Label")); props.setLook(wlPad); fdlPad=new FormData(); fdlPad.left = new FormAttachment(0, 0); fdlPad.top = new FormAttachment(wEncoding, margin); fdlPad.right= new FormAttachment(middle, -margin); wlPad.setLayoutData(fdlPad); wPad=new Button(wContentComp, SWT.CHECK ); props.setLook(wPad); fdPad=new FormData(); fdPad.left = new FormAttachment(middle, 0); fdPad.top = new FormAttachment(wEncoding, margin); fdPad.right= new FormAttachment(100, 0); wPad.setLayoutData(fdPad); wPad.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlFastDump=new Label(wContentComp, SWT.RIGHT); wlFastDump.setText(Messages.getString("TextFileOutputDialog.FastDump.Label")); props.setLook(wlFastDump); fdlFastDump=new FormData(); fdlFastDump.left = new FormAttachment(0, 0); fdlFastDump.top = new FormAttachment(wPad, margin); fdlFastDump.right= new FormAttachment(middle, -margin); wlFastDump.setLayoutData(fdlFastDump); wFastDump=new Button(wContentComp, SWT.CHECK ); props.setLook(wFastDump); fdFastDump=new FormData(); fdFastDump.left = new FormAttachment(middle, 0); fdFastDump.top = new FormAttachment(wPad, margin); fdFastDump.right= new FormAttachment(100, 0); wFastDump.setLayoutData(fdFastDump); wFastDump.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { input.setChanged(); } } ); wlSplitEvery=new Label(wContentComp, SWT.RIGHT); wlSplitEvery.setText(Messages.getString("TextFileOutputDialog.SplitEvery.Label")); props.setLook(wlSplitEvery); fdlSplitEvery=new FormData(); fdlSplitEvery.left = new FormAttachment(0, 0); fdlSplitEvery.top = new FormAttachment(wFastDump, margin); fdlSplitEvery.right= new FormAttachment(middle, -margin); wlSplitEvery.setLayoutData(fdlSplitEvery); wSplitEvery=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wSplitEvery); wSplitEvery.addModifyListener(lsMod); fdSplitEvery=new FormData(); fdSplitEvery.left = new FormAttachment(middle, 0); fdSplitEvery.top = new FormAttachment(wFastDump, margin); fdSplitEvery.right= new FormAttachment(100, 0); wSplitEvery.setLayoutData(fdSplitEvery); //Bruise: wlEndedLine=new Label(wContentComp, SWT.RIGHT); wlEndedLine.setText(Messages.getString("TextFileOutputDialog.EndedLine.Label")); props.setLook(wlEndedLine); fdlEndedLine=new FormData(); fdlEndedLine.left = new FormAttachment(0, 0); fdlEndedLine.top = new FormAttachment(wSplitEvery, margin); fdlEndedLine.right= new FormAttachment(middle, -margin); wlEndedLine.setLayoutData(fdlEndedLine); wEndedLine=new Text(wContentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wEndedLine); wEndedLine.addModifyListener(lsMod); fdEndedLine=new FormData(); fdEndedLine.left = new FormAttachment(middle, 0); fdEndedLine.top = new FormAttachment(wSplitEvery, margin); fdEndedLine.right= new FormAttachment(100, 0); wEndedLine.setLayoutData(fdEndedLine); fdContentComp = new FormData(); fdContentComp.left = new FormAttachment(0, 0); fdContentComp.top = new FormAttachment(0, 0); fdContentComp.right = new FormAttachment(100, 0); fdContentComp.bottom= new FormAttachment(100, 0); wContentComp.setLayoutData(fdContentComp); wContentComp.layout(); wContentTab.setControl(wContentComp); ///////////////////////////////////////////////////////////// /// END OF CONTENT TAB ///////////////////////////////////////////////////////////// // Fields tab... // wFieldsTab = new CTabItem(wTabFolder, SWT.NONE); wFieldsTab.setText(Messages.getString("TextFileOutputDialog.FieldsTab.TabTitle")); FormLayout fieldsLayout = new FormLayout (); fieldsLayout.marginWidth = Const.FORM_MARGIN; fieldsLayout.marginHeight = Const.FORM_MARGIN; Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE); wFieldsComp.setLayout(fieldsLayout); props.setLook(wFieldsComp); wGet=new Button(wFieldsComp, SWT.PUSH); wGet.setText(Messages.getString("System.Button.GetFields")); wGet.setToolTipText(Messages.getString("System.Tooltip.GetFields")); wMinWidth =new Button(wFieldsComp, SWT.PUSH); wMinWidth.setText(Messages.getString("TextFileOutputDialog.MinWidth.Button")); wMinWidth.setToolTipText(Messages.getString("TextFileOutputDialog.MinWidth.Tooltip")); setButtonPositions(new Button[] { wGet, wMinWidth}, margin, null); final int FieldsCols=9; final int FieldsRows=input.getOutputFields().length; // Prepare a list of possible formats... String dats[] = Const.dateFormats; String nums[] = Const.numberFormats; int totsize = dats.length + nums.length; String formats[] = new String[totsize]; for (int x=0;x<dats.length;x++) formats[x] = dats[x]; for (int x=0;x<nums.length;x++) formats[dats.length+x] = nums[x]; ColumnInfo[] colinf=new ColumnInfo[FieldsCols]; colinf[0]=new ColumnInfo(Messages.getString("TextFileOutputDialog.NameColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[1]=new ColumnInfo(Messages.getString("TextFileOutputDialog.TypeColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, Value.getTypes() ); colinf[2]=new ColumnInfo(Messages.getString("TextFileOutputDialog.FormatColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, formats); colinf[3]=new ColumnInfo(Messages.getString("TextFileOutputDialog.LengthColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[4]=new ColumnInfo(Messages.getString("TextFileOutputDialog.PrecisionColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[5]=new ColumnInfo(Messages.getString("TextFileOutputDialog.CurrencyColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[6]=new ColumnInfo(Messages.getString("TextFileOutputDialog.DecimalColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[7]=new ColumnInfo(Messages.getString("TextFileOutputDialog.GroupColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); colinf[8]=new ColumnInfo(Messages.getString("TextFileOutputDialog.NullColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false); wFields=new TableView(wFieldsComp, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props ); fdFields=new FormData(); fdFields.left = new FormAttachment(0, 0); fdFields.top = new FormAttachment(0, 0); fdFields.right = new FormAttachment(100, 0); fdFields.bottom= new FormAttachment(wGet, -margin); wFields.setLayoutData(fdFields); fdFieldsComp=new FormData(); fdFieldsComp.left = new FormAttachment(0, 0); fdFieldsComp.top = new FormAttachment(0, 0); fdFieldsComp.right = new FormAttachment(100, 0); fdFieldsComp.bottom= new FormAttachment(100, 0); wFieldsComp.setLayoutData(fdFieldsComp); wFieldsComp.layout(); wFieldsTab.setControl(wFieldsComp); fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment(0, 0); fdTabFolder.top = new FormAttachment(wStepname, margin); fdTabFolder.right = new FormAttachment(100, 0); fdTabFolder.bottom= new FormAttachment(100, -50); wTabFolder.setLayoutData(fdTabFolder); wOK=new Button(shell, SWT.PUSH); wOK.setText(Messages.getString("System.Button.OK")); wCancel=new Button(shell, SWT.PUSH); wCancel.setText(Messages.getString("System.Button.Cancel")); setButtonPositions(new Button[] { wOK, wCancel }, margin, wTabFolder); // Add listeners lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; lsGet = new Listener() { public void handleEvent(Event e) { get(); } }; lsMinWidth = new Listener() { public void handleEvent(Event e) { setMinimalWidth(); } }; lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; wOK.addListener (SWT.Selection, lsOK ); wGet.addListener (SWT.Selection, lsGet ); wMinWidth.addListener (SWT.Selection, lsMinWidth ); wCancel.addListener(SWT.Selection, lsCancel); lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wStepname.addSelectionListener( lsDef ); wFilename.addSelectionListener( lsDef ); wSeparator.addSelectionListener( lsDef ); // Whenever something changes, set the tooltip to the expanded version: wFilename.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wFilename.setToolTipText(StringUtil.environmentSubstitute( wFilename.getText() ) ); } } ); wbFilename.addSelectionListener ( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setFilterExtensions(new String[] {"*.txt", "*.csv", "*"}); if (wFilename.getText()!=null) { dialog.setFileName(StringUtil.environmentSubstitute(wFilename.getText())); } dialog.setFilterNames(new String[] {Messages.getString("System.FileType.TextFiles"), Messages.getString("System.FileType.CSVFiles"), Messages.getString("System.FileType.AllFiles")}); if (dialog.open()!=null) { String extension = wExtension.getText(); if ( extension != null && dialog.getFileName() != null && dialog.getFileName().endsWith("." + extension) ) { // The extension is filled in and matches the end // of the selected file => Strip off the extension. String fileName = dialog.getFileName(); wFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+ fileName.substring(0, fileName.length() - (extension.length()+1))); } else { wFilename.setText(dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName()); } } } } ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } ); lsResize = new Listener() { public void handleEvent(Event event) { Point size = shell.getSize(); wFields.setSize(size.x-10, size.y-50); wFields.table.setSize(size.x-10, size.y-50); wFields.redraw(); } }; shell.addListener(SWT.Resize, lsResize); wTabFolder.setSelection(0); // Set the shell size, based upon previous time... setSize(); getData(); input.setChanged(changed); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return stepname; }
diff --git a/src/com/appenjoyment/lfnw/WebViewActivity.java b/src/com/appenjoyment/lfnw/WebViewActivity.java index d37a236..4a88661 100644 --- a/src/com/appenjoyment/lfnw/WebViewActivity.java +++ b/src/com/appenjoyment/lfnw/WebViewActivity.java @@ -1,106 +1,107 @@ package com.appenjoyment.lfnw; import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.webkit.WebView; import android.webkit.WebViewClient; public class WebViewActivity extends ActionBarActivity { public static String KEY_URL = "KEY_URL"; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setProgressBarIndeterminate(true); super.onCreate(savedInstanceState); m_webView = new WebView(this); m_webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); setContentView(m_webView); m_webView.getSettings().setJavaScriptEnabled(true); m_webView.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // TODO:! } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); setProgressBarIndeterminateVisibility(true); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); setProgressBarIndeterminateVisibility(false); } }); - m_requestedUrl = getIntent().getExtras().getString(KEY_URL); + Bundle extras = getIntent().getExtras(); + m_requestedUrl = extras == null ? null : extras.getString(KEY_URL); if (m_requestedUrl == null || m_requestedUrl.length() == 0) throw new IllegalArgumentException("No Url"); m_webView.loadUrl(m_requestedUrl); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.webview, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_go_home: NavUtils.navigateUpFromSameTask(this); return true; case R.id.menu_open_in_browser: String currentUrl = m_webView.getUrl(); startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(currentUrl != null && currentUrl.length() != 0 ? currentUrl : m_requestedUrl))); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Check if the key event was the Back button and if there's history if ((keyCode == KeyEvent.KEYCODE_BACK) && m_webView.canGoBack()) { m_webView.goBack(); return true; } // If it wasn't the Back key or there's no web page history, bubble up to the default // system behavior (probably exit the activity) return super.onKeyDown(keyCode, event); } private WebView m_webView; private String m_requestedUrl; }
true
true
protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setProgressBarIndeterminate(true); super.onCreate(savedInstanceState); m_webView = new WebView(this); m_webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); setContentView(m_webView); m_webView.getSettings().setJavaScriptEnabled(true); m_webView.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // TODO:! } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); setProgressBarIndeterminateVisibility(true); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); setProgressBarIndeterminateVisibility(false); } }); m_requestedUrl = getIntent().getExtras().getString(KEY_URL); if (m_requestedUrl == null || m_requestedUrl.length() == 0) throw new IllegalArgumentException("No Url"); m_webView.loadUrl(m_requestedUrl); }
protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setProgressBarIndeterminate(true); super.onCreate(savedInstanceState); m_webView = new WebView(this); m_webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); setContentView(m_webView); m_webView.getSettings().setJavaScriptEnabled(true); m_webView.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // TODO:! } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); setProgressBarIndeterminateVisibility(true); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); setProgressBarIndeterminateVisibility(false); } }); Bundle extras = getIntent().getExtras(); m_requestedUrl = extras == null ? null : extras.getString(KEY_URL); if (m_requestedUrl == null || m_requestedUrl.length() == 0) throw new IllegalArgumentException("No Url"); m_webView.loadUrl(m_requestedUrl); }
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java index a28486d71..1cfd5fbc9 100644 --- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java +++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/StreetVertexIndexServiceImpl.java @@ -1,498 +1,498 @@ /* 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentripplanner.routing.impl; import static org.opentripplanner.common.IterableLibrary.filter; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import lombok.Getter; import lombok.Setter; import org.opentripplanner.common.IterableLibrary; import org.opentripplanner.common.geometry.DistanceLibrary; import org.opentripplanner.common.geometry.SphericalDistanceLibrary; import org.opentripplanner.common.model.NamedPlace; import org.opentripplanner.routing.core.LocationObservation; import org.opentripplanner.routing.core.RoutingRequest; import org.opentripplanner.routing.core.TraversalRequirements; import org.opentripplanner.routing.core.TraverseModeSet; import org.opentripplanner.routing.edgetype.FreeEdge; import org.opentripplanner.routing.edgetype.StreetEdge; import org.opentripplanner.routing.graph.Edge; import org.opentripplanner.routing.graph.Graph; import org.opentripplanner.routing.graph.Vertex; import org.opentripplanner.routing.location.StreetLocation; import org.opentripplanner.routing.services.StreetVertexIndexService; import org.opentripplanner.routing.vertextype.IntersectionVertex; import org.opentripplanner.routing.vertextype.StreetVertex; import org.opentripplanner.routing.vertextype.TransitStop; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Iterables; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.index.SpatialIndex; import com.vividsolutions.jts.index.quadtree.Quadtree; import com.vividsolutions.jts.index.strtree.STRtree; /** * Indexes all edges and transit vertices of the graph spatially. Has a variety of query methods used during network linking and trip planning. * * Creates a StreetLocation representing a location on a street that's not at an intersection, based on input latitude and longitude. Instantiating * this class is expensive, because it creates a spatial index of all of the intersections in the graph. */ // @Component public class StreetVertexIndexServiceImpl implements StreetVertexIndexService { private Graph graph; /** * Contains only instances of {@link StreetEdge} */ private SpatialIndex edgeTree; private STRtree transitStopTree; private STRtree intersectionTree; @Getter @Setter private DistanceLibrary distanceLibrary = SphericalDistanceLibrary.getInstance(); // private static final double SEARCH_RADIUS_M = 100; // meters // private static final double SEARCH_RADIUS_DEG = DistanceLibrary.metersToDegrees(SEARCH_RADIUS_M); /* all distance constants here are plate-carée Euclidean, 0.001 ~= 100m at equator */ // edges will only be found if they are closer than this distance public static final double MAX_DISTANCE_FROM_STREET = 0.01000; // maximum difference in distance for two geometries to be considered coincident public static final double DISTANCE_ERROR = 0.000001; // if a point is within MAX_CORNER_DISTANCE, it is treated as at the corner private static final double MAX_CORNER_DISTANCE = 0.0001; static final Logger _log = LoggerFactory.getLogger(StreetVertexIndexServiceImpl.class); public StreetVertexIndexServiceImpl(Graph graph) { this.graph = graph; setup(); } public StreetVertexIndexServiceImpl(Graph graph, DistanceLibrary distanceLibrary) { this.graph = graph; this.distanceLibrary = distanceLibrary; setup(); } public void setup_modifiable() { edgeTree = new Quadtree(); postSetup(); } public void setup() { edgeTree = new STRtree(); postSetup(); ((STRtree) edgeTree).build(); } private void postSetup() { transitStopTree = new STRtree(); intersectionTree = new STRtree(); for (Vertex gv : graph.getVertices()) { Vertex v = gv; // We only care about StreetEdges for (StreetEdge e : filter(gv.getOutgoing(), StreetEdge.class)) { if (e.getGeometry() == null) { continue; } Envelope env = e.getGeometry().getEnvelopeInternal(); edgeTree.insert(env, e); } if (v instanceof TransitStop) { // only index transit stops that (a) are entrances, or (b) have no associated // entrances TransitStop ts = (TransitStop) v; if (!ts.isEntrance() && ts.hasEntrances()) { continue; } Envelope env = new Envelope(v.getCoordinate()); transitStopTree.insert(env, v); } if (v instanceof IntersectionVertex) { Envelope env = new Envelope(v.getCoordinate()); intersectionTree.insert(env, v); } } transitStopTree.build(); } /** * Get all transit stops within a given distance of a coordinate * * @param distance in meters */ @SuppressWarnings("unchecked") public List<Vertex> getLocalTransitStops(Coordinate c, double distance) { Envelope env = new Envelope(c); env.expandBy(SphericalDistanceLibrary.metersToDegrees(distance)); List<Vertex> nearby = transitStopTree.query(env); List<Vertex> results = new ArrayList<Vertex>(); for (Vertex v : nearby) { if (distanceLibrary.distance(v.getCoordinate(), c) <= distance) { results.add(v); } } return results; } /** * Gets the closest vertex to a coordinate. If necessary, this vertex will be created by splitting nearby edges (non-permanently). */ public Vertex getClosestVertex(final Coordinate coordinate, String name, RoutingRequest options) { return getClosestVertex(coordinate, name, options, null); } public Vertex getClosestVertex(final Coordinate coordinate, String name, RoutingRequest options, List<Edge> extraEdges) { _log.debug("Looking for/making a vertex near {}", coordinate); // first, check for intersections very close by StreetVertex intersection = getIntersectionAt(coordinate, MAX_CORNER_DISTANCE); if (intersection != null) { // coordinate is at a street corner or endpoint if (name == null) { // generate names for corners when no name was given Set<String> uniqueNameSet = new HashSet<String>(); for (Edge e : intersection.getOutgoing()) { if (e instanceof StreetEdge) { uniqueNameSet.add(e.getName()); } } List<String> uniqueNames = new ArrayList<String>(uniqueNameSet); Locale locale; if (options == null) { locale = new Locale("en"); } else { locale = options.getLocale(); } ResourceBundle resources = ResourceBundle.getBundle("internals", locale); String fmt = resources.getString("corner"); if (uniqueNames.size() > 1) { name = String.format(fmt, uniqueNames.get(0), uniqueNames.get(1)); } else if (uniqueNames.size() == 1) { name = uniqueNames.get(0); } else { name = resources.getString("unnamedStreet"); } } StreetLocation closest = new StreetLocation(graph, "corner " + Math.random(), coordinate, name); FreeEdge e = new FreeEdge(closest, intersection); closest.getExtra().add(e); e = new FreeEdge(intersection, closest); closest.getExtra().add(e); return closest; } // if no intersection vertices were found, then find the closest transit stop // (we can return stops here because this method is not used when street-transit linking) - double closest_stop_distance = Double.POSITIVE_INFINITY; - Vertex closest_stop = null; + double closestStopDistance = Double.POSITIVE_INFINITY; + Vertex closestStop = null; // elsewhere options=null means no restrictions, find anything. // here we skip examining stops, as they are really only relevant when transit is being used if (options != null && options.getModes().isTransit()) { for (Vertex v : getLocalTransitStops(coordinate, 1000)) { double d = distanceLibrary.distance(v.getCoordinate(), coordinate); - if (d < closest_stop_distance) { - closest_stop_distance = d; - closest_stop = v; + if (d < closestStopDistance) { + closestStopDistance = d; + closestStop = v; } } } - _log.debug(" best stop: {} distance: {}", closest_stop, closest_stop_distance); + _log.debug(" best stop: {} distance: {}", closestStop, closestStopDistance); // then find closest walkable street StreetLocation closestStreet = null; CandidateEdgeBundle bundle = getClosestEdges(coordinate, options, extraEdges, null, false); CandidateEdge candidate = bundle.best; double closestStreetDistance = Double.POSITIVE_INFINITY; if (candidate != null) { StreetEdge bestStreet = candidate.edge; Coordinate nearestPoint = candidate.nearestPointOnEdge; - closestStreetDistance = candidate.getDistance(); + closestStreetDistance = distanceLibrary.distance(coordinate, nearestPoint); _log.debug("best street: {} dist: {}", bestStreet.toString(), closestStreetDistance); if (name == null) { name = bestStreet.getName(); } String closestName = String .format("%s_%s", bestStreet.getName(), coordinate.toString()); closestStreet = StreetLocation.createStreetLocation( graph, closestName, name, bundle.toEdgeList(), nearestPoint, coordinate); } // decide whether to return street, or street + stop if (closestStreet == null) { // no street found, return closest stop or null _log.debug("returning only transit stop (no street found)"); - return closest_stop; // which will be null if none was found + return closestStop; // which will be null if none was found } else { // street found - if (closest_stop != null) { + if (closestStop != null) { // both street and stop found - double relativeStopDistance = closest_stop_distance / closestStreetDistance; + double relativeStopDistance = closestStopDistance / closestStreetDistance; if (relativeStopDistance < 1.5) { _log.debug("linking transit stop to street (distances are comparable)"); - closestStreet.addExtraEdgeTo(closest_stop); + closestStreet.addExtraEdgeTo(closestStop); } } _log.debug("returning split street"); return closestStreet; } } @SuppressWarnings("unchecked") public Collection<Vertex> getVerticesForEnvelope(Envelope envelope) { return intersectionTree.query(envelope); } @Override @SuppressWarnings("unchecked") public CandidateEdgeBundle getClosestEdges(LocationObservation location, TraversalRequirements reqs, List<Edge> extraEdges, Collection<Edge> preferredEdges, boolean possibleTransitLinksOnly) { Coordinate coordinate = location.getCoordinate(); Envelope envelope = new Envelope(coordinate); // Collect the extra StreetEdges to consider. Iterable<StreetEdge> extraStreets = IterableLibrary.filter(graph.getTemporaryEdges(), StreetEdge.class); if (extraEdges != null) { extraStreets = Iterables.concat(IterableLibrary.filter(extraEdges, StreetEdge.class), extraStreets); } double envelopeGrowthAmount = 0.001; // ~= 100 meters double radius = 0; CandidateEdgeBundle candidateEdges = new CandidateEdgeBundle(); while (candidateEdges.size() == 0) { // expand envelope -- assumes many close searches and occasional far ones envelope.expandBy(envelopeGrowthAmount); radius += envelopeGrowthAmount; if (radius > MAX_DISTANCE_FROM_STREET) { return candidateEdges; // empty list } Iterable<StreetEdge> nearbyEdges = edgeTree.query(envelope); if (nearbyEdges != null) { nearbyEdges = Iterables.concat(nearbyEdges, extraStreets); } // oh. This is part of the problem: we're not linking to one-way // streets, even though that is a perfectly reasonable thing to do. // we need to handle that using bundles. for (StreetEdge e : nearbyEdges) { // Ignore invalid edges. if (e == null || e.getFromVertex() == null) { continue; } // Ignore those edges we can't traverse if (!reqs.canBeTraversed(e)) { // NOTE(flamholz): canBeTraversed checks internally if we // can walk our bike on this StreetEdge. continue; } // Compute preference value double preferrence = 1; if (preferredEdges != null && preferredEdges.contains(e)) { preferrence = 3.0; } TraverseModeSet modes = reqs.getModes(); CandidateEdge ce = new CandidateEdge(e, location, preferrence, modes); // Even if an edge is outside the query envelope, bounding boxes can // still intersect. In this case, distance to the edge is greater // than the query envelope size. if (ce.getDistance() < radius) { candidateEdges.add(ce); } } } Collection<CandidateEdgeBundle> bundles = candidateEdges.binByDistanceAndAngle(); // initially set best bundle to the closest bundle CandidateEdgeBundle best = null; for (CandidateEdgeBundle bundle : bundles) { if (best == null || bundle.best.score < best.best.score) { if (possibleTransitLinksOnly) { if (!(bundle.allowsCars() || bundle.isPlatform())) continue; } best = bundle; } } return best; } @Override public CandidateEdgeBundle getClosestEdges(LocationObservation location, TraversalRequirements reqs) { return getClosestEdges(location, reqs, null, null, false); } /** * Find edges closest to the given location. * * @param coordinate Point to get edges near * @param request RoutingRequest that must be able to traverse the edge (all edges if null) * @param extraEdges Any edges not in the graph that might be included (allows trips within one block) * @param preferredEdges Any edges to prefer in the search * @param possibleTransitLinksOnly only return edges traversable by cars or are platforms * @return */ public CandidateEdgeBundle getClosestEdges(Coordinate coordinate, RoutingRequest request, List<Edge> extraEdges, Collection<Edge> preferredEdges, boolean possibleTransitLinksOnly) { // Make a LocationObservation from a coordinate. LocationObservation loc = new LocationObservation(coordinate); // NOTE(flamholz): if request is null, will initialize TraversalRequirements // that accept all modes of travel. TraversalRequirements reqs = new TraversalRequirements(request); return getClosestEdges(loc, reqs, extraEdges, preferredEdges, possibleTransitLinksOnly); } public StreetVertex getIntersectionAt(Coordinate coordinate) { return getIntersectionAt(coordinate, MAX_CORNER_DISTANCE); } @SuppressWarnings("unchecked") public StreetVertex getIntersectionAt(Coordinate coordinate, double distanceError) { Envelope envelope = new Envelope(coordinate); envelope.expandBy(distanceError * 2); List<StreetVertex> nearby = intersectionTree.query(envelope); StreetVertex nearest = null; double bestDistance = Double.POSITIVE_INFINITY; for (StreetVertex v : nearby) { double distance = coordinate.distance(v.getCoordinate()); if (distance < distanceError) { if (distance < bestDistance) { bestDistance = distance; nearest = v; } } } return nearest; } @Override /** radius is meters */ public List<TransitStop> getNearbyTransitStops(Coordinate coordinate, double radius) { Envelope envelope = new Envelope(coordinate); envelope.expandBy(SphericalDistanceLibrary.metersToDegrees(radius)); List<?> stops = transitStopTree.query(envelope); ArrayList<TransitStop> out = new ArrayList<TransitStop>(); for (Object o : stops) { TransitStop stop = (TransitStop) o; if (distanceLibrary.distance(stop.getCoordinate(), coordinate) < radius) { out.add(stop); } } return out; } @Override /** radius is meters */ public List<TransitStop> getNearbyTransitStops(Coordinate coordinateOne, Coordinate coordinateTwo) { Envelope envelope = new Envelope(coordinateOne, coordinateTwo); List<?> stops = transitStopTree.query(envelope); ArrayList<TransitStop> out = new ArrayList<TransitStop>(); for (Object o : stops) { TransitStop stop = (TransitStop) o; out.add(stop); } return out; } /* EX-GENERICPATHSERVICE */ private static final String _doublePattern = "-{0,1}\\d+(\\.\\d+){0,1}"; private static final Pattern _latLonPattern = Pattern.compile("^\\s*(" + _doublePattern + ")(\\s*,\\s*|\\s+)(" + _doublePattern + ")\\s*$"); @Override public Vertex getVertexForPlace(NamedPlace place, RoutingRequest options) { return getVertexForPlace(place, options, null); } @Override public Vertex getVertexForPlace(NamedPlace place, RoutingRequest options, Vertex other) { if (place == null || place.place == null) { return null; } Matcher matcher = _latLonPattern.matcher(place.place); if (matcher.matches()) { double lat = Double.parseDouble(matcher.group(1)); double lon = Double.parseDouble(matcher.group(4)); Coordinate location = new Coordinate(lon, lat); if (other instanceof StreetLocation) { return getClosestVertex(location, place.name, options, ((StreetLocation) other).getExtra()); } else { return getClosestVertex(location, place.name, options); } } // did not match lat/lon, interpret place as a vertex label. // this should probably only be used in tests. return graph.getVertex(place.place); } @Override public boolean isAccessible(NamedPlace place, RoutingRequest options) { /* fixme: take into account slope for wheelchair accessibility */ Vertex vertex = getVertexForPlace(place, options); if (vertex instanceof TransitStop) { TransitStop ts = (TransitStop) vertex; return ts.hasWheelchairEntrance(); } else if (vertex instanceof StreetLocation) { StreetLocation sl = (StreetLocation) vertex; return sl.isWheelchairAccessible(); } return true; } }
false
true
public Vertex getClosestVertex(final Coordinate coordinate, String name, RoutingRequest options, List<Edge> extraEdges) { _log.debug("Looking for/making a vertex near {}", coordinate); // first, check for intersections very close by StreetVertex intersection = getIntersectionAt(coordinate, MAX_CORNER_DISTANCE); if (intersection != null) { // coordinate is at a street corner or endpoint if (name == null) { // generate names for corners when no name was given Set<String> uniqueNameSet = new HashSet<String>(); for (Edge e : intersection.getOutgoing()) { if (e instanceof StreetEdge) { uniqueNameSet.add(e.getName()); } } List<String> uniqueNames = new ArrayList<String>(uniqueNameSet); Locale locale; if (options == null) { locale = new Locale("en"); } else { locale = options.getLocale(); } ResourceBundle resources = ResourceBundle.getBundle("internals", locale); String fmt = resources.getString("corner"); if (uniqueNames.size() > 1) { name = String.format(fmt, uniqueNames.get(0), uniqueNames.get(1)); } else if (uniqueNames.size() == 1) { name = uniqueNames.get(0); } else { name = resources.getString("unnamedStreet"); } } StreetLocation closest = new StreetLocation(graph, "corner " + Math.random(), coordinate, name); FreeEdge e = new FreeEdge(closest, intersection); closest.getExtra().add(e); e = new FreeEdge(intersection, closest); closest.getExtra().add(e); return closest; } // if no intersection vertices were found, then find the closest transit stop // (we can return stops here because this method is not used when street-transit linking) double closest_stop_distance = Double.POSITIVE_INFINITY; Vertex closest_stop = null; // elsewhere options=null means no restrictions, find anything. // here we skip examining stops, as they are really only relevant when transit is being used if (options != null && options.getModes().isTransit()) { for (Vertex v : getLocalTransitStops(coordinate, 1000)) { double d = distanceLibrary.distance(v.getCoordinate(), coordinate); if (d < closest_stop_distance) { closest_stop_distance = d; closest_stop = v; } } } _log.debug(" best stop: {} distance: {}", closest_stop, closest_stop_distance); // then find closest walkable street StreetLocation closestStreet = null; CandidateEdgeBundle bundle = getClosestEdges(coordinate, options, extraEdges, null, false); CandidateEdge candidate = bundle.best; double closestStreetDistance = Double.POSITIVE_INFINITY; if (candidate != null) { StreetEdge bestStreet = candidate.edge; Coordinate nearestPoint = candidate.nearestPointOnEdge; closestStreetDistance = candidate.getDistance(); _log.debug("best street: {} dist: {}", bestStreet.toString(), closestStreetDistance); if (name == null) { name = bestStreet.getName(); } String closestName = String .format("%s_%s", bestStreet.getName(), coordinate.toString()); closestStreet = StreetLocation.createStreetLocation( graph, closestName, name, bundle.toEdgeList(), nearestPoint, coordinate); } // decide whether to return street, or street + stop if (closestStreet == null) { // no street found, return closest stop or null _log.debug("returning only transit stop (no street found)"); return closest_stop; // which will be null if none was found } else { // street found if (closest_stop != null) { // both street and stop found double relativeStopDistance = closest_stop_distance / closestStreetDistance; if (relativeStopDistance < 1.5) { _log.debug("linking transit stop to street (distances are comparable)"); closestStreet.addExtraEdgeTo(closest_stop); } } _log.debug("returning split street"); return closestStreet; } }
public Vertex getClosestVertex(final Coordinate coordinate, String name, RoutingRequest options, List<Edge> extraEdges) { _log.debug("Looking for/making a vertex near {}", coordinate); // first, check for intersections very close by StreetVertex intersection = getIntersectionAt(coordinate, MAX_CORNER_DISTANCE); if (intersection != null) { // coordinate is at a street corner or endpoint if (name == null) { // generate names for corners when no name was given Set<String> uniqueNameSet = new HashSet<String>(); for (Edge e : intersection.getOutgoing()) { if (e instanceof StreetEdge) { uniqueNameSet.add(e.getName()); } } List<String> uniqueNames = new ArrayList<String>(uniqueNameSet); Locale locale; if (options == null) { locale = new Locale("en"); } else { locale = options.getLocale(); } ResourceBundle resources = ResourceBundle.getBundle("internals", locale); String fmt = resources.getString("corner"); if (uniqueNames.size() > 1) { name = String.format(fmt, uniqueNames.get(0), uniqueNames.get(1)); } else if (uniqueNames.size() == 1) { name = uniqueNames.get(0); } else { name = resources.getString("unnamedStreet"); } } StreetLocation closest = new StreetLocation(graph, "corner " + Math.random(), coordinate, name); FreeEdge e = new FreeEdge(closest, intersection); closest.getExtra().add(e); e = new FreeEdge(intersection, closest); closest.getExtra().add(e); return closest; } // if no intersection vertices were found, then find the closest transit stop // (we can return stops here because this method is not used when street-transit linking) double closestStopDistance = Double.POSITIVE_INFINITY; Vertex closestStop = null; // elsewhere options=null means no restrictions, find anything. // here we skip examining stops, as they are really only relevant when transit is being used if (options != null && options.getModes().isTransit()) { for (Vertex v : getLocalTransitStops(coordinate, 1000)) { double d = distanceLibrary.distance(v.getCoordinate(), coordinate); if (d < closestStopDistance) { closestStopDistance = d; closestStop = v; } } } _log.debug(" best stop: {} distance: {}", closestStop, closestStopDistance); // then find closest walkable street StreetLocation closestStreet = null; CandidateEdgeBundle bundle = getClosestEdges(coordinate, options, extraEdges, null, false); CandidateEdge candidate = bundle.best; double closestStreetDistance = Double.POSITIVE_INFINITY; if (candidate != null) { StreetEdge bestStreet = candidate.edge; Coordinate nearestPoint = candidate.nearestPointOnEdge; closestStreetDistance = distanceLibrary.distance(coordinate, nearestPoint); _log.debug("best street: {} dist: {}", bestStreet.toString(), closestStreetDistance); if (name == null) { name = bestStreet.getName(); } String closestName = String .format("%s_%s", bestStreet.getName(), coordinate.toString()); closestStreet = StreetLocation.createStreetLocation( graph, closestName, name, bundle.toEdgeList(), nearestPoint, coordinate); } // decide whether to return street, or street + stop if (closestStreet == null) { // no street found, return closest stop or null _log.debug("returning only transit stop (no street found)"); return closestStop; // which will be null if none was found } else { // street found if (closestStop != null) { // both street and stop found double relativeStopDistance = closestStopDistance / closestStreetDistance; if (relativeStopDistance < 1.5) { _log.debug("linking transit stop to street (distances are comparable)"); closestStreet.addExtraEdgeTo(closestStop); } } _log.debug("returning split street"); return closestStreet; } }
diff --git a/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java b/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java index 0b7272b..c554bb1 100644 --- a/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java +++ b/plugins/reportal/src/azkaban/viewer/reportal/ReportalServlet.java @@ -1,1112 +1,1113 @@ /* * Copyright 2012 LinkedIn Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package azkaban.viewer.reportal; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.math.NumberUtils; import org.apache.log4j.Logger; import org.apache.velocity.tools.generic.EscapeTool; import org.joda.time.DateTime; import azkaban.executor.ExecutableFlow; import azkaban.executor.ExecutableNode; import azkaban.executor.ExecutionOptions; import azkaban.executor.ExecutorManagerAdapter; import azkaban.executor.ExecutorManagerException; import azkaban.flow.Flow; import azkaban.project.Project; import azkaban.project.ProjectManager; import azkaban.project.ProjectManagerException; import azkaban.reportal.util.IStreamProvider; import azkaban.reportal.util.Reportal; import azkaban.reportal.util.Reportal.Query; import azkaban.reportal.util.Reportal.Variable; import azkaban.reportal.util.ReportalHelper; import azkaban.reportal.util.ReportalUtil; import azkaban.reportal.util.StreamProviderHDFS; import azkaban.scheduler.ScheduleManager; import azkaban.scheduler.ScheduleManagerException; import azkaban.security.commons.HadoopSecurityManager; import azkaban.user.Permission.Type; import azkaban.user.User; import azkaban.user.UserManager; import azkaban.utils.FileIOUtils.LogData; import azkaban.utils.Props; import azkaban.webapp.AzkabanWebServer; import azkaban.webapp.servlet.LoginAbstractAzkabanServlet; import azkaban.webapp.servlet.Page; import azkaban.webapp.session.Session; public class ReportalServlet extends LoginAbstractAzkabanServlet { private static final String REPORTAL_VARIABLE_PREFIX = "reportal.variable."; private static final String HADOOP_SECURITY_MANAGER_CLASS_PARAM = "hadoop.security.manager.class"; private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(ReportalServlet.class); private CleanerThread cleanerThread; private File reportalMailDirectory; private AzkabanWebServer server; private Props props; private boolean shouldProxy; private String viewerName; private String reportalStorageUser; private File webResourcesFolder; private int itemsPerPage = 20; private boolean showNav; // private String viewerPath; private HadoopSecurityManager hadoopSecurityManager; public ReportalServlet(Props props) { this.props = props; viewerName = props.getString("viewer.name"); reportalStorageUser = props.getString("reportal.storage.user", "reportal"); itemsPerPage = props.getInt("reportal.items_per_page", 20); showNav = props.getBoolean("reportal.show.navigation", false); reportalMailDirectory = new File(props.getString("reportal.mail.temp.directory", "/tmp/reportal")); reportalMailDirectory.mkdirs(); ReportalMailCreator.reportalMailDirectory = reportalMailDirectory; ReportalMailCreator.outputLocation = props.getString("reportal.output.location", "/tmp/reportal"); ReportalMailCreator.outputFileSystem = props.getString("reportal.output.filesystem", "local"); ReportalMailCreator.reportalStorageUser = reportalStorageUser; webResourcesFolder = new File(new File(props.getSource()).getParentFile().getParentFile(), "web"); webResourcesFolder.mkdirs(); setResourceDirectory(webResourcesFolder); System.out.println("Reportal web resources: " + webResourcesFolder.getAbsolutePath()); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); server = (AzkabanWebServer)getApplication(); ReportalMailCreator.azkaban = server; shouldProxy = props.getBoolean("azkaban.should.proxy", false); logger.info("Hdfs browser should proxy: " + shouldProxy); try { hadoopSecurityManager = loadHadoopSecurityManager(props, logger); ReportalMailCreator.hadoopSecurityManager = hadoopSecurityManager; } catch (RuntimeException e) { e.printStackTrace(); throw new RuntimeException("Failed to get hadoop security manager!" + e.getCause()); } cleanerThread = new CleanerThread(); cleanerThread.start(); } private HadoopSecurityManager loadHadoopSecurityManager(Props props, Logger logger) throws RuntimeException { Class<?> hadoopSecurityManagerClass = props.getClass(HADOOP_SECURITY_MANAGER_CLASS_PARAM, true, ReportalServlet.class.getClassLoader()); logger.info("Initializing hadoop security manager " + hadoopSecurityManagerClass.getName()); HadoopSecurityManager hadoopSecurityManager = null; try { Method getInstanceMethod = hadoopSecurityManagerClass.getMethod("getInstance", Props.class); hadoopSecurityManager = (HadoopSecurityManager)getInstanceMethod.invoke(hadoopSecurityManagerClass, props); } catch (InvocationTargetException e) { logger.error("Could not instantiate Hadoop Security Manager " + hadoopSecurityManagerClass.getName() + e.getCause()); throw new RuntimeException(e.getCause()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getCause()); } return hadoopSecurityManager; } @Override protected void handleGet(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { if (hasParam(req, "ajax")) { handleAJAXAction(req, resp, session); } else { if (hasParam(req, "view")) { try { handleViewReportal(req, resp, session); } catch (Exception e) { e.printStackTrace(); } } else if (hasParam(req, "new")) { handleNewReportal(req, resp, session); } else if (hasParam(req, "edit")) { handleEditReportal(req, resp, session); } else if (hasParam(req, "run")) { handleRunReportal(req, resp, session); } else { handleListReportal(req, resp, session); } } } private void handleAJAXAction(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { HashMap<String, Object> ret = new HashMap<String, Object>(); String ajaxName = getParam(req, "ajax"); User user = session.getUser(); int id = getIntParam(req, "id"); ProjectManager projectManager = server.getProjectManager(); Project project = projectManager.getProject(id); Reportal reportal = Reportal.loadFromProject(project); // Delete reportal if (ajaxName.equals("delete")) { if (!project.hasPermission(user, Type.ADMIN)) { ret.put("error", "You do not have permissions to delete this reportal."); } else { try { ScheduleManager scheduleManager = server.getScheduleManager(); reportal.removeSchedules(scheduleManager); projectManager.removeProject(project, user); } catch (Exception e) { e.printStackTrace(); ret.put("error", "An exception occured while deleting this reportal."); } ret.put("result", "success"); } } // Bookmark reportal else if (ajaxName.equals("bookmark")) { boolean wasBookmarked = ReportalHelper.isBookmarkProject(project, user); try { if (wasBookmarked) { ReportalHelper.unBookmarkProject(server, project, user); ret.put("result", "success"); ret.put("bookmark", false); } else { ReportalHelper.bookmarkProject(server, project, user); ret.put("result", "success"); ret.put("bookmark", true); } } catch (ProjectManagerException e) { e.printStackTrace(); ret.put("error", "Error bookmarking reportal. " + e.getMessage()); } } // Subscribe reportal else if (ajaxName.equals("subscribe")) { boolean wasSubscribed = ReportalHelper.isSubscribeProject(project, user); if (!wasSubscribed && reportal.getAccessViewers().size() > 0 && !project.hasPermission(user, Type.READ)) { ret.put("error", "You do not have permissions to view this reportal."); } else { try { if (wasSubscribed) { ReportalHelper.unSubscribeProject(server, project, user); ret.put("result", "success"); ret.put("subscribe", false); } else { ReportalHelper.subscribeProject(server, project, user, user.getEmail()); ret.put("result", "success"); ret.put("subscribe", true); } } catch (ProjectManagerException e) { e.printStackTrace(); ret.put("error", "Error subscribing to reportal. " + e.getMessage()); } } } // Get a portion of logs else if (ajaxName.equals("log")) { int execId = getIntParam(req, "execId"); String jobId = getParam(req, "jobId"); int offset = getIntParam(req, "offset"); int length = getIntParam(req, "length"); ExecutableFlow exec; ExecutorManagerAdapter executorManager = server.getExecutorManager(); try { exec = executorManager.getExecutableFlow(execId); } catch (Exception e) { ret.put("error", "Log does not exist or isn't created yet."); return; } LogData data; try { data = executorManager.getExecutionJobLog(exec, jobId, offset, length, exec.getExecutableNode(jobId).getAttempt()); } catch (Exception e) { e.printStackTrace(); ret.put("error", "Log does not exist or isn't created yet."); return; } if (data != null) { ret.put("result", "success"); ret.put("log", data.getData()); ret.put("offset", data.getOffset()); ret.put("length", data.getLength()); ret.put("completed", exec.getEndTime() != -1); } else { // Return an empty result to indicate the end ret.put("result", "success"); ret.put("log", ""); ret.put("offset", offset); ret.put("length", 0); ret.put("completed", exec.getEndTime() != -1); } } if (ret != null) { this.writeJSON(resp, ret); } } private void handleListReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportallistpage.vm"); preparePage(page, session); List<Project> projects = ReportalHelper.getReportalProjects(server); page.add("ReportalHelper", ReportalHelper.class); page.add("esc", new EscapeTool()); page.add("user", session.getUser()); String startDate = DateTime.now().minusWeeks(1).toString("yyyy-MM-dd"); String endDate = DateTime.now().toString("yyyy-MM-dd"); page.add("startDate", startDate); page.add("endDate", endDate); if (!projects.isEmpty()) { page.add("projects", projects); } else { page.add("projects", false); } page.render(); } private void handleViewReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, Exception { int id = getIntParam(req, "id"); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaldatapage.vm"); preparePage(page, session); ProjectManager projectManager = server.getProjectManager(); ExecutorManagerAdapter executorManager = server.getExecutorManager(); Project project = projectManager.getProject(id); Reportal reportal = Reportal.loadFromProject(project); if (reportal == null) { page.add("errorMsg", "Report not found."); page.render(); return; } if (reportal.getAccessViewers().size() > 0 && !project.hasPermission(session.getUser(), Type.READ)) { page.add("errorMsg", "You are not allowed to view this report."); page.render(); return; } page.add("project", project); page.add("title", project.getMetadata().get("title")); if (hasParam(req, "execid")) { int execId = getIntParam(req, "execid"); page.add("execid", execId); // Show logs if (hasParam(req, "logs")) { ExecutableFlow exec; try { exec = executorManager.getExecutableFlow(execId); } catch (ExecutorManagerException e) { e.printStackTrace(); page.add("errorMsg", "ExecutableFlow not found. " + e.getMessage()); page.render(); return; } // View single log if (hasParam(req, "log")) { page.add("view-log", true); String jobId = getParam(req, "log"); page.add("execid", execId); page.add("jobId", jobId); } // List files else { page.add("view-logs", true); List<ExecutableNode> jobLogs = ReportalUtil.sortExecutableNodes(exec); boolean showDataCollector = hasParam(req, "debug"); if (!showDataCollector) { jobLogs.remove(jobLogs.size() - 1); } if (jobLogs.size() == 1) { resp.sendRedirect("/reportal?view&logs&id=" + project.getId() + "&execid=" + execId + "&log=" + jobLogs.get(0).getId()); } page.add("logs", jobLogs); } } // Show data files else { String outputFileSystem = props.getString("reportal.output.filesystem", "local"); String outputBase = props.getString("reportal.output.location", "/tmp/reportal"); String locationFull = (outputBase + "/" + execId).replace("//", "/"); IStreamProvider streamProvider = ReportalUtil.getStreamProvider(outputFileSystem); if (streamProvider instanceof StreamProviderHDFS) { StreamProviderHDFS hdfsStreamProvider = (StreamProviderHDFS)streamProvider; hdfsStreamProvider.setHadoopSecurityManager(hadoopSecurityManager); hdfsStreamProvider.setUser(reportalStorageUser); } try { if (hasParam(req, "download")) { String fileName = getParam(req, "download"); String filePath = locationFull + "/" + fileName; InputStream csvInputStream = null; OutputStream out = null; try { csvInputStream = streamProvider.getFileInputStream(filePath); resp.setContentType("application/octet-stream"); out = resp.getOutputStream(); IOUtils.copy(csvInputStream, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(csvInputStream); } return; } // Show file previews else { page.add("view-preview", true); try { String[] fileList = streamProvider.getFileList(locationFull); fileList = ReportalHelper.filterCSVFile(fileList); Arrays.sort(fileList); List<Object> files = getFilePreviews(fileList, locationFull, streamProvider); page.add("files", files); } catch (Exception e) { logger.debug("Error encountered while processing files in " + locationFull, e); } } } finally { streamProvider.cleanUp(); } } } // List executions and their data else { page.add("view-executions", true); ArrayList<ExecutableFlow> exFlows = new ArrayList<ExecutableFlow>(); int pageNumber = 0; boolean hasNextPage = false; if (hasParam(req, "page")) { pageNumber = getIntParam(req, "page") - 1; } if (pageNumber < 0) { pageNumber = 0; } try { Flow flow = project.getFlows().get(0); executorManager.getExecutableFlows(project.getId(), flow.getId(), pageNumber * itemsPerPage, itemsPerPage, exFlows); ArrayList<ExecutableFlow> tmp = new ArrayList<ExecutableFlow>(); executorManager.getExecutableFlows(project.getId(), flow.getId(), (pageNumber + 1) * itemsPerPage, 1, tmp); if (!tmp.isEmpty()) { hasNextPage = true; } } catch (ExecutorManagerException e) { page.add("error", "Error retrieving executable flows"); } if (!exFlows.isEmpty()) { ArrayList<Object> history = new ArrayList<Object>(); for (ExecutableFlow exFlow: exFlows) { HashMap<String, Object> flowInfo = new HashMap<String, Object>(); flowInfo.put("execId", exFlow.getExecutionId()); flowInfo.put("status", exFlow.getStatus().toString()); flowInfo.put("startTime", exFlow.getStartTime()); history.add(flowInfo); } page.add("executions", history); } if (pageNumber > 0) { page.add("pagePrev", pageNumber); } page.add("page", pageNumber + 1); if (hasNextPage) { page.add("pageNext", pageNumber + 2); } } page.render(); } /** * Returns a list of file Objects that contain a "name" property with the file name, * a "content" property with the lines in the file, and a "hasMore" property if the * file contains more than NUM_PREVIEW_ROWS lines. * @param fileList * @param locationFull * @param streamProvider * @return */ private List<Object> getFilePreviews(String[] fileList, String locationFull, IStreamProvider streamProvider) { List<Object> files = new ArrayList<Object>(); try { for (String fileName : fileList) { Map<String, Object> file = new HashMap<String, Object>(); file.put("name", fileName); String filePath = locationFull + "/" + fileName; InputStream csvInputStream = streamProvider.getFileInputStream(filePath); Scanner rowScanner = new Scanner(csvInputStream); List<Object> lines = new ArrayList<Object>(); int lineNumber = 0; while (rowScanner.hasNextLine() && lineNumber < ReportalMailCreator.NUM_PREVIEW_ROWS) { String csvLine = rowScanner.nextLine(); String[] data = csvLine.split("\",\""); List<String> line = new ArrayList<String>(); for (String item: data) { String column = StringEscapeUtils.escapeHtml(item.replace("\"", "")); line.add(column); } lines.add(line); lineNumber++; } file.put("content", lines); if (rowScanner.hasNextLine()) { file.put("hasMore", true); } rowScanner.close(); files.add(file); } } catch (Exception e) { logger.debug("Error encountered while processing files in " + locationFull, e); } return files; } private void handleRunReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { int id = getIntParam(req, "id"); ProjectManager projectManager = server.getProjectManager(); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportalrunpage.vm"); preparePage(page, session); Project project = projectManager.getProject(id); Reportal reportal = Reportal.loadFromProject(project); if (reportal == null) { page.add("errorMsg", "Report not found"); page.render(); return; } if (reportal.getAccessExecutors().size() > 0 && !project.hasPermission(session.getUser(), Type.EXECUTE)) { page.add("errorMsg", "You are not allowed to run this report."); page.render(); return; } page.add("projectId", id); page.add("title", reportal.title); page.add("description", reportal.description); if (reportal.variables.size() > 0) { page.add("variableNumber", reportal.variables.size()); page.add("variables", reportal.variables); } page.render(); } private void handleNewReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm"); preparePage(page, session); page.add("title", ""); page.add("description", ""); page.add("queryNumber", 1); List<Map<String, Object>> queryList = new ArrayList<Map<String, Object>>(); page.add("queries", queryList); Map<String, Object> query = new HashMap<String, Object>(); queryList.add(query); query.put("title", ""); query.put("type", ""); query.put("script", ""); page.add("accessViewer", ""); page.add("accessExecutor", ""); page.add("accessOwner", ""); page.add("notifications", ""); page.add("failureNotifications", ""); page.render(); } private void handleEditReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { int id = getIntParam(req, "id"); ProjectManager projectManager = server.getProjectManager(); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm"); preparePage(page, session); page.add("ReportalHelper", ReportalHelper.class); page.add("esc", new EscapeTool()); Project project = projectManager.getProject(id); Reportal reportal = Reportal.loadFromProject(project); if (reportal == null) { page.add("errorMsg", "Report not found"); page.render(); return; } if (!project.hasPermission(session.getUser(), Type.ADMIN)) { page.add("errorMsg", "You are not allowed to edit this report."); page.render(); return; } page.add("projectId", id); page.add("title", reportal.title); page.add("description", reportal.description); page.add("queryNumber", reportal.queries.size()); page.add("queries", reportal.queries); page.add("variableNumber", reportal.variables.size()); page.add("variables", reportal.variables); page.add("schedule", reportal.schedule); page.add("scheduleHour", reportal.scheduleHour); page.add("scheduleMinute", reportal.scheduleMinute); page.add("scheduleAmPm", reportal.scheduleAmPm); page.add("scheduleTimeZone", reportal.scheduleTimeZone); page.add("scheduleDate", reportal.scheduleDate); page.add("scheduleRepeat", reportal.scheduleRepeat); page.add("scheduleIntervalQuantity", reportal.scheduleIntervalQuantity); page.add("scheduleInterval", reportal.scheduleInterval); page.add("notifications", reportal.notifications); page.add("failureNotifications", reportal.failureNotifications); page.add("accessViewer", reportal.accessViewer); page.add("accessExecutor", reportal.accessExecutor); page.add("accessOwner", reportal.accessOwner); page.render(); } @Override protected void handlePost(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { if (hasParam(req, "ajax")) { HashMap<String, Object> ret = new HashMap<String, Object>(); handleRunReportalWithVariables(req, ret, session); if (ret != null) { this.writeJSON(resp, ret); } } else { handleSaveReportal(req, resp, session); } } private void handleSaveReportal(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { String projectId = validateAndSaveReport(req, resp, session); if (projectId != null) { this.setSuccessMessageInCookie(resp, "Report Saved."); String submitType = getParam(req, "submit"); if (submitType.equals("Save")) { resp.sendRedirect(req.getRequestURI() + "?edit&id=" + projectId); } else { resp.sendRedirect(req.getRequestURI() + "?run&id=" + projectId); } } } /** * Validates and saves a report, returning the project id of the saved report if successful, and null otherwise. * @param req * @param resp * @param session * @return The project id of the saved report if successful, and null otherwise * @throws ServletException * @throws IOException */ private String validateAndSaveReport(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { ProjectManager projectManager = server.getProjectManager(); User user = session.getUser(); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm"); preparePage(page, session); page.add("ReportalHelper", ReportalHelper.class); page.add("esc", new EscapeTool()); boolean isEdit = hasParam(req, "id"); if (isEdit) { page.add("projectId", getIntParam(req, "id")); } Project project = null; Reportal report = new Reportal(); report.title = getParam(req, "title"); report.description = getParam(req, "description"); page.add("title", report.title); page.add("description", report.description); report.schedule = hasParam(req, "schedule"); report.scheduleHour = getParam(req, "schedule-hour"); report.scheduleMinute = getParam(req, "schedule-minute"); report.scheduleAmPm = getParam(req, "schedule-am_pm"); report.scheduleTimeZone = getParam(req, "schedule-timezone"); report.scheduleDate = getParam(req, "schedule-date"); report.scheduleRepeat = hasParam(req, "schedule-repeat"); report.scheduleIntervalQuantity = getParam(req, "schedule-interval-quantity"); report.scheduleInterval = getParam(req, "schedule-interval"); page.add("schedule", report.schedule); page.add("scheduleHour", report.scheduleHour); page.add("scheduleMinute", report.scheduleMinute); page.add("scheduleAmPm", report.scheduleAmPm); page.add("scheduleTimeZone", report.scheduleTimeZone); page.add("scheduleDate", report.scheduleDate); page.add("scheduleRepeat", report.scheduleRepeat); page.add("scheduleIntervalQuantity", report.scheduleIntervalQuantity); page.add("scheduleInterval", report.scheduleInterval); report.accessViewer = getParam(req, "access-viewer"); report.accessExecutor = getParam(req, "access-executor"); report.accessOwner = getParam(req, "access-owner"); page.add("accessViewer", report.accessViewer); page.add("accessExecutor", report.accessExecutor); page.add("accessOwner", report.accessOwner); report.notifications = getParam(req, "notifications"); report.failureNotifications = getParam(req, "failure-notifications"); page.add("notifications", report.notifications); page.add("failureNotifications", report.failureNotifications); int numQueries = getIntParam(req, "queryNumber"); page.add("queryNumber", numQueries); List<Query> queryList = new ArrayList<Query>(numQueries); page.add("queries", queryList); report.queries = queryList; String typeError = null; String typePermissionError = null; for (int i = 0; i < numQueries; i++) { Query query = new Query(); query.title = getParam(req, "query" + i + "title"); query.type = getParam(req, "query" + i + "type"); query.script = getParam(req, "query" + i + "script"); // Type check ReportalType type = ReportalType.getTypeByName(query.type); if (type == null && typeError == null) { typeError = query.type; } if (!type.checkPermission(user)) { typePermissionError = query.type; } queryList.add(query); } int variables = getIntParam(req, "variableNumber"); page.add("variableNumber", variables); List<Variable> variableList = new ArrayList<Variable>(variables); page.add("variables", variableList); report.variables = variableList; boolean variableErrorOccurred = false; for (int i = 0; i < variables; i++) { Variable variable = new Variable(); variable.title = getParam(req, "variable" + i + "title"); variable.name = getParam(req, "variable" + i + "name"); if (variable.title.isEmpty() || variable.name.isEmpty()) { variableErrorOccurred = true; } variableList.add(variable); } // Make sure title isn't empty if (report.title.isEmpty()) { page.add("errorMsg", "Title must not be empty."); page.render(); return null; } // Make sure description isn't empty if (report.description.isEmpty()) { page.add("errorMsg", "Description must not be empty."); page.render(); return null; } // Verify schedule and repeat if (report.schedule) { // Verify schedule time if (!NumberUtils.isDigits(report.scheduleHour) || !NumberUtils.isDigits(report.scheduleMinute)) { page.add("errorMsg", "Schedule time is invalid."); page.render(); return null; } // Verify schedule date is not empty if (report.scheduleDate.isEmpty()) { page.add("errorMsg", "Schedule date must not be empty."); page.render(); return null; } if (report.scheduleRepeat) { // Verify repeat interval if (!NumberUtils.isDigits(report.scheduleIntervalQuantity)) { page.add("errorMsg", "Repeat interval quantity is invalid."); page.render(); return null; } } } // Empty query check if (numQueries <= 0) { page.add("errorMsg", "There needs to have at least one query."); page.render(); return null; } // Type error check if (typeError != null) { page.add("errorMsg", "Type " + typeError + " is invalid."); page.render(); return null; } // Type permission check if (typePermissionError != null && report.schedule) { page.add("errorMsg", "You do not have permission to schedule Type " + typePermissionError + "."); page.render(); return null; } // Variable error check if (variableErrorOccurred) { page.add("errorMsg", "Variable title and name cannot be empty."); page.render(); return null; } // Validate access users - UserManager userManager = getApplication().getUserManager(); - String[] accessLists = new String[] { report.accessViewer, report.accessExecutor, report.accessOwner }; - for (String accessList : accessLists) { - if (!accessList.trim().isEmpty()) { - String[] users = accessList.trim().split(Reportal.ACCESS_LIST_SPLIT_REGEX); - for (String accessUser : users) { - if (!userManager.validateUser(accessUser)) { - page.add("errorMsg", "User " + accessUser + " in access list is invalid."); - page.render(); - return null; - } - } - } - } + UserManager userManager = getApplication().getUserManager(); + String[] accessLists = new String[] { report.accessViewer, report.accessExecutor, report.accessOwner }; + for (String accessList : accessLists) { + accessList = accessList == null ? null : accessList.trim(); + if (accessList != null && !accessList.isEmpty()) { + String[] users = accessList.split(Reportal.ACCESS_LIST_SPLIT_REGEX); + for (String accessUser : users) { + if (!userManager.validateUser(accessUser)) { + page.add("errorMsg", "User " + accessUser + " in access list is invalid."); + page.render(); + return null; + } + } + } + } // Attempt to get a project object if (isEdit) { // Editing mode, load project int projectId = getIntParam(req, "id"); project = projectManager.getProject(projectId); report.loadImmutableFromProject(project); } else { // Creation mode, create project try { project = ReportalHelper.createReportalProject(server, report.title, report.description, user); report.reportalUser = user.getUserId(); report.ownerEmail = user.getEmail(); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating report. " + e.getMessage()); page.render(); return null; } // Project already exists if (project == null) { page.add("errorMsg", "A Report with the same name already exists."); page.render(); return null; } } if (project == null) { page.add("errorMsg", "Internal Error: Report not found"); page.render(); return null; } report.project = project; page.add("projectId", project.getId()); report.updatePermissions(); try { report.createZipAndUpload(projectManager, user, reportalStorageUser); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating Azkaban jobs. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, user); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return null; } // Prepare flow Flow flow = project.getFlows().get(0); project.getMetadata().put("flowName", flow.getId()); // Set reportal mailer flow.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR); // Create/Save schedule ScheduleManager scheduleManager = server.getScheduleManager(); try { report.updateSchedules(report, scheduleManager, user, flow); } catch (ScheduleManagerException e2) { e2.printStackTrace(); page.add("errorMsg", e2.getMessage()); page.render(); return null; } report.saveToProject(project); try { ReportalHelper.updateProjectNotifications(project, projectManager); projectManager.updateProjectSetting(project); projectManager.updateProjectDescription(project, report.description, user); projectManager.updateFlow(project, flow); } catch (ProjectManagerException e) { e.printStackTrace(); page.add("errorMsg", "Error while updating report. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, user); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return null; } return Integer.toString(project.getId()); } private void handleRunReportalWithVariables(HttpServletRequest req, HashMap<String, Object> ret, Session session) throws ServletException, IOException { boolean isTestRun = hasParam(req, "testRun"); int id = getIntParam(req, "id"); ProjectManager projectManager = server.getProjectManager(); Project project = projectManager.getProject(id); Reportal report = Reportal.loadFromProject(project); User user = session.getUser(); if (report.getAccessExecutors().size() > 0 && !project.hasPermission(user, Type.EXECUTE)) { ret.put("error", "You are not allowed to run this report."); return; } for (Query query: report.queries) { String jobType = query.type; ReportalType type = ReportalType.getTypeByName(jobType); if (!type.checkPermission(user)) { ret.put("error", "You are not allowed to run this report as you don't have permission to run job type " + type.toString() + "."); return; } } Flow flow = project.getFlows().get(0); ExecutableFlow exflow = new ExecutableFlow(project, flow); exflow.setSubmitUser(user.getUserId()); exflow.addAllProxyUsers(project.getProxyUsers()); ExecutionOptions options = exflow.getExecutionOptions(); int i = 0; for (Variable variable: report.variables) { options.getFlowParameters().put(REPORTAL_VARIABLE_PREFIX + i + ".from", variable.name); options.getFlowParameters().put(REPORTAL_VARIABLE_PREFIX + i + ".to", getParam(req, "variable" + i)); i++; } options.getFlowParameters().put("reportal.execution.user", user.getUserId()); // Add the execution user's email to the list of success and failure emails. String email = user.getEmail(); if (email != null && !email.isEmpty()) { if (isTestRun) { // Only email the executor List<String> emails = new ArrayList<String>(); emails.add(email); options.setSuccessEmails(emails); options.setFailureEmails(emails); } else { options.getSuccessEmails().add(email); options.getFailureEmails().add(email); } } options.getFlowParameters().put("reportal.title", report.title); options.getFlowParameters().put("reportal.unscheduled.run", "true"); try { String message = server.getExecutorManager().submitExecutableFlow(exflow, session.getUser().getUserId()) + "."; ret.put("message", message); ret.put("result", "success"); ret.put("redirect", "/reportal?view&logs&id=" + project.getId() + "&execid=" + exflow.getExecutionId()); } catch (ExecutorManagerException e) { e.printStackTrace(); ret.put("error", "Error running report " + report.title + ". " + e.getMessage()); } } private void preparePage(Page page, Session session) { page.add("viewerName", viewerName); page.add("hideNavigation", !showNav); page.add("userid", session.getUser().getUserId()); } private class CleanerThread extends Thread { // Every day, clean Reportal execution output directory. private static final long EXECUTION_DIR_CLEAN_INTERVAL_MS = 24 * 60 * 60 * 1000; private boolean shutdown = false; // Retain executions for 14 days. private static final long EXECUTION_DIR_RETENTION = 14 * 24 * 60 * 60 * 1000; public CleanerThread() { this.setName("Reportal-Cleaner-Thread"); } @SuppressWarnings("unused") public void shutdown() { shutdown = true; this.interrupt(); } public void run() { while (!shutdown) { synchronized (this) { logger.info("Cleaning old execution dirs"); cleanOldReportalDirs(); } try { Thread.sleep(EXECUTION_DIR_CLEAN_INTERVAL_MS); } catch (InterruptedException e) { logger.error("CleanerThread's sleep was interrupted.", e); } } } private void cleanOldReportalDirs() { IStreamProvider streamProvider = ReportalUtil.getStreamProvider(ReportalMailCreator.outputFileSystem); if (streamProvider instanceof StreamProviderHDFS) { StreamProviderHDFS hdfsStreamProvider = (StreamProviderHDFS) streamProvider; hdfsStreamProvider.setHadoopSecurityManager(hadoopSecurityManager); hdfsStreamProvider.setUser(reportalStorageUser); } final long pastTimeThreshold = System.currentTimeMillis() - EXECUTION_DIR_RETENTION; String[] oldFiles = null; try { oldFiles = streamProvider.getOldFiles(ReportalMailCreator.outputLocation, pastTimeThreshold); } catch (Exception e) { logger.error("Error getting old files from " + ReportalMailCreator.outputLocation + " on " + ReportalMailCreator.outputFileSystem + " file system.", e); } if (oldFiles != null) { for (String file: oldFiles) { String filePath = ReportalMailCreator.outputLocation + "/" + file; try { streamProvider.deleteFile(filePath); } catch (Exception e) { logger.error("Error deleting file " + filePath + " from " + ReportalMailCreator.outputFileSystem + " file system.", e); } } } } } }
true
true
private String validateAndSaveReport(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { ProjectManager projectManager = server.getProjectManager(); User user = session.getUser(); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm"); preparePage(page, session); page.add("ReportalHelper", ReportalHelper.class); page.add("esc", new EscapeTool()); boolean isEdit = hasParam(req, "id"); if (isEdit) { page.add("projectId", getIntParam(req, "id")); } Project project = null; Reportal report = new Reportal(); report.title = getParam(req, "title"); report.description = getParam(req, "description"); page.add("title", report.title); page.add("description", report.description); report.schedule = hasParam(req, "schedule"); report.scheduleHour = getParam(req, "schedule-hour"); report.scheduleMinute = getParam(req, "schedule-minute"); report.scheduleAmPm = getParam(req, "schedule-am_pm"); report.scheduleTimeZone = getParam(req, "schedule-timezone"); report.scheduleDate = getParam(req, "schedule-date"); report.scheduleRepeat = hasParam(req, "schedule-repeat"); report.scheduleIntervalQuantity = getParam(req, "schedule-interval-quantity"); report.scheduleInterval = getParam(req, "schedule-interval"); page.add("schedule", report.schedule); page.add("scheduleHour", report.scheduleHour); page.add("scheduleMinute", report.scheduleMinute); page.add("scheduleAmPm", report.scheduleAmPm); page.add("scheduleTimeZone", report.scheduleTimeZone); page.add("scheduleDate", report.scheduleDate); page.add("scheduleRepeat", report.scheduleRepeat); page.add("scheduleIntervalQuantity", report.scheduleIntervalQuantity); page.add("scheduleInterval", report.scheduleInterval); report.accessViewer = getParam(req, "access-viewer"); report.accessExecutor = getParam(req, "access-executor"); report.accessOwner = getParam(req, "access-owner"); page.add("accessViewer", report.accessViewer); page.add("accessExecutor", report.accessExecutor); page.add("accessOwner", report.accessOwner); report.notifications = getParam(req, "notifications"); report.failureNotifications = getParam(req, "failure-notifications"); page.add("notifications", report.notifications); page.add("failureNotifications", report.failureNotifications); int numQueries = getIntParam(req, "queryNumber"); page.add("queryNumber", numQueries); List<Query> queryList = new ArrayList<Query>(numQueries); page.add("queries", queryList); report.queries = queryList; String typeError = null; String typePermissionError = null; for (int i = 0; i < numQueries; i++) { Query query = new Query(); query.title = getParam(req, "query" + i + "title"); query.type = getParam(req, "query" + i + "type"); query.script = getParam(req, "query" + i + "script"); // Type check ReportalType type = ReportalType.getTypeByName(query.type); if (type == null && typeError == null) { typeError = query.type; } if (!type.checkPermission(user)) { typePermissionError = query.type; } queryList.add(query); } int variables = getIntParam(req, "variableNumber"); page.add("variableNumber", variables); List<Variable> variableList = new ArrayList<Variable>(variables); page.add("variables", variableList); report.variables = variableList; boolean variableErrorOccurred = false; for (int i = 0; i < variables; i++) { Variable variable = new Variable(); variable.title = getParam(req, "variable" + i + "title"); variable.name = getParam(req, "variable" + i + "name"); if (variable.title.isEmpty() || variable.name.isEmpty()) { variableErrorOccurred = true; } variableList.add(variable); } // Make sure title isn't empty if (report.title.isEmpty()) { page.add("errorMsg", "Title must not be empty."); page.render(); return null; } // Make sure description isn't empty if (report.description.isEmpty()) { page.add("errorMsg", "Description must not be empty."); page.render(); return null; } // Verify schedule and repeat if (report.schedule) { // Verify schedule time if (!NumberUtils.isDigits(report.scheduleHour) || !NumberUtils.isDigits(report.scheduleMinute)) { page.add("errorMsg", "Schedule time is invalid."); page.render(); return null; } // Verify schedule date is not empty if (report.scheduleDate.isEmpty()) { page.add("errorMsg", "Schedule date must not be empty."); page.render(); return null; } if (report.scheduleRepeat) { // Verify repeat interval if (!NumberUtils.isDigits(report.scheduleIntervalQuantity)) { page.add("errorMsg", "Repeat interval quantity is invalid."); page.render(); return null; } } } // Empty query check if (numQueries <= 0) { page.add("errorMsg", "There needs to have at least one query."); page.render(); return null; } // Type error check if (typeError != null) { page.add("errorMsg", "Type " + typeError + " is invalid."); page.render(); return null; } // Type permission check if (typePermissionError != null && report.schedule) { page.add("errorMsg", "You do not have permission to schedule Type " + typePermissionError + "."); page.render(); return null; } // Variable error check if (variableErrorOccurred) { page.add("errorMsg", "Variable title and name cannot be empty."); page.render(); return null; } // Validate access users UserManager userManager = getApplication().getUserManager(); String[] accessLists = new String[] { report.accessViewer, report.accessExecutor, report.accessOwner }; for (String accessList : accessLists) { if (!accessList.trim().isEmpty()) { String[] users = accessList.trim().split(Reportal.ACCESS_LIST_SPLIT_REGEX); for (String accessUser : users) { if (!userManager.validateUser(accessUser)) { page.add("errorMsg", "User " + accessUser + " in access list is invalid."); page.render(); return null; } } } } // Attempt to get a project object if (isEdit) { // Editing mode, load project int projectId = getIntParam(req, "id"); project = projectManager.getProject(projectId); report.loadImmutableFromProject(project); } else { // Creation mode, create project try { project = ReportalHelper.createReportalProject(server, report.title, report.description, user); report.reportalUser = user.getUserId(); report.ownerEmail = user.getEmail(); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating report. " + e.getMessage()); page.render(); return null; } // Project already exists if (project == null) { page.add("errorMsg", "A Report with the same name already exists."); page.render(); return null; } } if (project == null) { page.add("errorMsg", "Internal Error: Report not found"); page.render(); return null; } report.project = project; page.add("projectId", project.getId()); report.updatePermissions(); try { report.createZipAndUpload(projectManager, user, reportalStorageUser); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating Azkaban jobs. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, user); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return null; } // Prepare flow Flow flow = project.getFlows().get(0); project.getMetadata().put("flowName", flow.getId()); // Set reportal mailer flow.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR); // Create/Save schedule ScheduleManager scheduleManager = server.getScheduleManager(); try { report.updateSchedules(report, scheduleManager, user, flow); } catch (ScheduleManagerException e2) { e2.printStackTrace(); page.add("errorMsg", e2.getMessage()); page.render(); return null; } report.saveToProject(project); try { ReportalHelper.updateProjectNotifications(project, projectManager); projectManager.updateProjectSetting(project); projectManager.updateProjectDescription(project, report.description, user); projectManager.updateFlow(project, flow); } catch (ProjectManagerException e) { e.printStackTrace(); page.add("errorMsg", "Error while updating report. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, user); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return null; } return Integer.toString(project.getId()); }
private String validateAndSaveReport(HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { ProjectManager projectManager = server.getProjectManager(); User user = session.getUser(); Page page = newPage(req, resp, session, "azkaban/viewer/reportal/reportaleditpage.vm"); preparePage(page, session); page.add("ReportalHelper", ReportalHelper.class); page.add("esc", new EscapeTool()); boolean isEdit = hasParam(req, "id"); if (isEdit) { page.add("projectId", getIntParam(req, "id")); } Project project = null; Reportal report = new Reportal(); report.title = getParam(req, "title"); report.description = getParam(req, "description"); page.add("title", report.title); page.add("description", report.description); report.schedule = hasParam(req, "schedule"); report.scheduleHour = getParam(req, "schedule-hour"); report.scheduleMinute = getParam(req, "schedule-minute"); report.scheduleAmPm = getParam(req, "schedule-am_pm"); report.scheduleTimeZone = getParam(req, "schedule-timezone"); report.scheduleDate = getParam(req, "schedule-date"); report.scheduleRepeat = hasParam(req, "schedule-repeat"); report.scheduleIntervalQuantity = getParam(req, "schedule-interval-quantity"); report.scheduleInterval = getParam(req, "schedule-interval"); page.add("schedule", report.schedule); page.add("scheduleHour", report.scheduleHour); page.add("scheduleMinute", report.scheduleMinute); page.add("scheduleAmPm", report.scheduleAmPm); page.add("scheduleTimeZone", report.scheduleTimeZone); page.add("scheduleDate", report.scheduleDate); page.add("scheduleRepeat", report.scheduleRepeat); page.add("scheduleIntervalQuantity", report.scheduleIntervalQuantity); page.add("scheduleInterval", report.scheduleInterval); report.accessViewer = getParam(req, "access-viewer"); report.accessExecutor = getParam(req, "access-executor"); report.accessOwner = getParam(req, "access-owner"); page.add("accessViewer", report.accessViewer); page.add("accessExecutor", report.accessExecutor); page.add("accessOwner", report.accessOwner); report.notifications = getParam(req, "notifications"); report.failureNotifications = getParam(req, "failure-notifications"); page.add("notifications", report.notifications); page.add("failureNotifications", report.failureNotifications); int numQueries = getIntParam(req, "queryNumber"); page.add("queryNumber", numQueries); List<Query> queryList = new ArrayList<Query>(numQueries); page.add("queries", queryList); report.queries = queryList; String typeError = null; String typePermissionError = null; for (int i = 0; i < numQueries; i++) { Query query = new Query(); query.title = getParam(req, "query" + i + "title"); query.type = getParam(req, "query" + i + "type"); query.script = getParam(req, "query" + i + "script"); // Type check ReportalType type = ReportalType.getTypeByName(query.type); if (type == null && typeError == null) { typeError = query.type; } if (!type.checkPermission(user)) { typePermissionError = query.type; } queryList.add(query); } int variables = getIntParam(req, "variableNumber"); page.add("variableNumber", variables); List<Variable> variableList = new ArrayList<Variable>(variables); page.add("variables", variableList); report.variables = variableList; boolean variableErrorOccurred = false; for (int i = 0; i < variables; i++) { Variable variable = new Variable(); variable.title = getParam(req, "variable" + i + "title"); variable.name = getParam(req, "variable" + i + "name"); if (variable.title.isEmpty() || variable.name.isEmpty()) { variableErrorOccurred = true; } variableList.add(variable); } // Make sure title isn't empty if (report.title.isEmpty()) { page.add("errorMsg", "Title must not be empty."); page.render(); return null; } // Make sure description isn't empty if (report.description.isEmpty()) { page.add("errorMsg", "Description must not be empty."); page.render(); return null; } // Verify schedule and repeat if (report.schedule) { // Verify schedule time if (!NumberUtils.isDigits(report.scheduleHour) || !NumberUtils.isDigits(report.scheduleMinute)) { page.add("errorMsg", "Schedule time is invalid."); page.render(); return null; } // Verify schedule date is not empty if (report.scheduleDate.isEmpty()) { page.add("errorMsg", "Schedule date must not be empty."); page.render(); return null; } if (report.scheduleRepeat) { // Verify repeat interval if (!NumberUtils.isDigits(report.scheduleIntervalQuantity)) { page.add("errorMsg", "Repeat interval quantity is invalid."); page.render(); return null; } } } // Empty query check if (numQueries <= 0) { page.add("errorMsg", "There needs to have at least one query."); page.render(); return null; } // Type error check if (typeError != null) { page.add("errorMsg", "Type " + typeError + " is invalid."); page.render(); return null; } // Type permission check if (typePermissionError != null && report.schedule) { page.add("errorMsg", "You do not have permission to schedule Type " + typePermissionError + "."); page.render(); return null; } // Variable error check if (variableErrorOccurred) { page.add("errorMsg", "Variable title and name cannot be empty."); page.render(); return null; } // Validate access users UserManager userManager = getApplication().getUserManager(); String[] accessLists = new String[] { report.accessViewer, report.accessExecutor, report.accessOwner }; for (String accessList : accessLists) { accessList = accessList == null ? null : accessList.trim(); if (accessList != null && !accessList.isEmpty()) { String[] users = accessList.split(Reportal.ACCESS_LIST_SPLIT_REGEX); for (String accessUser : users) { if (!userManager.validateUser(accessUser)) { page.add("errorMsg", "User " + accessUser + " in access list is invalid."); page.render(); return null; } } } } // Attempt to get a project object if (isEdit) { // Editing mode, load project int projectId = getIntParam(req, "id"); project = projectManager.getProject(projectId); report.loadImmutableFromProject(project); } else { // Creation mode, create project try { project = ReportalHelper.createReportalProject(server, report.title, report.description, user); report.reportalUser = user.getUserId(); report.ownerEmail = user.getEmail(); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating report. " + e.getMessage()); page.render(); return null; } // Project already exists if (project == null) { page.add("errorMsg", "A Report with the same name already exists."); page.render(); return null; } } if (project == null) { page.add("errorMsg", "Internal Error: Report not found"); page.render(); return null; } report.project = project; page.add("projectId", project.getId()); report.updatePermissions(); try { report.createZipAndUpload(projectManager, user, reportalStorageUser); } catch (Exception e) { e.printStackTrace(); page.add("errorMsg", "Error while creating Azkaban jobs. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, user); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return null; } // Prepare flow Flow flow = project.getFlows().get(0); project.getMetadata().put("flowName", flow.getId()); // Set reportal mailer flow.setMailCreator(ReportalMailCreator.REPORTAL_MAIL_CREATOR); // Create/Save schedule ScheduleManager scheduleManager = server.getScheduleManager(); try { report.updateSchedules(report, scheduleManager, user, flow); } catch (ScheduleManagerException e2) { e2.printStackTrace(); page.add("errorMsg", e2.getMessage()); page.render(); return null; } report.saveToProject(project); try { ReportalHelper.updateProjectNotifications(project, projectManager); projectManager.updateProjectSetting(project); projectManager.updateProjectDescription(project, report.description, user); projectManager.updateFlow(project, flow); } catch (ProjectManagerException e) { e.printStackTrace(); page.add("errorMsg", "Error while updating report. " + e.getMessage()); page.render(); if (!isEdit) { try { projectManager.removeProject(project, user); } catch (ProjectManagerException e1) { e1.printStackTrace(); } } return null; } return Integer.toString(project.getId()); }
diff --git a/src/jrds/MuninsProbe.java b/src/jrds/MuninsProbe.java index 6a7e778a..a15679f7 100644 --- a/src/jrds/MuninsProbe.java +++ b/src/jrds/MuninsProbe.java @@ -1,119 +1,118 @@ /* * Created on 7 janv. 2005 * * TODO */ package jrds; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.log4j.Logger; /** * @author bacchell * * TODO */ public abstract class MuninsProbe extends Probe { static final private Logger logger = JrdsLogger.getLogger(MuninsProbe.class); private Collection muninsName = null; protected Map nameMap; /** * @param monitoredHost * @param pd */ public MuninsProbe(RdsHost monitoredHost, ProbeDesc pd) { super(monitoredHost, pd); } /* (non-Javadoc) * @see com.aol.jrds.MuninsProbe#initMuninsName() */ protected Collection initMuninsName() { return getPd().getNamedProbesNames(); } public Collection getMuninsName() { if(muninsName == null) muninsName = initMuninsName(); return muninsName; } public Map getNewSampleValues() { Map retValue = new HashMap(); Socket muninsSocket = null; PrintWriter out = null; BufferedReader in = null; try { muninsSocket = new Socket(getHost().getName(), 4949); out = new PrintWriter(muninsSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(muninsSocket.getInputStream())); for(Iterator i = getMuninsName().iterator() ; i.hasNext() ; ) { String currentProbe = (String) i.next(); try { out.println("fetch " + currentProbe); String lastLine; boolean dotFound = false; while(! dotFound && ( lastLine = in.readLine()) != null ) { lastLine.replaceFirst("#.*", ""); if(".".equals(lastLine)) { dotFound = true; } else { String[] kvp = lastLine.split(" "); if(kvp.length == 2) { String name = kvp[0].trim(); Double value = new Double(kvp[1].trim()); if(name != null && value != null) retValue.put(name, value); }; }; } } catch (IOException e) { - logger.error("Unable to read munins probe " + currentProbe - + "because: " + e.getLocalizedMessage()); + logger.error("Error with munins probe " + this + ": " + e); } } } catch (IOException e) { - logger.error("Unable to connect to munins because: " + e.getLocalizedMessage()); + logger.error("Unable to connect to munins because: " + e); } if(out != null) { out.close(); } try { if(in != null) in.close(); } catch (IOException e1) {} try { if(muninsSocket != null) muninsSocket.close(); } catch (IOException e2) {}; return retValue; } /* (non-Javadoc) * @see com.aol.jrds.MuninsProbe#initNameMap() */ protected Map initNameMap() { return getPd().getProbesNamesMap(); } }
false
true
public Map getNewSampleValues() { Map retValue = new HashMap(); Socket muninsSocket = null; PrintWriter out = null; BufferedReader in = null; try { muninsSocket = new Socket(getHost().getName(), 4949); out = new PrintWriter(muninsSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(muninsSocket.getInputStream())); for(Iterator i = getMuninsName().iterator() ; i.hasNext() ; ) { String currentProbe = (String) i.next(); try { out.println("fetch " + currentProbe); String lastLine; boolean dotFound = false; while(! dotFound && ( lastLine = in.readLine()) != null ) { lastLine.replaceFirst("#.*", ""); if(".".equals(lastLine)) { dotFound = true; } else { String[] kvp = lastLine.split(" "); if(kvp.length == 2) { String name = kvp[0].trim(); Double value = new Double(kvp[1].trim()); if(name != null && value != null) retValue.put(name, value); }; }; } } catch (IOException e) { logger.error("Unable to read munins probe " + currentProbe + "because: " + e.getLocalizedMessage()); } } } catch (IOException e) { logger.error("Unable to connect to munins because: " + e.getLocalizedMessage()); } if(out != null) { out.close(); } try { if(in != null) in.close(); } catch (IOException e1) {} try { if(muninsSocket != null) muninsSocket.close(); } catch (IOException e2) {}; return retValue; }
public Map getNewSampleValues() { Map retValue = new HashMap(); Socket muninsSocket = null; PrintWriter out = null; BufferedReader in = null; try { muninsSocket = new Socket(getHost().getName(), 4949); out = new PrintWriter(muninsSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(muninsSocket.getInputStream())); for(Iterator i = getMuninsName().iterator() ; i.hasNext() ; ) { String currentProbe = (String) i.next(); try { out.println("fetch " + currentProbe); String lastLine; boolean dotFound = false; while(! dotFound && ( lastLine = in.readLine()) != null ) { lastLine.replaceFirst("#.*", ""); if(".".equals(lastLine)) { dotFound = true; } else { String[] kvp = lastLine.split(" "); if(kvp.length == 2) { String name = kvp[0].trim(); Double value = new Double(kvp[1].trim()); if(name != null && value != null) retValue.put(name, value); }; }; } } catch (IOException e) { logger.error("Error with munins probe " + this + ": " + e); } } } catch (IOException e) { logger.error("Unable to connect to munins because: " + e); } if(out != null) { out.close(); } try { if(in != null) in.close(); } catch (IOException e1) {} try { if(muninsSocket != null) muninsSocket.close(); } catch (IOException e2) {}; return retValue; }
diff --git a/app/controllers/ProjectApp.java b/app/controllers/ProjectApp.java index 931ad6a1..d9fb9381 100644 --- a/app/controllers/ProjectApp.java +++ b/app/controllers/ProjectApp.java @@ -1,700 +1,700 @@ package controllers; import com.avaje.ebean.Page; import com.avaje.ebean.ExpressionList; import models.*; import models.enumeration.*; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.NoHeadException; import org.tmatesoft.svn.core.SVNException; import play.data.Form; import play.db.ebean.Transactional; import play.mvc.Controller; import play.mvc.Http; import play.mvc.Http.MultipartFormData; import play.mvc.Http.MultipartFormData.FilePart; import play.mvc.Result; import playRepository.Commit; import playRepository.PlayRepository; import playRepository.RepositoryService; import utils.AccessControl; import utils.Constants; import utils.HttpUtil; import views.html.project.*; import play.i18n.Messages; import javax.servlet.ServletException; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ArrayList; import static play.data.Form.form; import static play.libs.Json.toJson; import static com.avaje.ebean.Expr.contains; /** * ProjectApp * */ public class ProjectApp extends Controller { private static final int LOGO_FILE_LIMIT_SIZE = 1048576; /** 프로젝트 로고로 사용할 수 있는 이미지 확장자 */ public static final String[] LOGO_TYPE = {"jpg", "jpeg", "png", "gif", "bmp"}; /** 자동완성에서 보여줄 최대 프로젝트 개수 */ private static final int MAX_FETCH_PROJECTS = 1000; private static final int COMMIT_HISTORY_PAGE = 0; private static final int COMMIT_HISTORY_SHOW_LIMIT = 10; private static final int RECENLTY_ISSUE_SHOW_LIMIT = 10; private static final int RECENLTY_POSTING_SHOW_LIMIT = 10; private static final int RECENT_PULL_REQUEST_SHOW_LIMIT = 10; private static final int PROJECT_COUNT_PER_PAGE = 10; private static final String HTML = "text/html"; private static final String JSON = "application/json"; /** * getProject * @param userName * @param projectName * @return */ public static Project getProject(String userName, String projectName) { return Project.findByOwnerAndProjectName(userName, projectName); } /** * 프로젝트 Overview 페이지를 처리한다.<p /> * * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br /> * 읽기 권한이 없을 경우는 unauthorized로 응답한다.<br /> * 해당 프로젝트의 최근 커밋, 이슈, 포스팅 목록을 가져와서 히스토리를 만든다.<br /> * * @param loginId * @param projectName * @return 프로젝트, 히스토리 정보 * @throws IOException Signals that an I/O exception has occurred. * @throws ServletException the servlet exception * @throws SVNException the svn exception * @throws GitAPIException the git api exception */ public static Result project(String loginId, String projectName) throws IOException, ServletException, SVNException, GitAPIException { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if(project == null) { return notFound("No project matches given parameters'" + loginId + "' and project_name '" + projectName + "'"); } project.fixInvalidForkData(); if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { return unauthorized(views.html.error.unauthorized.render(project)); } PlayRepository repository = RepositoryService.getRepository(project); List<Commit> commits = null; try { commits = repository.getHistory(COMMIT_HISTORY_PAGE, COMMIT_HISTORY_SHOW_LIMIT, null); } catch (NoHeadException e) { // NOOP } List<Issue> issues = Issue.findRecentlyCreated(project, RECENLTY_ISSUE_SHOW_LIMIT); List<Posting> postings = Posting.findRecentlyCreated(project, RECENLTY_POSTING_SHOW_LIMIT); List<PullRequest> pullRequests = PullRequest.findRecentlyReceived(project, RECENT_PULL_REQUEST_SHOW_LIMIT); List<History> histories = History.makeHistory(loginId, project, commits, issues, postings, pullRequests); return ok(overview.render("title.projectHome", project, histories)); } /** * 신규 프로젝트 생성 페이지로 이동한다.<p /> * * 비로그인 상태({@link models.User#anonymous})이면 로그인 경고메세지와 함께 로그인페이지로 redirect 된다.<br /> * 로그인 상태이면 프로젝트 생성 페이지로 이동한다.<br /> * * @return 익명사용자이면 로그인페이지, 로그인 상태이면 프로젝트 생성페이지 */ public static Result newProjectForm() { if (UserApp.currentUser().isAnonymous()) { flash(Constants.WARNING, "user.login.alert"); return redirect(routes.UserApp.loginForm()); } else { return ok(create.render("title.newProject", form(Project.class))); } } /** * 프로젝트 설정(업데이트) 페이지로 이동한다.<p /> * * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br /> * 업데이트 권한이 없을 경우는 unauthorized로 응답한다.<br /> * * @param loginId * @param projectName * @return 프로젝트 정보 */ public static Result settingForm(String loginId, String projectName) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { return unauthorized(views.html.error.unauthorized.render(project)); } Form<Project> projectForm = form(Project.class).fill(project); return ok(setting.render("title.projectSetting", projectForm, project)); } /** * 신규 프로젝트 생성(관리자Role 설정/코드 저장소를 생성)하고 Overview 페이지로 redirect 된다.<p /> * * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 조회하여 <br /> * 프로젝트가 이미 존재할 경우 경고메세지와 함께 badRequest로 응답한다.<br /> * 프로젝트폼 입력데이터에 오류가 있을 경우 경고메시지와 함께 badRequest로 응답한다.<br /> * * @return 프로젝트 존재시 경고메세지, 입력폼 오류시 경고메세지, 프로젝트 생성시 프로젝트 정보 * @throws Exception */ @Transactional public static Result newProject() throws Exception { if( !AccessControl.isCreatable(UserApp.currentUser(), ResourceType.PROJECT) ){ return forbidden("'" + UserApp.currentUser().name + "' has no permission"); } Form<Project> filledNewProjectForm = form(Project.class).bindFromRequest(); if (Project.exists(UserApp.currentUser().loginId, filledNewProjectForm.field("name").value())) { flash(Constants.WARNING, "project.name.duplicate"); filledNewProjectForm.reject("name"); return badRequest(create.render("title.newProject", filledNewProjectForm)); } else if (filledNewProjectForm.hasErrors()) { filledNewProjectForm.reject("name"); flash(Constants.WARNING, "project.name.alert"); return badRequest(create.render("title.newProject", filledNewProjectForm)); } else { Project project = filledNewProjectForm.get(); project.owner = UserApp.currentUser().loginId; ProjectUser.assignRole(UserApp.currentUser().id, Project.create(project), RoleType.MANAGER); RepositoryService.createRepository(project); return redirect(routes.ProjectApp.project(project.owner, project.name)); } } /** * 프로젝트 설정을 업데이트한다.<p /> * * 업데이트 권한이 없을 경우 경고메세지와 함께 프로젝트 설정페이지로 redirect된다.<br /> * {@code loginId}의 프로젝트중 변경하고자 하는 이름과 동일한 프로젝트명이 있으면 경고메세지와 함께 badRequest를 응답한다.<br /> * 프로젝트 로고({@code filePart})가 이미지파일이 아니거나 제한사이즈(1MB) 보다 크다면 경고메세지와 함께 badRequest를 응답한다.<br /> * 프로젝트 로고({@code filePart})가 이미지파일이고 제한사이즈(1MB) 보다 크지 않다면 첨부파일과 프로젝트 정보를 저장하고 프로젝트 설정(업데이트) 페이지로 이동한다.<br /> * * @param loginId user login id * @param projectName the project name * @return * @throws IOException Signals that an I/O exception has occurred. * @throws NoSuchAlgorithmException the no such algorithm exception */ @Transactional public static Result settingProject(String loginId, String projectName) throws IOException, NoSuchAlgorithmException { Form<Project> filledUpdatedProjectForm = form(Project.class).bindFromRequest(); Project project = filledUpdatedProjectForm.get(); if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { flash(Constants.WARNING, "project.member.isManager"); return redirect(routes.ProjectApp.settingForm(loginId, project.name)); } if (!Project.projectNameChangeable(project.id, loginId, project.name)) { flash(Constants.WARNING, "project.name.duplicate"); filledUpdatedProjectForm.reject("name"); } MultipartFormData body = request().body().asMultipartFormData(); FilePart filePart = body.getFile("logoPath"); if (!isEmptyFilePart(filePart)) { if(!isImageFile(filePart.getFilename())) { flash(Constants.WARNING, "project.logo.alert"); filledUpdatedProjectForm.reject("logoPath"); } else if (filePart.getFile().length() > LOGO_FILE_LIMIT_SIZE) { flash(Constants.WARNING, "project.logo.fileSizeAlert"); filledUpdatedProjectForm.reject("logoPath"); } else { Attachment.deleteAll(project.asResource()); new Attachment().store(filePart.getFile(), filePart.getFilename(), project.asResource()); } } if (filledUpdatedProjectForm.hasErrors()) { return badRequest(setting.render("title.projectSetting", filledUpdatedProjectForm, Project.find.byId(project.id))); } project.update(); return redirect(routes.ProjectApp.settingForm(loginId, project.name)); } /** * {@code filePart} 정보가 비어있는지 확인한다.<p /> * @param filePart * @return {@code filePart}가 null이면 true, {@code filename}이 null이면 true, {@code fileLength}가 0 이하이면 true */ private static boolean isEmptyFilePart(FilePart filePart) { return filePart == null || filePart.getFilename() == null || filePart.getFilename().length() <= 0; } /** * {@code filename}의 확장자를 체크하여 이미지인지 확인한다.<p /> * * 이미지 확장자는 {@link controllers.ProjectApp#LOGO_TYPE} 에 정의한다. * @param filename the filename * @return true, if is image file */ public static boolean isImageFile(String filename) { boolean isImageFile = false; for(String suffix : LOGO_TYPE) { if(filename.toLowerCase().endsWith(suffix)) isImageFile = true; } return isImageFile; } /** * 프로젝트 삭제 페이지로 이동한다.<p /> * * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br /> * 업데이트 권한이 없을 경우는 unauthorized로 응답한다.<br /> * * @param loginId user login id * @param projectName the project name * @return 프로젝트폼, 프로젝트 정보 */ public static Result deleteForm(String loginId, String projectName) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { return unauthorized(views.html.error.unauthorized.render(project)); } Form<Project> projectForm = form(Project.class).fill(project); return ok(delete.render("title.projectSetting", projectForm, project)); } /** * 프로젝트를 삭제한다.<p /> * * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br /> * 삭제 권한이 없을 경우는 경고 메시지와 함께 설정페이지로 redirect된다. <br /> * * @param loginId the user login id * @param projectName the project name * @return the result * @throws Exception the exception */ public static Result deleteProject(String loginId, String projectName) throws Exception { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(); } if (AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.DELETE)) { RepositoryService.deleteRepository(loginId, projectName, project.vcs); project.delete(); return redirect(routes.Application.index()); } else { flash(Constants.WARNING, "project.member.isManager"); return redirect(routes.ProjectApp.settingForm(loginId, projectName)); } } /** * 프로젝트 멤버설정 페이지로 이동한다.<p /> * * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br /> * 프로젝트 아이디로 해당 프로젝트의 멤버목록을 가져온다.<br /> * 프로젝트 관련 Role 목록을 가져온다.<br /> * 프로젝트 수정 권한이 없을 경우 unauthorized 로 응답한다<br /> * * @param loginId the user login id * @param projectName the project name * @return 프로젝트, 멤버목록, Role 목록 */ public static Result members(String loginId, String projectName) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { return unauthorized(views.html.error.unauthorized.render(project)); } return ok(views.html.project.members.render("title.memberList", ProjectUser.findMemberListByProject(project.id), project, Role.getActiveRoles())); } /** * 프로젝트의 신규 멤버를 추가한다.<p /> * * 입력폼 오류시 경고메세지와 함께 프로젝트 설정페이지로 redirect 된다.<br /> * 입력폼으로부터 멤버로 추가한 사용자 정보를 가져온다.<br /> * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br /> * <br /> * 현재 로그인 사용자가 UPDATE 권한이 없을경우 경고메세지와 함께 멤버설정 페이지로 redirect 된다.<br /> * 추가한 사용자 정보가 null일 경우 경고메세지와 함께 멤버설정 페이지로 redirect 된다.<br /> * 추가한 사용자가 이미 프로젝트 멤버일 경우 경고메시지와 함께 멤버설정 페이지로 redirect 된다.<br /> * * @param loginId the user login id * @param projectName the project name * @return 프로젝트, 멤버목록, Role 목록 */ public static Result newMember(String loginId, String projectName) { // TODO change into view validation Form<User> addMemberForm = form(User.class).bindFromRequest(); if (addMemberForm.hasErrors()){ flash(Constants.WARNING, "project.member.notExist"); return redirect(routes.ProjectApp.members(loginId, projectName)); } User user = User.findByLoginId(form(User.class).bindFromRequest().get().loginId); Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { flash(Constants.WARNING, "project.member.isManager"); return redirect(routes.ProjectApp.members(loginId, projectName)); } else if (user == null) { flash(Constants.WARNING, "project.member.notExist"); return redirect(routes.ProjectApp.members(loginId, projectName)); } else if (!ProjectUser.isMember(user.id, project.id)){ ProjectUser.assignRole(user.id, project.id, RoleType.MEMBER); } else{ flash(Constants.WARNING, "project.member.alreadyMember"); } return redirect(routes.ProjectApp.members(loginId, projectName)); } /** * 프로젝트 멤버를 삭제한다.<p /> * * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br /> * 삭제할 멤버가 로그인 사용자 이거나 프로젝트 업데이트 권한이 있을 경우 삭제하고 멤버 설정페이지로 redirect 된다.<br /> * 삭제할 멤버가 프로젝트 관리자일 경우 경고메세지와 함께 forbidden을 응답한다.<br /> * * @param loginId the user login id * @param projectName the project name * @param userId 삭제할 멤버 아이디 * @return the result */ public static Result deleteMember(String loginId, String projectName, Long userId) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(); } if (UserApp.currentUser().id == userId || AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { if (project.isOwner(User.find.byId(userId))) { return forbidden(Messages.get("project.member.ownerCannotLeave")); } ProjectUser.delete(userId, project.id); return redirect(routes.ProjectApp.members(loginId, projectName)); } else { return forbidden(views.html.error.forbidden.render(project)); } } /** * 멤버의 Role을 설정하고 NO_CONTENT를 응답한다.<p /> * * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br /> * 로그인 사용자가 업데이트 권한이 있을경우 멤버에게 새로 설정한 Role을 할당한다.<br /> * <br /> * 변경하고자 하는 멤버가 프로젝트 관리자일 경우 경고메세지와 함께 forbidden을 응답한다.<br /> * 업데이트 권한이 없을 경우 경고메세지와 함께 forbidden을 응답한다.<br /> * * @param loginId the user login id * @param projectName the project name * @param userId the user id * @return */ public static Result editMember(String loginId, String projectName, Long userId) { Project project = Project.findByOwnerAndProjectName(loginId, projectName); if (project == null) { return notFound(); } if (AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.UPDATE)) { if (project.isOwner(User.find.byId(userId))) { return forbidden(Messages.get("project.member.ownerMustBeAManager")); } ProjectUser.assignRole(userId, project.id, form(Role.class) .bindFromRequest().get().id); return status(Http.Status.NO_CONTENT); } else { return forbidden(Messages.get("project.member.isManager")); } } /** * accepted가능한 Content-type에 따라 JSON 목록을 반환하거나 프로젝트 목록 페이지로 이동한다.<p /> * HTML 또는 JSON 요청이 아닌경우 NOT_ACCEPTABLE 을 응답한다.<br /> * <br /> * 1. JSON 목록 반환 ( 자동완성용 )<br /> * 프로젝트 관리자 또는 이름에 {@code query}값를 포함하고 있는 프로젝트 목록을 가져온다.<br /> * 반환되는 최대 목록개수는 {@link ProjectApp#MAX_FETCH_PROJECTS} 로 설정한다.<br /> * 프로젝트 목록의 {@code owner}와 {@code name}을 조합하여 새로운 목록을 만들고 JSON 형태로 반환한다.<br /> * <br /> * 2. 프로젝트 목록 페이지 이동<br /> * 프로젝트 목록을 최근 생성일 기준으로 정렬하여 페이지(사이즈 : {@link Project#PROJECT_COUNT_PER_PAGE}) 단위로 가져오고<br /> * 조회 조건은 프로젝트명 또는 프로젝트관리자({@code query}), 공개 여부({@code state}) 이다.<br /> * * @param query the query * @param state the state * @param pageNum the page num * @return json일 경우 json형태의 프로젝트명 목록, html일 경우 java객체 형태의 프로젝트 목록 */ public static Result projects(String query, String state, int pageNum) { String prefer = HttpUtil.getPreferType(request(), JSON, HTML); if (prefer == null) { return status(Http.Status.NOT_ACCEPTABLE); } if (prefer.equals(JSON)) { return getProjectsToJSON(query); } else { return getPagingProjects(query, state, pageNum); } } /** * 프로젝트 목록을 가져온다. * * when : 프로젝트명, 프로젝트 관리자, 공개여부로 프로젝트 목록 조회시 * * 프로젝트명 또는 관리자 로그인 아이디가 {@code query}를 포함하고 * 공개여부가 @{code state} 인 프로젝트 목록을 최근생성일로 정렬하여 페이징 형태로 가져온다. * * @param query 검색질의(프로젝트명 또는 관리자) * @param state 프로젝트 상태(공개/비공개) * @param pageNum 페이지번호 * @return 프로젝트명 또는 관리자 로그인 아이디가 {@code query}를 포함하고 공개여부가 @{code state} 인 프로젝트 목록 */ private static Result getPagingProjects(String query, String state, int pageNum) { ExpressionList<Project> el = Project.find.where().or(contains("name", query), contains("owner", query)); Project.State stateType = Project.State.valueOf(state.toUpperCase()); if (stateType == Project.State.PUBLIC) { el.eq("isPublic", true); } else if (stateType == Project.State.PRIVATE) { el.eq("isPublic", false); } el.orderBy("createdDate desc"); Page<Project> projects = el.findPagingList(PROJECT_COUNT_PER_PAGE).getPage(pageNum - 1); return ok(views.html.project.list.render("title.projectList", projects, query, state)); } /** * 프로젝트 정보를 JSON으로 가져온다. * * 프로젝트명 또는 관리자 아이디에 {@code query} 가 포함되는 프로젝트 목록을 {@link MAX_FETCH_PROJECTS} 만큼 가져오고 * JSON으로 변환하여 반환한다. * * @param query 검색질의(프로젝트명 또는 관리자) * @return JSON 형태의 프로젝트 목록 */ private static Result getProjectsToJSON(String query) { List<String> projectNames = new ArrayList<String>(); ExpressionList<Project> el = Project.find.where().or(contains("name", query), contains("owner", query)); int total = el.findRowCount(); if (total > MAX_FETCH_PROJECTS) { el.setMaxRows(MAX_FETCH_PROJECTS); response().setHeader("Content-Range", "items " + MAX_FETCH_PROJECTS + "/" + total); } for (Project project: el.findList()) { projectNames.add(project.owner + "/" + project.name); } return ok(toJson(projectNames)); } /** * 프로젝트 설정페이지에서 사용하며 태그목록을 JSON 형태로 반환한다.<p /> * * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br /> * 읽기 권한이 없을경우 forbidden을 반환한다.<br /> * application/json 요청이 아닐경우 not_acceptable을 반환한다.<br /> * * * @param owner the owner login id * @param projectName the project name * @return 프로젝트 태그 JSON 데이터 */ public static Result tags(String owner, String projectName) { Project project = Project.findByOwnerAndProjectName(owner, projectName); if (project == null) { return notFound(); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { return forbidden(); } if (!request().accepts("application/json")) { return status(Http.Status.NOT_ACCEPTABLE); } Map<Long, String> tags = new HashMap<Long, String>(); for (Tag tag: project.tags) { tags.put(tag.id, tag.toString()); } return ok(toJson(tags)); } /** * 프로젝트 설정 페이지에서 사용하며 새로운 태그를 추가하고 추가된 태그를 JSON으로 반환한다.<p /> * * {@code loginId}와 {@code projectName}으로 프로젝트 정보를 가져온다.<br /> * 업데이트 권한이 없을경우 forbidden을 반환한다.<br /> * 태그명 파라미터가 null일 경우 empty 데이터를 JSON으로 반환한다.<br /> * 프로젝트내 동일한 태그가 존재할 경우 empty 데이터를 JSON으로 반환한다.<br /> * * @param ownerName the owner name * @param projectName the project name * @return the result */ public static Result tag(String ownerName, String projectName) { Project project = Project.findByOwnerAndProjectName(ownerName, projectName); if (project == null) { return notFound(); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.tagsAsResource(), Operation.UPDATE)) { return forbidden(); } // Get category and name from the request. Return 400 Bad Request if name is not given. Map<String, String[]> data = request().body().asFormUrlEncoded(); String category = HttpUtil.getFirstValueFromQuery(data, "category"); String name = HttpUtil.getFirstValueFromQuery(data, "name"); if (name == null || name.length() == 0) { // A tag must have its name. return badRequest("Tag name is missing."); } Tag tag = Tag.find .where().eq("category", category).eq("name", name).findUnique(); boolean isCreated = false; if (tag == null) { // Create new tag if there is no tag which has the given name. tag = new Tag(category, name); tag.save(); isCreated = true; } Boolean isAttached = project.tag(tag); if (!isCreated && !isAttached) { // Something is wrong. This case is not possible. play.Logger.warn( "A tag '" + tag + "' is created but failed to attach to project '" + project + "'."); } if (isAttached) { // Return the attached tag. The return type is Map<Long, String> // even if there is only one tag, to unify the return type with // ProjectApp.tags(). Map<Long, String> tags = new HashMap<Long, String>(); tags.put(tag.id, tag.toString()); if (isCreated) { return created(toJson(tags)); } else { return ok(toJson(tags)); } } else { - // Return 204 No Content if the tag has been attached already. + // Return 204 No Content if the tag is already attached. return status(Http.Status.NO_CONTENT); } } /** * 프로젝트 설정 페이지에서 사용하며 태그를 삭제한다.<p /> * * _method 파라미터가 delete가 아니면 badRequest를 반환한다.<br /> * 삭제할 태그가 존재하지 않으면 notfound를 반환한다. * * @param ownerName the owner name * @param projectName the project name * @param id the id * @return the result */ public static Result untag(String ownerName, String projectName, Long id) { Project project = Project.findByOwnerAndProjectName(ownerName, projectName); if (project == null) { return notFound(); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.tagsAsResource(), Operation.UPDATE)) { return forbidden(); } // _method must be 'delete' Map<String, String[]> data = request().body().asFormUrlEncoded(); if (!HttpUtil.getFirstValueFromQuery(data, "_method").toLowerCase() .equals("delete")) { return badRequest("_method must be 'delete'."); } Tag tag = Tag.find.byId(id); if (tag == null) { return notFound(); } project.untag(tag); return status(Http.Status.NO_CONTENT); } }
true
true
public static Result tag(String ownerName, String projectName) { Project project = Project.findByOwnerAndProjectName(ownerName, projectName); if (project == null) { return notFound(); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.tagsAsResource(), Operation.UPDATE)) { return forbidden(); } // Get category and name from the request. Return 400 Bad Request if name is not given. Map<String, String[]> data = request().body().asFormUrlEncoded(); String category = HttpUtil.getFirstValueFromQuery(data, "category"); String name = HttpUtil.getFirstValueFromQuery(data, "name"); if (name == null || name.length() == 0) { // A tag must have its name. return badRequest("Tag name is missing."); } Tag tag = Tag.find .where().eq("category", category).eq("name", name).findUnique(); boolean isCreated = false; if (tag == null) { // Create new tag if there is no tag which has the given name. tag = new Tag(category, name); tag.save(); isCreated = true; } Boolean isAttached = project.tag(tag); if (!isCreated && !isAttached) { // Something is wrong. This case is not possible. play.Logger.warn( "A tag '" + tag + "' is created but failed to attach to project '" + project + "'."); } if (isAttached) { // Return the attached tag. The return type is Map<Long, String> // even if there is only one tag, to unify the return type with // ProjectApp.tags(). Map<Long, String> tags = new HashMap<Long, String>(); tags.put(tag.id, tag.toString()); if (isCreated) { return created(toJson(tags)); } else { return ok(toJson(tags)); } } else { // Return 204 No Content if the tag has been attached already. return status(Http.Status.NO_CONTENT); } }
public static Result tag(String ownerName, String projectName) { Project project = Project.findByOwnerAndProjectName(ownerName, projectName); if (project == null) { return notFound(); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.tagsAsResource(), Operation.UPDATE)) { return forbidden(); } // Get category and name from the request. Return 400 Bad Request if name is not given. Map<String, String[]> data = request().body().asFormUrlEncoded(); String category = HttpUtil.getFirstValueFromQuery(data, "category"); String name = HttpUtil.getFirstValueFromQuery(data, "name"); if (name == null || name.length() == 0) { // A tag must have its name. return badRequest("Tag name is missing."); } Tag tag = Tag.find .where().eq("category", category).eq("name", name).findUnique(); boolean isCreated = false; if (tag == null) { // Create new tag if there is no tag which has the given name. tag = new Tag(category, name); tag.save(); isCreated = true; } Boolean isAttached = project.tag(tag); if (!isCreated && !isAttached) { // Something is wrong. This case is not possible. play.Logger.warn( "A tag '" + tag + "' is created but failed to attach to project '" + project + "'."); } if (isAttached) { // Return the attached tag. The return type is Map<Long, String> // even if there is only one tag, to unify the return type with // ProjectApp.tags(). Map<Long, String> tags = new HashMap<Long, String>(); tags.put(tag.id, tag.toString()); if (isCreated) { return created(toJson(tags)); } else { return ok(toJson(tags)); } } else { // Return 204 No Content if the tag is already attached. return status(Http.Status.NO_CONTENT); } }
diff --git a/src/edu/wpi/first/wpilibj/templates/RobotTemplate.java b/src/edu/wpi/first/wpilibj/templates/RobotTemplate.java index 8e709db..5ae3b43 100755 --- a/src/edu/wpi/first/wpilibj/templates/RobotTemplate.java +++ b/src/edu/wpi/first/wpilibj/templates/RobotTemplate.java @@ -1,216 +1,216 @@ /*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Jaguar; import edu.wpi.first.wpilibj.Joystick; //import edu.wpi.first.wpilibj.Relay; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Timer; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class RobotTemplate extends IterativeRobot { public void printMsg(String message) { userMessages.println(DriverStationLCD.Line.kMain6, 1, message ); } RobotDrive drivetrain; //Relay spikeA; Joystick leftStick; Joystick rightStick; //public String controlScheme = "twostick"; int leftStickX, leftStickY; DriverStationLCD userMessages; String controlScheme = "twostick"; Timer timer; DigitalInput switchA, switchB; Jaguar launcher; double voltage; //DriverStation driverStation = new DriverStation(); /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { //Instantialize objects for RobotTemplate //driverStation = new DriverStation(); rightStick = new Joystick(1); leftStick = new Joystick(2); userMessages = DriverStationLCD.getInstance(); //2-Wheel tank drive //spikeA = new Relay(1); drivetrain = new RobotDrive(1,2); launcher = new Jaguar(5); /*pistonUp = new Solenoid(1); pistonDown = new Solenoid(2); sol3 = new Solenoid(3); sol4 = new Solenoid(4); sol5 = new Solenoid(5);*/ //4-Wheel tank drive //Motors must be set in the following order: //LeftFront=1; LeftRear=2; RightFront=3; RightRear=4; //drivetrain = new RobotDrive(1,2,3,4); //drivetrain.tankDrive(leftStick, rightStick); /*pistonDown.set(true); pistonUp.set(true);*/ switchA = new DigitalInput(1); switchB = new DigitalInput(2);//remember to check port } /** * This function is called periodically during autonomous */ public void autonomousInit() { voltage = DriverStation.getInstance().getBatteryVoltage(); if (switchA.get() && switchB.get()) { - PrintMsg("Moving Forward"); + printMsg("Moving Forward"); drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else if (!switchA.get() && !switchB.get()) { - PrintMsg("Moving backward"); + printMsg("Moving backward"); drivetrain.setLeftRightMotorOutputs(-1.0, -1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else if (switchA.get() && !switchB.get()) { - PrintMsg("turning"); + printMsg("turning"); drivetrain.setLeftRightMotorOutputs(1.0, -1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else if (!switchA.get() && switchB.get()) { - PrintMsg("turning"); + printMsg("turning"); drivetrain.setLeftRightMotorOutputs(-1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else { - PrintMsg("Switch not detected"); + printMsg("Switch not detected"); Timer.delay(15000); } teleopInit(); /*drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(-1.0, 1.0); Timer.delay(500); drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); */ } public void telopInit() { //drivetrain.setSafetyEnabled(true); //drivetrain.tankDrive(leftStick.getY(), rightStick.getY()); //compressorA.start(); printMsg("Teleop started."); } /** * This function is called periodically during operator control */ public void teleopPeriodic() { /*if(switchA.get()){//if switch isn't tripped printMsg("Moving motor."); //victor.set(0.5); //start motor } else{ printMsg("Motor stopped"); //victor.set(0); //stop motor }*/ //getWatchdog().setEnabled(true); while(isEnabled() && isOperatorControl()) { drivetrain.tankDrive(leftStick, rightStick); } //Pneumatics test code if (leftStick.getTrigger()) { launcher.set(-1); } else { //don't set to 0 to avoid conflicts with right stick } if (rightStick.getTrigger()) { launcher.set(1); } else { launcher.set(0); } //Switch between "onestick" and "twostick" control schemes if (leftStick.getRawButton(6)) { controlScheme = "twostick"; } if (leftStick.getRawButton(7)) { controlScheme = "onestick"; } if (controlScheme.equals("twostick")) { drivetrain.tankDrive(rightStick, leftStick); printMsg("Tankdrive activated."); } else if (controlScheme.equals("onestick")) { drivetrain.arcadeDrive(leftStick); printMsg("Arcade drive activated."); } if(switchA.get()){//if switch isn't tripped printMsg("Moving motor."); //victor.set(0.5); //start motor } else{ printMsg("Motor stopped"); //victor.set(0); //stop motor } //Rotate in-place left and right, respectively if (leftStick.getRawButton(8)) { drivetrain.setLeftRightMotorOutputs(-1.0, 1.0); printMsg("Rotating counterclockwise in place."); } if (leftStick.getRawButton(9)) { drivetrain.setLeftRightMotorOutputs(1.0, -1.0); printMsg("Rotating clockwise in place."); } //userMessages.println(DriverStationLCD.Line.kMain6, 1, "This is a test" ); userMessages.updateLCD(); } /*public void disabledInit() { }*/ }
false
true
public void autonomousInit() { voltage = DriverStation.getInstance().getBatteryVoltage(); if (switchA.get() && switchB.get()) { PrintMsg("Moving Forward"); drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else if (!switchA.get() && !switchB.get()) { PrintMsg("Moving backward"); drivetrain.setLeftRightMotorOutputs(-1.0, -1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else if (switchA.get() && !switchB.get()) { PrintMsg("turning"); drivetrain.setLeftRightMotorOutputs(1.0, -1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else if (!switchA.get() && switchB.get()) { PrintMsg("turning"); drivetrain.setLeftRightMotorOutputs(-1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else { PrintMsg("Switch not detected"); Timer.delay(15000); } teleopInit(); /*drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(-1.0, 1.0); Timer.delay(500); drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); */ }
public void autonomousInit() { voltage = DriverStation.getInstance().getBatteryVoltage(); if (switchA.get() && switchB.get()) { printMsg("Moving Forward"); drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else if (!switchA.get() && !switchB.get()) { printMsg("Moving backward"); drivetrain.setLeftRightMotorOutputs(-1.0, -1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else if (switchA.get() && !switchB.get()) { printMsg("turning"); drivetrain.setLeftRightMotorOutputs(1.0, -1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else if (!switchA.get() && switchB.get()) { printMsg("turning"); drivetrain.setLeftRightMotorOutputs(-1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); } else { printMsg("Switch not detected"); Timer.delay(15000); } teleopInit(); /*drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(-1.0, 1.0); Timer.delay(500); drivetrain.setLeftRightMotorOutputs(1.0, 1.0); Timer.delay(1000); drivetrain.setLeftRightMotorOutputs(0, 0); */ }
diff --git a/java/src/memoplayer/Transform2D.java b/java/src/memoplayer/Transform2D.java index 8cb4977..a1a7fe5 100644 --- a/java/src/memoplayer/Transform2D.java +++ b/java/src/memoplayer/Transform2D.java @@ -1,69 +1,69 @@ /* * Copyright (C) 2010 France Telecom * * 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 memoplayer; public class Transform2D extends Group { int m_tx, m_ty, m_sx, m_sy, m_a/*RCA*/; boolean m_hasTrs, m_hasScale, m_hasRot; Transform2D () { super (4); // RC /13/10/07 av:super (3); //System.out.println ("Transform2D created"); // m_field[0] is created by class Group m_field[1] = new SFVec2f (0, 0, this); // translation m_field[2] = new SFVec2f (1<<16, 1<<16, this); // scale m_field[3] = new SFFloat (0, this); // rotationAngle // RC /13/10/07 } void start (Context c) { super.start (c); fieldChanged (m_field[1]); fieldChanged (m_field[2]); fieldChanged (m_field[3]); // RC /13/10/07 } boolean compose (Context c, Region clip, boolean forceUpdate) { boolean updated = m_isUpdated | forceUpdate; m_isUpdated = false; c.matrix.push (); if (m_hasTrs) c.matrix.translate (m_tx, m_ty); if (m_hasRot) c.matrix.rotate (m_a); // RC /13/10/07 if (m_hasScale) c.matrix.scale (m_sx, m_sy); updated |= super.compose (c, clip, updated); //RC 13/10/07 //updated |= super.compose (c, clip, forceUpdate); c.matrix.pop (); return updated; } public void fieldChanged (Field f) { m_isUpdated = true; if (f == m_field[1]) { m_tx = ((SFVec2f)f).m_x; m_ty = ((SFVec2f)f).m_y; m_hasTrs = m_tx != 0 || m_ty != 0; } else if (f == m_field[2]) { m_sx = ((SFVec2f)f).m_x; m_sy = ((SFVec2f)f).m_y; - m_hasScale = m_sx != 1 || m_sy != 1; + m_hasScale = m_sx != 1<<16 || m_sy != 1<<16; } else { // RC 13/10/07 m_a = ((SFFloat)f).m_f; m_hasRot = m_a != 0; } } }
true
true
public void fieldChanged (Field f) { m_isUpdated = true; if (f == m_field[1]) { m_tx = ((SFVec2f)f).m_x; m_ty = ((SFVec2f)f).m_y; m_hasTrs = m_tx != 0 || m_ty != 0; } else if (f == m_field[2]) { m_sx = ((SFVec2f)f).m_x; m_sy = ((SFVec2f)f).m_y; m_hasScale = m_sx != 1 || m_sy != 1; } else { // RC 13/10/07 m_a = ((SFFloat)f).m_f; m_hasRot = m_a != 0; } }
public void fieldChanged (Field f) { m_isUpdated = true; if (f == m_field[1]) { m_tx = ((SFVec2f)f).m_x; m_ty = ((SFVec2f)f).m_y; m_hasTrs = m_tx != 0 || m_ty != 0; } else if (f == m_field[2]) { m_sx = ((SFVec2f)f).m_x; m_sy = ((SFVec2f)f).m_y; m_hasScale = m_sx != 1<<16 || m_sy != 1<<16; } else { // RC 13/10/07 m_a = ((SFFloat)f).m_f; m_hasRot = m_a != 0; } }
diff --git a/src/org/rsbot/script/methods/Walking.java b/src/org/rsbot/script/methods/Walking.java index 58043c66..f51995e7 100644 --- a/src/org/rsbot/script/methods/Walking.java +++ b/src/org/rsbot/script/methods/Walking.java @@ -1,551 +1,551 @@ package org.rsbot.script.methods; import org.rsbot.script.wrappers.*; import java.awt.*; /** * Walking related operations. */ public class Walking extends MethodProvider { public final int INTERFACE_RUN_ORB = 750; Walking(final MethodContext ctx) { super(ctx); } private RSPath lastPath; private RSTile lastDestination; private RSTile lastStep; /** * Creates a new path based on a provided array of tile waypoints. * * @param tiles The waypoint tiles. * @return An RSTilePath. */ public RSTilePath newTilePath(final RSTile[] tiles) { if (tiles == null) { throw new IllegalArgumentException("null waypoint list"); } return new RSTilePath(methods, tiles); } /** * Generates a path from the player's current location to a destination * tile. * * @param destination The destination tile. * @return The path as an RSTile array. */ public RSPath getPath(final RSTile destination) { return new RSLocalPath(methods, destination); } /** * Determines whether or not a given tile is in the loaded map area. * * @param tile The tile to check. * @return <tt>true</tt> if local; otherwise <tt>false</tt>. */ public boolean isLocal(final RSTile tile) { int[][] flags = getCollisionFlags(methods.game.getPlane()); int x = tile.getX() - methods.game.getBaseX(); int y = tile.getY() - methods.game.getBaseY(); return (flags != null && x >= 0 && y >= 0 && x < flags.length && y < flags.length); } /** * Walks one tile towards the given destination using a generated path. * * @param destination The destination tile. * @return <tt>true</tt> if the next tile was walked to; otherwise * <tt>false</tt>. */ public boolean walkTo(final RSTile destination) { if (destination.equals(lastDestination) && methods.calc.distanceTo(lastStep) < 10) { return lastPath.traverse(); } lastDestination = destination; lastPath = getPath(destination); if (!lastPath.isValid()) { return false; } lastStep = lastPath.getNext(); return lastPath.traverse(); } /** * Walks to the given tile using the minimap with 1 tile randomness. * * @param t The tile to walk to. * @return <tt>true</tt> if the tile was clicked; otherwise <tt>false</tt>. * @see #walkTileMM(RSTile, int, int) */ public boolean walkTileMM(final RSTile t) { return walkTileMM(t, 0, 0); } /** * Walks to the given tile using the minimap with given randomness. * * @param t The tile to walk to. * @param x The x randomness (between 0 and x-1). * @param y The y randomness (between 0 and y-1). * @return <tt>true</tt> if the tile was clicked; otherwise <tt>false</tt>. */ public boolean walkTileMM(final RSTile t, final int x, final int y) { RSTile dest = new RSTile(t.getX() + random(0, x), t.getY() + random(0, y)); if (!methods.calc.tileOnMap(dest)) { dest = getClosestTileOnMap(dest); } Point p = methods.calc.tileToMinimap(dest); if (p.x != -1 && p.y != -1) { - int x = p.x, y = p.y; + int xx = p.x, yy = p.y; if (random(1, 2) == random(1, 2)) { - x += random(0, 50); + xx += random(0, 50); } else { - x -= random(0, 50); + xx -= random(0, 50); } if (random(1, 2) == random(1, 2)) { - y += random(0, 50); + yy += random(0, 50); } else { - y -= random(0, 50); + yy -= random(0, 50); } - methods.mouse.move(x, y); - p = calc.tileToMinimap(dest); + methods.mouse.move(xx, yy); + p = methods.calc.tileToMinimap(dest); if (p.x == -1 || p.y == -1) { return false; } methods.mouse.move(p); Point p2 = methods.calc.tileToMinimap(dest); if (p2.x != -1 && p2.y != -1) { methods.mouse.move(p2); if (!methods.mouse.getLocation().equals(p2)) { methods.mouse.hop(p2); } methods.mouse.click(p2, true); return true; } } return false; } /** * Walks to the given tile using the minimap with given randomness. * * @param t The tile to walk to. * @param r The maximum deviation from the tile to allow. * @return <tt>true</tt> if the tile was clicked; otherwise <tt>false</tt>. */ public boolean walkTileMM(final RSTile t, final int r) { int x = t.getX(); int y = t.getY(); if (random(1, 2) == random(1, 2)) { x += random(0, r); } else { x -= random(0, r); } if (random(1, 2) == random(1, 2)) { y += random(0, r); } else { y -= random(0, r); } RSTile dest = new RSTile(x, y); if (methods.players.getMyPlayer().getLocation().equals(dest)) { return false; } return walkTileMM(dest, 0, 0); } /** * Walks to a tile using onScreen clicks and not the MiniMap. If the tile is * not on the screen, it will find the closest tile that is on screen and it * will walk there instead. * * @param tileToWalk Tile to walk. * @return True if successful. */ public boolean walkTileOnScreen(final RSTile tileToWalk) { return methods.tiles.doAction(methods.calc.getTileOnScreen(tileToWalk), "Walk "); } /** * Rests until 100% energy * * @return <tt>true</tt> if rest was enabled; otherwise false. * @see #rest(int) */ public boolean rest() { return rest(100); } /** * Rests until a certain amount of energy is reached. * * @param stopEnergy Amount of energy at which it should stop resting. * @return <tt>true</tt> if rest was enabled; otherwise false. */ public boolean rest(final int stopEnergy) { int energy = getEnergy(); for (int d = 0; d < 5; d++) { methods.interfaces.getComponent(INTERFACE_RUN_ORB, 1).doAction( "Rest"); methods.mouse.moveSlightly(); sleep(random(400, 600)); int anim = methods.players.getMyPlayer().getAnimation(); if (anim == 12108 || anim == 2033 || anim == 2716 || anim == 11786 || anim == 5713) { break; } if (d == 4) { return false; } } while (energy < stopEnergy) { sleep(random(250, 500)); energy = getEnergy(); } return true; } /** * Turns run on or off using the game GUI controls. * * @param enable <tt>true</tt> to enable run, <tt>false</tt> to disable it. */ public void setRun(final boolean enable) { if (isRunEnabled() != enable) { methods.interfaces.getComponent(INTERFACE_RUN_ORB, 0).doClick(); } } /** * Generates a path from the player's current location to a destination * tile. * * @param destination The destination tile. * @return The path as an RSTile array. */ @Deprecated public RSTile[] findPath(RSTile destination) { RSLocalPath path = new RSLocalPath(methods, destination); if (path.isValid()) { RSTilePath tp = path.getCurrentTilePath(); if (tp != null) { return tp.toArray(); } } return new RSTile[0]; } /** * Randomizes a single tile. * * @param tile The RSTile to randomize. * @param maxXDeviation Max X distance from tile.getX(). * @param maxYDeviation Max Y distance from tile.getY(). * @return The randomized tile. * @deprecated Use * {@link org.rsbot.script.wrappers.RSTile#randomize(int, int)}. */ @Deprecated public RSTile randomize(RSTile tile, int maxXDeviation, int maxYDeviation) { return tile.randomize(maxXDeviation, maxYDeviation); } /** * Returns the closest tile on the minimap to a given tile. * * @param tile The destination tile. * @return Returns the closest tile to the destination on the minimap. */ public RSTile getClosestTileOnMap(final RSTile tile) { if (!methods.calc.tileOnMap(tile) && methods.game.isLoggedIn()) { RSTile loc = methods.players.getMyPlayer().getLocation(); RSTile walk = new RSTile((loc.getX() + tile.getX()) / 2, (loc.getY() + tile.getY()) / 2); return methods.calc.tileOnMap(walk) ? walk : getClosestTileOnMap(walk); } return tile; } /** * Returns whether or not run is enabled. * * @return <tt>true</tt> if run mode is enabled; otherwise <tt>false</tt>. */ public boolean isRunEnabled() { return methods.settings.getSetting(173) == 1; } /** * Returns the player's current run energy. * * @return The player's current run energy. */ public int getEnergy() { try { return Integer.parseInt(methods.interfaces.getComponent(750, 5) .getText()); } catch (NumberFormatException e) { return 0; } } /** * Gets the destination tile (where the flag is on the minimap). If there is * no destination currently, null will be returned. * * @return The current destination tile, or null. */ public RSTile getDestination() { if (methods.client.getDestX() <= 0) { return null; } return new RSTile( methods.client.getDestX() + methods.client.getBaseX(), methods.client.getDestY() + methods.client.getBaseY()); } /** * Gets the collision flags for a given floor level in the loaded region. * * @param plane The floor level (0, 1, 2 or 3). * @return the collision flags. */ public int[][] getCollisionFlags(final int plane) { return methods.client.getRSGroundDataArray()[plane].getBlocks(); } /** * Returns the collision map offset from the current region base on a given * plane. * * @param plane The floor level. * @return The offset as an RSTile. */ public RSTile getCollisionOffset(final int plane) { org.rsbot.client.RSGroundData data = methods.client .getRSGroundDataArray()[plane]; return new RSTile(data.getX(), data.getY()); } // DEPRECATED /** * Randomizes a single tile. * * @param tile The RSTile to randomize. * @param maxXDeviation Max X distance from tile.getX(). * @param maxYDeviation Max Y distance from tile.getY(). * @return The randomized tile. * @deprecated Use * {@link #randomize(org.rsbot.script.wrappers.RSTile, int, int)} * . */ @Deprecated public RSTile randomizeTile(RSTile tile, int maxXDeviation, int maxYDeviation) { return randomize(tile, maxXDeviation, maxYDeviation); } /** * Walks towards the end of a path. This method should be looped. * * @param path The path to walk along. * @return <tt>true</tt> if the next tile was reached; otherwise * <tt>false</tt>. * @see #walkPathMM(RSTile[], int) */ @Deprecated public boolean walkPathMM(RSTile[] path) { return walkPathMM(path, 16); } /** * Walks towards the end of a path. This method should be looped. * * @param path The path to walk along. * @param maxDist See {@link #nextTile(RSTile[], int)}. * @return <tt>true</tt> if the next tile was reached; otherwise * <tt>false</tt>. * @see #walkPathMM(RSTile[], int, int) */ @Deprecated public boolean walkPathMM(RSTile[] path, int maxDist) { return walkPathMM(path, maxDist, 1, 1); } /** * Walks towards the end of a path. This method should be looped. * * @param path The path to walk along. * @param randX The X value to randomize each tile in the path by. * @param randY The Y value to randomize each tile in the path by. * @return <tt>true</tt> if the next tile was reached; otherwise * <tt>false</tt>. * @see #walkPathMM(RSTile[], int, int, int) */ @Deprecated public boolean walkPathMM(RSTile[] path, int randX, int randY) { return walkPathMM(path, 16, randX, randY); } /** * Walks towards the end of a path. This method should be looped. * * @param path The path to walk along. * @param maxDist See {@link #nextTile(RSTile[], int)}. * @param randX The X value to randomize each tile in the path by. * @param randY The Y value to randomize each tile in the path by. * @return <tt>true</tt> if the next tile was reached; otherwise * <tt>false</tt>. */ @Deprecated public boolean walkPathMM(RSTile[] path, int maxDist, int randX, int randY) { try { RSTile next = nextTile(path, maxDist); return next != null && walkTileMM(next, randX, randY); } catch (Exception e) { return false; } } /** * Walks to the end of a path via the screen. This method should be looped. * * @param path The path to walk along. * @return <tt>true</tt> if the next tile was reached; otherwise * <tt>false</tt>. * @see #walkPathOnScreen(RSTile[], int) */ @Deprecated public boolean walkPathOnScreen(RSTile[] path) { return walkPathOnScreen(path, 16); } /** * Walks a path using onScreen clicks and not the MiniMap. If the next tile * is not on the screen, it will find the closest tile that is on screen and * it will walk there instead. * * @param path Path to walk. * @param maxDist Max distance between tiles in the path. * @return True if successful. */ @Deprecated public boolean walkPathOnScreen(RSTile[] path, int maxDist) { RSTile next = nextTile(path, maxDist); if (next != null) { RSTile os = methods.calc.getTileOnScreen(next); return os != null && methods.tiles.doAction(os, "Walk"); } return false; } /** * Reverses an array of tiles. * * @param other The <tt>RSTile</tt> path array to reverse. * @return The reverse <tt>RSTile</tt> path for the given <tt>RSTile</tt> * path. */ @Deprecated public RSTile[] reversePath(RSTile[] other) { RSTile[] t = new RSTile[other.length]; for (int i = 0; i < t.length; i++) { t[i] = other[other.length - i - 1]; } return t; } /** * Returns the next tile to walk to on a path. * * @param path The path. * @return The next <tt>RSTile</tt> to walk to on the provided path; or * <code>null</code> if far from path or at destination. * @see #nextTile(RSTile[], int) */ @Deprecated public RSTile nextTile(RSTile path[]) { return nextTile(path, 17); } /** * Returns the next tile to walk to in a path. * * @param path The path. * @param skipDist If the distance to the tile after the next in the path is less * than or equal to this distance, the tile after next will be * returned rather than the next tile, skipping one. This * interlacing aids continuous walking. * @return The next <tt>RSTile</tt> to walk to on the provided path; or * <code>null</code> if far from path or at destination. */ @Deprecated public RSTile nextTile(RSTile path[], int skipDist) { int dist = 99; int closest = -1; for (int i = path.length - 1; i >= 0; i--) { RSTile tile = path[i]; int d = methods.calc.distanceTo(tile); if (d < dist) { dist = d; closest = i; } } int feasibleTileIndex = -1; for (int i = closest; i < path.length; i++) { if (methods.calc.distanceTo(path[i]) <= skipDist) { feasibleTileIndex = i; } else { break; } } if (feasibleTileIndex == -1) { return null; } else { return path[feasibleTileIndex]; } } /** * Randomizes a path of tiles. * * @param path The RSTiles to randomize. * @param maxXDeviation Max X distance from tile.getX(). * @param maxYDeviation Max Y distance from tile.getY(). * @return The new, randomized path. */ @Deprecated public RSTile[] randomizePath(RSTile[] path, int maxXDeviation, int maxYDeviation) { RSTile[] rez = new RSTile[path.length]; for (int i = 0; i < path.length; i++) { rez[i] = randomize(path[i], maxXDeviation, maxYDeviation); } return rez; } /** * Returns the web of a path. * * @param to The tile to walk to. * @return Returns the web allocation. */ public Web getWebPath(final RSTile to) { return new Web(methods, methods.players.getMyPlayer().getLocation(), to); } }
false
true
public boolean walkTileMM(final RSTile t, final int x, final int y) { RSTile dest = new RSTile(t.getX() + random(0, x), t.getY() + random(0, y)); if (!methods.calc.tileOnMap(dest)) { dest = getClosestTileOnMap(dest); } Point p = methods.calc.tileToMinimap(dest); if (p.x != -1 && p.y != -1) { int x = p.x, y = p.y; if (random(1, 2) == random(1, 2)) { x += random(0, 50); } else { x -= random(0, 50); } if (random(1, 2) == random(1, 2)) { y += random(0, 50); } else { y -= random(0, 50); } methods.mouse.move(x, y); p = calc.tileToMinimap(dest); if (p.x == -1 || p.y == -1) { return false; } methods.mouse.move(p); Point p2 = methods.calc.tileToMinimap(dest); if (p2.x != -1 && p2.y != -1) { methods.mouse.move(p2); if (!methods.mouse.getLocation().equals(p2)) { methods.mouse.hop(p2); } methods.mouse.click(p2, true); return true; } } return false; }
public boolean walkTileMM(final RSTile t, final int x, final int y) { RSTile dest = new RSTile(t.getX() + random(0, x), t.getY() + random(0, y)); if (!methods.calc.tileOnMap(dest)) { dest = getClosestTileOnMap(dest); } Point p = methods.calc.tileToMinimap(dest); if (p.x != -1 && p.y != -1) { int xx = p.x, yy = p.y; if (random(1, 2) == random(1, 2)) { xx += random(0, 50); } else { xx -= random(0, 50); } if (random(1, 2) == random(1, 2)) { yy += random(0, 50); } else { yy -= random(0, 50); } methods.mouse.move(xx, yy); p = methods.calc.tileToMinimap(dest); if (p.x == -1 || p.y == -1) { return false; } methods.mouse.move(p); Point p2 = methods.calc.tileToMinimap(dest); if (p2.x != -1 && p2.y != -1) { methods.mouse.move(p2); if (!methods.mouse.getLocation().equals(p2)) { methods.mouse.hop(p2); } methods.mouse.click(p2, true); return true; } } return false; }
diff --git a/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.diagram.ui.render/src/org/eclipse/gmf/runtime/diagram/ui/render/util/PartPositionInfoGenerator.java b/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.diagram.ui.render/src/org/eclipse/gmf/runtime/diagram/ui/render/util/PartPositionInfoGenerator.java index 5e5541e1..14b78bf9 100644 --- a/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.diagram.ui.render/src/org/eclipse/gmf/runtime/diagram/ui/render/util/PartPositionInfoGenerator.java +++ b/org.eclipse.gmf.runtime/plugins/org.eclipse.gmf.runtime.diagram.ui.render/src/org/eclipse/gmf/runtime/diagram/ui/render/util/PartPositionInfoGenerator.java @@ -1,273 +1,273 @@ /****************************************************************************** * Copyright (c) 2009, 2010 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ****************************************************************************/ package org.eclipse.gmf.runtime.diagram.ui.render.util; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.PolylineConnection; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.PointList; import org.eclipse.draw2d.geometry.PrecisionPoint; import org.eclipse.draw2d.geometry.PrecisionRectangle; import org.eclipse.gef.ConnectionEditPart; import org.eclipse.gef.LayerConstants; import org.eclipse.gef.editparts.LayerManager; import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil; import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.LabelEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeCompartmentEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeEditPart; import org.eclipse.gmf.runtime.diagram.ui.image.PartPositionInfo; import org.eclipse.gmf.runtime.draw2d.ui.geometry.LineSeg; import org.eclipse.gmf.runtime.draw2d.ui.geometry.PointListUtilities; import org.eclipse.gmf.runtime.draw2d.ui.geometry.PrecisionPointList; import org.eclipse.gmf.runtime.draw2d.ui.geometry.LineSeg.Sign; import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode; import org.eclipse.gmf.runtime.draw2d.ui.mapmode.MapModeUtil; import org.eclipse.gmf.runtime.notation.View; /** * A Utility class to generate the info for images of diagrams * * @author aboyko * @since 1.3 * */ public final class PartPositionInfoGenerator { /** * Margin around the connection. <code>Double</code> value is expected. The * generator picks the maximum between this value and the line width of the * connection. The value must be in logical units. * <p>Default value of 0 is taken if options is not provided</p> */ public static final String CONNECTION_MARGIN = "connectionMargin"; //$NON-NLS-1$ /** * Point of the origin of the diagram, this is expected to be a * {@link org.eclipse.draw2d.geometry.Point} in logical units, relative to * printable layer. * <p>Default value of (0,0) is taken if this option is not provided</p> */ public static final String DIAGRAM_ORIGIN = "diagramOrigin"; //$NON-NLS-1$ /** * Scaling factor for generating parts info for scaled down or up diagram. * Double is expected. * <p>Default value of 1.0 will be taken if this option is * not provided</p> */ public static final String SCALE_FACTOR = "scaleFactor"; //$NON-NLS-1$ /** * Generates the info for a diagram * * @param diagramEditPart the diagram * @param options options affecting positional info * @return a list of <code>PartPositionInfo</code> */ public static final List<PartPositionInfo> getDiagramPartInfo( DiagramEditPart diagramEditPart, Map<String, Object> options) { List<PartPositionInfo> result = new ArrayList<PartPositionInfo>(); List<IGraphicalEditPart> editParts = new ArrayList<IGraphicalEditPart>(); List<IGraphicalEditPart> children = (List<IGraphicalEditPart>) diagramEditPart.getPrimaryEditParts(); IMapMode mm = MapModeUtil.getMapMode(diagramEditPart.getFigure()); - double connectionMargin = options.get(PartPositionInfoGenerator.CONNECTION_MARGIN) != null ? - ((Double)options.get(PartPositionInfoGenerator.CONNECTION_MARGIN)).doubleValue() : 0; - Point origin = options.get(PartPositionInfoGenerator.DIAGRAM_ORIGIN) != null ? - (Point)options.get(PartPositionInfoGenerator.DIAGRAM_ORIGIN) : new Point(); - double scale = options.get(PartPositionInfoGenerator.SCALE_FACTOR) != null ? - ((Double)options.get(PartPositionInfoGenerator.CONNECTION_MARGIN)).doubleValue() : 1.0; + Object optionConnectionMargin = options.get(PartPositionInfoGenerator.CONNECTION_MARGIN); + double connectionMargin = optionConnectionMargin != null ? ((Double)optionConnectionMargin).doubleValue() : 0; + Object optionDiagramOrigin = options.get(PartPositionInfoGenerator.DIAGRAM_ORIGIN); + Point origin = optionDiagramOrigin != null ? (Point)optionDiagramOrigin : new Point(); + Object optionScaleFactor = options.get(PartPositionInfoGenerator.SCALE_FACTOR); + double scale = optionScaleFactor != null ? ((Double)optionScaleFactor).doubleValue() : 1.0; if (scale <= 0) { throw new IllegalArgumentException(); } for (IGraphicalEditPart part : children) { editParts.add(part); getNestedEditParts(part, editParts); } IFigure printableLayer = LayerManager.Helper.find(diagramEditPart) .getLayer(LayerConstants.PRINTABLE_LAYERS); for (IGraphicalEditPart part : editParts) { IFigure figure = part.getFigure(); // Need to support any kind of shape edit part // and shape compartments, too, because these sometimes // correspond to distinct semantic elements View view = part.getNotationView(); if (part instanceof ConnectionEditPart && figure instanceof PolylineConnection) { // find a way to get (P1, P2, ... PN) for connection edit part // add MARGIN and calculate "stripe" for the polyline instead of // bounding box. PartPositionInfo position = new PartPositionInfo(); position.setView(view); position.setSemanticElement(ViewUtil .resolveSemanticElement(view)); PolylineConnection mainPoly = (PolylineConnection) figure; if (mainPoly.isVisible() && !mainPoly.getBounds().isEmpty()) { PointList mainPts = mainPoly.getPoints().getCopy(); DiagramImageUtils.translateTo(mainPts, figure, printableLayer); PointList envelopingPts = calculateEnvelopingPolyline(mainPts, (int) Math.max(connectionMargin, mainPoly .getLineWidth() >> 1)); envelopingPts.translate(new PrecisionPoint(-origin.preciseX(), -origin.preciseY())); mm.LPtoDP(envelopingPts); envelopingPts.performScale(scale); List<Point> pts = new ArrayList(envelopingPts.size()); for (int i = 0; i < envelopingPts.size(); i++) { pts.add(envelopingPts.getPoint(i)); } position.setPolyline(pts); } result.add(0, position); } else if ((view != null && view.isSetElement()) || (part instanceof ShapeEditPart || part instanceof ShapeCompartmentEditPart || part instanceof LabelEditPart)) { PartPositionInfo position = new PartPositionInfo(); position.setView(view); position.setSemanticElement(ViewUtil .resolveSemanticElement(view)); if (figure.isShowing() && !figure.getBounds().isEmpty()) { PrecisionRectangle bounds = new PrecisionRectangle(figure .getBounds()); DiagramImageUtils.translateTo(bounds, figure, printableLayer); bounds.translate(new PrecisionPoint(-origin.preciseX(), -origin .preciseY())); mm.LPtoDP(bounds); bounds.performScale(scale); position.setPartHeight(bounds.height); position.setPartWidth(bounds.width); position.setPartX(bounds.x); position.setPartY(bounds.y); } result.add(0, position); } } return result; } private static void getNestedEditParts(IGraphicalEditPart childEditPart, Collection editParts) { for (Iterator iter = childEditPart.getChildren().iterator(); iter .hasNext();) { IGraphicalEditPart child = (IGraphicalEditPart) iter.next(); editParts.add(child); getNestedEditParts(child, editParts); } } /** * Calculates enveloping polyline for a given polyline with margin MARGIN * * E1 E2 * +----------------+ * | |<------- MARGIN * A *----------------* B * | | * +----------------+ * E4 E3 * * On the figure above: AB is a given polyline. E1E2E3E4 is enveloping * polyline built around AB perimeter using margin MARGIN. * * * @param polyPts * @param origin * location of the main diagram bounding box used to shift * coordinates to be relative against diagram * * @return List of Point type objects (that carry X and Y coordinate pair) * representing the polyline */ private static PointList calculateEnvelopingPolyline(PointList polyPts, int margin) { PointList result = new PrecisionPointList(polyPts.size() << 1); List<LineSeg> mainSegs = (List<LineSeg>) PointListUtilities.getLineSegments(polyPts); removeRedundantSegments(mainSegs); if (mainSegs.size() > 0) { result = calculateParallelPolyline(mainSegs, margin); PointList pts = calculateParallelPolyline(mainSegs, -margin); for (int i = pts.size() - 1; i >= 0; i--) { result.addPoint(pts.getPoint(i)); } result.addPoint(result.getFirstPoint()); } return result; } private static void removeRedundantSegments(List<LineSeg> polyPts) { for (Iterator<LineSeg> itr = polyPts.listIterator(); itr.hasNext();) { LineSeg lineSeg = itr.next(); if (lineSeg.getOrigin().equals(lineSeg.getTerminus())) { itr.remove(); } } } /** * Calculates polyline offset from the given polyline by the margin value * * ResultA ResultB * +----------------+ * | |<------- MARGIN * A *----------------* B * * On the figure above: AB is a given polyline. ResultA-ResultB is the result * @param polySegs given polyline * @param margin offset from given poly-line, can be negative. * @return offset or parallel polyline. */ private static PointList calculateParallelPolyline(List<LineSeg> polySegs, int margin) { PointList result = new PrecisionPointList(polySegs.size() << 2); int index = 0; int absMargin = Math.abs(margin); Sign sign = margin < 0 ? Sign.NEGATIVE : Sign.POSITIVE; LineSeg parallel_1, parallel_2; result.addPoint(polySegs.get(index++).locatePoint(0, absMargin, sign)); parallel_1 = polySegs.get(index - 1).getParallelLineSegThroughPoint(result.getLastPoint()); for (; index < polySegs.size(); index++) { parallel_2 = polySegs.get(index).getParallelLineSegThroughPoint( polySegs.get(index).locatePoint(0, absMargin, sign)); PointList intersections = parallel_1.getLinesIntersections(parallel_2); if (intersections.size() > 0) { result.addPoint(intersections.getFirstPoint()); } else { result.addPoint(parallel_1.getTerminus()); result.addPoint(parallel_2.getOrigin()); } parallel_1 = parallel_2; } result.addPoint(polySegs.get(index - 1).locatePoint(1.0, absMargin, sign)); return result; } }
true
true
public static final List<PartPositionInfo> getDiagramPartInfo( DiagramEditPart diagramEditPart, Map<String, Object> options) { List<PartPositionInfo> result = new ArrayList<PartPositionInfo>(); List<IGraphicalEditPart> editParts = new ArrayList<IGraphicalEditPart>(); List<IGraphicalEditPart> children = (List<IGraphicalEditPart>) diagramEditPart.getPrimaryEditParts(); IMapMode mm = MapModeUtil.getMapMode(diagramEditPart.getFigure()); double connectionMargin = options.get(PartPositionInfoGenerator.CONNECTION_MARGIN) != null ? ((Double)options.get(PartPositionInfoGenerator.CONNECTION_MARGIN)).doubleValue() : 0; Point origin = options.get(PartPositionInfoGenerator.DIAGRAM_ORIGIN) != null ? (Point)options.get(PartPositionInfoGenerator.DIAGRAM_ORIGIN) : new Point(); double scale = options.get(PartPositionInfoGenerator.SCALE_FACTOR) != null ? ((Double)options.get(PartPositionInfoGenerator.CONNECTION_MARGIN)).doubleValue() : 1.0; if (scale <= 0) { throw new IllegalArgumentException(); } for (IGraphicalEditPart part : children) { editParts.add(part); getNestedEditParts(part, editParts); } IFigure printableLayer = LayerManager.Helper.find(diagramEditPart) .getLayer(LayerConstants.PRINTABLE_LAYERS); for (IGraphicalEditPart part : editParts) { IFigure figure = part.getFigure(); // Need to support any kind of shape edit part // and shape compartments, too, because these sometimes // correspond to distinct semantic elements View view = part.getNotationView(); if (part instanceof ConnectionEditPart && figure instanceof PolylineConnection) { // find a way to get (P1, P2, ... PN) for connection edit part // add MARGIN and calculate "stripe" for the polyline instead of // bounding box. PartPositionInfo position = new PartPositionInfo(); position.setView(view); position.setSemanticElement(ViewUtil .resolveSemanticElement(view)); PolylineConnection mainPoly = (PolylineConnection) figure; if (mainPoly.isVisible() && !mainPoly.getBounds().isEmpty()) { PointList mainPts = mainPoly.getPoints().getCopy(); DiagramImageUtils.translateTo(mainPts, figure, printableLayer); PointList envelopingPts = calculateEnvelopingPolyline(mainPts, (int) Math.max(connectionMargin, mainPoly .getLineWidth() >> 1)); envelopingPts.translate(new PrecisionPoint(-origin.preciseX(), -origin.preciseY())); mm.LPtoDP(envelopingPts); envelopingPts.performScale(scale); List<Point> pts = new ArrayList(envelopingPts.size()); for (int i = 0; i < envelopingPts.size(); i++) { pts.add(envelopingPts.getPoint(i)); } position.setPolyline(pts); } result.add(0, position); } else if ((view != null && view.isSetElement()) || (part instanceof ShapeEditPart || part instanceof ShapeCompartmentEditPart || part instanceof LabelEditPart)) { PartPositionInfo position = new PartPositionInfo(); position.setView(view); position.setSemanticElement(ViewUtil .resolveSemanticElement(view)); if (figure.isShowing() && !figure.getBounds().isEmpty()) { PrecisionRectangle bounds = new PrecisionRectangle(figure .getBounds()); DiagramImageUtils.translateTo(bounds, figure, printableLayer); bounds.translate(new PrecisionPoint(-origin.preciseX(), -origin .preciseY())); mm.LPtoDP(bounds); bounds.performScale(scale); position.setPartHeight(bounds.height); position.setPartWidth(bounds.width); position.setPartX(bounds.x); position.setPartY(bounds.y); } result.add(0, position); } } return result; }
public static final List<PartPositionInfo> getDiagramPartInfo( DiagramEditPart diagramEditPart, Map<String, Object> options) { List<PartPositionInfo> result = new ArrayList<PartPositionInfo>(); List<IGraphicalEditPart> editParts = new ArrayList<IGraphicalEditPart>(); List<IGraphicalEditPart> children = (List<IGraphicalEditPart>) diagramEditPart.getPrimaryEditParts(); IMapMode mm = MapModeUtil.getMapMode(diagramEditPart.getFigure()); Object optionConnectionMargin = options.get(PartPositionInfoGenerator.CONNECTION_MARGIN); double connectionMargin = optionConnectionMargin != null ? ((Double)optionConnectionMargin).doubleValue() : 0; Object optionDiagramOrigin = options.get(PartPositionInfoGenerator.DIAGRAM_ORIGIN); Point origin = optionDiagramOrigin != null ? (Point)optionDiagramOrigin : new Point(); Object optionScaleFactor = options.get(PartPositionInfoGenerator.SCALE_FACTOR); double scale = optionScaleFactor != null ? ((Double)optionScaleFactor).doubleValue() : 1.0; if (scale <= 0) { throw new IllegalArgumentException(); } for (IGraphicalEditPart part : children) { editParts.add(part); getNestedEditParts(part, editParts); } IFigure printableLayer = LayerManager.Helper.find(diagramEditPart) .getLayer(LayerConstants.PRINTABLE_LAYERS); for (IGraphicalEditPart part : editParts) { IFigure figure = part.getFigure(); // Need to support any kind of shape edit part // and shape compartments, too, because these sometimes // correspond to distinct semantic elements View view = part.getNotationView(); if (part instanceof ConnectionEditPart && figure instanceof PolylineConnection) { // find a way to get (P1, P2, ... PN) for connection edit part // add MARGIN and calculate "stripe" for the polyline instead of // bounding box. PartPositionInfo position = new PartPositionInfo(); position.setView(view); position.setSemanticElement(ViewUtil .resolveSemanticElement(view)); PolylineConnection mainPoly = (PolylineConnection) figure; if (mainPoly.isVisible() && !mainPoly.getBounds().isEmpty()) { PointList mainPts = mainPoly.getPoints().getCopy(); DiagramImageUtils.translateTo(mainPts, figure, printableLayer); PointList envelopingPts = calculateEnvelopingPolyline(mainPts, (int) Math.max(connectionMargin, mainPoly .getLineWidth() >> 1)); envelopingPts.translate(new PrecisionPoint(-origin.preciseX(), -origin.preciseY())); mm.LPtoDP(envelopingPts); envelopingPts.performScale(scale); List<Point> pts = new ArrayList(envelopingPts.size()); for (int i = 0; i < envelopingPts.size(); i++) { pts.add(envelopingPts.getPoint(i)); } position.setPolyline(pts); } result.add(0, position); } else if ((view != null && view.isSetElement()) || (part instanceof ShapeEditPart || part instanceof ShapeCompartmentEditPart || part instanceof LabelEditPart)) { PartPositionInfo position = new PartPositionInfo(); position.setView(view); position.setSemanticElement(ViewUtil .resolveSemanticElement(view)); if (figure.isShowing() && !figure.getBounds().isEmpty()) { PrecisionRectangle bounds = new PrecisionRectangle(figure .getBounds()); DiagramImageUtils.translateTo(bounds, figure, printableLayer); bounds.translate(new PrecisionPoint(-origin.preciseX(), -origin .preciseY())); mm.LPtoDP(bounds); bounds.performScale(scale); position.setPartHeight(bounds.height); position.setPartWidth(bounds.width); position.setPartX(bounds.x); position.setPartY(bounds.y); } result.add(0, position); } } return result; }
diff --git a/console/embed/src/test/java/org/javasimon/console/JettyMain.java b/console/embed/src/test/java/org/javasimon/console/JettyMain.java index 935feaf2..41879b17 100644 --- a/console/embed/src/test/java/org/javasimon/console/JettyMain.java +++ b/console/embed/src/test/java/org/javasimon/console/JettyMain.java @@ -1,212 +1,216 @@ package org.javasimon.console; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.javasimon.SimonManager; import org.javasimon.Split; import org.javasimon.Stopwatch; import org.javasimon.callback.CompositeCallback; import org.javasimon.callback.CompositeCallbackImpl; import org.javasimon.callback.async.AsyncCallbackProxyFactory; import org.javasimon.callback.calltree.CallTreeCallback; import org.javasimon.callback.quantiles.AutoQuantilesCallback; import org.javasimon.callback.timeline.TimelineCallback; import org.javasimon.console.plugin.CallTreeDetailPlugin; import org.javasimon.console.plugin.QuantilesDetailPlugin; import org.javasimon.console.plugin.TimelineDetailPlugin; import org.javasimon.utils.SimonUtils; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Main using Jetty to test Simon Console. * @author gquintana */ public class JettyMain { /** * Jetty Server */ private Server server; private Lock lock=new ReentrantLock(); /** * Time for changing Simons */ private Timer timer=new Timer(); /** * Random generator to generate Simons */ private final RandomHelper random=new RandomHelper(); /** * Initialize Jetty Server */ private void initServer() { // Server server = new Server(8080); // Context ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); // Callbacks CompositeCallback compositeCallback=new CompositeCallbackImpl(); + // QuantilesCallback automatically configured after 5 splits (5 buckets) compositeCallback.addCallback(new AutoQuantilesCallback(5, 5)); -// compositeCallback.addCallback(new FixedQuantilesCallback(0L, 200L, 5)); - compositeCallback.addCallback(new CallTreeCallback(50)); + // QuantilesCallback manually configured 5 duration buckets 200ms wide each + // compositeCallback.addCallback(new FixedQuantilesCallback(0L, 200L, 5)); + // TimelineCallback 10 time range buckets of 1 minute each compositeCallback.addCallback(new TimelineCallback(10, 60000L)); SimonManager.callback().addCallback(new AsyncCallbackProxyFactory(compositeCallback).newProxy()); + // CallTreeCallback doesn't support asynchronism + SimonManager.callback().addCallback(new CallTreeCallback(50)); // Simon Servlet final SimonConsoleServlet simonConsoleServlet = new SimonConsoleServlet(); ServletHolder servletHolder=new ServletHolder(simonConsoleServlet); servletHolder.setInitParameter("console-path", ""); servletHolder.setInitParameter("plugin-classes", QuantilesDetailPlugin.class.getName() +","+CallTreeDetailPlugin.class.getName() +","+TimelineDetailPlugin.class.getName()); context.addServlet(servletHolder, "/*"); } /** * Add Simons */ private void initData() { addDefaultSimons(); addChangingSimons(); addStackedSimons(); addManySimons(); } /** * Run Jetty and wait till it stops */ private void runAndWait() throws Exception { // Start server thread server.start(); server.join(); } /** * Main method */ public static void main(String[] args) { try { JettyMain main=new JettyMain(); main.initServer(); main.initData(); main.runAndWait(); } catch (Exception e) { e.printStackTrace(); } } /** * Add basic simons A, B, C and X. * X is used to test Counter rendering * */ private void addDefaultSimons() { SimonData.initialize(); } /** * Starts a timer which changes Simons values. * TL is used to test Timeline and Quantiles plugins rendering */ private void addChangingSimons() { timer.schedule(new TimerTask(){ final Stopwatch tlStopwatch= SimonManager.getStopwatch("TL"); @Override public void run() { try { lock.lock(); System.out.println("TL "+ addStopwatchSplit(tlStopwatch)); } finally { lock.unlock(); } } }, 0, 10000L); } /** * Add many Simons for performances testing * Z.* Simons are used for performance testing */ private void addManySimons() { new Thread() { @Override public void run() { addManySimons("Z", 4, 3, 3, 6); } }.start(); } private static final String ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; /** * Recursively Add many Simons for performances testing */ private void addManySimons(String prefix, int depth, int groupWidth, int leafWidth, int splitWidth) { if (depth==0) { // Generate Simons of type Stopwatch final int sibblings = random.randomInt(Math.min(1, groupWidth / 2), leafWidth); for(int i=0;i<sibblings;i++) { String name=prefix+"."+ALPHABET.charAt(i); addStopwatchSplits(SimonManager.getStopwatch(name), splitWidth); } } else { // Generate Simons of type Unknown final int sibblings = random.randomInt(Math.min(1, groupWidth / 2), groupWidth); for(int i=0;i<sibblings;i++) { String name=prefix+"."+ALPHABET.charAt(i); addManySimons(name, depth - 1, groupWidth, leafWidth, splitWidth); } } } /** * Generate a split for a Stopwatch */ private long addStopwatchSplit(Stopwatch stopwatch) { Split split=stopwatch.start(); try { random.randomWait(50,150); } finally { split.stop(); } return split.runningFor()/SimonUtils.NANOS_IN_MILLIS; } /** * Generate a Simon of type "Stopwatch" and fill it with some Splits * @param splitWidth Max number of splits per Stopwatch */ private void addStopwatchSplits(Stopwatch stopwatch, int splitWidth) { final int splits = random.randomInt(splitWidth / 2, splitWidth); try { lock.lock(); System.out.print(stopwatch.getName()+" "+splits+": "); for(int i=0;i<splits;i++) { System.out.print(addStopwatchSplit(stopwatch)+","); } System.out.println(); } finally { lock.unlock(); } } /** * Stacked stopwatches to test call tree */ private void addStackedSimons() { Split splitA=SimonManager.getStopwatch("Y.A").start(); Split splitB=SimonManager.getStopwatch("Y.B").start(); addStopwatchSplits(SimonManager.getStopwatch("Y.C"), 6); splitB.stop(); Split splitD=SimonManager.getStopwatch("Y.D").start(); random.randomWait(100,250); random.randomWait(100,250); splitD.stop(); splitA.stop(); } }
false
true
private void initServer() { // Server server = new Server(8080); // Context ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); // Callbacks CompositeCallback compositeCallback=new CompositeCallbackImpl(); compositeCallback.addCallback(new AutoQuantilesCallback(5, 5)); // compositeCallback.addCallback(new FixedQuantilesCallback(0L, 200L, 5)); compositeCallback.addCallback(new CallTreeCallback(50)); compositeCallback.addCallback(new TimelineCallback(10, 60000L)); SimonManager.callback().addCallback(new AsyncCallbackProxyFactory(compositeCallback).newProxy()); // Simon Servlet final SimonConsoleServlet simonConsoleServlet = new SimonConsoleServlet(); ServletHolder servletHolder=new ServletHolder(simonConsoleServlet); servletHolder.setInitParameter("console-path", ""); servletHolder.setInitParameter("plugin-classes", QuantilesDetailPlugin.class.getName() +","+CallTreeDetailPlugin.class.getName() +","+TimelineDetailPlugin.class.getName()); context.addServlet(servletHolder, "/*"); }
private void initServer() { // Server server = new Server(8080); // Context ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); // Callbacks CompositeCallback compositeCallback=new CompositeCallbackImpl(); // QuantilesCallback automatically configured after 5 splits (5 buckets) compositeCallback.addCallback(new AutoQuantilesCallback(5, 5)); // QuantilesCallback manually configured 5 duration buckets 200ms wide each // compositeCallback.addCallback(new FixedQuantilesCallback(0L, 200L, 5)); // TimelineCallback 10 time range buckets of 1 minute each compositeCallback.addCallback(new TimelineCallback(10, 60000L)); SimonManager.callback().addCallback(new AsyncCallbackProxyFactory(compositeCallback).newProxy()); // CallTreeCallback doesn't support asynchronism SimonManager.callback().addCallback(new CallTreeCallback(50)); // Simon Servlet final SimonConsoleServlet simonConsoleServlet = new SimonConsoleServlet(); ServletHolder servletHolder=new ServletHolder(simonConsoleServlet); servletHolder.setInitParameter("console-path", ""); servletHolder.setInitParameter("plugin-classes", QuantilesDetailPlugin.class.getName() +","+CallTreeDetailPlugin.class.getName() +","+TimelineDetailPlugin.class.getName()); context.addServlet(servletHolder, "/*"); }
diff --git a/beam-visat/src/main/java/org/esa/beam/visat/toolviews/pin/GcpGeoCodingForm.java b/beam-visat/src/main/java/org/esa/beam/visat/toolviews/pin/GcpGeoCodingForm.java index 7cf11923f..0c32a7b43 100644 --- a/beam-visat/src/main/java/org/esa/beam/visat/toolviews/pin/GcpGeoCodingForm.java +++ b/beam-visat/src/main/java/org/esa/beam/visat/toolviews/pin/GcpGeoCodingForm.java @@ -1,288 +1,288 @@ package org.esa.beam.visat.toolviews.pin; import org.esa.beam.framework.datamodel.GcpGeoCoding; import org.esa.beam.framework.datamodel.GeoCoding; import org.esa.beam.framework.datamodel.Pin; import org.esa.beam.framework.datamodel.Product; import org.esa.beam.framework.datamodel.ProductManager; import org.esa.beam.framework.datamodel.ProductNodeGroup; import org.esa.beam.framework.dataop.maptransf.Datum; import org.esa.beam.framework.ui.TableLayout; import org.esa.beam.util.Debug; import org.esa.beam.visat.VisatApp; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.SwingWorker; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import java.text.FieldPosition; import java.text.Format; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; /** * GCP geo-coding form. * * @author Marco Peters * @version $Revision:$ $Date:$ */ class GcpGeoCodingForm extends JPanel { private JTextField methodTextField; private JTextField rmseLatTextField; private JTextField rmseLonTextField; private JComboBox methodComboBox; private JToggleButton attachButton; private JTextField warningLabel; private Product currentProduct; private Format rmseNumberFormat; private Map<Product, GeoCoding> geoCodingMap; public GcpGeoCodingForm() { geoCodingMap = new HashMap<Product, GeoCoding>(); rmseNumberFormat = new RmseNumberFormat(); VisatApp.getApp().getProductManager().addListener(new ProductManager.ProductManagerListener() { public void productAdded(ProductManager.ProductManagerEvent event) { } public void productRemoved(ProductManager.ProductManagerEvent event) { geoCodingMap.remove(event.getProduct()); } }); initComponents(); } private void initComponents() { TableLayout layout = new TableLayout(2); this.setLayout(layout); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableWeightY(1.0); layout.setTableFill(TableLayout.Fill.BOTH); layout.setTablePadding(2, 2); layout.setColumnWeightX(0, 0.5); layout.setColumnWeightX(1, 0.5); add(createInfoPanel()); add(createAttachDetachPanel()); updateUIState(); } private JPanel createInfoPanel() { TableLayout layout = new TableLayout(2); layout.setTablePadding(2, 4); layout.setColumnWeightX(0, 0.0); layout.setColumnWeightX(1, 1.0); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableFill(TableLayout.Fill.BOTH); JPanel panel = new JPanel(layout); panel.setBorder(BorderFactory.createTitledBorder("Current GCP Geo-Coding")); panel.add(new JLabel("Method:")); methodTextField = new JTextField(); setComponentName(methodTextField, "methodTextField"); methodTextField.setEditable(false); methodTextField.setHorizontalAlignment(JLabel.TRAILING); panel.add(methodTextField); rmseLatTextField = new JTextField(); setComponentName(rmseLatTextField, "rmseLatTextField"); rmseLatTextField.setEditable(false); rmseLatTextField.setHorizontalAlignment(JLabel.TRAILING); panel.add(new JLabel("RMSE Lat:")); panel.add(rmseLatTextField); rmseLonTextField = new JTextField(); setComponentName(rmseLonTextField, "rmseLonTextField"); rmseLonTextField.setEditable(false); rmseLonTextField.setHorizontalAlignment(JLabel.TRAILING); panel.add(new JLabel("RMSE Lon:")); panel.add(rmseLonTextField); return panel; } private JPanel createAttachDetachPanel() { methodComboBox = new JComboBox(GcpGeoCoding.Method.values()); setComponentName(methodComboBox, "methodComboBox"); methodComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateUIState(); } }); attachButton = new JToggleButton(); setComponentName(attachButton, "attachButton"); attachButton.setName("attachButton"); AbstractAction applyAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { - if (attachButton.isSelected()) { + if (!(currentProduct.getGeoCoding() instanceof GcpGeoCoding)) { attachGeoCoding(currentProduct); } else { detachGeoCoding(currentProduct); } } }; attachButton.setAction(applyAction); attachButton.setHideActionText(true); warningLabel = new JTextField(); warningLabel.setEditable(false); TableLayout layout = new TableLayout(2); layout.setTablePadding(2, 4); layout.setColumnWeightX(0, 0.0); layout.setColumnWeightX(1, 1.0); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableFill(TableLayout.Fill.BOTH); layout.setCellColspan(2, 0, 2); layout.setCellFill(2, 0, TableLayout.Fill.VERTICAL); layout.setCellAnchor(2, 0, TableLayout.Anchor.CENTER); JPanel panel = new JPanel(layout); panel.setBorder(BorderFactory.createTitledBorder("Attach / Detach GCP Geo-Coding")); panel.add(new JLabel("Method:")); panel.add(methodComboBox); panel.add(new JLabel("Status:")); panel.add(warningLabel); panel.add(attachButton); return panel; } void updateUIState() { if (currentProduct != null && currentProduct.getGeoCoding() instanceof GcpGeoCoding) { final GcpGeoCoding gcpGeoCoding = (GcpGeoCoding) currentProduct.getGeoCoding(); rmseLatTextField.setText(rmseNumberFormat.format(gcpGeoCoding.getRmseLat())); rmseLonTextField.setText(rmseNumberFormat.format(gcpGeoCoding.getRmseLon())); methodTextField.setText(gcpGeoCoding.getMethod().getName()); methodComboBox.setSelectedItem(gcpGeoCoding.getMethod()); methodComboBox.setEnabled(false); attachButton.setText("Detach"); attachButton.setSelected(true); attachButton.setEnabled(true); warningLabel.setText("GCP geo-coding attached"); warningLabel.setForeground(Color.BLACK); } else { methodComboBox.setEnabled(true); methodTextField.setText("Not available"); rmseLatTextField.setText(rmseNumberFormat.format(Double.NaN)); rmseLonTextField.setText(rmseNumberFormat.format(Double.NaN)); attachButton.setText("Attach"); attachButton.setSelected(false); updateAttachButtonAndStatus(); } } private void updateAttachButtonAndStatus() { final GcpGeoCoding.Method method = (GcpGeoCoding.Method) methodComboBox.getSelectedItem(); if (currentProduct != null && currentProduct.getGcpGroup().getNodeCount() >= method.getTermCountP()) { attachButton.setEnabled(true); warningLabel.setText("OK, enough GCP's for selected method"); warningLabel.setForeground(Color.GREEN.darker()); } else { attachButton.setEnabled(false); warningLabel.setText("Not enough GCP's for selected method"); warningLabel.setForeground(Color.RED.darker()); } } private void detachGeoCoding(Product product) { if (product.getGeoCoding() instanceof GcpGeoCoding) { product.getGeoCoding().dispose(); product.setGeoCoding(geoCodingMap.get(product)); } updateUIState(); } private void attachGeoCoding(final Product product) { final GcpGeoCoding.Method method = (GcpGeoCoding.Method) methodComboBox.getSelectedItem(); final ProductNodeGroup<Pin> gcpGroup = product.getGcpGroup(); final Pin[] gcps = gcpGroup.toArray(new Pin[0]); final GeoCoding geoCoding = product.getGeoCoding(); final Datum datum; if(geoCoding == null) { datum = Datum.WGS_84; }else { datum = geoCoding.getDatum(); } SwingWorker sw = new SwingWorker<GcpGeoCoding, GcpGeoCoding>() { protected GcpGeoCoding doInBackground() throws Exception { return new GcpGeoCoding(method, gcps, product.getSceneRasterWidth(), product.getSceneRasterHeight(), datum); } @Override protected void done() { final GcpGeoCoding gcpGeoCoding; try { gcpGeoCoding = get(); product.setGeoCoding(gcpGeoCoding); updateUIState(); } catch (InterruptedException e) { Debug.trace(e); } catch (ExecutionException e) { Debug.trace(e.getCause()); } } }; sw.execute(); } public void setProduct(Product product) { if (product == currentProduct) { return; } currentProduct = product; if (product != null && !geoCodingMap.containsKey(product) && !(product.getGeoCoding() instanceof GcpGeoCoding)) { geoCodingMap.put(product, product.getGeoCoding()); } } private void setComponentName(JComponent component, String name) { component.setName(getClass().getName() + name); } private static class RmseNumberFormat extends NumberFormat { DecimalFormat format = new DecimalFormat("0.0####"); public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { if (Double.isNaN(number)) { return toAppendTo.append("Not available"); } else { return format.format(number, toAppendTo, pos); } } public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { return format.format(number, toAppendTo, pos); } public Number parse(String source, ParsePosition parsePosition) { return format.parse(source, parsePosition); } } }
true
true
private JPanel createAttachDetachPanel() { methodComboBox = new JComboBox(GcpGeoCoding.Method.values()); setComponentName(methodComboBox, "methodComboBox"); methodComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateUIState(); } }); attachButton = new JToggleButton(); setComponentName(attachButton, "attachButton"); attachButton.setName("attachButton"); AbstractAction applyAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { if (attachButton.isSelected()) { attachGeoCoding(currentProduct); } else { detachGeoCoding(currentProduct); } } }; attachButton.setAction(applyAction); attachButton.setHideActionText(true); warningLabel = new JTextField(); warningLabel.setEditable(false); TableLayout layout = new TableLayout(2); layout.setTablePadding(2, 4); layout.setColumnWeightX(0, 0.0); layout.setColumnWeightX(1, 1.0); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableFill(TableLayout.Fill.BOTH); layout.setCellColspan(2, 0, 2); layout.setCellFill(2, 0, TableLayout.Fill.VERTICAL); layout.setCellAnchor(2, 0, TableLayout.Anchor.CENTER); JPanel panel = new JPanel(layout); panel.setBorder(BorderFactory.createTitledBorder("Attach / Detach GCP Geo-Coding")); panel.add(new JLabel("Method:")); panel.add(methodComboBox); panel.add(new JLabel("Status:")); panel.add(warningLabel); panel.add(attachButton); return panel; }
private JPanel createAttachDetachPanel() { methodComboBox = new JComboBox(GcpGeoCoding.Method.values()); setComponentName(methodComboBox, "methodComboBox"); methodComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateUIState(); } }); attachButton = new JToggleButton(); setComponentName(attachButton, "attachButton"); attachButton.setName("attachButton"); AbstractAction applyAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { if (!(currentProduct.getGeoCoding() instanceof GcpGeoCoding)) { attachGeoCoding(currentProduct); } else { detachGeoCoding(currentProduct); } } }; attachButton.setAction(applyAction); attachButton.setHideActionText(true); warningLabel = new JTextField(); warningLabel.setEditable(false); TableLayout layout = new TableLayout(2); layout.setTablePadding(2, 4); layout.setColumnWeightX(0, 0.0); layout.setColumnWeightX(1, 1.0); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableFill(TableLayout.Fill.BOTH); layout.setCellColspan(2, 0, 2); layout.setCellFill(2, 0, TableLayout.Fill.VERTICAL); layout.setCellAnchor(2, 0, TableLayout.Anchor.CENTER); JPanel panel = new JPanel(layout); panel.setBorder(BorderFactory.createTitledBorder("Attach / Detach GCP Geo-Coding")); panel.add(new JLabel("Method:")); panel.add(methodComboBox); panel.add(new JLabel("Status:")); panel.add(warningLabel); panel.add(attachButton); return panel; }
diff --git a/expleo/app/models/Template.java b/expleo/app/models/Template.java index 6b11f37..c94d73c 100644 --- a/expleo/app/models/Template.java +++ b/expleo/app/models/Template.java @@ -1,162 +1,161 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package models; import java.io.File; import play.db.jpa.*; import play.data.validation.*; import java.util.*; import javax.persistence.*; import utils.io.FileStringReader; @Entity public class Template extends Model { public String name_; public String filename_; public String author_; public Date dateCreated_; public String description_; public int counterDownloads_; public HashMap templates_ = new HashMap<String, String>(); public TextFile textFile; public Template(String name_, String filename_, String author_, Date dateCreated_, String description_, int counterDownloads_) { this.name_ = name_; this.filename_ = filename_; this.author_ = author_; this.dateCreated_ = dateCreated_; this.description_ = description_; this.counterDownloads_ = counterDownloads_; } public void calculateForm() { this.textFile = new TextFile("/home/dave/sw11/Alt_F4/expleo/public/templates/" + filename_); Set<String> commands = new TreeSet<String>(); String[] commands_temp = this.textFile.getText().split("%%"); for (int i = 1; i < commands_temp.length; i += 2) { commands.add(commands_temp[i]); } Iterator iterator = commands.iterator(); while (iterator.hasNext()) { String command = (String) iterator.next(); templates_.put(command, ""); } } public static String upload(String name, String description, File template) { try { FileStringReader reader = new FileStringReader(template); String text = reader.read(); - //System.out.println(text); if(!Helper.isUtf8(text)) { return "File must be in UTF 8."; } Date now = new Date(); Template temp = new Template(name, template.getName(), "DummyAuthor", now, description, 4); temp.save(); int dotPos = template.getName().lastIndexOf("."); String newName; String extension; if (dotPos != -1) { extension = template.getName().substring(dotPos); newName = temp.id + "_" + name + extension; } else { newName = temp.id + "_" + name; } - File copy_to = new File("public/templates/" + newName); + File copy_to = new File("expleo/public/templates/" + newName); - //template.renameTo(copy_to); + System.out.println(copy_to.getAbsolutePath()); Helper.copy(template, copy_to); temp.filename_ = newName; temp.save(); return null; } catch (Exception e) { System.out.println(e.toString()); return e.toString(); } } public static void delete(long id) { Template temp = Template.find("id", id).first(); if (temp != null) { temp.delete(); } } public void addCommand(String command) { templates_.put(command, ""); } public void addSubstitution(String key, String userInput) { templates_.put(key, userInput); } public String getValue(String command) { return templates_.get(command).toString(); } @Override public String toString() { return this.name_; } public HashMap getTemplates_() { return templates_; } public void doMap(Map<String, String[]> map) { Iterator mapIterator = map.keySet().iterator(); while (mapIterator.hasNext()) { String temp = (String) mapIterator.next(); if (this.templates_.containsKey(temp)) { this.addSubstitution(temp, map.get(temp)[0]); } } } }
false
true
public static String upload(String name, String description, File template) { try { FileStringReader reader = new FileStringReader(template); String text = reader.read(); //System.out.println(text); if(!Helper.isUtf8(text)) { return "File must be in UTF 8."; } Date now = new Date(); Template temp = new Template(name, template.getName(), "DummyAuthor", now, description, 4); temp.save(); int dotPos = template.getName().lastIndexOf("."); String newName; String extension; if (dotPos != -1) { extension = template.getName().substring(dotPos); newName = temp.id + "_" + name + extension; } else { newName = temp.id + "_" + name; } File copy_to = new File("public/templates/" + newName); //template.renameTo(copy_to); Helper.copy(template, copy_to); temp.filename_ = newName; temp.save(); return null; } catch (Exception e) { System.out.println(e.toString()); return e.toString(); } }
public static String upload(String name, String description, File template) { try { FileStringReader reader = new FileStringReader(template); String text = reader.read(); if(!Helper.isUtf8(text)) { return "File must be in UTF 8."; } Date now = new Date(); Template temp = new Template(name, template.getName(), "DummyAuthor", now, description, 4); temp.save(); int dotPos = template.getName().lastIndexOf("."); String newName; String extension; if (dotPos != -1) { extension = template.getName().substring(dotPos); newName = temp.id + "_" + name + extension; } else { newName = temp.id + "_" + name; } File copy_to = new File("expleo/public/templates/" + newName); System.out.println(copy_to.getAbsolutePath()); Helper.copy(template, copy_to); temp.filename_ = newName; temp.save(); return null; } catch (Exception e) { System.out.println(e.toString()); return e.toString(); } }