lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
epl-1.0
556f7f7e746d122eff237e4e872a6cda8c1de4f4
0
opendaylight/yangtools,opendaylight/yangtools
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.yang.data.impl.schema.tree; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import java.util.Collection; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.concurrent.NotThreadSafe; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer; import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType; import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode; import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode; import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory; import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version; /** * Node Modification Node and Tree * * Tree which structurally resembles data tree and captures client modifications to the data store tree. This tree is * lazily created and populated via {@link #modifyChild(PathArgument)} and {@link TreeNode} which represents original * state as tracked by {@link #getOriginal()}. * * The contract is that the state information exposed here preserves the temporal ordering of whatever modifications * were executed. A child's effects pertain to data node as modified by its ancestors. This means that in order to * reconstruct the effective data node presentation, it is sufficient to perform a depth-first pre-order traversal of * the tree. */ @NotThreadSafe final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> { static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = new Predicate<ModifiedNode>() { @Override public boolean apply(@Nonnull final ModifiedNode input) { Preconditions.checkNotNull(input); switch (input.getOperation()) { case DELETE: case MERGE: case WRITE: return true; case TOUCH: case NONE: return false; } throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation())); } }; private final Map<PathArgument, ModifiedNode> children; private final Optional<TreeNode> original; private final PathArgument identifier; private LogicalOperation operation = LogicalOperation.NONE; private Optional<TreeNode> snapshotCache; private NormalizedNode<?, ?> value; private ModificationType modType; // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node. private TreeNode writtenOriginal; private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final ChildTrackingPolicy childPolicy) { this.identifier = identifier; this.original = original; this.children = childPolicy.createMap(); } @Override public PathArgument getIdentifier() { return identifier; } @Override LogicalOperation getOperation() { return operation; } @Override Optional<TreeNode> getOriginal() { return original; } /** * Return the value which was written to this node. The returned object is only valid for * {@link LogicalOperation#MERGE} and {@link LogicalOperation#WRITE}. * operations. It should only be consulted when this modification is going to end up being * {@link ModificationType#WRITE}. * * @return Currently-written value */ NormalizedNode<?, ?> getWrittenValue() { return value; } /** * * Returns child modification if child was modified * * @return Child modification if direct child or it's subtree * was modified. * */ @Override public Optional<ModifiedNode> getChild(final PathArgument child) { return Optional.<ModifiedNode> fromNullable(children.get(child)); } private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) { return original.isPresent() ? original.get().getChild(child) : Optional.<TreeNode>absent(); } private Optional<TreeNode> metadataFromData(@Nonnull final PathArgument child, final Version modVersion) { if (writtenOriginal == null) { // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting // modifications. writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion); } return writtenOriginal.getChild(child); } /** * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need * to take the current node's operation into account. * * @param child Child we are looking to modify * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification} * @return Before-image tree node as observed by that child. */ private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) { switch (operation) { case DELETE: // DELETE implies non-presence return Optional.absent(); case NONE: case TOUCH: case MERGE: return metadataFromSnapshot(child); case WRITE: // WRITE implies presence based on written data return metadataFromData(child, modVersion); } throw new IllegalStateException("Unhandled node operation " + operation); } /** * * Returns child modification if child was modified, creates {@link ModifiedNode} * for child otherwise. * * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED} * changes modification type to {@link ModificationType#SUBTREE_MODIFIED} * * @param child child identifier, may not be null * @param childPolicy child tracking policy for the node we are looking for * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification} * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()} * containing child metadata if child was present in original data. */ ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ChildTrackingPolicy childPolicy, @Nonnull final Version modVersion) { clearSnapshot(); if (operation == LogicalOperation.NONE) { updateOperationType(LogicalOperation.TOUCH); } final ModifiedNode potential = children.get(child); if (potential != null) { return potential; } final Optional<TreeNode> currentMetadata = findOriginalMetadata(child, modVersion); final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childPolicy); if (operation == LogicalOperation.MERGE && value != null) { /* * We are attempting to modify a previously-unmodified part of a MERGE node. If the * value contains this component, we need to materialize it as a MERGE modification. */ @SuppressWarnings({ "rawtypes", "unchecked" }) final Optional<NormalizedNode<?, ?>> childData = ((NormalizedNodeContainer)value).getChild(child); if (childData.isPresent()) { newlyCreated.updateValue(LogicalOperation.MERGE, childData.get()); } } children.put(child, newlyCreated); return newlyCreated; } /** * Returns all recorded direct child modification * * @return all recorded direct child modifications */ @Override Collection<ModifiedNode> getChildren() { return children.values(); } /** * Records a delete for associated node. */ void delete() { final LogicalOperation newType; switch (operation) { case DELETE: case NONE: // We need to record this delete. newType = LogicalOperation.DELETE; break; case MERGE: // In case of merge - delete needs to be recored and must not to be changed into // NONE, because lazy expansion of parent MERGE node would reintroduce it // again. newType = LogicalOperation.DELETE; break; case TOUCH: case WRITE: /* * We are canceling a previous modification. This is a bit tricky, * as the original write may have just introduced the data, or it * may have modified it. * * As documented in BUG-2470, a delete of data introduced in this * transaction needs to be turned into a no-op. */ newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE; break; default: throw new IllegalStateException("Unhandled deletion of node with " + operation); } clearSnapshot(); children.clear(); this.value = null; updateOperationType(newType); } /** * Records a write for associated node. * * @param value */ void write(final NormalizedNode<?, ?> value) { updateValue(LogicalOperation.WRITE, value); children.clear(); } /** * Seal the modification node and prune any children which has not been modified. * * @param schema */ void seal(final ModificationApplyOperation schema, final Version version) { clearSnapshot(); writtenOriginal = null; switch (operation) { case TOUCH: // A TOUCH node without any children is a no-op if (children.isEmpty()) { updateOperationType(LogicalOperation.NONE); } break; case WRITE: // A WRITE can collapse all of its children if (!children.isEmpty()) { value = schema.apply(this, getOriginal(), version).get().getData(); children.clear(); } schema.verifyStructure(value, true); break; default: break; } } private void clearSnapshot() { snapshotCache = null; } Optional<TreeNode> getSnapshot() { return snapshotCache; } Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) { snapshotCache = Preconditions.checkNotNull(snapshot); return snapshot; } void updateOperationType(final LogicalOperation type) { operation = type; modType = null; // Make sure we do not reuse previously-instantiated data-derived metadata writtenOriginal = null; clearSnapshot(); } @Override public String toString() { return "NodeModification [identifier=" + identifier + ", modificationType=" + operation + ", childModification=" + children + "]"; } void resolveModificationType(@Nonnull final ModificationType type) { modType = type; } /** * Update this node's value and operation type without disturbing any of its child modifications. * * @param type New operation type * @param value New node value */ void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> value) { this.value = Preconditions.checkNotNull(value); updateOperationType(type); } /** * Return the physical modification done to data. May return null if the * operation has not been applied to the underlying tree. This is different * from the logical operation in that it can actually be a no-op if the * operation has no side-effects (like an empty merge on a container). * * @return Modification type. */ ModificationType getModificationType() { return modType; } public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) { return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy); } }
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/ModifiedNode.java
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.yangtools.yang.data.impl.schema.tree; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import java.util.Collection; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.concurrent.NotThreadSafe; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer; import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType; import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode; import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode; import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory; import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version; /** * Node Modification Node and Tree * * Tree which structurally resembles data tree and captures client modifications to the data store tree. This tree is * lazily created and populated via {@link #modifyChild(PathArgument)} and {@link TreeNode} which represents original * state as tracked by {@link #getOriginal()}. * * The contract is that the state information exposed here preserves the temporal ordering of whatever modifications * were executed. A child's effects pertain to data node as modified by its ancestors. This means that in order to * reconstruct the effective data node presentation, it is sufficient to perform a depth-first pre-order traversal of * the tree. */ @NotThreadSafe final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> { static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = new Predicate<ModifiedNode>() { @Override public boolean apply(@Nonnull final ModifiedNode input) { Preconditions.checkNotNull(input); switch (input.getOperation()) { case DELETE: case MERGE: case WRITE: return true; case TOUCH: case NONE: return false; } throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation())); } }; private final Map<PathArgument, ModifiedNode> children; private final Optional<TreeNode> original; private final PathArgument identifier; private LogicalOperation operation = LogicalOperation.NONE; private Optional<TreeNode> snapshotCache; private NormalizedNode<?, ?> value; private ModificationType modType; // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node. private TreeNode writtenOriginal; private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final ChildTrackingPolicy childPolicy) { this.identifier = identifier; this.original = original; this.children = childPolicy.createMap(); } @Override public PathArgument getIdentifier() { return identifier; } @Override LogicalOperation getOperation() { return operation; } @Override Optional<TreeNode> getOriginal() { return original; } /** * Return the value which was written to this node. The returned object is only valid for * {@link LogicalOperation#MERGE} and {@link LogicalOperation#WRITE}. * operations. It should only be consulted when this modification is going to end up being * {@link ModificationType#WRITE}. * * @return Currently-written value */ NormalizedNode<?, ?> getWrittenValue() { return value; } /** * * Returns child modification if child was modified * * @return Child modification if direct child or it's subtree * was modified. * */ @Override public Optional<ModifiedNode> getChild(final PathArgument child) { return Optional.<ModifiedNode> fromNullable(children.get(child)); } private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) { return original.isPresent() ? original.get().getChild(child) : Optional.<TreeNode>absent(); } private Optional<TreeNode> metadataFromData(@Nonnull final PathArgument child, final Version modVersion) { if (writtenOriginal == null) { // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting // modifications. writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion); } return writtenOriginal.getChild(child); } /** * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need * to take the current node's operation into account. * * @param child Child we are looking to modify * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification} * @return Before-image tree node as observed by that child. */ private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) { switch (operation) { case DELETE: // DELETE implies non-presence return Optional.absent(); case NONE: case TOUCH: case MERGE: return metadataFromSnapshot(child); case WRITE: // WRITE implies presence based on written data return metadataFromData(child, modVersion); } throw new IllegalStateException("Unhandled node operation " + operation); } /** * * Returns child modification if child was modified, creates {@link ModifiedNode} * for child otherwise. * * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED} * changes modification type to {@link ModificationType#SUBTREE_MODIFIED} * * @param child child identifier, may not be null * @param childPolicy child tracking policy for the node we are looking for * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification} * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()} * containing child metadata if child was present in original data. */ ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ChildTrackingPolicy childPolicy, @Nonnull final Version modVersion) { clearSnapshot(); if (operation == LogicalOperation.NONE) { updateOperationType(LogicalOperation.TOUCH); } final ModifiedNode potential = children.get(child); if (potential != null) { return potential; } final Optional<TreeNode> currentMetadata = findOriginalMetadata(child, modVersion); final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childPolicy); if (operation == LogicalOperation.MERGE && value != null) { /* * We are attempting to modify a previously-unmodified part of a MERGE node. If the * value contains this component, we need to materialize it as a MERGE modification. */ @SuppressWarnings({ "rawtypes", "unchecked" }) final Optional<NormalizedNode<?, ?>> childData = ((NormalizedNodeContainer)value).getChild(child); if (childData.isPresent()) { newlyCreated.updateValue(LogicalOperation.MERGE, childData.get()); } } children.put(child, newlyCreated); return newlyCreated; } /** * Returns all recorded direct child modification * * @return all recorded direct child modifications */ @Override Collection<ModifiedNode> getChildren() { return children.values(); } /** * Records a delete for associated node. */ void delete() { final LogicalOperation newType; switch (operation) { case DELETE: case NONE: // We need to record this delete. newType = LogicalOperation.DELETE; break; case MERGE: case TOUCH: case WRITE: /* * We are canceling a previous modification. This is a bit tricky, * as the original write may have just introduced the data, or it * may have modified it. * * As documented in BUG-2470, a delete of data introduced in this * transaction needs to be turned into a no-op. */ newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE; break; default: throw new IllegalStateException("Unhandled deletion of node with " + operation); } clearSnapshot(); children.clear(); this.value = null; updateOperationType(newType); } /** * Records a write for associated node. * * @param value */ void write(final NormalizedNode<?, ?> value) { updateValue(LogicalOperation.WRITE, value); children.clear(); } /** * Seal the modification node and prune any children which has not been modified. * * @param schema */ void seal(final ModificationApplyOperation schema, final Version version) { clearSnapshot(); writtenOriginal = null; switch (operation) { case TOUCH: // A TOUCH node without any children is a no-op if (children.isEmpty()) { updateOperationType(LogicalOperation.NONE); } break; case WRITE: // A WRITE can collapse all of its children if (!children.isEmpty()) { value = schema.apply(this, getOriginal(), version).get().getData(); children.clear(); } schema.verifyStructure(value, true); break; default: break; } } private void clearSnapshot() { snapshotCache = null; } Optional<TreeNode> getSnapshot() { return snapshotCache; } Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) { snapshotCache = Preconditions.checkNotNull(snapshot); return snapshot; } void updateOperationType(final LogicalOperation type) { operation = type; modType = null; // Make sure we do not reuse previously-instantiated data-derived metadata writtenOriginal = null; clearSnapshot(); } @Override public String toString() { return "NodeModification [identifier=" + identifier + ", modificationType=" + operation + ", childModification=" + children + "]"; } void resolveModificationType(@Nonnull final ModificationType type) { modType = type; } /** * Update this node's value and operation type without disturbing any of its child modifications. * * @param type New operation type * @param value New node value */ void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> value) { this.value = Preconditions.checkNotNull(value); updateOperationType(type); } /** * Return the physical modification done to data. May return null if the * operation has not been applied to the underlying tree. This is different * from the logical operation in that it can actually be a no-op if the * operation has no side-effects (like an empty merge on a container). * * @return Modification type. */ ModificationType getModificationType() { return modType; } public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) { return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy); } }
Bug 4295: Fixed incorrectly introduced nodes when MERGE was followed by DELETE ModificationNode lost state in situations when parent node was MERGE which indroduced child nodes and child node was deleted. That resulted into recording NONE, which during apply of MERGE was expanded back to original MERGE which caused reintroduction of deleted node. Change-Id: Ia2085f5475b49957ef8ac7ab6c629ca3eef803f2 Signed-off-by: Tony Tkacik <[email protected]>
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/ModifiedNode.java
Bug 4295: Fixed incorrectly introduced nodes when MERGE was followed by DELETE
<ide><path>ang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/ModifiedNode.java <ide> newType = LogicalOperation.DELETE; <ide> break; <ide> case MERGE: <add> // In case of merge - delete needs to be recored and must not to be changed into <add> // NONE, because lazy expansion of parent MERGE node would reintroduce it <add> // again. <add> newType = LogicalOperation.DELETE; <add> break; <ide> case TOUCH: <ide> case WRITE: <ide> /*
Java
mit
7e51d094f83cc338d2890adc08db64751a4de1d9
0
CS2103JAN2017-W14-B2/main,CS2103JAN2017-W14-B2/main
package guitests; import static org.junit.Assert.assertTrue; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import org.junit.Test; import guitests.guihandles.TaskCardHandle; import seedu.taskboss.commons.core.Messages; import seedu.taskboss.logic.commands.EditCommand; import seedu.taskboss.model.category.Category; import seedu.taskboss.model.task.Name; import seedu.taskboss.model.task.PriorityLevel; import seedu.taskboss.testutil.TaskBuilder; import seedu.taskboss.testutil.TestTask; // TODO: reduce GUI tests by transferring some tests to be covered by lower level tests. public class EditCommandTest extends TaskBossGuiTest { // The list of tasks in the task list panel is expected to match this list. // This list is updated with every successful call to assertEditSuccess(). TestTask[] expectedTasksList = td.getTypicalTasks(); @Test public void edit_allFieldsSpecified_success() throws Exception { String detailsToEdit = "n/Alice p/Yes sd/10am Feb 19, 2017 ed/10am Feb 28, 2017 i/123," + " Jurong West Ave 6, #08-111 c/friends"; int taskBossIndex = 1; TestTask editedTask = new TaskBuilder().withName("Alice").withPriorityLevel("Yes") .withStartDateTime("10am Feb 19, 2017").withEndDateTime("10am Feb 28, 2017") .withInformation("123, Jurong West Ave 6, #08-111").withCategories("friends").build(); assertEditSuccess(false, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } //@@author A0143157J // EP: edit all fields @Test public void edit_allFieldsWithShortCommand_success() throws Exception { String detailsToEdit = "n/Amanda p/Yes sd/feb 27 2016 ed/feb 28 2016 i/discuss about life c/relax"; int taskBossIndex = 1; TestTask editedTask = new TaskBuilder().withName("Amanda").withPriorityLevel("Yes") .withStartDateTime("feb 27 2016").withEndDateTime("feb 28 2016") .withInformation("discuss about life").withCategories("relax").build(); assertEditSuccess(true, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } // EP: edit categories with short command @Test public void edit_notAllFieldsWithShortCommand_success() throws Exception { String detailsToEdit = "c/work c/fun"; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withCategories("work", "fun").build(); assertEditSuccess(true, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } //@@author @Test public void edit_notAllFieldsSpecified_success() throws Exception { String detailsToEdit = "c/sweetie c/bestie"; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withCategories("sweetie", "bestie").build(); assertEditSuccess(false, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } @Test public void edit_clearCategories_success() throws Exception { String detailsToEdit = "c/"; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withCategories().build(); assertEditSuccess(false, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } @Test public void edit_findThenEdit_success() throws Exception { commandBox.runCommand("find k/Elle"); String detailsToEdit = "n/Belle"; int filteredTaskListIndex = 1; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withName("Belle").build(); assertEditSuccess(false, filteredTaskListIndex, taskBossIndex, detailsToEdit, editedTask); } @Test public void edit_missingTaskIndex_failure() { commandBox.runCommand("edit n/Bobby"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } @Test public void edit_invalidTaskIndex_failure() { commandBox.runCommand("edit 8 n/Bobby"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } @Test public void edit_noFieldsSpecified_failure() { commandBox.runCommand("edit 1"); assertResultMessage(EditCommand.MESSAGE_NOT_EDITED); } @Test public void edit_invalidValues_failure() { commandBox.runCommand("edit 1 n/*&"); assertResultMessage(Name.MESSAGE_NAME_CONSTRAINTS); commandBox.runCommand("edit 1 p/abcd"); assertResultMessage(PriorityLevel.MESSAGE_PRIORITY_CONSTRAINTS); commandBox.runCommand("edit 1 c/*&"); assertResultMessage(Category.MESSAGE_CATEGORY_CONSTRAINTS); } @Test public void edit_duplicateTask_failure() { commandBox.runCommand("edit 1 n/Alice Pauline p/Yes sd/Feb 18, 2017 5pm 5pm ed/Mar 28, 2017 5pm" + "i/123, Jurong West Ave 6, #08-111 c/friends"); assertResultMessage(EditCommand.MESSAGE_DUPLICATE_TASK); } //@@author A01431457J // EP: invalid edit command with start date later than end date @Test public void edit_invalidDates_failure() { commandBox.runCommand("edit 3 sd/next fri 5pm ed/tomorrow"); assertResultMessage(EditCommand.ERROR_INVALID_DATES); } //@@author /** * Checks whether the edited task has the correct updated details. * * @param filteredTaskListIndex index of task to edit in filtered list * @param taskBossIndex index of task to edit in TaskBoss. * Must refer to the same task as {@code filteredTaskListIndex} * @param detailsToEdit details to edit the task with as input to the edit command * @param editedTask the expected task after editing the task's details */ private void assertEditSuccess(boolean isShortCommand, int filteredTaskListIndex, int taskBossIndex, String detailsToEdit, TestTask editedTask) { if (isShortCommand) { commandBox.runCommand("e " + filteredTaskListIndex + " " + detailsToEdit); } else { commandBox.runCommand("edit " + filteredTaskListIndex + " " + detailsToEdit); } // confirm the new card contains the right data TaskCardHandle editedCard = taskListPanel.navigateToTask(editedTask.getName().fullName); assertMatching(editedTask, editedCard); // confirm the list now contains all previous tasks plus the task with updated details expectedTasksList[taskBossIndex - 1] = editedTask; assertTrue(taskListPanel.isListMatching(expectedTasksList)); assertResultMessage(String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, editedTask)); } }
src/test/java/guitests/EditCommandTest.java
package guitests; import static org.junit.Assert.assertTrue; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import org.junit.Test; import guitests.guihandles.TaskCardHandle; import seedu.taskboss.commons.core.Messages; import seedu.taskboss.logic.commands.EditCommand; import seedu.taskboss.model.category.Category; import seedu.taskboss.model.task.Name; import seedu.taskboss.model.task.PriorityLevel; import seedu.taskboss.testutil.TaskBuilder; import seedu.taskboss.testutil.TestTask; // TODO: reduce GUI tests by transferring some tests to be covered by lower level tests. public class EditCommandTest extends TaskBossGuiTest { // The list of tasks in the task list panel is expected to match this list. // This list is updated with every successful call to assertEditSuccess(). TestTask[] expectedTasksList = td.getTypicalTasks(); @Test public void edit_allFieldsSpecified_success() throws Exception { String detailsToEdit = "n/Alice p/Yes sd/10am Feb 19, 2017 ed/10am Feb 28, 2017 i/123," + " Jurong West Ave 6, #08-111 c/friends"; int taskBossIndex = 1; TestTask editedTask = new TaskBuilder().withName("Alice").withPriorityLevel("Yes") .withStartDateTime("10am Feb 19, 2017").withEndDateTime("10am Feb 28, 2017") .withInformation("123, Jurong West Ave 6, #08-111").withCategories("friends").build(); assertEditSuccess(false, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } //@@author A0143157J // EP: edit all fields @Test public void edit_allFieldsWithShortCommand_success() throws Exception { String detailsToEdit = "n/Amanda p/Yes sd/feb 27 2016 ed/feb 28 2016 i/discuss about life c/relax"; int taskBossIndex = 1; TestTask editedTask = new TaskBuilder().withName("Amanda").withPriorityLevel("Yes") .withStartDateTime("feb 27 2016").withEndDateTime("feb 28 2016") .withInformation("discuss about life").withCategories("relax").build(); assertEditSuccess(true, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } // EP: edit categories with short command @Test public void edit_notAllFieldsWithShortCommand_success() throws Exception { String detailsToEdit = "c/work c/fun"; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withCategories("work", "fun").build(); assertEditSuccess(true, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } //@@author @Test public void edit_notAllFieldsSpecified_success() throws Exception { String detailsToEdit = "c/sweetie c/bestie"; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withCategories("sweetie", "bestie").build(); assertEditSuccess(false, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } @Test public void edit_clearCategories_success() throws Exception { String detailsToEdit = "c/"; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withCategories().build(); assertEditSuccess(false, taskBossIndex, taskBossIndex, detailsToEdit, editedTask); } @Test public void edit_findThenEdit_success() throws Exception { commandBox.runCommand("find k/Elle"); String detailsToEdit = "n/Belle"; int filteredTaskListIndex = 1; int taskBossIndex = 2; TestTask taskToEdit = expectedTasksList[taskBossIndex - 1]; TestTask editedTask = new TaskBuilder(taskToEdit).withName("Belle").build(); assertEditSuccess(false, filteredTaskListIndex, taskBossIndex, detailsToEdit, editedTask); } @Test public void edit_missingTaskIndex_failure() { commandBox.runCommand("edit n/Bobby"); assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } @Test public void edit_invalidTaskIndex_failure() { commandBox.runCommand("edit 8 n/Bobby"); assertResultMessage(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } @Test public void edit_noFieldsSpecified_failure() { commandBox.runCommand("edit 1"); assertResultMessage(EditCommand.MESSAGE_NOT_EDITED); } @Test public void edit_invalidValues_failure() { commandBox.runCommand("edit 1 n/*&"); assertResultMessage(Name.MESSAGE_NAME_CONSTRAINTS); commandBox.runCommand("edit 1 p/abcd"); assertResultMessage(PriorityLevel.MESSAGE_PRIORITY_CONSTRAINTS); commandBox.runCommand("edit 1 c/*&"); assertResultMessage(Category.MESSAGE_CATEGORY_CONSTRAINTS); } @Test public void edit_duplicateTask_failure() { commandBox.runCommand("edit 1 n/Alice Pauline p/Yes sd/Feb 18, 2017 5pm 5pm ed/Mar 28, 2017 5pm" + "i/123, Jurong West Ave 6, #08-111 c/friends"); assertResultMessage(EditCommand.MESSAGE_DUPLICATE_TASK); } //@@author A01431457J // EP: invalid edit command with start date later than end date @Test public void edit_invalidDates_failure() { commandBox.runCommand("edit 3 sd/next fri 5pm ed/tomorrow"); assertResultMessage(EditCommand.ERROR_INVALID_DATES); } //@@author /** * Checks whether the edited task has the correct updated details. * * @param filteredTaskListIndex index of task to edit in filtered list * @param taskBossIndex index of task to edit in TaskBoss. * Must refer to the same task as {@code filteredTaskListIndex} * @param detailsToEdit details to edit the task with as input to the edit command * @param editedTask the expected task after editing the task's details */ private void assertEditSuccess(boolean isShortCommand, int filteredTaskListIndex, int taskBossIndex, String detailsToEdit, TestTask editedTask) { if (isShortCommand) { commandBox.runCommand("e " + filteredTaskListIndex + " " + detailsToEdit); } else { commandBox.runCommand("edit " + filteredTaskListIndex + " " + detailsToEdit); } // confirm the new card contains the right data TaskCardHandle editedCard = taskListPanel.navigateToTask(editedTask.getName().fullName); assertMatching(editedTask, editedCard); // confirm the list now contains all previous tasks plus the task with updated details expectedTasksList[taskBossIndex - 1] = editedTask; assertTrue(taskListPanel.isListMatching(expectedTasksList)); assertResultMessage(String.format(EditCommand.MESSAGE_EDIT_TASK_SUCCESS, editedTask)); } }
remove whitespace
src/test/java/guitests/EditCommandTest.java
remove whitespace
<ide><path>rc/test/java/guitests/EditCommandTest.java <ide> <ide> assertEditSuccess(false, filteredTaskListIndex, taskBossIndex, detailsToEdit, editedTask); <ide> } <del> <ide> <ide> @Test <ide> public void edit_missingTaskIndex_failure() {
Java
apache-2.0
a1e8005499c7d9009d3fdd5821fd145eb52c8d26
0
elunez/eladmin
/* * Copyright 2019-2020 Zheng Jie * * 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 me.zhengjie.config; import com.fasterxml.classmate.TypeResolver; import com.google.common.base.Predicates; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.data.domain.Pageable; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.schema.AlternateTypeRule; import springfox.documentation.schema.AlternateTypeRuleConvention; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static springfox.documentation.schema.AlternateTypeRules.newRule; /** * api页面 /doc.html * @author Zheng Jie * @date 2018-11-23 */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Value("${jwt.header}") private String tokenHeader; @Value("${swagger.enabled}") private Boolean enabled; @Bean @SuppressWarnings("all") public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .enable(enabled) .pathMapping("/") .apiInfo(apiInfo()) .select() .paths(Predicates.not(PathSelectors.regex("/error.*"))) .paths(PathSelectors.any()) .build() //添加登陆认证 .securitySchemes(securitySchemes()) .securityContexts(securityContexts()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .description("一个简单且易上手的 Spring boot 后台管理框架") .title("EL-ADMIN 接口文档") .version("2.6") .build(); } private List<SecurityScheme> securitySchemes() { //设置请求头信息 List<SecurityScheme> securitySchemes = new ArrayList<>(); ApiKey apiKey = new ApiKey(tokenHeader, tokenHeader, "header"); securitySchemes.add(apiKey); return securitySchemes; } private List<SecurityContext> securityContexts() { //设置需要登录认证的路径 List<SecurityContext> securityContexts = new ArrayList<>(); // ^(?!auth).*$ 表示所有包含auth的接口不需要使用securitySchemes即不需要带token // ^标识开始 ()里是一子表达式 ?!/auth表示匹配不是/auth的位置,匹配上则添加请求头,注意路径已/开头 .表示任意字符 *表示前面的字符匹配多次 $标识结束 securityContexts.add(getContextByPath()); return securityContexts; } private SecurityContext getContextByPath() { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex("^(?!/auth).*$")) .build(); } private List<SecurityReference> defaultAuth() { List<SecurityReference> securityReferences = new ArrayList<>(); AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; securityReferences.add(new SecurityReference(tokenHeader, authorizationScopes)); return securityReferences; } } /** * 将Pageable转换展示在swagger中 */ @Configuration class SwaggerDataConfig { @Bean public AlternateTypeRuleConvention pageableConvention(final TypeResolver resolver) { return new AlternateTypeRuleConvention() { @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public List<AlternateTypeRule> rules() { return newArrayList(newRule(resolver.resolve(Pageable.class), resolver.resolve(Page.class))); } }; } @ApiModel @Data private static class Page { @ApiModelProperty("页码 (0..N)") private Integer page; @ApiModelProperty("每页显示的数目") private Integer size; @ApiModelProperty("以下列格式排序标准:property[,asc | desc]。 默认排序顺序为升序。 支持多种排序条件:如:id,asc") private List<String> sort; } }
eladmin-common/src/main/java/me/zhengjie/config/SwaggerConfig.java
/* * Copyright 2019-2020 Zheng Jie * * 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 me.zhengjie.config; import com.fasterxml.classmate.TypeResolver; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.data.domain.Pageable; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.schema.AlternateTypeRule; import springfox.documentation.schema.AlternateTypeRuleConvention; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static springfox.documentation.schema.AlternateTypeRules.newRule; /** * api页面 /doc.html * @author Zheng Jie * @date 2018-11-23 */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Value("${jwt.header}") private String tokenHeader; @Value("${jwt.token-start-with}") private String tokenStartWith; @Value("${swagger.enabled}") private Boolean enabled; @Bean @SuppressWarnings("all") public Docket createRestApi() { // ParameterBuilder ticketPar = new ParameterBuilder(); //// List<Parameter> pars = new ArrayList<>(); //// ticketPar.name(tokenHeader).description("token") //// .modelRef(new ModelRef("string")) //// .parameterType("header") //// .defaultValue(tokenStartWith + " ") //// .required(true) //// .build(); // pars.add(ticketPar.build()); return new Docket(DocumentationType.SWAGGER_2) .enable(enabled) .apiInfo(apiInfo()) .select() // .paths(Predicates.not(PathSelectors.regex("/error.*"))) .paths(PathSelectors.any()) .build() // .globalOperationParameters(pars) //添加登陆认证 .securitySchemes(securitySchemes()) .securityContexts(securityContexts()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .description("一个简单且易上手的 Spring boot 后台管理框架") .title("EL-ADMIN 接口文档") .version("2.4") .build(); } private List<SecurityScheme> securitySchemes() { //设置请求头信息 List<SecurityScheme> securitySchemes = new ArrayList<>(); ApiKey apiKey = new ApiKey(tokenHeader, tokenHeader, "header"); securitySchemes.add(apiKey); return securitySchemes; } private List<SecurityContext> securityContexts() { //设置需要登录认证的路径 List<SecurityContext> securityContexts = new ArrayList<>(); // ^(?!auth).*$ 表示所有包含auth的接口不需要使用securitySchemes即不需要带token // ^标识开始 ()里是一子表达式 ?!/auth表示匹配不是/auth的位置,匹配上则添加请求头,注意路径已/开头 .表示任意字符 *表示前面的字符匹配多次 $标识结束 securityContexts.add(getContextByPath("^(?!/auth).*$")); return securityContexts; } private SecurityContext getContextByPath(String pathRegex) { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex(pathRegex)) .build(); } private List<SecurityReference> defaultAuth() { List<SecurityReference> securityReferences = new ArrayList<>(); AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; securityReferences.add(new SecurityReference(tokenHeader, authorizationScopes)); return securityReferences; } } /** * 将Pageable转换展示在swagger中 */ @Configuration class SwaggerDataConfig { @Bean public AlternateTypeRuleConvention pageableConvention(final TypeResolver resolver) { return new AlternateTypeRuleConvention() { @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public List<AlternateTypeRule> rules() { return newArrayList(newRule(resolver.resolve(Pageable.class), resolver.resolve(Page.class))); } }; } @ApiModel @Data private static class Page { @ApiModelProperty("页码 (0..N)") private Integer page; @ApiModelProperty("每页显示的数目") private Integer size; @ApiModelProperty("以下列格式排序标准:property[,asc | desc]。 默认排序顺序为升序。 支持多种排序条件:如:id,asc") private List<String> sort; } }
[代码优化](v2.6):update swagger
eladmin-common/src/main/java/me/zhengjie/config/SwaggerConfig.java
[代码优化](v2.6):update swagger
<ide><path>ladmin-common/src/main/java/me/zhengjie/config/SwaggerConfig.java <ide> package me.zhengjie.config; <ide> <ide> import com.fasterxml.classmate.TypeResolver; <add>import com.google.common.base.Predicates; <ide> import io.swagger.annotations.ApiModel; <ide> import io.swagger.annotations.ApiModelProperty; <ide> import lombok.Data; <ide> import springfox.documentation.spi.service.contexts.SecurityContext; <ide> import springfox.documentation.spring.web.plugins.Docket; <ide> import springfox.documentation.swagger2.annotations.EnableSwagger2; <del> <ide> import java.util.ArrayList; <ide> import java.util.List; <del> <ide> import static com.google.common.collect.Lists.newArrayList; <ide> import static springfox.documentation.schema.AlternateTypeRules.newRule; <ide> <ide> @Value("${jwt.header}") <ide> private String tokenHeader; <ide> <del> @Value("${jwt.token-start-with}") <del> private String tokenStartWith; <del> <ide> @Value("${swagger.enabled}") <ide> private Boolean enabled; <ide> <ide> @Bean <ide> @SuppressWarnings("all") <ide> public Docket createRestApi() { <del>// ParameterBuilder ticketPar = new ParameterBuilder(); <del>//// List<Parameter> pars = new ArrayList<>(); <del>//// ticketPar.name(tokenHeader).description("token") <del>//// .modelRef(new ModelRef("string")) <del>//// .parameterType("header") <del>//// .defaultValue(tokenStartWith + " ") <del>//// .required(true) <del>//// .build(); <del>// pars.add(ticketPar.build()); <ide> return new Docket(DocumentationType.SWAGGER_2) <ide> .enable(enabled) <add> .pathMapping("/") <ide> .apiInfo(apiInfo()) <ide> .select() <del>// .paths(Predicates.not(PathSelectors.regex("/error.*"))) <add> .paths(Predicates.not(PathSelectors.regex("/error.*"))) <ide> .paths(PathSelectors.any()) <ide> .build() <del>// .globalOperationParameters(pars) <ide> //添加登陆认证 <ide> .securitySchemes(securitySchemes()) <ide> .securityContexts(securityContexts()); <ide> return new ApiInfoBuilder() <ide> .description("一个简单且易上手的 Spring boot 后台管理框架") <ide> .title("EL-ADMIN 接口文档") <del> .version("2.4") <add> .version("2.6") <ide> .build(); <ide> } <ide> <ide> List<SecurityContext> securityContexts = new ArrayList<>(); <ide> // ^(?!auth).*$ 表示所有包含auth的接口不需要使用securitySchemes即不需要带token <ide> // ^标识开始 ()里是一子表达式 ?!/auth表示匹配不是/auth的位置,匹配上则添加请求头,注意路径已/开头 .表示任意字符 *表示前面的字符匹配多次 $标识结束 <del> securityContexts.add(getContextByPath("^(?!/auth).*$")); <add> securityContexts.add(getContextByPath()); <ide> return securityContexts; <ide> } <ide> <del> private SecurityContext getContextByPath(String pathRegex) { <add> private SecurityContext getContextByPath() { <ide> return SecurityContext.builder() <ide> .securityReferences(defaultAuth()) <del> .forPaths(PathSelectors.regex(pathRegex)) <add> .forPaths(PathSelectors.regex("^(?!/auth).*$")) <ide> .build(); <ide> } <ide>
Java
agpl-3.0
d388d019ff257eaea8b1ef299a963eb20156aa09
0
opencadc/caom2,opencadc/caom2,opencadc/caom2,opencadc/caom2
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2011. (c) 2011. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 5 $ * ************************************************************************ */ package ca.nrc.cadc.caom2.types; import ca.nrc.cadc.caom2.Artifact; import ca.nrc.cadc.caom2.Chunk; import ca.nrc.cadc.caom2.util.EnergyConverter; import ca.nrc.cadc.caom2.Energy; import ca.nrc.cadc.caom2.EnergyBand; import ca.nrc.cadc.caom2.EnergyTransition; import ca.nrc.cadc.caom2.Part; import ca.nrc.cadc.caom2.Plane; import ca.nrc.cadc.caom2.ProductType; import ca.nrc.cadc.caom2.wcs.Axis; import ca.nrc.cadc.caom2.wcs.CoordAxis1D; import ca.nrc.cadc.caom2.wcs.CoordBounds1D; import ca.nrc.cadc.caom2.wcs.CoordFunction1D; import ca.nrc.cadc.caom2.wcs.CoordRange1D; import ca.nrc.cadc.caom2.wcs.RefCoord; import ca.nrc.cadc.caom2.wcs.SpectralWCS; import ca.nrc.cadc.util.Log4jInit; import ca.nrc.cadc.wcs.exceptions.WCSLibRuntimeException; import java.net.URI; import java.net.URISyntaxException; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.Assert; import org.junit.Test; /** * * @author pdowler */ public class EnergyUtilTest { private static final Logger log = Logger.getLogger(EnergyUtilTest.class); static { Log4jInit.setLevel("ca.nrc.cadc.caom2", Level.INFO); } String BANDPASS_NAME= "H-Alpha-narrow"; EnergyTransition TRANSITION = new EnergyTransition("H", "alpha"); //@Test public void testTemplate() { try { } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testEmptyList() { try { Plane plane = new Plane("foo"); Energy nrg = EnergyUtil.compute(plane.getArtifacts()); Assert.assertNotNull(nrg); Assert.assertNull(nrg.bandpassName); Assert.assertNull(nrg.bounds); Assert.assertNull(nrg.dimension); Assert.assertNull(nrg.emBand); Assert.assertNull(nrg.resolvingPower); Assert.assertNull(nrg.sampleSize); Assert.assertNull(nrg.transition); Assert.assertNull(nrg.getFreqWidth()); Assert.assertNull(nrg.getFreqSampleSize()); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromRange() { log.debug("testComputeFromRange: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200L; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetRange(1, 1, 1); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromRange: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue()); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 0.0001); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); plane = getTestSetRange(1, 3, 1); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromRange: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB+400.0e-9, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension*3, actual.dimension.longValue()); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 0.0001); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromBounds() { log.debug("testComputeFromBounds: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200*2/3; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetBounds(1, 1, 1); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromBounds: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertEquals(2, actual.bounds.getSamples().size()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue(), 1L); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 0.0001); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromFunction() { log.debug("testComputeFromFunction: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200L; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetFunction(1, 1, 1); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromFunction: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue()); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 1.0); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); Assert.assertNotNull(actual.getFreqWidth()); Assert.assertNotNull(actual.getFreqSampleSize()); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromFreqRange() { try { EnergyConverter ec = new EnergyConverter(); double expectedLB = ec.convert(20.0, "FREQ", "MHz"); double expectedUB = ec.convert(2.0, "FREQ", "MHz"); long expectedDimension = 1024L; double expectedSS = (expectedUB - expectedLB)/expectedDimension; CoordAxis1D axis = new CoordAxis1D(new Axis("FREQ", "MHz")); SpectralWCS spec = new SpectralWCS(axis, "TOPOCENT"); RefCoord c1 = new RefCoord(0.5, 2.0); RefCoord c2 = new RefCoord(1024.5, 20.0); spec.getAxis().range = new CoordRange1D(c1, c2); //[2,20] MHz log.debug("testComputeFromFreqRange: " + spec.getAxis().range + " " + spec.getAxis().getAxis().getCunit()); // use this to create teh objects, then replace the single SpectralWCS with above Plane plane = getTestSetRange(1,1,1); // ouch :-) Chunk c = plane.getArtifacts().iterator().next().getParts().iterator().next().getChunks().iterator().next(); c.energy = spec; Energy actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromFreqRange: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue()); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testInvalidComputeFromFunction() { log.debug("testComputeFromFunction: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200L; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetFunction(1, 1, 1); Chunk c = plane.getArtifacts().iterator().next().getParts().iterator().next().getChunks().iterator().next(); c.energy = getInvalidFunction(); // replace the func actual = EnergyUtil.compute(plane.getArtifacts()); Assert.fail("expected WCSlibRuntimeException"); } catch(WCSLibRuntimeException expected) { log.info("caught expected exception: " + expected); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testGetBoundsWave() { try { SpectralWCS wcs = getTestFunction(false, 0.5, 400, 2000.0, 0.1); // [400,600] Interval all = new Interval(300e-9, 800e-9); Interval none = new Interval(700e-9, 900e-9); Interval cut = new Interval(450e-9, 550e-9); long[] allPix = EnergyUtil.getBounds(wcs, all); Assert.assertNotNull(allPix); Assert.assertEquals("long[0]", 0, allPix.length); long[] noPix = EnergyUtil.getBounds(wcs, none); Assert.assertNull(noPix); long[] cutPix = EnergyUtil.getBounds(wcs, cut); Assert.assertNotNull(cutPix); Assert.assertEquals("long[2]", 2, cutPix.length); Assert.assertEquals("cut LB", 500, cutPix[0], 1); Assert.assertEquals("cut LB", 1500, cutPix[1], 1); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testGetBoundsFreq() { try { SpectralWCS wcs = getTestFreqFunction(false, 0.5, 10.0, 1000.0, 0.1); // [10-110] MHz Interval all = new Interval(2.5, 60.0); Interval none = new Interval(1.0, 2.0); Interval cut = new Interval(4.283, 7.5); long[] allPix = EnergyUtil.getBounds(wcs, all); Assert.assertNotNull(allPix); Assert.assertEquals("long[0]", 0, allPix.length); long[] noPix = EnergyUtil.getBounds(wcs, none); Assert.assertNull(noPix); long[] cutPix = EnergyUtil.getBounds(wcs, cut); Assert.assertNotNull(cutPix); Assert.assertEquals("long[2]", 2, cutPix.length); log.debug("cut: " + cutPix[0] + ":" + cutPix[1]); Assert.assertEquals("cut LB", 300, cutPix[0], 1); Assert.assertEquals("cut UB", 600, cutPix[1], 1); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromCalibration() { log.debug("testComputeFromCalibration: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200L; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetRange(1, 1, 1, ProductType.CALIBRATION); // add some aux artifacts, should not effect result Plane tmp = getTestSetRange(1, 1, 3); Artifact tmpA = tmp.getArtifacts().iterator().next(); Artifact aux = new Artifact(new URI("ad:foo/bar/aux")); aux.productType = ProductType.AUXILIARY; aux.getParts().addAll(tmpA.getParts()); plane.getArtifacts().add(aux); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromCalibration: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue()); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 0.0001); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromMixed() { log.debug("testComputeFromMixed: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200L; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetRange(1, 1, 1, ProductType.SCIENCE); // add some cal artifacts, should not effect result Plane tmp = getTestSetRange(1, 1, 3); Artifact tmpA = tmp.getArtifacts().iterator().next(); Artifact aux = new Artifact(new URI("ad:foo/bar/aux")); aux.productType = ProductType.CALIBRATION; aux.getParts().addAll(tmpA.getParts()); plane.getArtifacts().add(aux); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromMixed: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue()); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 0.0001); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } Plane getTestSetRange(int numA, int numP, int numC) throws URISyntaxException { return getTestSetRange(numA, numP, numC, ProductType.SCIENCE); } Plane getTestSetRange(int numA, int numP, int numC, ProductType ptype) throws URISyntaxException { double px = 0.5; double sx = 400.0; double nx = 200.0; double ds = 1.0; double tot = nx*ds; Plane plane = new Plane("foo"); int n = 0; for (int a=0; a<numA; a++) { Artifact na = new Artifact(new URI("foo", "bar"+a, null)); na.productType = ptype; plane.getArtifacts().add(na); for (int p=0; p<numP; p++) { Part np = new Part(new Integer(p)); na.getParts().add(np); for (int c=0; c<numC; c++) { Chunk nc = new Chunk(); np.getChunks().add(nc); // just shift to higher values of x for each subsequent chunk nc.energy = getTestRange(true, px, sx+n*nx*ds, nx, ds); n++; } } } log.debug("getTestSetRange: " + n + " chunks"); return plane; } Plane getTestSetBounds(int numA, int numP, int numC) throws URISyntaxException { double px = 0.5; double sx = 400.0; double nx = 200.0; double ds = 1.0; double tot = nx*ds; Plane plane = new Plane("foo"); int n = 0; for (int a=0; a<numA; a++) { Artifact na = new Artifact(new URI("foo", "bar"+a, null)); na.productType = ProductType.SCIENCE; plane.getArtifacts().add(na); for (int p=0; p<numP; p++) { Part np = new Part(new Integer(p)); na.getParts().add(np); for (int c=0; c<numC; c++) { Chunk nc = new Chunk(); np.getChunks().add(nc); // just shift to higher values of x for each subsequent chunk nc.energy = getTestBounds(true, px, sx+n*nx*ds, nx, ds); n++; } } } log.debug("getTestSetBounds: " + n + " chunks"); return plane; } Plane getTestSetFunction(int numA, int numP, int numC) throws URISyntaxException { double px = 0.5; double sx = 400.0; double nx = 200.0; double ds = 1.0; double tot = nx*ds; Plane plane = new Plane("foo"); int n = 0; for (int a=0; a<numA; a++) { Artifact na = new Artifact(new URI("foo", "bar"+a, null)); na.productType = ProductType.SCIENCE; plane.getArtifacts().add(na); for (int p=0; p<numP; p++) { Part np = new Part(new Integer(p)); na.getParts().add(np); for (int c=0; c<numC; c++) { Chunk nc = new Chunk(); np.getChunks().add(nc); // shift px to larger values nc.energy = getTestFunction(true, px, sx+n*nx*ds, nx, ds); n++; } } } log.debug("getTestSetFunction: " + n + " chunks"); return plane; } private SpectralWCS getTestRange(boolean complete, double px, double sx, double nx, double ds) { CoordAxis1D axis = new CoordAxis1D(new Axis("WAVE", "nm")); SpectralWCS wcs = new SpectralWCS(axis, "TOPOCENT"); if (complete) { wcs.bandpassName = BANDPASS_NAME; wcs.restwav = 656.3; wcs.resolvingPower = 33000.0; wcs.transition = TRANSITION; } RefCoord c1 = new RefCoord(px, sx); RefCoord c2 = new RefCoord(px+nx, sx + nx*ds); wcs.getAxis().range = new CoordRange1D(c1, c2); return wcs; } private SpectralWCS getTestBounds(boolean complete, double px, double sx, double nx, double ds) { CoordAxis1D axis = new CoordAxis1D(new Axis("WAVE", "nm")); SpectralWCS wcs = new SpectralWCS(axis, "TOPOCENT"); if (complete) { wcs.bandpassName = BANDPASS_NAME; wcs.restwav = 656.3; wcs.resolvingPower = 33000.0; wcs.transition = TRANSITION; } // divide into 2 samples with a gap between RefCoord c1 = new RefCoord(px, sx); RefCoord c2 = new RefCoord(px+nx*0.33, sx + nx*0.33); RefCoord c3 = new RefCoord(px+nx*0.66, sx + nx*0.66); RefCoord c4 = new RefCoord(px+nx, sx + nx*ds); wcs.getAxis().bounds = new CoordBounds1D(); wcs.getAxis().bounds.getSamples().add(new CoordRange1D(c1, c2)); wcs.getAxis().bounds.getSamples().add(new CoordRange1D(c3, c4)); return wcs; } private SpectralWCS getTestFunction(boolean complete, double px, double sx, double nx, double ds) { CoordAxis1D axis = new CoordAxis1D(new Axis("WAVE", "nm")); SpectralWCS wcs = new SpectralWCS(axis, "TOPOCENT"); if (complete) { wcs.bandpassName = BANDPASS_NAME; wcs.restwav = 656.3; wcs.resolvingPower = 33000.0; wcs.transition = TRANSITION; } RefCoord c1 = new RefCoord(px, sx); wcs.getAxis().function = new CoordFunction1D((long) nx, ds, c1); return wcs; } private SpectralWCS getTestFreqFunction(boolean complete, double px, double sx, double nx, double ds) { CoordAxis1D axis = new CoordAxis1D(new Axis("FREQ", "MHz")); SpectralWCS wcs = new SpectralWCS(axis, "TOPOCENT"); if (complete) { wcs.bandpassName = BANDPASS_NAME; wcs.restwav = 656.3; wcs.resolvingPower = 33000.0; wcs.transition = TRANSITION; } RefCoord c1 = new RefCoord(px, sx); wcs.getAxis().function = new CoordFunction1D((long) nx, ds, c1); return wcs; } private SpectralWCS getInvalidFunction() { CoordAxis1D axis = new CoordAxis1D(new Axis("WAVE", "Angstroms")); SpectralWCS wcs = new SpectralWCS(axis, "TOPOCENT"); wcs.bandpassName = BANDPASS_NAME; wcs.restwav = 6563.0; wcs.resolvingPower = 33000.0; wcs.transition = TRANSITION; Double delta = 0.05; RefCoord c1 = new RefCoord(0.5, 2000.0); wcs.getAxis().function = new CoordFunction1D((long) 100.0, 10.0, c1); return wcs; } }
source/caom2/test/src/ca/nrc/cadc/caom2/types/EnergyUtilTest.java
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2011. (c) 2011. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * $Revision: 5 $ * ************************************************************************ */ package ca.nrc.cadc.caom2.types; import ca.nrc.cadc.caom2.Artifact; import ca.nrc.cadc.caom2.Chunk; import ca.nrc.cadc.caom2.util.EnergyConverter; import ca.nrc.cadc.caom2.Energy; import ca.nrc.cadc.caom2.EnergyBand; import ca.nrc.cadc.caom2.EnergyTransition; import ca.nrc.cadc.caom2.Part; import ca.nrc.cadc.caom2.Plane; import ca.nrc.cadc.caom2.ProductType; import ca.nrc.cadc.caom2.wcs.Axis; import ca.nrc.cadc.caom2.wcs.CoordAxis1D; import ca.nrc.cadc.caom2.wcs.CoordBounds1D; import ca.nrc.cadc.caom2.wcs.CoordFunction1D; import ca.nrc.cadc.caom2.wcs.CoordRange1D; import ca.nrc.cadc.caom2.wcs.RefCoord; import ca.nrc.cadc.caom2.wcs.SpectralWCS; import ca.nrc.cadc.util.Log4jInit; import ca.nrc.cadc.wcs.exceptions.WCSLibRuntimeException; import java.net.URI; import java.net.URISyntaxException; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.Assert; import org.junit.Test; /** * * @author pdowler */ public class EnergyUtilTest { private static final Logger log = Logger.getLogger(EnergyUtilTest.class); static { Log4jInit.setLevel("ca.nrc.cadc.caom2", Level.INFO); } String BANDPASS_NAME= "H-Alpha-narrow"; EnergyTransition TRANSITION = new EnergyTransition("H", "alpha"); //@Test public void testTemplate() { try { } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testEmptyList() { try { Plane plane = new Plane("foo"); Energy nrg = EnergyUtil.compute(plane.getArtifacts()); Assert.assertNotNull(nrg); Assert.assertNull(nrg.bandpassName); Assert.assertNull(nrg.bounds); Assert.assertNull(nrg.dimension); Assert.assertNull(nrg.emBand); Assert.assertNull(nrg.resolvingPower); Assert.assertNull(nrg.sampleSize); Assert.assertNull(nrg.transition); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromRange() { log.debug("testComputeFromRange: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200L; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetRange(1, 1, 1); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromRange: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue()); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 0.0001); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); plane = getTestSetRange(1, 3, 1); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromRange: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB+400.0e-9, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension*3, actual.dimension.longValue()); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 0.0001); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromBounds() { log.debug("testComputeFromBounds: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200*2/3; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetBounds(1, 1, 1); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromBounds: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertEquals(2, actual.bounds.getSamples().size()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue(), 1L); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 0.0001); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromFunction() { log.debug("testComputeFromFunction: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200L; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetFunction(1, 1, 1); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromFunction: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue()); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 1.0); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromFreqRange() { try { EnergyConverter ec = new EnergyConverter(); double expectedLB = ec.convert(20.0, "FREQ", "MHz"); double expectedUB = ec.convert(2.0, "FREQ", "MHz"); long expectedDimension = 1024L; double expectedSS = (expectedUB - expectedLB)/expectedDimension; CoordAxis1D axis = new CoordAxis1D(new Axis("FREQ", "MHz")); SpectralWCS spec = new SpectralWCS(axis, "TOPOCENT"); RefCoord c1 = new RefCoord(0.5, 2.0); RefCoord c2 = new RefCoord(1024.5, 20.0); spec.getAxis().range = new CoordRange1D(c1, c2); //[2,20] MHz log.debug("testComputeFromFreqRange: " + spec.getAxis().range + " " + spec.getAxis().getAxis().getCunit()); // use this to create teh objects, then replace the single SpectralWCS with above Plane plane = getTestSetRange(1,1,1); // ouch :-) Chunk c = plane.getArtifacts().iterator().next().getParts().iterator().next().getChunks().iterator().next(); c.energy = spec; Energy actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromFreqRange: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue()); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testInvalidComputeFromFunction() { log.debug("testComputeFromFunction: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200L; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetFunction(1, 1, 1); Chunk c = plane.getArtifacts().iterator().next().getParts().iterator().next().getChunks().iterator().next(); c.energy = getInvalidFunction(); // replace the func actual = EnergyUtil.compute(plane.getArtifacts()); Assert.fail("expected WCSlibRuntimeException"); } catch(WCSLibRuntimeException expected) { log.info("caught expected exception: " + expected); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testGetBoundsWave() { try { SpectralWCS wcs = getTestFunction(false, 0.5, 400, 2000.0, 0.1); // [400,600] Interval all = new Interval(300e-9, 800e-9); Interval none = new Interval(700e-9, 900e-9); Interval cut = new Interval(450e-9, 550e-9); long[] allPix = EnergyUtil.getBounds(wcs, all); Assert.assertNotNull(allPix); Assert.assertEquals("long[0]", 0, allPix.length); long[] noPix = EnergyUtil.getBounds(wcs, none); Assert.assertNull(noPix); long[] cutPix = EnergyUtil.getBounds(wcs, cut); Assert.assertNotNull(cutPix); Assert.assertEquals("long[2]", 2, cutPix.length); Assert.assertEquals("cut LB", 500, cutPix[0], 1); Assert.assertEquals("cut LB", 1500, cutPix[1], 1); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testGetBoundsFreq() { try { SpectralWCS wcs = getTestFreqFunction(false, 0.5, 10.0, 1000.0, 0.1); // [10-110] MHz Interval all = new Interval(2.5, 60.0); Interval none = new Interval(1.0, 2.0); Interval cut = new Interval(4.283, 7.5); long[] allPix = EnergyUtil.getBounds(wcs, all); Assert.assertNotNull(allPix); Assert.assertEquals("long[0]", 0, allPix.length); long[] noPix = EnergyUtil.getBounds(wcs, none); Assert.assertNull(noPix); long[] cutPix = EnergyUtil.getBounds(wcs, cut); Assert.assertNotNull(cutPix); Assert.assertEquals("long[2]", 2, cutPix.length); log.debug("cut: " + cutPix[0] + ":" + cutPix[1]); Assert.assertEquals("cut LB", 300, cutPix[0], 1); Assert.assertEquals("cut UB", 600, cutPix[1], 1); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromCalibration() { log.debug("testComputeFromCalibration: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200L; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetRange(1, 1, 1, ProductType.CALIBRATION); // add some aux artifacts, should not effect result Plane tmp = getTestSetRange(1, 1, 3); Artifact tmpA = tmp.getArtifacts().iterator().next(); Artifact aux = new Artifact(new URI("ad:foo/bar/aux")); aux.productType = ProductType.AUXILIARY; aux.getParts().addAll(tmpA.getParts()); plane.getArtifacts().add(aux); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromCalibration: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue()); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 0.0001); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } @Test public void testComputeFromMixed() { log.debug("testComputeFromMixed: START"); try { double expectedLB = 400e-9; double expectedUB = 600e-9; long expectedDimension = 200L; double expectedSS = 1.0e-9; double expectedRP = 33000.0; Plane plane; Energy actual; plane = getTestSetRange(1, 1, 1, ProductType.SCIENCE); // add some cal artifacts, should not effect result Plane tmp = getTestSetRange(1, 1, 3); Artifact tmpA = tmp.getArtifacts().iterator().next(); Artifact aux = new Artifact(new URI("ad:foo/bar/aux")); aux.productType = ProductType.CALIBRATION; aux.getParts().addAll(tmpA.getParts()); plane.getArtifacts().add(aux); actual = EnergyUtil.compute(plane.getArtifacts()); log.debug("testComputeFromMixed: " + actual); Assert.assertNotNull(actual); Assert.assertNotNull(actual.bounds); Assert.assertEquals(expectedLB, actual.bounds.getLower(), 0.01); Assert.assertEquals(expectedUB, actual.bounds.getUpper(), 0.01); Assert.assertTrue(actual.bounds.getSamples().isEmpty()); Assert.assertNotNull(actual.dimension); Assert.assertEquals(expectedDimension, actual.dimension.longValue()); Assert.assertNotNull(actual.resolvingPower); Assert.assertEquals(expectedRP, actual.resolvingPower.doubleValue(), 0.0001); Assert.assertNotNull(actual.sampleSize); Assert.assertEquals(expectedSS, actual.sampleSize, 0.01); Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); Assert.assertEquals(TRANSITION, actual.transition); Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); } catch(Exception unexpected) { log.error("unexpected exception", unexpected); Assert.fail("unexpected exception: " + unexpected); } } Plane getTestSetRange(int numA, int numP, int numC) throws URISyntaxException { return getTestSetRange(numA, numP, numC, ProductType.SCIENCE); } Plane getTestSetRange(int numA, int numP, int numC, ProductType ptype) throws URISyntaxException { double px = 0.5; double sx = 400.0; double nx = 200.0; double ds = 1.0; double tot = nx*ds; Plane plane = new Plane("foo"); int n = 0; for (int a=0; a<numA; a++) { Artifact na = new Artifact(new URI("foo", "bar"+a, null)); na.productType = ptype; plane.getArtifacts().add(na); for (int p=0; p<numP; p++) { Part np = new Part(new Integer(p)); na.getParts().add(np); for (int c=0; c<numC; c++) { Chunk nc = new Chunk(); np.getChunks().add(nc); // just shift to higher values of x for each subsequent chunk nc.energy = getTestRange(true, px, sx+n*nx*ds, nx, ds); n++; } } } log.debug("getTestSetRange: " + n + " chunks"); return plane; } Plane getTestSetBounds(int numA, int numP, int numC) throws URISyntaxException { double px = 0.5; double sx = 400.0; double nx = 200.0; double ds = 1.0; double tot = nx*ds; Plane plane = new Plane("foo"); int n = 0; for (int a=0; a<numA; a++) { Artifact na = new Artifact(new URI("foo", "bar"+a, null)); na.productType = ProductType.SCIENCE; plane.getArtifacts().add(na); for (int p=0; p<numP; p++) { Part np = new Part(new Integer(p)); na.getParts().add(np); for (int c=0; c<numC; c++) { Chunk nc = new Chunk(); np.getChunks().add(nc); // just shift to higher values of x for each subsequent chunk nc.energy = getTestBounds(true, px, sx+n*nx*ds, nx, ds); n++; } } } log.debug("getTestSetBounds: " + n + " chunks"); return plane; } Plane getTestSetFunction(int numA, int numP, int numC) throws URISyntaxException { double px = 0.5; double sx = 400.0; double nx = 200.0; double ds = 1.0; double tot = nx*ds; Plane plane = new Plane("foo"); int n = 0; for (int a=0; a<numA; a++) { Artifact na = new Artifact(new URI("foo", "bar"+a, null)); na.productType = ProductType.SCIENCE; plane.getArtifacts().add(na); for (int p=0; p<numP; p++) { Part np = new Part(new Integer(p)); na.getParts().add(np); for (int c=0; c<numC; c++) { Chunk nc = new Chunk(); np.getChunks().add(nc); // shift px to larger values nc.energy = getTestFunction(true, px, sx+n*nx*ds, nx, ds); n++; } } } log.debug("getTestSetFunction: " + n + " chunks"); return plane; } private SpectralWCS getTestRange(boolean complete, double px, double sx, double nx, double ds) { CoordAxis1D axis = new CoordAxis1D(new Axis("WAVE", "nm")); SpectralWCS wcs = new SpectralWCS(axis, "TOPOCENT"); if (complete) { wcs.bandpassName = BANDPASS_NAME; wcs.restwav = 656.3; wcs.resolvingPower = 33000.0; wcs.transition = TRANSITION; } RefCoord c1 = new RefCoord(px, sx); RefCoord c2 = new RefCoord(px+nx, sx + nx*ds); wcs.getAxis().range = new CoordRange1D(c1, c2); return wcs; } private SpectralWCS getTestBounds(boolean complete, double px, double sx, double nx, double ds) { CoordAxis1D axis = new CoordAxis1D(new Axis("WAVE", "nm")); SpectralWCS wcs = new SpectralWCS(axis, "TOPOCENT"); if (complete) { wcs.bandpassName = BANDPASS_NAME; wcs.restwav = 656.3; wcs.resolvingPower = 33000.0; wcs.transition = TRANSITION; } // divide into 2 samples with a gap between RefCoord c1 = new RefCoord(px, sx); RefCoord c2 = new RefCoord(px+nx*0.33, sx + nx*0.33); RefCoord c3 = new RefCoord(px+nx*0.66, sx + nx*0.66); RefCoord c4 = new RefCoord(px+nx, sx + nx*ds); wcs.getAxis().bounds = new CoordBounds1D(); wcs.getAxis().bounds.getSamples().add(new CoordRange1D(c1, c2)); wcs.getAxis().bounds.getSamples().add(new CoordRange1D(c3, c4)); return wcs; } private SpectralWCS getTestFunction(boolean complete, double px, double sx, double nx, double ds) { CoordAxis1D axis = new CoordAxis1D(new Axis("WAVE", "nm")); SpectralWCS wcs = new SpectralWCS(axis, "TOPOCENT"); if (complete) { wcs.bandpassName = BANDPASS_NAME; wcs.restwav = 656.3; wcs.resolvingPower = 33000.0; wcs.transition = TRANSITION; } RefCoord c1 = new RefCoord(px, sx); wcs.getAxis().function = new CoordFunction1D((long) nx, ds, c1); return wcs; } private SpectralWCS getTestFreqFunction(boolean complete, double px, double sx, double nx, double ds) { CoordAxis1D axis = new CoordAxis1D(new Axis("FREQ", "MHz")); SpectralWCS wcs = new SpectralWCS(axis, "TOPOCENT"); if (complete) { wcs.bandpassName = BANDPASS_NAME; wcs.restwav = 656.3; wcs.resolvingPower = 33000.0; wcs.transition = TRANSITION; } RefCoord c1 = new RefCoord(px, sx); wcs.getAxis().function = new CoordFunction1D((long) nx, ds, c1); return wcs; } private SpectralWCS getInvalidFunction() { CoordAxis1D axis = new CoordAxis1D(new Axis("WAVE", "Angstroms")); SpectralWCS wcs = new SpectralWCS(axis, "TOPOCENT"); wcs.bandpassName = BANDPASS_NAME; wcs.restwav = 6563.0; wcs.resolvingPower = 33000.0; wcs.transition = TRANSITION; Double delta = 0.05; RefCoord c1 = new RefCoord(0.5, 2000.0); wcs.getAxis().function = new CoordFunction1D((long) 100.0, 10.0, c1); return wcs; } }
test coverage
source/caom2/test/src/ca/nrc/cadc/caom2/types/EnergyUtilTest.java
test coverage
<ide><path>ource/caom2/test/src/ca/nrc/cadc/caom2/types/EnergyUtilTest.java <ide> Assert.assertNull(nrg.resolvingPower); <ide> Assert.assertNull(nrg.sampleSize); <ide> Assert.assertNull(nrg.transition); <add> <add> Assert.assertNull(nrg.getFreqWidth()); <add> Assert.assertNull(nrg.getFreqSampleSize()); <add> <ide> } <ide> catch(Exception unexpected) <ide> { <ide> Assert.assertEquals(BANDPASS_NAME, actual.bandpassName); <ide> Assert.assertEquals(TRANSITION, actual.transition); <ide> Assert.assertEquals(EnergyBand.OPTICAL, actual.emBand); <add> <add> Assert.assertNotNull(actual.getFreqWidth()); <add> Assert.assertNotNull(actual.getFreqSampleSize()); <ide> <ide> } <ide> catch(Exception unexpected)
Java
apache-2.0
07c73acd0b3e93426eb219ff07974f7dced953d9
0
fmakari/systemml,aloknsingh/systemml,wjuncdl/systemml,dusenberrymw/systemml_old,fmakari/systemml,aloknsingh/systemml,fmakari/systemml,ckadner/systemml,fmakari/systemml,aloknsingh/systemml,dusenberrymw/systemml_old,ckadner/systemml,dusenberrymw/systemml_old,dusenberrymw/systemml_old,Myasuka/systemml,aloknsingh/systemml,ckadner/systemml,aloknsingh/systemml,ckadner/systemml,ckadner/systemml,aloknsingh/systemml,Myasuka/systemml,wjuncdl/systemml,Myasuka/systemml,dusenberrymw/systemml_old,Myasuka/systemml,wjuncdl/systemml,dusenberrymw/systemml_old,wjuncdl/systemml,fmakari/systemml,wjuncdl/systemml,ckadner/systemml,Myasuka/systemml,Myasuka/systemml,wjuncdl/systemml,fmakari/systemml
package com.ibm.bi.dml.runtime.controlprogram.parfor.opt; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.Random; import java.util.StringTokenizer; import java.util.Vector; import java.util.Map.Entry; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; import com.ibm.bi.dml.api.DMLScript; import com.ibm.bi.dml.lops.Lops; import com.ibm.bi.dml.parser.DMLProgram; import com.ibm.bi.dml.parser.DMLTranslator; import com.ibm.bi.dml.parser.DataIdentifier; import com.ibm.bi.dml.parser.ParseException; import com.ibm.bi.dml.parser.Expression.DataType; import com.ibm.bi.dml.parser.Expression.ValueType; import com.ibm.bi.dml.runtime.controlprogram.ExternalFunctionProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.ExternalFunctionProgramBlockCP; import com.ibm.bi.dml.runtime.controlprogram.Program; import com.ibm.bi.dml.runtime.controlprogram.ProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.parfor.stat.Timing; import com.ibm.bi.dml.runtime.controlprogram.parfor.util.IDHandler; import com.ibm.bi.dml.runtime.controlprogram.parfor.util.IDSequence; import com.ibm.bi.dml.runtime.instructions.CPInstructionParser; import com.ibm.bi.dml.runtime.instructions.Instruction; import com.ibm.bi.dml.runtime.instructions.CPInstructions.Data; import com.ibm.bi.dml.runtime.instructions.CPInstructions.FunctionCallCPInstruction; import com.ibm.bi.dml.runtime.instructions.CPInstructions.MatrixObjectNew; import com.ibm.bi.dml.runtime.instructions.CPInstructions.RandCPInstruction; import com.ibm.bi.dml.runtime.matrix.MatrixCharacteristics; import com.ibm.bi.dml.runtime.matrix.MatrixFormatMetaData; import com.ibm.bi.dml.runtime.matrix.io.InputInfo; import com.ibm.bi.dml.runtime.matrix.io.MatrixBlock; import com.ibm.bi.dml.runtime.matrix.io.OutputInfo; import com.ibm.bi.dml.runtime.util.MapReduceTool; import com.ibm.bi.dml.utils.CacheException; import com.ibm.bi.dml.utils.DMLException; import com.ibm.bi.dml.utils.DMLRuntimeException; import com.ibm.bi.dml.utils.DMLUnsupportedOperationException; import com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter; /** * DML Instructions Performance Test Tool: * * Creates an offline performance profile (required once per installation) of DML instructions. * The profile is a combination of all individual statistical models trained per combination of * instruction and test configuration. In order to train those models, we execute and measure * real executions of DML instructions on random input data. Finally, during runtime, the profile * is used by the costs estimator in order to create statistic estimates for cost-based optimization. * * TODO: complete all CP instructions * TODO: add support for MR instructions * TODO: add support for TestVariable.PARALLELISM * TODO: add support for instruction-invariant cost functions * TODO: add support for constants such as IO throughput (e.g., DFSIOTest) * TODO: add support for known external functions and DML scripts / functions */ public class PerfTestTool { //internal parameters public static final boolean READ_STATS_ON_STARTUP = false; public static final int TEST_REPETITIONS = 5; public static final int NUM_SAMPLES_PER_TEST = 11; public static final int MODEL_MAX_ORDER = 2; public static final boolean MODEL_INTERCEPT = true; public static final long MIN_DATASIZE = 100; public static final long MAX_DATASIZE = 1000000; public static final long DEFAULT_DATASIZE = (MAX_DATASIZE-MIN_DATASIZE)/2; public static final double MIN_DIMSIZE = 1; public static final double MAX_DIMSIZE = 1000; public static final double MIN_SPARSITY = 0.1; public static final double MAX_SPARSITY = 1.0; public static final double DEFAULT_SPARSITY = (MAX_SPARSITY-MIN_SPARSITY)/2; public static final String PERF_TOOL_DIR = "./conf/PerfTestTool/"; public static final String PERF_RESULTS_FNAME = PERF_TOOL_DIR + "%id%.dat"; public static final String PERF_PROFILE_FNAME = PERF_TOOL_DIR + "performance_profile.xml"; public static final String DML_SCRIPT_FNAME = "./src/com/ibm/bi/dml/runtime/controlprogram/parfor/opt/PerfTestToolRegression.dml"; public static final String DML_TMP_FNAME = PERF_TOOL_DIR + "temp.dml"; //XML profile tags and attributes public static final String XML_PROFILE = "profile"; public static final String XML_DATE = "date"; public static final String XML_INSTRUCTION = "instruction"; public static final String XML_ID = "id"; public static final String XML_NAME = "name"; public static final String XML_COSTFUNCTION = "cost_function"; public static final String XML_MEASURE = "measure"; public static final String XML_VARIABLE = "lvariable"; public static final String XML_INTERNAL_VARIABLES = "pvariables"; public static final String XML_DATAFORMAT = "dataformat"; public static final String XML_ELEMENT_DELIMITER = ","; //ID sequences for instructions and test definitions private static IDSequence _seqInst = null; private static IDSequence _seqTestDef = null; //registered instructions and test definitions private static HashMap<Integer, PerfTestDef> _regTestDef = null; private static HashMap<Integer, Instruction> _regInst = null; private static HashMap<Integer, String> _regInst_IDNames = null; private static HashMap<String, Integer> _regInst_NamesID = null; private static HashMap<Integer, Integer[]> _regInst_IDTestDef = null; private static HashMap<Integer, Boolean> _regInst_IDVectors = null; private static HashMap<Integer, IOSchema> _regInst_IDIOSchema = null; private static Integer[] _defaultConf = null; //raw measurement data (instID, physical defID, results) private static HashMap<Integer,HashMap<Integer,LinkedList<Double>>> _results = null; //profile data private static boolean _flagReadData = false; private static HashMap<Integer,HashMap<Integer,CostFunction>> _profile = null; public enum TestMeasure //logical test measure { EXEC_TIME, MEMORY_USAGE } public enum TestVariable //logical test variable { DATA_SIZE, SPARSITY, PARALLELISM } public enum InternalTestVariable //physical test variable { DATA_SIZE, DIM1_SIZE, DIM2_SIZE, DIM3_SIZE, SPARSITY, NUM_THREADS, NUM_MAPPERS, NUM_REDUCERS, } public enum IOSchema { NONE_NONE, NONE_UNARY, UNARY_NONE, UNARY_UNARY, BINARY_NONE, BINARY_UNARY } public enum DataFormat //logical data format { DENSE, SPARSE } public enum TestConstants //logical test constants { DFS_READ_THROUGHPUT, DFS_WRITE_THROUGHPUT, LFS_READ_THROUGHPUT, LFS_WRITE_THROUGHPUT } static { //init repository _seqInst = new IDSequence(); _seqTestDef = new IDSequence(); _regTestDef = new HashMap<Integer, PerfTestDef>(); _regInst = new HashMap<Integer, Instruction>(); _regInst_IDNames = new HashMap<Integer, String>(); _regInst_NamesID = new HashMap<String, Integer>(); _regInst_IDTestDef = new HashMap<Integer, Integer[]>(); _regInst_IDVectors = new HashMap<Integer, Boolean>(); _regInst_IDIOSchema = new HashMap<Integer, IOSchema>(); _results = new HashMap<Integer, HashMap<Integer,LinkedList<Double>>>(); _profile = new HashMap<Integer, HashMap<Integer,CostFunction>>(); _flagReadData = false; //load existing profile if required try { if( READ_STATS_ON_STARTUP ) { readProfile( PERF_PROFILE_FNAME ); } } catch(Exception ex) { throw new RuntimeException(ex); } } /** * * @throws DMLRuntimeException */ public static void lazyInit() throws DMLRuntimeException { //read profile for first access if( !_flagReadData ) { try { //register all testdefs and instructions registerTestConfigurations(); registerInstructions(); //read profile readProfile( PERF_PROFILE_FNAME ); } catch(Exception ex) { throw new DMLRuntimeException(ex); } } if( _profile == null ) throw new DMLRuntimeException("Performance test results have not been loaded completely."); } /** * * @param opStr * @return * @throws DMLRuntimeException */ public static boolean isRegisteredInstruction(String opStr) throws DMLRuntimeException { //init if required lazyInit(); //determine if inst registered return _regInst_NamesID.containsKey(opStr); } /** * * @param instName * @return * @throws DMLRuntimeException */ public static CostFunction getCostFunction( String instName, TestMeasure measure, TestVariable variable, DataFormat dataformat ) throws DMLRuntimeException { //init if required lazyInit(); CostFunction tmp = null; int instID = getInstructionID( instName ); if( instID != -1 ) //existing profile { int tdefID = getMappedTestDefID(instID, measure, variable, dataformat); tmp = _profile.get(instID).get(tdefID); } return tmp; } /** * * @param measure * @param variable * @param dataformat * @return */ public CostFunction getInvariantCostFunction( TestMeasure measure, TestVariable[] variable, DataFormat dataformat ) { //TODO: implement for additional rewrites throw new RuntimeException("Not implemented yet."); } /** * * @return */ @SuppressWarnings("all") public static boolean runTest() { boolean ret = false; try { Timing time = new Timing(); time.start(); //register all testdefs and instructions registerTestConfigurations(); registerInstructions(); //execute tests for all confs and all instructions executeTest(); //compute regression models int rows = NUM_SAMPLES_PER_TEST; int cols = MODEL_MAX_ORDER + (MODEL_INTERCEPT ? 1 : 0); HashMap<Integer,Long> tmp = writeResults( PERF_TOOL_DIR ); computeRegressionModels( DML_SCRIPT_FNAME, DML_TMP_FNAME, PERF_TOOL_DIR, tmp.size(), rows, cols); readRegressionModels( PERF_TOOL_DIR, tmp); //execConstantRuntimeTest(); //execConstantMemoryTest(); //write final profile to XML file writeProfile(PERF_TOOL_DIR, PERF_PROFILE_FNAME); System.out.format("SystemML PERFORMANCE TEST TOOL: finished profiling (in %.2f min), profile written to "+PERF_PROFILE_FNAME+"%n", time.stop()/60000); ret = true; } catch(Exception ex) { ex.printStackTrace(); } return ret; } /** * */ private static void registerTestConfigurations() { //reset ID Sequence for consistent IDs _seqTestDef.reset(); //register default testdefs TestMeasure[] M = new TestMeasure[]{ TestMeasure.EXEC_TIME, TestMeasure.MEMORY_USAGE }; DataFormat[] D = new DataFormat[]{DataFormat.DENSE,DataFormat.SPARSE}; Integer[] defaultConf = new Integer[M.length*D.length*2]; int i=0; for( TestMeasure m : M ) //for all measures for( DataFormat d : D ) //for all data formats { defaultConf[i++] = registerTestDef( new PerfTestDef(m, TestVariable.DATA_SIZE, d, InternalTestVariable.DATA_SIZE, MIN_DATASIZE, MAX_DATASIZE, NUM_SAMPLES_PER_TEST ) ); defaultConf[i++] = registerTestDef( new PerfTestDef(m, TestVariable.SPARSITY, d, InternalTestVariable.SPARSITY, MIN_SPARSITY, MAX_SPARSITY, NUM_SAMPLES_PER_TEST ) ); } //register advanced (multi-dim) test defs for( TestMeasure m : M ) //for all measures for( DataFormat d : D ) //for all data formats { registerTestDef( new PerfTestDef( m, TestVariable.DATA_SIZE, d, new InternalTestVariable[]{InternalTestVariable.DIM1_SIZE,InternalTestVariable.DIM2_SIZE,InternalTestVariable.DIM3_SIZE}, MIN_DIMSIZE, MAX_DIMSIZE, NUM_SAMPLES_PER_TEST ) ); } //set default testdefs _defaultConf = defaultConf; } /** * * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException */ private static void registerInstructions() throws DMLUnsupportedOperationException, DMLRuntimeException { //reset ID sequences for consistent IDs _seqInst.reset(); //matrix multiply registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"ba+*", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"ba+*"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), getDefaultTestDefs(), false, IOSchema.BINARY_UNARY ); ////registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"ba+*", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"ba+*"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), //// changeToMuliDimTestDefs(TestVariable.DATA_SIZE, getDefaultTestDefs()) ); //rand registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"Rand", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"Rand"+Lops.OPERAND_DELIMITOR+"rows=1"+Lops.OPERAND_DELIMITOR+"cols=1"+Lops.OPERAND_DELIMITOR+"min=1.0"+Lops.OPERAND_DELIMITOR+"max=100.0"+Lops.OPERAND_DELIMITOR+"sparsity=1.0"+Lops.OPERAND_DELIMITOR+"pdf=uniform"+Lops.OPERAND_DELIMITOR+"dir=."+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), getDefaultTestDefs(), false, IOSchema.NONE_UNARY ); //matrix transpose registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"r'", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"r'"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), getDefaultTestDefs(), false, IOSchema.UNARY_UNARY ); //sum registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"uak+", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"uak+"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), //needs B instead of C getDefaultTestDefs(), false, IOSchema.UNARY_UNARY ); //external function registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"extfunct", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"extfunct"+Lops.OPERAND_DELIMITOR+DMLProgram.DEFAULT_NAMESPACE+""+Lops.OPERAND_DELIMITOR+"execPerfTestExtFunct"+Lops.OPERAND_DELIMITOR+"1"+Lops.OPERAND_DELIMITOR+"1"+Lops.OPERAND_DELIMITOR+"A"+Lops.OPERAND_DELIMITOR+"C"), getDefaultTestDefs(), false, IOSchema.UNARY_UNARY ); //central moment registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"cm", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"cm"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"2"+Lops.DATATYPE_PREFIX+"SCALAR"+Lops.VALUETYPE_PREFIX+"INT"+Lops.OPERAND_DELIMITOR+"c"+Lops.DATATYPE_PREFIX+"SCALAR"+Lops.VALUETYPE_PREFIX+"DOUBLE"), getDefaultTestDefs(), true, IOSchema.UNARY_NONE ); //co-variance registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"cov", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"cov"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"c"+Lops.DATATYPE_PREFIX+"SCALAR"+Lops.VALUETYPE_PREFIX+"DOUBLE"), getDefaultTestDefs(), true, IOSchema.BINARY_NONE ); /*ADD ADDITIONAL INSTRUCTIONS HERE*/ //extend list to all (expensive) instructions; maybe also: createvar, assignvar, mvvar, rm, mv, setfilename, rmfilevar, print2 } /** * * @param def * @return */ private static int registerTestDef( PerfTestDef def ) { int ID = (int)_seqTestDef.getNextID(); _regTestDef.put( ID, def ); return ID; } /** * * @param iname * @param inst * @param testDefIDs * @param vectors * @param schema */ private static void registerInstruction( String iname, Instruction inst, Integer[] testDefIDs, boolean vectors, IOSchema schema ) { int ID = (int)_seqInst.getNextID(); registerInstruction(ID, iname, inst, testDefIDs, vectors, schema); } /** * * @param ID * @param iname * @param inst * @param testDefIDs * @param vector * @param schema */ private static void registerInstruction( int ID, String iname, Instruction inst, Integer[] testDefIDs, boolean vector, IOSchema schema ) { _regInst.put( ID, inst ); _regInst_IDNames.put( ID, iname ); _regInst_NamesID.put( iname, ID ); _regInst_IDTestDef.put( ID, testDefIDs ); _regInst_IDVectors.put( ID, vector ); _regInst_IDIOSchema.put( ID, schema ); } /** * * @param instID * @param measure * @param variable * @param dataformat * @return */ private static int getMappedTestDefID( int instID, TestMeasure measure, TestVariable variable, DataFormat dataformat ) { int ret = -1; for( Integer defID : _regInst_IDTestDef.get(instID) ) { PerfTestDef def = _regTestDef.get(defID); if( def.getMeasure()==measure && def.getVariable()==variable && def.getDataformat()==dataformat ) { ret = defID; break; } } return ret; } /** * * @param measure * @param lvariable * @param dataformat * @param pvariable * @return */ @SuppressWarnings("unused") private static int getTestDefID( TestMeasure measure, TestVariable lvariable, DataFormat dataformat, InternalTestVariable pvariable ) { return getTestDefID(measure, lvariable, dataformat, new InternalTestVariable[]{pvariable}); } /** * * @param measure * @param lvariable * @param dataformat * @param pvariables * @return */ private static int getTestDefID( TestMeasure measure, TestVariable lvariable, DataFormat dataformat, InternalTestVariable[] pvariables ) { int ret = -1; for( Entry<Integer,PerfTestDef> e : _regTestDef.entrySet() ) { PerfTestDef def = e.getValue(); TestMeasure tmp1 = def.getMeasure(); TestVariable tmp2 = def.getVariable(); DataFormat tmp3 = def.getDataformat(); InternalTestVariable[] tmp4 = def.getInternalVariables(); if( tmp1==measure && tmp2==lvariable && tmp3==dataformat ) { boolean flag = true; for( int i=0; i<tmp4.length; i++ ) flag &= ( tmp4[i] == pvariables[i] ); if( flag ) { ret = e.getKey(); break; } } } return ret; } /** * * @param instName * @return */ private static int getInstructionID( String instName ) { Integer ret = _regInst_NamesID.get( instName ); return ( ret!=null )? ret : -1; } /** * * @return */ @SuppressWarnings("unused") private static Integer[] getAllTestDefs() { return _regTestDef.keySet().toArray(new Integer[0]); } /** * * @return */ private static Integer[] getDefaultTestDefs() { return _defaultConf; } /** * * @param v * @param IDs * @return */ @SuppressWarnings("unused") private static Integer[] changeToMuliDimTestDefs( TestVariable v, Integer[] IDs ) { Integer[] tmp = new Integer[IDs.length]; for( int i=0; i<tmp.length; i++ ) { PerfTestDef def = _regTestDef.get(IDs[i]); if( def.getVariable() == v ) //filter logical variables { //find multidim version InternalTestVariable[] in = null; switch( v ) { case DATA_SIZE: in = new InternalTestVariable[]{InternalTestVariable.DIM1_SIZE,InternalTestVariable.DIM2_SIZE,InternalTestVariable.DIM3_SIZE}; break; } int newid = getTestDefID(def.getMeasure(), def.getVariable(), def.getDataformat(), in ); //exchange testdef ID tmp[i] = newid; } else { tmp[i] = IDs[i]; } } return tmp; } /** * * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException * @throws IOException */ private static void executeTest( ) throws DMLRuntimeException, DMLUnsupportedOperationException, IOException { System.out.println("SystemML PERFORMANCE TEST TOOL:"); //foreach registered instruction for( Entry<Integer,Instruction> inst : _regInst.entrySet() ) { int instID = inst.getKey(); System.out.println( "Running INSTRUCTION "+_regInst_IDNames.get(instID) ); Integer[] testDefIDs = _regInst_IDTestDef.get(instID); boolean vectors = _regInst_IDVectors.get(instID); IOSchema schema = _regInst_IDIOSchema.get(instID); //create tmp program block and set instruction Program prog = new Program(); ProgramBlock pb = new ProgramBlock( prog ); ArrayList<Instruction> ainst = new ArrayList<Instruction>(); ainst.add( inst.getValue() ); pb.setInstructions(ainst); //foreach registered test configuration for( Integer defID : testDefIDs ) { PerfTestDef def = _regTestDef.get(defID); TestMeasure m = def.getMeasure(); TestVariable lv = def.getVariable(); DataFormat df = def.getDataformat(); InternalTestVariable[] pv = def.getInternalVariables(); double min = def.getMin(); double max = def.getMax(); double samples = def.getNumSamples(); System.out.println( "Running TESTDEF(measure="+m+", variable="+String.valueOf(lv)+" "+pv.length+", format="+String.valueOf(df)+")" ); //vary input variable LinkedList<Double> dmeasure = new LinkedList<Double>(); LinkedList<Double> dvariable = generateSequence(min, max, samples); int plen = pv.length; if( plen == 1 ) //1D function { for( Double var : dvariable ) { dmeasure.add(executeTestCase1D(m, pv[0], df, var, pb, vectors, schema)); } } else //multi-dim function { //init index stack int[] index = new int[plen]; for( int i=0; i<plen; i++ ) index[i] = 0; //execute test int dlen = dvariable.size(); double[] buff = new double[plen]; while( index[0]<dlen ) { //set buffer values for( int i=0; i<plen; i++ ) buff[i] = dvariable.get(index[i]); //core execution dmeasure.add(executeTestCaseMD(m, pv, df, buff, pb, schema)); //not applicable for vector flag //increment indexes for( int i=plen-1; i>=0; i-- ) { if(i==plen-1) index[i]++; else if( index[i+1] >= dlen ) { index[i]++; index[i+1]=0; } } } } //append values to results if( !_results.containsKey(instID) ) _results.put(instID, new HashMap<Integer, LinkedList<Double>>()); _results.get(instID).put(defID, dmeasure); } } } /** * * @param m * @param v * @param df * @param varValue * @param pb * @param vectors * @param schema * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException * @throws IOException */ private static double executeTestCase1D( TestMeasure m, InternalTestVariable v, DataFormat df, double varValue, ProgramBlock pb, boolean vectors, IOSchema schema ) throws DMLRuntimeException, DMLUnsupportedOperationException, IOException { double datasize = -1; double dim1 = -1, dim2 = -1; double sparsity = -1; System.out.println( "VAR VALUE "+varValue ); //set test variables switch ( v ) { case DATA_SIZE: datasize = varValue; sparsity = DEFAULT_SPARSITY; break; case SPARSITY: datasize = DEFAULT_DATASIZE; sparsity = varValue; break; } //set specific dimensions if( vectors ) { dim1 = datasize; dim2 = 1; } else { dim1 = Math.sqrt( datasize ); dim2 = dim1; } //instruction-specific configurations Instruction inst = pb.getInstruction(0); //always exactly one instruction if( inst instanceof RandCPInstruction ) { RandCPInstruction rand = (RandCPInstruction) inst; rand.rows = (long)dim1; rand.cols = (long)dim2; rand.sparsity = sparsity; } else if ( inst instanceof FunctionCallCPInstruction ) //ExternalFunctionInvocationInstruction { Program prog = pb.getProgram(); Vector<DataIdentifier> in = new Vector<DataIdentifier>(); DataIdentifier dat1 = new DataIdentifier("A"); dat1.setDataType(DataType.MATRIX); dat1.setValueType(ValueType.DOUBLE); in.add(dat1); Vector<DataIdentifier> out = new Vector<DataIdentifier>(); DataIdentifier dat2 = new DataIdentifier("C"); dat2.setDataType(DataType.MATRIX); dat2.setValueType(ValueType.DOUBLE); out.add(dat2); HashMap<String, String> params = new HashMap<String, String>(); params.put(ExternalFunctionProgramBlock.CLASSNAME, PerfTestExtFunctCP.class.getName()); ExternalFunctionProgramBlockCP fpb = new ExternalFunctionProgramBlockCP(prog, in, out, params, PERF_TOOL_DIR); prog.addFunctionProgramBlock(DMLProgram.DEFAULT_NAMESPACE, "execPerfTestExtFunct", fpb); } //generate input and output matrices pb.getVariables().removeAll(); double mem1 = PerfTestMemoryObserver.getUsedMemory(); if( schema!=IOSchema.NONE_NONE && schema!=IOSchema.NONE_UNARY ) pb.getVariables().put("A", generateInputDataset(PERF_TOOL_DIR+"/A", dim1, dim2, sparsity, df)); if( schema==IOSchema.BINARY_NONE || schema==IOSchema.BINARY_UNARY || schema==IOSchema.UNARY_UNARY ) pb.getVariables().put("B", generateInputDataset(PERF_TOOL_DIR+"/B", dim1, dim2, sparsity, df)); if( schema==IOSchema.NONE_UNARY || schema==IOSchema.UNARY_UNARY || schema==IOSchema.BINARY_UNARY) pb.getVariables().put("C", generateEmptyResult(PERF_TOOL_DIR+"/C", dim1, dim2, df)); double mem2 = PerfTestMemoryObserver.getUsedMemory(); //foreach repetition double value = 0; for( int i=0; i<TEST_REPETITIONS; i++ ) { System.out.println("run "+i); value += executeGenericProgramBlock( m, pb ); } value/=TEST_REPETITIONS; //result correction and print result switch( m ) { case EXEC_TIME: System.out.println("--- RESULT: "+value+" ms"); break; case MEMORY_USAGE: //System.out.println("--- RESULT: "+value+" byte"); if( (mem2-mem1) > 0 ) value = value + mem2-mem1; //correction: input sizes added System.out.println("--- RESULT: "+value+" byte"); break; default: System.out.println("--- RESULT: "+value); break; } return value; } /** * * @param m * @param v * @param df * @param varValue * @param pb * @param schema * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException * @throws IOException */ private static double executeTestCaseMD( TestMeasure m, InternalTestVariable[] v, DataFormat df, double[] varValue, ProgramBlock pb, IOSchema schema ) throws DMLRuntimeException, DMLUnsupportedOperationException, IOException { //double datasize = DEFAULT_DATASIZE; double sparsity = DEFAULT_SPARSITY; double dim1 = -1; double dim2 = -1; double dim3 = -1; for( int i=0; i<v.length; i++ ) { System.out.println( "VAR VALUE "+varValue[i] ); switch( v[i] ) { case DIM1_SIZE: dim1=varValue[i]; break; case DIM2_SIZE: dim2=varValue[i]; break; case DIM3_SIZE: dim3=varValue[i]; break; } } //generate input and output matrices pb.getVariables().removeAll(); double mem1 = PerfTestMemoryObserver.getUsedMemory(); if( schema!=IOSchema.NONE_NONE && schema!=IOSchema.NONE_UNARY ) pb.getVariables().put("A", generateInputDataset(PERF_TOOL_DIR+"/A", dim1, dim2, sparsity, df)); if( schema==IOSchema.BINARY_NONE || schema==IOSchema.BINARY_UNARY || schema==IOSchema.UNARY_UNARY ) pb.getVariables().put("B", generateInputDataset(PERF_TOOL_DIR+"/B", dim2, dim3, sparsity, df)); if( schema==IOSchema.NONE_UNARY || schema==IOSchema.UNARY_UNARY || schema==IOSchema.BINARY_UNARY) pb.getVariables().put("C", generateEmptyResult(PERF_TOOL_DIR+"/C", dim1, dim3, df)); double mem2 = PerfTestMemoryObserver.getUsedMemory(); //foreach repetition double value = 0; for( int i=0; i<TEST_REPETITIONS; i++ ) { System.out.println("run "+i); value += executeGenericProgramBlock( m, pb ); } value/=TEST_REPETITIONS; //result correction and print result switch( m ) { case EXEC_TIME: System.out.println("--- RESULT: "+value+" ms"); break; case MEMORY_USAGE: //System.out.println("--- RESULT: "+value+" byte"); if( (mem2-mem1) > 0 ) value = value + mem2-mem1; //correction: input sizes added System.out.println("--- RESULT: "+value+" byte"); break; default: System.out.println("--- RESULT: "+value); break; } return value; } /** * * @param measure * @param pb * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static double executeGenericProgramBlock( TestMeasure measure, ProgramBlock pb ) throws DMLRuntimeException, DMLUnsupportedOperationException { double value = 0; try { switch( measure ) { case EXEC_TIME: Timing time = new Timing(); time.start(); pb.execute( null ); value = time.stop(); break; case MEMORY_USAGE: PerfTestMemoryObserver mo = new PerfTestMemoryObserver(); mo.measureStartMem(); Thread t = new Thread(mo); t.start(); pb.execute( null ); mo.setStopped(); value = mo.getMaxMemConsumption(); t.join(); break; } } catch(Exception ex) { throw new DMLRuntimeException(ex); } //clear matrixes from cache for( String str : pb.getVariables().keySet() ) { Data dat = pb.getVariable(str); if( dat.getDataType() == DataType.MATRIX ) ((MatrixObjectNew)dat).clearData(); } return value; } /** * * @param min * @param max * @param num * @return */ public static LinkedList<Double> generateSequence( double min, double max, double num ) { LinkedList<Double> data = new LinkedList<Double>(); double increment = (max-min)/(num-1); for( int i=0; i<num; i++ ) data.add( new Double(min+i*increment) ); return data; } /** * * @param fname * @param datasize * @param sparsity * @param df * @return * @throws IOException * @throws CacheException */ public static MatrixObjectNew generateInputDataset(String fname, double datasize, double sparsity, DataFormat df) throws IOException, CacheException { int dim = (int)Math.sqrt( datasize ); //create random test data double[][] d = generateTestMatrix(dim, dim, 1, 100, sparsity, 7); //create matrix block MatrixBlock mb = null; switch( df ) { case DENSE: mb = new MatrixBlock(dim,dim,false); break; case SPARSE: mb = new MatrixBlock(dim,dim,true); break; } //insert data for(int i=0; i < dim; i++) for(int j=0; j < dim; j++) if( d[i][j]!=0 ) mb.setValue(i, j, d[i][j]); MapReduceTool.deleteFileIfExistOnHDFS(fname); MatrixCharacteristics mc = new MatrixCharacteristics(dim, dim, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize); MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo); MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md); mo.acquireModify(mb); mo.release(); mo.exportData(); //write to HDFS return mo; } /** * * @param fname * @param dim1 * @param dim2 * @param sparsity * @param df * @return * @throws IOException * @throws CacheException */ public static MatrixObjectNew generateInputDataset(String fname, double dim1, double dim2, double sparsity, DataFormat df) throws IOException, CacheException { int d1 = (int) dim1; int d2 = (int) dim2; System.out.println(d1+" "+d2); //create random test data double[][] d = generateTestMatrix(d1, d2, 1, 100, sparsity, 7); //create matrix block MatrixBlock mb = null; switch( df ) { case DENSE: mb = new MatrixBlock(d1,d2,false); break; case SPARSE: mb = new MatrixBlock(d1,d2,true); break; } //insert data for(int i=0; i < d1; i++) for(int j=0; j < d2; j++) if( d[i][j]!=0 ) mb.setValue(i, j, d[i][j]); MapReduceTool.deleteFileIfExistOnHDFS(fname); MatrixCharacteristics mc = new MatrixCharacteristics(d1, d2, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize); MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo); MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md); mo.acquireModify(mb); mo.release(); mo.exportData(); //write to HDFS return mo; } /** * * @param fname * @param datasize * @param df * @return * @throws IOException * @throws CacheException */ public static MatrixObjectNew generateEmptyResult(String fname, double datasize, DataFormat df ) throws IOException, CacheException { int dim = (int)Math.sqrt( datasize ); /* MatrixBlock mb = null; switch( df ) { case DENSE: mb = new MatrixBlock(dim,dim,false); break; case SPARSE: mb = new MatrixBlock(dim,dim,true); break; }*/ MatrixCharacteristics mc = new MatrixCharacteristics(dim, dim, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize); MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo); MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md); return mo; } /** * * @param fname * @param dim1 * @param dim2 * @param df * @return * @throws IOException * @throws CacheException */ public static MatrixObjectNew generateEmptyResult(String fname, double dim1, double dim2, DataFormat df ) throws IOException, CacheException { int d1 = (int)dim1; int d2 = (int)dim2; /* MatrixBlock mb = null; switch( df ) { case DENSE: mb = new MatrixBlock(dim,dim,false); break; case SPARSE: mb = new MatrixBlock(dim,dim,true); break; }*/ MatrixCharacteristics mc = new MatrixCharacteristics(d1, d2, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize); MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo); MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md); return mo; } /** * NOTE: This is a copy of TestUtils.generateTestMatrix, it was replicated in order to prevent * dependency of SystemML.jar to our test package. */ public static double[][] generateTestMatrix(int rows, int cols, double min, double max, double sparsity, long seed) { double[][] matrix = new double[rows][cols]; Random random; if (seed == -1) random = new Random(System.nanoTime()); else random = new Random(seed); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (random.nextDouble() > sparsity) continue; matrix[i][j] = (random.nextDouble() * (max - min) + min); } } return matrix; } /** * * @param fname * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException * @throws XMLStreamException * @throws IOException */ public static void externalReadProfile( String fname ) throws DMLUnsupportedOperationException, DMLRuntimeException, XMLStreamException, IOException { registerTestConfigurations(); registerInstructions(); readProfile( fname ); } /** * * @param dirname * @return * @throws IOException * @throws DMLUnsupportedOperationException */ @SuppressWarnings("all") private static HashMap<Integer,Long> writeResults( String dirname ) throws IOException, DMLUnsupportedOperationException { HashMap<Integer,Long> map = new HashMap<Integer, Long>(); int count = 1; int offset = (MODEL_INTERCEPT ? 1 : 0); int cols = MODEL_MAX_ORDER + offset; for( Entry<Integer,HashMap<Integer,LinkedList<Double>>> inst : _results.entrySet() ) { int instID = inst.getKey(); HashMap<Integer,LinkedList<Double>> instCF = inst.getValue(); for( Entry<Integer,LinkedList<Double>> cfun : instCF.entrySet() ) { int tDefID = cfun.getKey(); long ID = IDHandler.concatIntIDsToLong(instID, tDefID); LinkedList<Double> dmeasure = cfun.getValue(); PerfTestDef def = _regTestDef.get(tDefID); LinkedList<Double> dvariable = generateSequence(def.getMin(), def.getMax(), NUM_SAMPLES_PER_TEST); int dlen = dvariable.size(); int plen = def.getInternalVariables().length; //write variable data set CSVWriter writer1 = new CSVWriter( new FileWriter( dirname+count+"_in1.csv" ),',', CSVWriter.NO_QUOTE_CHARACTER); if( plen == 1 ) //one dimensional function { //write 1, x, x^2, x^3, ... String[] sbuff = new String[cols]; for( Double val : dvariable ) { for( int j=0; j<cols; j++ ) sbuff[j] = String.valueOf( Math.pow(val, j+1-offset) ); writer1.writeNext(sbuff); } } else // multi-dimensional function { //write 1, x,y,z,x^2,y^2,z^2, xy, xz, yz, xyz String[] sbuff = new String[(int)Math.pow(2,plen)-1+plen+offset-1]; //String[] sbuff = new String[plen+offset]; if(offset==1) sbuff[0]="1"; //init index stack int[] index = new int[plen]; for( int i=0; i<plen; i++ ) index[i] = 0; //execute test double[] buff = new double[plen]; while( index[0]<dlen ) { //set buffer values for( int i=0; i<plen; i++ ) buff[i] = dvariable.get(index[i]); //core writing for( int i=1; i<=plen; i++ ) { if( i==1 ) { for( int j=0; j<plen; j++ ) sbuff[offset+j] = String.valueOf( buff[j] ); for( int j=0; j<plen; j++ ) sbuff[offset+plen+j] = String.valueOf( Math.pow(buff[j],2) ); } else if( i==2 ) { int ix=0; for( int j=0; j<plen-1; j++ ) for( int k=j+1; k<plen; k++, ix++ ) sbuff[offset+2*plen+ix] = String.valueOf( buff[j]*buff[k] ); } else if( i==plen ) { //double tmp=1; //for( int j=0; j<plen; j++ ) // tmp *= buff[j]; //sbuff[offset+2*plen+plen*(plen-1)/2] = String.valueOf(tmp); } else throw new DMLUnsupportedOperationException("More than 3 dims currently not supported."); } //for( int i=0; i<plen; i++ ) // sbuff[offset+i] = String.valueOf( buff[i] ); writer1.writeNext(sbuff); //increment indexes for( int i=plen-1; i>=0; i-- ) { if(i==plen-1) index[i]++; else if( index[i+1] >= dlen ) { index[i]++; index[i+1]=0; } } } } writer1.close(); //write measure data set CSVWriter writer2 = new CSVWriter( new FileWriter( dirname+count+"_in2.csv" ),',', CSVWriter.NO_QUOTE_CHARACTER); String[] buff2 = new String[1]; for( Double val : dmeasure ) { buff2[0] = String.valueOf( val ); writer2.writeNext(buff2); } writer2.close(); map.put(count, ID); count++; } } return map; } /** * * @param dmlname * @param dmltmpname * @param dir * @param models * @param rows * @param cols * @throws IOException * @throws ParseException * @throws DMLException */ private static void computeRegressionModels( String dmlname, String dmltmpname, String dir, int models, int rows, int cols ) throws IOException, ParseException, DMLException { //clean scratch space //AutomatedTestBase.cleanupScratchSpace(); //read DML template StringBuffer buffer = new StringBuffer(); BufferedReader br = new BufferedReader( new FileReader(new File( dmlname )) ); String line = ""; while( (line=br.readLine()) != null ) { buffer.append(line); buffer.append("\n"); } br.close(); String template = buffer.toString(); //replace parameters template = template.replaceAll("%numModels%", String.valueOf(models)); template = template.replaceAll("%numRows%", String.valueOf(rows)); template = template.replaceAll("%numCols%", String.valueOf(cols)); template = template.replaceAll("%indir%", String.valueOf(dir)); // write temp DML file File fout = new File(dmltmpname); FileOutputStream fos = new FileOutputStream(fout); fos.write(template.getBytes()); fos.close(); // execute DML script DMLScript.main(new String[] { "-f", dmltmpname }); } /** * * @param dname * @param IDMapping * @throws IOException */ private static void readRegressionModels( String dname, HashMap<Integer,Long> IDMapping ) throws IOException { for( Integer count : IDMapping.keySet() ) { long ID = IDMapping.get(count); int instID = IDHandler.extractIntIDFromLong(ID, 1); int tDefID = IDHandler.extractIntIDFromLong(ID, 2); //read file and parse LinkedList<Double> params = new LinkedList<Double>(); CSVReader reader1 = new CSVReader( new FileReader(dname+count+"_out.csv"), ',' ); String[] nextline = null; while( (nextline = reader1.readNext()) != null ) { params.add(Double.parseDouble(nextline[0])); } reader1.close(); double[] dparams = new double[params.size()]; int i=0; for( Double d : params ) { dparams[i] = d; i++; } //create new cost function boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1; CostFunction cf = new CostFunction(dparams, multidim); //append to profile if( !_profile.containsKey(instID) ) _profile.put(instID, new HashMap<Integer, CostFunction>()); _profile.get(instID).put(tDefID, cf); } } /** * * @param vars * @return */ private static String serializeTestVariables( InternalTestVariable[] vars ) { StringBuffer sb = new StringBuffer(); for( int i=0; i<vars.length; i++ ) { if( i>0 ) sb.append( XML_ELEMENT_DELIMITER ); sb.append( String.valueOf(vars[i]) ); } return sb.toString(); } /** * * @param vars * @return */ private static InternalTestVariable[] parseTestVariables(String vars) { StringTokenizer st = new StringTokenizer(vars, XML_ELEMENT_DELIMITER); InternalTestVariable[] v = new InternalTestVariable[st.countTokens()]; for( int i=0; i<v.length; i++ ) v[i] = InternalTestVariable.valueOf(st.nextToken()); return v; } /** * * @param vals * @return */ private static String serializeParams( double[] vals ) { StringBuffer sb = new StringBuffer(); for( int i=0; i<vals.length; i++ ) { if( i>0 ) sb.append( XML_ELEMENT_DELIMITER ); sb.append( String.valueOf(vals[i]) ); } return sb.toString(); } /** * * @param valStr * @return */ private static double[] parseParams( String valStr ) { StringTokenizer st = new StringTokenizer(valStr, XML_ELEMENT_DELIMITER); double[] params = new double[st.countTokens()]; for( int i=0; i<params.length; i++ ) params[i] = Double.parseDouble(st.nextToken()); return params; } /** * * @param fname * @throws XMLStreamException * @throws IOException */ private static void readProfile( String fname ) throws XMLStreamException, IOException { //init profile map _profile = new HashMap<Integer, HashMap<Integer,CostFunction>>(); //check file for existence File f = new File( fname ); if( !f.exists() ) System.out.println("ParFOR PerfTestTool: Warning cannot read profile file "+fname); FileInputStream fis = new FileInputStream( f ); //xml parsing XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader( fis ); int e = xsr.nextTag(); // profile start while( true ) //read all instructions { e = xsr.nextTag(); // instruction start if( e == XMLStreamConstants.END_ELEMENT ) break; //reached profile end tag //parse instruction int ID = Integer.parseInt( xsr.getAttributeValue(null, XML_ID) ); //String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR); HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>(); _profile.put( ID, tmp ); while( true ) { e = xsr.nextTag(); // cost function start if( e == XMLStreamConstants.END_ELEMENT ) break; //reached instruction end tag //parse cost function TestMeasure m = TestMeasure.valueOf( xsr.getAttributeValue(null, XML_MEASURE) ); TestVariable lv = TestVariable.valueOf( xsr.getAttributeValue(null, XML_VARIABLE) ); InternalTestVariable[] pv = parseTestVariables( xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES) ); DataFormat df = DataFormat.valueOf( xsr.getAttributeValue(null, XML_DATAFORMAT) ); int tDefID = getTestDefID(m, lv, df, pv); xsr.next(); //read characters double[] params = parseParams(xsr.getText()); boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1; CostFunction cf = new CostFunction( params, multidim ); tmp.put(tDefID, cf); xsr.nextTag(); // cost function end //System.out.println("added cost function"); } } xsr.close(); fis.close(); //mark profile as successfully read _flagReadData = true; } /** * StAX for efficient streaming XML writing. * * @throws IOException * @throws XMLStreamException */ private static void writeProfile( String dname, String fname ) throws IOException, XMLStreamException { //create initial directory and file File dir = new File( dname ); if( !dir.exists() ) dir.mkdir(); File f = new File( fname ); f.createNewFile(); FileOutputStream fos = new FileOutputStream( f ); //create document XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter xsw = xof.createXMLStreamWriter( fos ); xsw = new IndentingXMLStreamWriter( xsw ); //remove this line if no indenting required //write document content xsw.writeStartDocument(); xsw.writeStartElement( XML_PROFILE ); xsw.writeAttribute(XML_DATE, String.valueOf(new Date()) ); //foreach instruction (boundle of cost functions) for( Entry<Integer,HashMap<Integer,CostFunction>> inst : _profile.entrySet() ) { int instID = inst.getKey(); String instName = _regInst_IDNames.get( instID ); xsw.writeStartElement( XML_INSTRUCTION ); xsw.writeAttribute(XML_ID, String.valueOf( instID )); xsw.writeAttribute(XML_NAME, instName.replaceAll(Lops.OPERAND_DELIMITOR, " ")); //foreach testdef cost function for( Entry<Integer,CostFunction> cfun : inst.getValue().entrySet() ) { int tdefID = cfun.getKey(); PerfTestDef def = _regTestDef.get(tdefID); CostFunction cf = cfun.getValue(); xsw.writeStartElement( XML_COSTFUNCTION ); xsw.writeAttribute( XML_ID, String.valueOf( tdefID )); xsw.writeAttribute( XML_MEASURE, def.getMeasure().toString() ); xsw.writeAttribute( XML_VARIABLE, def.getVariable().toString() ); xsw.writeAttribute( XML_INTERNAL_VARIABLES, serializeTestVariables(def.getInternalVariables()) ); xsw.writeAttribute( XML_DATAFORMAT, def.getDataformat().toString() ); xsw.writeCharacters(serializeParams( cf.getParams() )); xsw.writeEndElement();// XML_COSTFUNCTION } xsw.writeEndElement(); //XML_INSTRUCTION } xsw.writeEndElement();//XML_PROFILE xsw.writeEndDocument(); xsw.close(); fos.close(); } /** * Main for invoking the actual performance test in order to produce profile.xml * * @param args */ public static void main(String[] args) { //execute the local / remote performance test try { PerfTestTool.runTest(); } catch (Exception e) { e.printStackTrace(); } } }
SystemML/DML/src/com/ibm/bi/dml/runtime/controlprogram/parfor/opt/PerfTestTool.java
package com.ibm.bi.dml.runtime.controlprogram.parfor.opt; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.StringTokenizer; import java.util.Vector; import java.util.Map.Entry; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; import com.ibm.bi.dml.api.DMLScript; import com.ibm.bi.dml.lops.Lops; import com.ibm.bi.dml.parser.DMLProgram; import com.ibm.bi.dml.parser.DMLTranslator; import com.ibm.bi.dml.parser.DataIdentifier; import com.ibm.bi.dml.parser.ParseException; import com.ibm.bi.dml.parser.Expression.DataType; import com.ibm.bi.dml.parser.Expression.ValueType; import com.ibm.bi.dml.runtime.controlprogram.ExternalFunctionProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.ExternalFunctionProgramBlockCP; import com.ibm.bi.dml.runtime.controlprogram.Program; import com.ibm.bi.dml.runtime.controlprogram.ProgramBlock; import com.ibm.bi.dml.runtime.controlprogram.parfor.stat.Timing; import com.ibm.bi.dml.runtime.controlprogram.parfor.util.IDHandler; import com.ibm.bi.dml.runtime.controlprogram.parfor.util.IDSequence; import com.ibm.bi.dml.runtime.instructions.CPInstructionParser; import com.ibm.bi.dml.runtime.instructions.Instruction; import com.ibm.bi.dml.runtime.instructions.CPInstructions.Data; import com.ibm.bi.dml.runtime.instructions.CPInstructions.FunctionCallCPInstruction; import com.ibm.bi.dml.runtime.instructions.CPInstructions.MatrixObjectNew; import com.ibm.bi.dml.runtime.instructions.CPInstructions.RandCPInstruction; import com.ibm.bi.dml.runtime.matrix.MatrixCharacteristics; import com.ibm.bi.dml.runtime.matrix.MatrixFormatMetaData; import com.ibm.bi.dml.runtime.matrix.io.InputInfo; import com.ibm.bi.dml.runtime.matrix.io.MatrixBlock; import com.ibm.bi.dml.runtime.matrix.io.OutputInfo; import com.ibm.bi.dml.runtime.util.MapReduceTool; //import com.ibm.bi.dml.test.integration.AutomatedTestBase; import com.ibm.bi.dml.test.utils.TestUtils; import com.ibm.bi.dml.utils.CacheException; import com.ibm.bi.dml.utils.DMLException; import com.ibm.bi.dml.utils.DMLRuntimeException; import com.ibm.bi.dml.utils.DMLUnsupportedOperationException; import com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter; /** * DML Instructions Performance Test Tool: * * Creates an offline performance profile (required once per installation) of DML instructions. * The profile is a combination of all individual statistical models trained per combination of * instruction and test configuration. In order to train those models, we execute and measure * real executions of DML instructions on random input data. Finally, during runtime, the profile * is used by the costs estimator in order to create statistic estimates for cost-based optimization. * * TODO: complete all CP instructions * TODO: add support for MR instructions * TODO: add support for TestVariable.PARALLELISM * TODO: add support for instruction-invariant cost functions * TODO: add support for constants such as IO throughput (e.g., DFSIOTest) * TODO: add support for known external functions and DML scripts / functions */ public class PerfTestTool { //internal parameters public static final boolean READ_STATS_ON_STARTUP = false; public static final int TEST_REPETITIONS = 5; public static final int NUM_SAMPLES_PER_TEST = 11; public static final int MODEL_MAX_ORDER = 2; public static final boolean MODEL_INTERCEPT = true; public static final long MIN_DATASIZE = 100; public static final long MAX_DATASIZE = 1000000; public static final long DEFAULT_DATASIZE = (MAX_DATASIZE-MIN_DATASIZE)/2; public static final double MIN_DIMSIZE = 1; public static final double MAX_DIMSIZE = 1000; public static final double MIN_SPARSITY = 0.1; public static final double MAX_SPARSITY = 1.0; public static final double DEFAULT_SPARSITY = (MAX_SPARSITY-MIN_SPARSITY)/2; public static final String PERF_TOOL_DIR = "./conf/PerfTestTool/"; public static final String PERF_RESULTS_FNAME = PERF_TOOL_DIR + "%id%.dat"; public static final String PERF_PROFILE_FNAME = PERF_TOOL_DIR + "performance_profile.xml"; public static final String DML_SCRIPT_FNAME = "./src/com/ibm/bi/dml/runtime/controlprogram/parfor/opt/PerfTestToolRegression.dml"; public static final String DML_TMP_FNAME = PERF_TOOL_DIR + "temp.dml"; //XML profile tags and attributes public static final String XML_PROFILE = "profile"; public static final String XML_DATE = "date"; public static final String XML_INSTRUCTION = "instruction"; public static final String XML_ID = "id"; public static final String XML_NAME = "name"; public static final String XML_COSTFUNCTION = "cost_function"; public static final String XML_MEASURE = "measure"; public static final String XML_VARIABLE = "lvariable"; public static final String XML_INTERNAL_VARIABLES = "pvariables"; public static final String XML_DATAFORMAT = "dataformat"; public static final String XML_ELEMENT_DELIMITER = ","; //ID sequences for instructions and test definitions private static IDSequence _seqInst = null; private static IDSequence _seqTestDef = null; //registered instructions and test definitions private static HashMap<Integer, PerfTestDef> _regTestDef = null; private static HashMap<Integer, Instruction> _regInst = null; private static HashMap<Integer, String> _regInst_IDNames = null; private static HashMap<String, Integer> _regInst_NamesID = null; private static HashMap<Integer, Integer[]> _regInst_IDTestDef = null; private static HashMap<Integer, Boolean> _regInst_IDVectors = null; private static HashMap<Integer, IOSchema> _regInst_IDIOSchema = null; private static Integer[] _defaultConf = null; //raw measurement data (instID, physical defID, results) private static HashMap<Integer,HashMap<Integer,LinkedList<Double>>> _results = null; //profile data private static boolean _flagReadData = false; private static HashMap<Integer,HashMap<Integer,CostFunction>> _profile = null; public enum TestMeasure //logical test measure { EXEC_TIME, MEMORY_USAGE } public enum TestVariable //logical test variable { DATA_SIZE, SPARSITY, PARALLELISM } public enum InternalTestVariable //physical test variable { DATA_SIZE, DIM1_SIZE, DIM2_SIZE, DIM3_SIZE, SPARSITY, NUM_THREADS, NUM_MAPPERS, NUM_REDUCERS, } public enum IOSchema { NONE_NONE, NONE_UNARY, UNARY_NONE, UNARY_UNARY, BINARY_NONE, BINARY_UNARY } public enum DataFormat //logical data format { DENSE, SPARSE } public enum TestConstants //logical test constants { DFS_READ_THROUGHPUT, DFS_WRITE_THROUGHPUT, LFS_READ_THROUGHPUT, LFS_WRITE_THROUGHPUT } static { //init repository _seqInst = new IDSequence(); _seqTestDef = new IDSequence(); _regTestDef = new HashMap<Integer, PerfTestDef>(); _regInst = new HashMap<Integer, Instruction>(); _regInst_IDNames = new HashMap<Integer, String>(); _regInst_NamesID = new HashMap<String, Integer>(); _regInst_IDTestDef = new HashMap<Integer, Integer[]>(); _regInst_IDVectors = new HashMap<Integer, Boolean>(); _regInst_IDIOSchema = new HashMap<Integer, IOSchema>(); _results = new HashMap<Integer, HashMap<Integer,LinkedList<Double>>>(); _profile = new HashMap<Integer, HashMap<Integer,CostFunction>>(); _flagReadData = false; //load existing profile if required try { if( READ_STATS_ON_STARTUP ) { readProfile( PERF_PROFILE_FNAME ); } } catch(Exception ex) { throw new RuntimeException(ex); } } /** * * @throws DMLRuntimeException */ public static void lazyInit() throws DMLRuntimeException { //read profile for first access if( !_flagReadData ) { try { //register all testdefs and instructions registerTestConfigurations(); registerInstructions(); //read profile readProfile( PERF_PROFILE_FNAME ); } catch(Exception ex) { throw new DMLRuntimeException(ex); } } if( _profile == null ) throw new DMLRuntimeException("Performance test results have not been loaded completely."); } /** * * @param opStr * @return * @throws DMLRuntimeException */ public static boolean isRegisteredInstruction(String opStr) throws DMLRuntimeException { //init if required lazyInit(); //determine if inst registered return _regInst_NamesID.containsKey(opStr); } /** * * @param instName * @return * @throws DMLRuntimeException */ public static CostFunction getCostFunction( String instName, TestMeasure measure, TestVariable variable, DataFormat dataformat ) throws DMLRuntimeException { //init if required lazyInit(); CostFunction tmp = null; int instID = getInstructionID( instName ); if( instID != -1 ) //existing profile { int tdefID = getMappedTestDefID(instID, measure, variable, dataformat); tmp = _profile.get(instID).get(tdefID); } return tmp; } /** * * @param measure * @param variable * @param dataformat * @return */ public CostFunction getInvariantCostFunction( TestMeasure measure, TestVariable[] variable, DataFormat dataformat ) { //TODO: implement for additional rewrites throw new RuntimeException("Not implemented yet."); } /** * * @return */ @SuppressWarnings("all") public static boolean runTest() { boolean ret = false; try { Timing time = new Timing(); time.start(); //register all testdefs and instructions registerTestConfigurations(); registerInstructions(); //execute tests for all confs and all instructions executeTest(); //compute regression models int rows = NUM_SAMPLES_PER_TEST; int cols = MODEL_MAX_ORDER + (MODEL_INTERCEPT ? 1 : 0); HashMap<Integer,Long> tmp = writeResults( PERF_TOOL_DIR ); computeRegressionModels( DML_SCRIPT_FNAME, DML_TMP_FNAME, PERF_TOOL_DIR, tmp.size(), rows, cols); readRegressionModels( PERF_TOOL_DIR, tmp); //execConstantRuntimeTest(); //execConstantMemoryTest(); //write final profile to XML file writeProfile(PERF_TOOL_DIR, PERF_PROFILE_FNAME); System.out.format("SystemML PERFORMANCE TEST TOOL: finished profiling (in %.2f min), profile written to "+PERF_PROFILE_FNAME+"%n", time.stop()/60000); ret = true; } catch(Exception ex) { ex.printStackTrace(); } return ret; } /** * */ private static void registerTestConfigurations() { //reset ID Sequence for consistent IDs _seqTestDef.reset(); //register default testdefs TestMeasure[] M = new TestMeasure[]{ TestMeasure.EXEC_TIME, TestMeasure.MEMORY_USAGE }; DataFormat[] D = new DataFormat[]{DataFormat.DENSE,DataFormat.SPARSE}; Integer[] defaultConf = new Integer[M.length*D.length*2]; int i=0; for( TestMeasure m : M ) //for all measures for( DataFormat d : D ) //for all data formats { defaultConf[i++] = registerTestDef( new PerfTestDef(m, TestVariable.DATA_SIZE, d, InternalTestVariable.DATA_SIZE, MIN_DATASIZE, MAX_DATASIZE, NUM_SAMPLES_PER_TEST ) ); defaultConf[i++] = registerTestDef( new PerfTestDef(m, TestVariable.SPARSITY, d, InternalTestVariable.SPARSITY, MIN_SPARSITY, MAX_SPARSITY, NUM_SAMPLES_PER_TEST ) ); } //register advanced (multi-dim) test defs for( TestMeasure m : M ) //for all measures for( DataFormat d : D ) //for all data formats { registerTestDef( new PerfTestDef( m, TestVariable.DATA_SIZE, d, new InternalTestVariable[]{InternalTestVariable.DIM1_SIZE,InternalTestVariable.DIM2_SIZE,InternalTestVariable.DIM3_SIZE}, MIN_DIMSIZE, MAX_DIMSIZE, NUM_SAMPLES_PER_TEST ) ); } //set default testdefs _defaultConf = defaultConf; } /** * * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException */ private static void registerInstructions() throws DMLUnsupportedOperationException, DMLRuntimeException { //reset ID sequences for consistent IDs _seqInst.reset(); //matrix multiply registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"ba+*", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"ba+*"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), getDefaultTestDefs(), false, IOSchema.BINARY_UNARY ); ////registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"ba+*", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"ba+*"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), //// changeToMuliDimTestDefs(TestVariable.DATA_SIZE, getDefaultTestDefs()) ); //rand registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"Rand", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"Rand"+Lops.OPERAND_DELIMITOR+"rows=1"+Lops.OPERAND_DELIMITOR+"cols=1"+Lops.OPERAND_DELIMITOR+"min=1.0"+Lops.OPERAND_DELIMITOR+"max=100.0"+Lops.OPERAND_DELIMITOR+"sparsity=1.0"+Lops.OPERAND_DELIMITOR+"pdf=uniform"+Lops.OPERAND_DELIMITOR+"dir=."+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), getDefaultTestDefs(), false, IOSchema.NONE_UNARY ); //matrix transpose registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"r'", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"r'"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"C"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), getDefaultTestDefs(), false, IOSchema.UNARY_UNARY ); //sum registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"uak+", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"uak+"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"), //needs B instead of C getDefaultTestDefs(), false, IOSchema.UNARY_UNARY ); //external function registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"extfunct", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"extfunct"+Lops.OPERAND_DELIMITOR+DMLProgram.DEFAULT_NAMESPACE+""+Lops.OPERAND_DELIMITOR+"execPerfTestExtFunct"+Lops.OPERAND_DELIMITOR+"1"+Lops.OPERAND_DELIMITOR+"1"+Lops.OPERAND_DELIMITOR+"A"+Lops.OPERAND_DELIMITOR+"C"), getDefaultTestDefs(), false, IOSchema.UNARY_UNARY ); //central moment registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"cm", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"cm"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"2"+Lops.DATATYPE_PREFIX+"SCALAR"+Lops.VALUETYPE_PREFIX+"INT"+Lops.OPERAND_DELIMITOR+"c"+Lops.DATATYPE_PREFIX+"SCALAR"+Lops.VALUETYPE_PREFIX+"DOUBLE"), getDefaultTestDefs(), true, IOSchema.UNARY_NONE ); //co-variance registerInstruction( "CP"+Lops.OPERAND_DELIMITOR+"cov", CPInstructionParser.parseSingleInstruction("CP"+Lops.OPERAND_DELIMITOR+"cov"+Lops.OPERAND_DELIMITOR+"A"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"B"+Lops.DATATYPE_PREFIX+"MATRIX"+Lops.VALUETYPE_PREFIX+"DOUBLE"+Lops.OPERAND_DELIMITOR+"c"+Lops.DATATYPE_PREFIX+"SCALAR"+Lops.VALUETYPE_PREFIX+"DOUBLE"), getDefaultTestDefs(), true, IOSchema.BINARY_NONE ); /*ADD ADDITIONAL INSTRUCTIONS HERE*/ //extend list to all (expensive) instructions; maybe also: createvar, assignvar, mvvar, rm, mv, setfilename, rmfilevar, print2 } /** * * @param def * @return */ private static int registerTestDef( PerfTestDef def ) { int ID = (int)_seqTestDef.getNextID(); _regTestDef.put( ID, def ); return ID; } /** * * @param iname * @param inst * @param testDefIDs * @param vectors * @param schema */ private static void registerInstruction( String iname, Instruction inst, Integer[] testDefIDs, boolean vectors, IOSchema schema ) { int ID = (int)_seqInst.getNextID(); registerInstruction(ID, iname, inst, testDefIDs, vectors, schema); } /** * * @param ID * @param iname * @param inst * @param testDefIDs * @param vector * @param schema */ private static void registerInstruction( int ID, String iname, Instruction inst, Integer[] testDefIDs, boolean vector, IOSchema schema ) { _regInst.put( ID, inst ); _regInst_IDNames.put( ID, iname ); _regInst_NamesID.put( iname, ID ); _regInst_IDTestDef.put( ID, testDefIDs ); _regInst_IDVectors.put( ID, vector ); _regInst_IDIOSchema.put( ID, schema ); } /** * * @param instID * @param measure * @param variable * @param dataformat * @return */ private static int getMappedTestDefID( int instID, TestMeasure measure, TestVariable variable, DataFormat dataformat ) { int ret = -1; for( Integer defID : _regInst_IDTestDef.get(instID) ) { PerfTestDef def = _regTestDef.get(defID); if( def.getMeasure()==measure && def.getVariable()==variable && def.getDataformat()==dataformat ) { ret = defID; break; } } return ret; } /** * * @param measure * @param lvariable * @param dataformat * @param pvariable * @return */ @SuppressWarnings("unused") private static int getTestDefID( TestMeasure measure, TestVariable lvariable, DataFormat dataformat, InternalTestVariable pvariable ) { return getTestDefID(measure, lvariable, dataformat, new InternalTestVariable[]{pvariable}); } /** * * @param measure * @param lvariable * @param dataformat * @param pvariables * @return */ private static int getTestDefID( TestMeasure measure, TestVariable lvariable, DataFormat dataformat, InternalTestVariable[] pvariables ) { int ret = -1; for( Entry<Integer,PerfTestDef> e : _regTestDef.entrySet() ) { PerfTestDef def = e.getValue(); TestMeasure tmp1 = def.getMeasure(); TestVariable tmp2 = def.getVariable(); DataFormat tmp3 = def.getDataformat(); InternalTestVariable[] tmp4 = def.getInternalVariables(); if( tmp1==measure && tmp2==lvariable && tmp3==dataformat ) { boolean flag = true; for( int i=0; i<tmp4.length; i++ ) flag &= ( tmp4[i] == pvariables[i] ); if( flag ) { ret = e.getKey(); break; } } } return ret; } /** * * @param instName * @return */ private static int getInstructionID( String instName ) { Integer ret = _regInst_NamesID.get( instName ); return ( ret!=null )? ret : -1; } /** * * @return */ @SuppressWarnings("unused") private static Integer[] getAllTestDefs() { return _regTestDef.keySet().toArray(new Integer[0]); } /** * * @return */ private static Integer[] getDefaultTestDefs() { return _defaultConf; } /** * * @param v * @param IDs * @return */ @SuppressWarnings("unused") private static Integer[] changeToMuliDimTestDefs( TestVariable v, Integer[] IDs ) { Integer[] tmp = new Integer[IDs.length]; for( int i=0; i<tmp.length; i++ ) { PerfTestDef def = _regTestDef.get(IDs[i]); if( def.getVariable() == v ) //filter logical variables { //find multidim version InternalTestVariable[] in = null; switch( v ) { case DATA_SIZE: in = new InternalTestVariable[]{InternalTestVariable.DIM1_SIZE,InternalTestVariable.DIM2_SIZE,InternalTestVariable.DIM3_SIZE}; break; } int newid = getTestDefID(def.getMeasure(), def.getVariable(), def.getDataformat(), in ); //exchange testdef ID tmp[i] = newid; } else { tmp[i] = IDs[i]; } } return tmp; } /** * * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException * @throws IOException */ private static void executeTest( ) throws DMLRuntimeException, DMLUnsupportedOperationException, IOException { System.out.println("SystemML PERFORMANCE TEST TOOL:"); //foreach registered instruction for( Entry<Integer,Instruction> inst : _regInst.entrySet() ) { int instID = inst.getKey(); System.out.println( "Running INSTRUCTION "+_regInst_IDNames.get(instID) ); Integer[] testDefIDs = _regInst_IDTestDef.get(instID); boolean vectors = _regInst_IDVectors.get(instID); IOSchema schema = _regInst_IDIOSchema.get(instID); //create tmp program block and set instruction Program prog = new Program(); ProgramBlock pb = new ProgramBlock( prog ); ArrayList<Instruction> ainst = new ArrayList<Instruction>(); ainst.add( inst.getValue() ); pb.setInstructions(ainst); //foreach registered test configuration for( Integer defID : testDefIDs ) { PerfTestDef def = _regTestDef.get(defID); TestMeasure m = def.getMeasure(); TestVariable lv = def.getVariable(); DataFormat df = def.getDataformat(); InternalTestVariable[] pv = def.getInternalVariables(); double min = def.getMin(); double max = def.getMax(); double samples = def.getNumSamples(); System.out.println( "Running TESTDEF(measure="+m+", variable="+String.valueOf(lv)+" "+pv.length+", format="+String.valueOf(df)+")" ); //vary input variable LinkedList<Double> dmeasure = new LinkedList<Double>(); LinkedList<Double> dvariable = generateSequence(min, max, samples); int plen = pv.length; if( plen == 1 ) //1D function { for( Double var : dvariable ) { dmeasure.add(executeTestCase1D(m, pv[0], df, var, pb, vectors, schema)); } } else //multi-dim function { //init index stack int[] index = new int[plen]; for( int i=0; i<plen; i++ ) index[i] = 0; //execute test int dlen = dvariable.size(); double[] buff = new double[plen]; while( index[0]<dlen ) { //set buffer values for( int i=0; i<plen; i++ ) buff[i] = dvariable.get(index[i]); //core execution dmeasure.add(executeTestCaseMD(m, pv, df, buff, pb, schema)); //not applicable for vector flag //increment indexes for( int i=plen-1; i>=0; i-- ) { if(i==plen-1) index[i]++; else if( index[i+1] >= dlen ) { index[i]++; index[i+1]=0; } } } } //append values to results if( !_results.containsKey(instID) ) _results.put(instID, new HashMap<Integer, LinkedList<Double>>()); _results.get(instID).put(defID, dmeasure); } } } /** * * @param m * @param v * @param df * @param varValue * @param pb * @param vectors * @param schema * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException * @throws IOException */ private static double executeTestCase1D( TestMeasure m, InternalTestVariable v, DataFormat df, double varValue, ProgramBlock pb, boolean vectors, IOSchema schema ) throws DMLRuntimeException, DMLUnsupportedOperationException, IOException { double datasize = -1; double dim1 = -1, dim2 = -1; double sparsity = -1; System.out.println( "VAR VALUE "+varValue ); //set test variables switch ( v ) { case DATA_SIZE: datasize = varValue; sparsity = DEFAULT_SPARSITY; break; case SPARSITY: datasize = DEFAULT_DATASIZE; sparsity = varValue; break; } //set specific dimensions if( vectors ) { dim1 = datasize; dim2 = 1; } else { dim1 = Math.sqrt( datasize ); dim2 = dim1; } //instruction-specific configurations Instruction inst = pb.getInstruction(0); //always exactly one instruction if( inst instanceof RandCPInstruction ) { RandCPInstruction rand = (RandCPInstruction) inst; rand.rows = (long)dim1; rand.cols = (long)dim2; rand.sparsity = sparsity; } else if ( inst instanceof FunctionCallCPInstruction ) //ExternalFunctionInvocationInstruction { Program prog = pb.getProgram(); Vector<DataIdentifier> in = new Vector<DataIdentifier>(); DataIdentifier dat1 = new DataIdentifier("A"); dat1.setDataType(DataType.MATRIX); dat1.setValueType(ValueType.DOUBLE); in.add(dat1); Vector<DataIdentifier> out = new Vector<DataIdentifier>(); DataIdentifier dat2 = new DataIdentifier("C"); dat2.setDataType(DataType.MATRIX); dat2.setValueType(ValueType.DOUBLE); out.add(dat2); HashMap<String, String> params = new HashMap<String, String>(); params.put(ExternalFunctionProgramBlock.CLASSNAME, PerfTestExtFunctCP.class.getName()); ExternalFunctionProgramBlockCP fpb = new ExternalFunctionProgramBlockCP(prog, in, out, params, PERF_TOOL_DIR); prog.addFunctionProgramBlock(DMLProgram.DEFAULT_NAMESPACE, "execPerfTestExtFunct", fpb); } //generate input and output matrices pb.getVariables().removeAll(); double mem1 = PerfTestMemoryObserver.getUsedMemory(); if( schema!=IOSchema.NONE_NONE && schema!=IOSchema.NONE_UNARY ) pb.getVariables().put("A", generateInputDataset(PERF_TOOL_DIR+"/A", dim1, dim2, sparsity, df)); if( schema==IOSchema.BINARY_NONE || schema==IOSchema.BINARY_UNARY || schema==IOSchema.UNARY_UNARY ) pb.getVariables().put("B", generateInputDataset(PERF_TOOL_DIR+"/B", dim1, dim2, sparsity, df)); if( schema==IOSchema.NONE_UNARY || schema==IOSchema.UNARY_UNARY || schema==IOSchema.BINARY_UNARY) pb.getVariables().put("C", generateEmptyResult(PERF_TOOL_DIR+"/C", dim1, dim2, df)); double mem2 = PerfTestMemoryObserver.getUsedMemory(); //foreach repetition double value = 0; for( int i=0; i<TEST_REPETITIONS; i++ ) { System.out.println("run "+i); value += executeGenericProgramBlock( m, pb ); } value/=TEST_REPETITIONS; //result correction and print result switch( m ) { case EXEC_TIME: System.out.println("--- RESULT: "+value+" ms"); break; case MEMORY_USAGE: //System.out.println("--- RESULT: "+value+" byte"); if( (mem2-mem1) > 0 ) value = value + mem2-mem1; //correction: input sizes added System.out.println("--- RESULT: "+value+" byte"); break; default: System.out.println("--- RESULT: "+value); break; } return value; } /** * * @param m * @param v * @param df * @param varValue * @param pb * @param schema * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException * @throws IOException */ private static double executeTestCaseMD( TestMeasure m, InternalTestVariable[] v, DataFormat df, double[] varValue, ProgramBlock pb, IOSchema schema ) throws DMLRuntimeException, DMLUnsupportedOperationException, IOException { //double datasize = DEFAULT_DATASIZE; double sparsity = DEFAULT_SPARSITY; double dim1 = -1; double dim2 = -1; double dim3 = -1; for( int i=0; i<v.length; i++ ) { System.out.println( "VAR VALUE "+varValue[i] ); switch( v[i] ) { case DIM1_SIZE: dim1=varValue[i]; break; case DIM2_SIZE: dim2=varValue[i]; break; case DIM3_SIZE: dim3=varValue[i]; break; } } //generate input and output matrices pb.getVariables().removeAll(); double mem1 = PerfTestMemoryObserver.getUsedMemory(); if( schema!=IOSchema.NONE_NONE && schema!=IOSchema.NONE_UNARY ) pb.getVariables().put("A", generateInputDataset(PERF_TOOL_DIR+"/A", dim1, dim2, sparsity, df)); if( schema==IOSchema.BINARY_NONE || schema==IOSchema.BINARY_UNARY || schema==IOSchema.UNARY_UNARY ) pb.getVariables().put("B", generateInputDataset(PERF_TOOL_DIR+"/B", dim2, dim3, sparsity, df)); if( schema==IOSchema.NONE_UNARY || schema==IOSchema.UNARY_UNARY || schema==IOSchema.BINARY_UNARY) pb.getVariables().put("C", generateEmptyResult(PERF_TOOL_DIR+"/C", dim1, dim3, df)); double mem2 = PerfTestMemoryObserver.getUsedMemory(); //foreach repetition double value = 0; for( int i=0; i<TEST_REPETITIONS; i++ ) { System.out.println("run "+i); value += executeGenericProgramBlock( m, pb ); } value/=TEST_REPETITIONS; //result correction and print result switch( m ) { case EXEC_TIME: System.out.println("--- RESULT: "+value+" ms"); break; case MEMORY_USAGE: //System.out.println("--- RESULT: "+value+" byte"); if( (mem2-mem1) > 0 ) value = value + mem2-mem1; //correction: input sizes added System.out.println("--- RESULT: "+value+" byte"); break; default: System.out.println("--- RESULT: "+value); break; } return value; } /** * * @param measure * @param pb * @return * @throws DMLRuntimeException * @throws DMLUnsupportedOperationException */ public static double executeGenericProgramBlock( TestMeasure measure, ProgramBlock pb ) throws DMLRuntimeException, DMLUnsupportedOperationException { double value = 0; try { switch( measure ) { case EXEC_TIME: Timing time = new Timing(); time.start(); pb.execute( null ); value = time.stop(); break; case MEMORY_USAGE: PerfTestMemoryObserver mo = new PerfTestMemoryObserver(); mo.measureStartMem(); Thread t = new Thread(mo); t.start(); pb.execute( null ); mo.setStopped(); value = mo.getMaxMemConsumption(); t.join(); break; } } catch(Exception ex) { throw new DMLRuntimeException(ex); } //clear matrixes from cache for( String str : pb.getVariables().keySet() ) { Data dat = pb.getVariable(str); if( dat.getDataType() == DataType.MATRIX ) ((MatrixObjectNew)dat).clearData(); } return value; } /** * * @param min * @param max * @param num * @return */ public static LinkedList<Double> generateSequence( double min, double max, double num ) { LinkedList<Double> data = new LinkedList<Double>(); double increment = (max-min)/(num-1); for( int i=0; i<num; i++ ) data.add( new Double(min+i*increment) ); return data; } /** * * @param fname * @param datasize * @param sparsity * @param df * @return * @throws IOException * @throws CacheException */ public static MatrixObjectNew generateInputDataset(String fname, double datasize, double sparsity, DataFormat df) throws IOException, CacheException { int dim = (int)Math.sqrt( datasize ); //create random test data double[][] d = TestUtils.generateTestMatrix(dim, dim, 1, 100, sparsity, 7); //create matrix block MatrixBlock mb = null; switch( df ) { case DENSE: mb = new MatrixBlock(dim,dim,false); break; case SPARSE: mb = new MatrixBlock(dim,dim,true); break; } //insert data for(int i=0; i < dim; i++) for(int j=0; j < dim; j++) if( d[i][j]!=0 ) mb.setValue(i, j, d[i][j]); MapReduceTool.deleteFileIfExistOnHDFS(fname); MatrixCharacteristics mc = new MatrixCharacteristics(dim, dim, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize); MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo); MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md); mo.acquireModify(mb); mo.release(); mo.exportData(); //write to HDFS return mo; } /** * * @param fname * @param dim1 * @param dim2 * @param sparsity * @param df * @return * @throws IOException * @throws CacheException */ public static MatrixObjectNew generateInputDataset(String fname, double dim1, double dim2, double sparsity, DataFormat df) throws IOException, CacheException { int d1 = (int) dim1; int d2 = (int) dim2; System.out.println(d1+" "+d2); //create random test data double[][] d = TestUtils.generateTestMatrix(d1, d2, 1, 100, sparsity, 7); //create matrix block MatrixBlock mb = null; switch( df ) { case DENSE: mb = new MatrixBlock(d1,d2,false); break; case SPARSE: mb = new MatrixBlock(d1,d2,true); break; } //insert data for(int i=0; i < d1; i++) for(int j=0; j < d2; j++) if( d[i][j]!=0 ) mb.setValue(i, j, d[i][j]); MapReduceTool.deleteFileIfExistOnHDFS(fname); MatrixCharacteristics mc = new MatrixCharacteristics(d1, d2, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize); MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo); MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md); mo.acquireModify(mb); mo.release(); mo.exportData(); //write to HDFS return mo; } /** * * @param fname * @param datasize * @param df * @return * @throws IOException * @throws CacheException */ public static MatrixObjectNew generateEmptyResult(String fname, double datasize, DataFormat df ) throws IOException, CacheException { int dim = (int)Math.sqrt( datasize ); /* MatrixBlock mb = null; switch( df ) { case DENSE: mb = new MatrixBlock(dim,dim,false); break; case SPARSE: mb = new MatrixBlock(dim,dim,true); break; }*/ MatrixCharacteristics mc = new MatrixCharacteristics(dim, dim, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize); MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo); MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md); return mo; } /** * * @param fname * @param dim1 * @param dim2 * @param df * @return * @throws IOException * @throws CacheException */ public static MatrixObjectNew generateEmptyResult(String fname, double dim1, double dim2, DataFormat df ) throws IOException, CacheException { int d1 = (int)dim1; int d2 = (int)dim2; /* MatrixBlock mb = null; switch( df ) { case DENSE: mb = new MatrixBlock(dim,dim,false); break; case SPARSE: mb = new MatrixBlock(dim,dim,true); break; }*/ MatrixCharacteristics mc = new MatrixCharacteristics(d1, d2, DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize); MatrixFormatMetaData md = new MatrixFormatMetaData(mc, OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo); MatrixObjectNew mo = new MatrixObjectNew(ValueType.DOUBLE,fname,md); return mo; } /** * * @param fname * @throws DMLUnsupportedOperationException * @throws DMLRuntimeException * @throws XMLStreamException * @throws IOException */ public static void externalReadProfile( String fname ) throws DMLUnsupportedOperationException, DMLRuntimeException, XMLStreamException, IOException { registerTestConfigurations(); registerInstructions(); readProfile( fname ); } /** * * @param dirname * @return * @throws IOException * @throws DMLUnsupportedOperationException */ @SuppressWarnings("all") private static HashMap<Integer,Long> writeResults( String dirname ) throws IOException, DMLUnsupportedOperationException { HashMap<Integer,Long> map = new HashMap<Integer, Long>(); int count = 1; int offset = (MODEL_INTERCEPT ? 1 : 0); int cols = MODEL_MAX_ORDER + offset; for( Entry<Integer,HashMap<Integer,LinkedList<Double>>> inst : _results.entrySet() ) { int instID = inst.getKey(); HashMap<Integer,LinkedList<Double>> instCF = inst.getValue(); for( Entry<Integer,LinkedList<Double>> cfun : instCF.entrySet() ) { int tDefID = cfun.getKey(); long ID = IDHandler.concatIntIDsToLong(instID, tDefID); LinkedList<Double> dmeasure = cfun.getValue(); PerfTestDef def = _regTestDef.get(tDefID); LinkedList<Double> dvariable = generateSequence(def.getMin(), def.getMax(), NUM_SAMPLES_PER_TEST); int dlen = dvariable.size(); int plen = def.getInternalVariables().length; //write variable data set CSVWriter writer1 = new CSVWriter( new FileWriter( dirname+count+"_in1.csv" ),',', CSVWriter.NO_QUOTE_CHARACTER); if( plen == 1 ) //one dimensional function { //write 1, x, x^2, x^3, ... String[] sbuff = new String[cols]; for( Double val : dvariable ) { for( int j=0; j<cols; j++ ) sbuff[j] = String.valueOf( Math.pow(val, j+1-offset) ); writer1.writeNext(sbuff); } } else // multi-dimensional function { //write 1, x,y,z,x^2,y^2,z^2, xy, xz, yz, xyz String[] sbuff = new String[(int)Math.pow(2,plen)-1+plen+offset-1]; //String[] sbuff = new String[plen+offset]; if(offset==1) sbuff[0]="1"; //init index stack int[] index = new int[plen]; for( int i=0; i<plen; i++ ) index[i] = 0; //execute test double[] buff = new double[plen]; while( index[0]<dlen ) { //set buffer values for( int i=0; i<plen; i++ ) buff[i] = dvariable.get(index[i]); //core writing for( int i=1; i<=plen; i++ ) { if( i==1 ) { for( int j=0; j<plen; j++ ) sbuff[offset+j] = String.valueOf( buff[j] ); for( int j=0; j<plen; j++ ) sbuff[offset+plen+j] = String.valueOf( Math.pow(buff[j],2) ); } else if( i==2 ) { int ix=0; for( int j=0; j<plen-1; j++ ) for( int k=j+1; k<plen; k++, ix++ ) sbuff[offset+2*plen+ix] = String.valueOf( buff[j]*buff[k] ); } else if( i==plen ) { //double tmp=1; //for( int j=0; j<plen; j++ ) // tmp *= buff[j]; //sbuff[offset+2*plen+plen*(plen-1)/2] = String.valueOf(tmp); } else throw new DMLUnsupportedOperationException("More than 3 dims currently not supported."); } //for( int i=0; i<plen; i++ ) // sbuff[offset+i] = String.valueOf( buff[i] ); writer1.writeNext(sbuff); //increment indexes for( int i=plen-1; i>=0; i-- ) { if(i==plen-1) index[i]++; else if( index[i+1] >= dlen ) { index[i]++; index[i+1]=0; } } } } writer1.close(); //write measure data set CSVWriter writer2 = new CSVWriter( new FileWriter( dirname+count+"_in2.csv" ),',', CSVWriter.NO_QUOTE_CHARACTER); String[] buff2 = new String[1]; for( Double val : dmeasure ) { buff2[0] = String.valueOf( val ); writer2.writeNext(buff2); } writer2.close(); map.put(count, ID); count++; } } return map; } /** * * @param dmlname * @param dmltmpname * @param dir * @param models * @param rows * @param cols * @throws IOException * @throws ParseException * @throws DMLException */ private static void computeRegressionModels( String dmlname, String dmltmpname, String dir, int models, int rows, int cols ) throws IOException, ParseException, DMLException { //clean scratch space //AutomatedTestBase.cleanupScratchSpace(); //read DML template StringBuffer buffer = new StringBuffer(); BufferedReader br = new BufferedReader( new FileReader(new File( dmlname )) ); String line = ""; while( (line=br.readLine()) != null ) { buffer.append(line); buffer.append("\n"); } br.close(); String template = buffer.toString(); //replace parameters template = template.replaceAll("%numModels%", String.valueOf(models)); template = template.replaceAll("%numRows%", String.valueOf(rows)); template = template.replaceAll("%numCols%", String.valueOf(cols)); template = template.replaceAll("%indir%", String.valueOf(dir)); // write temp DML file File fout = new File(dmltmpname); FileOutputStream fos = new FileOutputStream(fout); fos.write(template.getBytes()); fos.close(); // execute DML script DMLScript.main(new String[] { "-f", dmltmpname }); } /** * * @param dname * @param IDMapping * @throws IOException */ private static void readRegressionModels( String dname, HashMap<Integer,Long> IDMapping ) throws IOException { for( Integer count : IDMapping.keySet() ) { long ID = IDMapping.get(count); int instID = IDHandler.extractIntIDFromLong(ID, 1); int tDefID = IDHandler.extractIntIDFromLong(ID, 2); //read file and parse LinkedList<Double> params = new LinkedList<Double>(); CSVReader reader1 = new CSVReader( new FileReader(dname+count+"_out.csv"), ',' ); String[] nextline = null; while( (nextline = reader1.readNext()) != null ) { params.add(Double.parseDouble(nextline[0])); } reader1.close(); double[] dparams = new double[params.size()]; int i=0; for( Double d : params ) { dparams[i] = d; i++; } //create new cost function boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1; CostFunction cf = new CostFunction(dparams, multidim); //append to profile if( !_profile.containsKey(instID) ) _profile.put(instID, new HashMap<Integer, CostFunction>()); _profile.get(instID).put(tDefID, cf); } } /** * * @param vars * @return */ private static String serializeTestVariables( InternalTestVariable[] vars ) { StringBuffer sb = new StringBuffer(); for( int i=0; i<vars.length; i++ ) { if( i>0 ) sb.append( XML_ELEMENT_DELIMITER ); sb.append( String.valueOf(vars[i]) ); } return sb.toString(); } /** * * @param vars * @return */ private static InternalTestVariable[] parseTestVariables(String vars) { StringTokenizer st = new StringTokenizer(vars, XML_ELEMENT_DELIMITER); InternalTestVariable[] v = new InternalTestVariable[st.countTokens()]; for( int i=0; i<v.length; i++ ) v[i] = InternalTestVariable.valueOf(st.nextToken()); return v; } /** * * @param vals * @return */ private static String serializeParams( double[] vals ) { StringBuffer sb = new StringBuffer(); for( int i=0; i<vals.length; i++ ) { if( i>0 ) sb.append( XML_ELEMENT_DELIMITER ); sb.append( String.valueOf(vals[i]) ); } return sb.toString(); } /** * * @param valStr * @return */ private static double[] parseParams( String valStr ) { StringTokenizer st = new StringTokenizer(valStr, XML_ELEMENT_DELIMITER); double[] params = new double[st.countTokens()]; for( int i=0; i<params.length; i++ ) params[i] = Double.parseDouble(st.nextToken()); return params; } /** * * @param fname * @throws XMLStreamException * @throws IOException */ private static void readProfile( String fname ) throws XMLStreamException, IOException { //init profile map _profile = new HashMap<Integer, HashMap<Integer,CostFunction>>(); //check file for existence File f = new File( fname ); if( !f.exists() ) System.out.println("ParFOR PerfTestTool: Warning cannot read profile file "+fname); FileInputStream fis = new FileInputStream( f ); //xml parsing XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader( fis ); int e = xsr.nextTag(); // profile start while( true ) //read all instructions { e = xsr.nextTag(); // instruction start if( e == XMLStreamConstants.END_ELEMENT ) break; //reached profile end tag //parse instruction int ID = Integer.parseInt( xsr.getAttributeValue(null, XML_ID) ); //String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR); HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>(); _profile.put( ID, tmp ); while( true ) { e = xsr.nextTag(); // cost function start if( e == XMLStreamConstants.END_ELEMENT ) break; //reached instruction end tag //parse cost function TestMeasure m = TestMeasure.valueOf( xsr.getAttributeValue(null, XML_MEASURE) ); TestVariable lv = TestVariable.valueOf( xsr.getAttributeValue(null, XML_VARIABLE) ); InternalTestVariable[] pv = parseTestVariables( xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES) ); DataFormat df = DataFormat.valueOf( xsr.getAttributeValue(null, XML_DATAFORMAT) ); int tDefID = getTestDefID(m, lv, df, pv); xsr.next(); //read characters double[] params = parseParams(xsr.getText()); boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1; CostFunction cf = new CostFunction( params, multidim ); tmp.put(tDefID, cf); xsr.nextTag(); // cost function end //System.out.println("added cost function"); } } xsr.close(); fis.close(); //mark profile as successfully read _flagReadData = true; } /** * StAX for efficient streaming XML writing. * * @throws IOException * @throws XMLStreamException */ private static void writeProfile( String dname, String fname ) throws IOException, XMLStreamException { //create initial directory and file File dir = new File( dname ); if( !dir.exists() ) dir.mkdir(); File f = new File( fname ); f.createNewFile(); FileOutputStream fos = new FileOutputStream( f ); //create document XMLOutputFactory xof = XMLOutputFactory.newInstance(); XMLStreamWriter xsw = xof.createXMLStreamWriter( fos ); xsw = new IndentingXMLStreamWriter( xsw ); //remove this line if no indenting required //write document content xsw.writeStartDocument(); xsw.writeStartElement( XML_PROFILE ); xsw.writeAttribute(XML_DATE, String.valueOf(new Date()) ); //foreach instruction (boundle of cost functions) for( Entry<Integer,HashMap<Integer,CostFunction>> inst : _profile.entrySet() ) { int instID = inst.getKey(); String instName = _regInst_IDNames.get( instID ); xsw.writeStartElement( XML_INSTRUCTION ); xsw.writeAttribute(XML_ID, String.valueOf( instID )); xsw.writeAttribute(XML_NAME, instName.replaceAll(Lops.OPERAND_DELIMITOR, " ")); //foreach testdef cost function for( Entry<Integer,CostFunction> cfun : inst.getValue().entrySet() ) { int tdefID = cfun.getKey(); PerfTestDef def = _regTestDef.get(tdefID); CostFunction cf = cfun.getValue(); xsw.writeStartElement( XML_COSTFUNCTION ); xsw.writeAttribute( XML_ID, String.valueOf( tdefID )); xsw.writeAttribute( XML_MEASURE, def.getMeasure().toString() ); xsw.writeAttribute( XML_VARIABLE, def.getVariable().toString() ); xsw.writeAttribute( XML_INTERNAL_VARIABLES, serializeTestVariables(def.getInternalVariables()) ); xsw.writeAttribute( XML_DATAFORMAT, def.getDataformat().toString() ); xsw.writeCharacters(serializeParams( cf.getParams() )); xsw.writeEndElement();// XML_COSTFUNCTION } xsw.writeEndElement(); //XML_INSTRUCTION } xsw.writeEndElement();//XML_PROFILE xsw.writeEndDocument(); xsw.close(); fos.close(); } /** * Main for invoking the actual performance test in order to produce profile.xml * * @param args */ public static void main(String[] args) { //execute the local / remote performance test try { PerfTestTool.runTest(); } catch (Exception e) { e.printStackTrace(); } } }
20974: ParFor construct - Fix removed dependency to test package
SystemML/DML/src/com/ibm/bi/dml/runtime/controlprogram/parfor/opt/PerfTestTool.java
20974: ParFor construct - Fix removed dependency to test package
<ide><path>ystemML/DML/src/com/ibm/bi/dml/runtime/controlprogram/parfor/opt/PerfTestTool.java <ide> import java.util.Date; <ide> import java.util.HashMap; <ide> import java.util.LinkedList; <add>import java.util.Random; <ide> import java.util.StringTokenizer; <ide> import java.util.Vector; <ide> import java.util.Map.Entry; <ide> import com.ibm.bi.dml.runtime.matrix.io.MatrixBlock; <ide> import com.ibm.bi.dml.runtime.matrix.io.OutputInfo; <ide> import com.ibm.bi.dml.runtime.util.MapReduceTool; <del>//import com.ibm.bi.dml.test.integration.AutomatedTestBase; <del>import com.ibm.bi.dml.test.utils.TestUtils; <ide> import com.ibm.bi.dml.utils.CacheException; <ide> import com.ibm.bi.dml.utils.DMLException; <ide> import com.ibm.bi.dml.utils.DMLRuntimeException; <ide> int dim = (int)Math.sqrt( datasize ); <ide> <ide> //create random test data <del> double[][] d = TestUtils.generateTestMatrix(dim, dim, 1, 100, sparsity, 7); <add> double[][] d = generateTestMatrix(dim, dim, 1, 100, sparsity, 7); <ide> <ide> //create matrix block <ide> MatrixBlock mb = null; <ide> System.out.println(d1+" "+d2); <ide> <ide> //create random test data <del> double[][] d = TestUtils.generateTestMatrix(d1, d2, 1, 100, sparsity, 7); <add> double[][] d = generateTestMatrix(d1, d2, 1, 100, sparsity, 7); <ide> <ide> //create matrix block <ide> MatrixBlock mb = null; <ide> <ide> return mo; <ide> } <add> <add> <add> /** <add> * NOTE: This is a copy of TestUtils.generateTestMatrix, it was replicated in order to prevent <add> * dependency of SystemML.jar to our test package. <add> */ <add> public static double[][] generateTestMatrix(int rows, int cols, double min, double max, double sparsity, long seed) { <add> double[][] matrix = new double[rows][cols]; <add> Random random; <add> if (seed == -1) <add> random = new Random(System.nanoTime()); <add> else <add> random = new Random(seed); <add> <add> for (int i = 0; i < rows; i++) { <add> for (int j = 0; j < cols; j++) { <add> if (random.nextDouble() > sparsity) <add> continue; <add> matrix[i][j] = (random.nextDouble() * (max - min) + min); <add> } <add> } <add> <add> return matrix; <add> } <add> <ide> <ide> /** <ide> *
JavaScript
mit
ad83ede31d52b923ad80536471eef6558deef34d
0
dschmidt/ember-component-css,dschmidt/ember-component-css
/* jshint node: true */ 'use strict'; var Writer = require('broccoli-writer'); var walkSync = require('walk-sync'); var path = require('path'); var css = require('css'); var fs = require('fs'); var mkdirp = require('mkdirp'); var HAS_SELF_SELECTOR = /&|:--component/; var guid = function fn(n) { return n ? (n ^ Math.random() * 16 >> n/4).toString(16) : ('10000000'.replace(/[018]/g, fn)); }; // Define different processors based on file extension var processors = { css: function(fileContents, podGuid) { var parsedCss = css.parse(fileContents); var transformedParsedCSS = transformCSS(podGuid, parsedCss); return css.stringify(transformedParsedCSS); }, styl: function(fileContents, podGuid) { fileContents = fileContents.replace(/:--component/g, '&'); fileContents = '.' + podGuid + '\n' + fileContents; // Indent styles for scoping return fileContents.replace(/\n/g, '\n '); }, scss: wrapStyles, less: wrapStyles }; function wrapStyles(fileContents, podGuid) { // Replace instances of :--component with '&' fileContents = fileContents.replace(/:--component/g, '&'); // Wrap the styles inside the generated class return '.' + podGuid + '{' + fileContents + '}'; } function transformCSS(podGuid, parsedCss) { var rules = parsedCss.stylesheet.rules; rules.forEach(function(rule) { rule.selectors = rule.selectors.map(function(selector) { var selfSelectorMatch = HAS_SELF_SELECTOR.exec(selector); if (selfSelectorMatch) { return selector.replace(selfSelectorMatch[0], '.' + podGuid); } else { return '.' + podGuid + ' ' + selector; } }); }); return parsedCss; } function BrocComponentCssPreprocessor(inputTree, options) { this.inputTree = inputTree; this.options = options; } BrocComponentCssPreprocessor.prototype = Object.create(Writer.prototype); BrocComponentCssPreprocessor.prototype.constructor = BrocComponentCssPreprocessor; BrocComponentCssPreprocessor.prototype.write = function (readTree, destDir) { var pod = this.options.pod; return readTree(this.inputTree).then(function(srcDir) { var paths = walkSync(srcDir); var buffer = []; var filepath; for (var i = 0, l = paths.length; i < l; i++) { filepath = paths[i]; // Check that it's not a directory if (filepath[filepath.length-1] !== '/') { if (!pod.extension || pod.extension === 'css') { pod.extension = filepath.substr(filepath.lastIndexOf('.') + 1); } var podPath = filepath.split('/').slice(0, -1); // Handle pod-formatted components that are in the 'components' directory if (podPath[0] === 'components') { podPath.shift(); } var podGuid = podPath.join('--') + '-' + guid(); var fileContents = fs.readFileSync(path.join(srcDir, filepath)).toString(); if(pod.extension === 'scss') { var outFilepath = filepath; // TODO: introduce a useComponentNameAsFileName option which defaults to false if (true) { outFilepath = path.join('pod-styles', podPath.join('/') + '.' + pod.extension); } mkdirp.sync(path.join(destDir,path.dirname(outFilepath))); fs.writeFileSync(path.join(destDir, outFilepath), processors[pod.extension](fileContents, podGuid)); buffer.push('@import "' + outFilepath + '"; \r\n'); } else { buffer.push(processors[pod.extension](fileContents, podGuid)); } pod.lookup[podPath.join('/')] = podGuid; } } pod.styles = buffer.join(''); fs.writeFileSync(path.join(destDir, 'pod-styles.' + pod.extension), pod.styles); }); }; module.exports = BrocComponentCssPreprocessor;
lib/broc-component-css-preprocessor.js
/* jshint node: true */ 'use strict'; var Writer = require('broccoli-writer'); var walkSync = require('walk-sync'); var path = require('path'); var css = require('css'); var fs = require('fs'); var mkdirp = require('mkdirp'); var HAS_SELF_SELECTOR = /&|:--component/; var guid = function fn(n) { return n ? (n ^ Math.random() * 16 >> n/4).toString(16) : ('10000000'.replace(/[018]/g, fn)); }; // Define different processors based on file extension var processors = { css: function(fileContents, podGuid) { var parsedCss = css.parse(fileContents); var transformedParsedCSS = transformCSS(podGuid, parsedCss); return css.stringify(transformedParsedCSS); }, styl: function(fileContents, podGuid) { fileContents = fileContents.replace(/:--component/g, '&'); fileContents = '.' + podGuid + '\n' + fileContents; // Indent styles for scoping return fileContents.replace(/\n/g, '\n '); }, scss: wrapStyles, less: wrapStyles }; function wrapStyles(fileContents, podGuid) { // Replace instances of :--component with '&' fileContents = fileContents.replace(/:--component/g, '&'); // Wrap the styles inside the generated class return '.' + podGuid + '{' + fileContents + '}'; } function transformCSS(podGuid, parsedCss) { var rules = parsedCss.stylesheet.rules; rules.forEach(function(rule) { rule.selectors = rule.selectors.map(function(selector) { var selfSelectorMatch = HAS_SELF_SELECTOR.exec(selector); if (selfSelectorMatch) { return selector.replace(selfSelectorMatch[0], '.' + podGuid); } else { return '.' + podGuid + ' ' + selector; } }); }); return parsedCss; } function BrocComponentCssPreprocessor(inputTree, options) { this.inputTree = inputTree; this.options = options; } BrocComponentCssPreprocessor.prototype = Object.create(Writer.prototype); BrocComponentCssPreprocessor.prototype.constructor = BrocComponentCssPreprocessor; BrocComponentCssPreprocessor.prototype.write = function (readTree, destDir) { var pod = this.options.pod; return readTree(this.inputTree).then(function(srcDir) { var paths = walkSync(srcDir); var buffer = []; var filepath; for (var i = 0, l = paths.length; i < l; i++) { filepath = paths[i]; // Check that it's not a directory if (filepath[filepath.length-1] !== '/') { if (!pod.extension || pod.extension === 'css') { pod.extension = filepath.substr(filepath.lastIndexOf('.') + 1); } var podPath = filepath.split('/').slice(0, -1); // Handle pod-formatted components that are in the 'components' directory if (podPath[0] === 'components') { podPath.shift(); } var podGuid = podPath.join('--') + '-' + guid(); var fileContents = fs.readFileSync(path.join(srcDir, filepath)).toString(); if(extension === 'scss') { var outFilepath = filepath; // TODO: introduce a useComponentNameAsFileName option which defaults to false if (true) { outFilepath = path.join('pod-styles', podPath.join('/') + '.' + extension); } mkdirp.sync(path.join(destDir,path.dirname(outFilepath))); fs.writeFileSync(path.join(destDir, outFilepath), processors[extension](fileContents, podGuid)); buffer.push('@import "' + outFilepath + '"; \r\n'); } else { buffer.push(processors[pod.extension](fileContents, podGuid)); } pod.lookup[podPath.join('/')] = podGuid; } } pod.styles = buffer.join(''); fs.writeFileSync(path.join(destDir, 'pod-styles.' + pod.extension), pod.styles); }); }; module.exports = BrocComponentCssPreprocessor;
Fix merge
lib/broc-component-css-preprocessor.js
Fix merge
<ide><path>ib/broc-component-css-preprocessor.js <ide> var podGuid = podPath.join('--') + '-' + guid(); <ide> var fileContents = fs.readFileSync(path.join(srcDir, filepath)).toString(); <ide> <del> if(extension === 'scss') { <add> if(pod.extension === 'scss') { <ide> var outFilepath = filepath; <ide> // TODO: introduce a useComponentNameAsFileName option which defaults to false <ide> if (true) { <del> outFilepath = path.join('pod-styles', podPath.join('/') + '.' + extension); <add> outFilepath = path.join('pod-styles', podPath.join('/') + '.' + pod.extension); <ide> } <ide> <ide> mkdirp.sync(path.join(destDir,path.dirname(outFilepath))); <del> fs.writeFileSync(path.join(destDir, outFilepath), processors[extension](fileContents, podGuid)); <add> fs.writeFileSync(path.join(destDir, outFilepath), processors[pod.extension](fileContents, podGuid)); <ide> <ide> buffer.push('@import "' + outFilepath + '"; \r\n'); <ide> } else {
Java
apache-2.0
7dae85e3e75cc13a52353a6e638792cca54f9e91
0
LearnLib/learnlib,LearnLib/learnlib,LearnLib/learnlib
/* Copyright (C) 2013-2021 TU Dortmund * This file is part of LearnLib, http://www.learnlib.de/. * * 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 de.learnlib.datastructure.observationtable; import java.awt.Desktop; import java.awt.HeadlessException; import java.io.File; import java.io.IOException; import java.io.Writer; import java.util.Objects; import java.util.function.Function; import de.learnlib.datastructure.observationtable.reader.ObservationTableReader; import de.learnlib.datastructure.observationtable.writer.ObservationTableHTMLWriter; import de.learnlib.datastructure.observationtable.writer.ObservationTableWriter; import net.automatalib.commons.util.IOUtil; import net.automatalib.words.Alphabet; import net.automatalib.words.Word; public final class OTUtils { private static final String HTML_FILE_HEADER = "<!doctype html>" + System.lineSeparator() + "<html><head>" + System.lineSeparator() + "<meta charset=\"UTF-8\">" + System.lineSeparator() + "<style type=\"text/css\">" + System.lineSeparator() + "table.learnlib-observationtable { border-width: 1px; border: solid; }" + System.lineSeparator() + "table.learnlib-observationtable th.suffixes-header { text-align: center; }" + System.lineSeparator() + "table.learnlib-observationtable th.prefix { vertical-align: top; }" + System.lineSeparator() + "table.learnlib-observationtable .suffix-column { text-align: left; }" + System.lineSeparator() + "table.learnlib-observationtable tr { border-width: 1px; border: solid; }" + System.lineSeparator() + "table.learnlib-observationtable tr.long-prefix { background-color: #dfdfdf; }" + System.lineSeparator() + "</style></head>" + System.lineSeparator() + "<body>" + System.lineSeparator(); private static final String HTML_FILE_FOOTER = "</body></html>" + System.lineSeparator(); private OTUtils() { // prevent instantiation } public static <I, D> String toString(ObservationTable<I, D> table, ObservationTableWriter<I, D> writer) { StringBuilder sb = new StringBuilder(); writer.write(table, sb); return sb.toString(); } public static <I, D> ObservationTable<I, D> fromString(String source, Alphabet<I> alphabet, ObservationTableReader<I, D> reader) { return reader.read(source, alphabet); } public static <I, D> void writeHTMLToFile(ObservationTable<I, D> table, File file) throws IOException { writeHTMLToFile(table, file, Objects::toString, Objects::toString); } public static <I, D> void writeHTMLToFile(ObservationTable<I, D> table, File file, Function<? super Word<? extends I>, ? extends String> wordToString, Function<? super D, ? extends String> outputToString) throws IOException { try (Writer w = IOUtil.asBufferedUTF8Writer(file)) { w.write(HTML_FILE_HEADER); ObservationTableHTMLWriter<I, D> otWriter = new ObservationTableHTMLWriter<>(wordToString, outputToString); otWriter.write(table, w); w.write(HTML_FILE_FOOTER); } } /** * Convenience method for {@link #displayHTMLInBrowser(ObservationTable, Function, Function)} that uses {@link * Object#toString()} to render words and outputs of the observation table. */ public static <I, D> void displayHTMLInBrowser(ObservationTable<I, D> table) throws IOException { displayHTMLInBrowser(table, Objects::toString, Objects::toString); } /** * Displays the observation table as a HTML document in the default browser. * <p> * This method internally relies on {@link Desktop#browse(java.net.URI)}, hence it will not work if {@link Desktop} * is not supported, or if the application is running in headless mode. * <p> * <b>IMPORTANT NOTE:</b> Calling this method may delay the termination of the JVM by up to 5 seconds. This is due * to the fact that the temporary file created in this method is marked for deletion upon JVM termination. If the * JVM terminates too early, it might be deleted before it was loaded by the browser. * * @param table * the observation table to display * @param wordToString * the transformation from words to strings. This transformation is <b>not</b> required nor expected to * escape HTML entities * @param outputToString * the transformation from outputs to strings. This transformation is <b>not</b> required nor expected to * escape HTML entities * * @throws IOException * if creating or writing to the temporary file fails * @throws HeadlessException * if the JVM is running in headless mode * @throws UnsupportedOperationException * if {@link Desktop#getDesktop()} is not supported by the system */ public static <I, D> void displayHTMLInBrowser(ObservationTable<I, D> table, Function<? super Word<? extends I>, ? extends String> wordToString, Function<? super D, ? extends String> outputToString) throws IOException { File tempFile = File.createTempFile("learnlib-ot", ".html"); // Doing this might cause problems if the startup delay of the browser // causes it to start only after the JVM has exited. // Temp directory should be wiped regularly anyway. // tempFile.deleteOnExit(); writeHTMLToFile(table, tempFile, wordToString, outputToString); Desktop desktop = Desktop.getDesktop(); // We use browse() instead of open() because, e.g., web developers may have // an HTML editor set up as their default application to open HTML files desktop.browse(tempFile.toURI()); } }
datastructures/observation-table/src/main/java/de/learnlib/datastructure/observationtable/OTUtils.java
/* Copyright (C) 2013-2021 TU Dortmund * This file is part of LearnLib, http://www.learnlib.de/. * * 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 de.learnlib.datastructure.observationtable; import java.awt.Desktop; import java.awt.HeadlessException; import java.io.File; import java.io.IOException; import java.io.Writer; import java.util.Objects; import java.util.function.Function; import de.learnlib.datastructure.observationtable.reader.ObservationTableReader; import de.learnlib.datastructure.observationtable.writer.ObservationTableHTMLWriter; import de.learnlib.datastructure.observationtable.writer.ObservationTableWriter; import net.automatalib.commons.util.IOUtil; import net.automatalib.words.Alphabet; import net.automatalib.words.Word; public final class OTUtils { private static final String HTML_FILE_HEADER = "<!doctype html>" + System.lineSeparator() + "<html><head>" + System.lineSeparator() + "<meta charset=\"UTF-8\">" + System.lineSeparator() + "<style type=\"text/css\">" + System.lineSeparator() + "table.learnlib-observationtable { border-width: 1px; border: solid; }" + System.lineSeparator() + "table.learnlib-observationtable th.suffixes-header { text-align: center; }" + System.lineSeparator() + "table.learnlib-observationtable th.prefix { vertical-align: top; }" + System.lineSeparator() + "table.learnlib-observationtable .suffix-column { text-align: left; }" + System.lineSeparator() + "table.learnlib-observationtable tr { border-width: 1px; border: solid; }" + System.lineSeparator() + "table.learnlib-observationtable tr.long-prefix { background-color: #dfdfdf; }" + System.lineSeparator() + "</style></head>" + System.lineSeparator() + "<body>" + System.lineSeparator(); private static final String HTML_FILE_FOOTER = "</body></html>" + System.lineSeparator(); private OTUtils() { throw new AssertionError("Constructor should never be invoked"); } public static <I, D> String toString(ObservationTable<I, D> table, ObservationTableWriter<I, D> writer) { StringBuilder sb = new StringBuilder(); writer.write(table, sb); return sb.toString(); } public static <I, D> ObservationTable<I, D> fromString(String source, Alphabet<I> alphabet, ObservationTableReader<I, D> reader) { return reader.read(source, alphabet); } public static <I, D> void writeHTMLToFile(ObservationTable<I, D> table, File file) throws IOException { writeHTMLToFile(table, file, Objects::toString, Objects::toString); } public static <I, D> void writeHTMLToFile(ObservationTable<I, D> table, File file, Function<? super Word<? extends I>, ? extends String> wordToString, Function<? super D, ? extends String> outputToString) throws IOException { try (Writer w = IOUtil.asBufferedUTF8Writer(file)) { w.write(HTML_FILE_HEADER); ObservationTableHTMLWriter<I, D> otWriter = new ObservationTableHTMLWriter<>(wordToString, outputToString); otWriter.write(table, w); w.write(HTML_FILE_FOOTER); } } /** * Convenience method for {@link #displayHTMLInBrowser(ObservationTable, Function, Function)} that uses {@link * Object#toString()} to render words and outputs of the observation table. */ public static <I, D> void displayHTMLInBrowser(ObservationTable<I, D> table) throws IOException { displayHTMLInBrowser(table, Objects::toString, Objects::toString); } /** * Displays the observation table as a HTML document in the default browser. * <p> * This method internally relies on {@link Desktop#browse(java.net.URI)}, hence it will not work if {@link Desktop} * is not supported, or if the application is running in headless mode. * <p> * <b>IMPORTANT NOTE:</b> Calling this method may delay the termination of the JVM by up to 5 seconds. This is due * to the fact that the temporary file created in this method is marked for deletion upon JVM termination. If the * JVM terminates too early, it might be deleted before it was loaded by the browser. * * @param table * the observation table to display * @param wordToString * the transformation from words to strings. This transformation is <b>not</b> required nor expected to * escape HTML entities * @param outputToString * the transformation from outputs to strings. This transformation is <b>not</b> required nor expected to * escape HTML entities * * @throws IOException * if creating or writing to the temporary file fails * @throws HeadlessException * if the JVM is running in headless mode * @throws UnsupportedOperationException * if {@link Desktop#getDesktop()} is not supported by the system */ public static <I, D> void displayHTMLInBrowser(ObservationTable<I, D> table, Function<? super Word<? extends I>, ? extends String> wordToString, Function<? super D, ? extends String> outputToString) throws IOException { File tempFile = File.createTempFile("learnlib-ot", ".html"); // Doing this might cause problems if the startup delay of the browser // causes it to start only after the JVM has exited. // Temp directory should be wiped regularly anyway. // tempFile.deleteOnExit(); writeHTMLToFile(table, tempFile, wordToString, outputToString); Desktop desktop = Desktop.getDesktop(); // We use browse() instead of open() because, e.g., web developers may have // an HTML editor set up as their default application to open HTML files desktop.browse(tempFile.toURI()); } }
remove dead code
datastructures/observation-table/src/main/java/de/learnlib/datastructure/observationtable/OTUtils.java
remove dead code
<ide><path>atastructures/observation-table/src/main/java/de/learnlib/datastructure/observationtable/OTUtils.java <ide> private static final String HTML_FILE_FOOTER = "</body></html>" + System.lineSeparator(); <ide> <ide> private OTUtils() { <del> throw new AssertionError("Constructor should never be invoked"); <add> // prevent instantiation <ide> } <ide> <ide> public static <I, D> String toString(ObservationTable<I, D> table, ObservationTableWriter<I, D> writer) {
Java
apache-2.0
f4487daf24c9c33d0ef1a0bffed91e36e78c466b
0
jitsi/otr4j
package net.java.otr4j.session; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.util.ArrayList; import java.util.List; import net.java.otr4j.OtrEngineHost; import net.java.otr4j.OtrException; import net.java.otr4j.crypto.OtrCryptoEngineImpl; import net.java.otr4j.crypto.OtrCryptoException; import net.java.otr4j.crypto.SM; import net.java.otr4j.crypto.SM.SMException; import net.java.otr4j.crypto.SM.SMState; import net.java.otr4j.io.OtrOutputStream; /** * Socialist Millionaire Protocol handler. */ public class OtrSm { private SMState smstate; private final OtrEngineHost engineHost; private final Session session; /** * Construct an OTR Socialist Millionaire handler object. * * @param session The session reference. * @param engineHost The host where we can present messages or ask for the shared secret. */ public OtrSm(Session session, OtrEngineHost engineHost) { this.session = session; this.engineHost = engineHost; reset(); } public void reset() { smstate = new SMState(); } /* Compute secret session ID as hash of agreed secret */ private static byte[] computeSessionId(BigInteger s) throws SMException { byte[] sdata; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); OtrOutputStream oos = new OtrOutputStream(out); oos.write(0x00); oos.writeBigInt(s); sdata = out.toByteArray(); oos.close(); } catch (IOException e1) { throw new SMException(e1); } /* Calculate the session id */ MessageDigest sha256; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new SMException("cannot find SHA-256"); } byte[] res = sha256.digest(sdata); byte[] secureSessionId = new byte[8]; System.arraycopy(res, 0, secureSessionId, 0, 8); return secureSessionId; } /** * Respond to or initiate an SMP negotiation * * @param question * The question to present to the peer, if initiating. * May be <code>null</code> for no question. * If not initiating, then it should be received question * in order to clarify whether this is shared secret verification. * @param secret The secret. * @param initiating Whether we are initiating or responding to an initial request. * * @return TLVs to send to the peer * @throws OtrException MVN_PASS_JAVADOC_INSPECTION */ public List<TLV> initRespondSmp(String question, String secret, boolean initiating) throws OtrException { if (!initiating && !smstate.asked) throw new OtrException(new IllegalStateException( "There is no question to be answered.")); /* * Construct the combined secret as a SHA256 hash of: * Version byte (0x01), Initiator fingerprint (20 bytes), * responder fingerprint (20 bytes), secure session id, input secret */ byte[] ourFp = engineHost.getLocalFingerprintRaw(session .getSessionID()); byte[] theirFp; PublicKey remotePublicKey = session.getRemotePublicKey(); try { theirFp = new OtrCryptoEngineImpl() .getFingerprintRaw(remotePublicKey); } catch (OtrCryptoException e) { throw new OtrException(e); } byte[] sessionId; try { sessionId = computeSessionId(session.getS()); } catch (SMException ex) { throw new OtrException(ex); } int combinedBufLen = 41 + sessionId.length + secret.length(); byte[] combinedBuf = new byte[combinedBufLen]; combinedBuf[0] = 1; if (initiating){ System.arraycopy(ourFp, 0, combinedBuf, 1, 20); System.arraycopy(theirFp, 0, combinedBuf, 21, 20); } else { System.arraycopy(theirFp, 0, combinedBuf, 1, 20); System.arraycopy(ourFp, 0, combinedBuf, 21, 20); } System.arraycopy(sessionId, 0, combinedBuf, 41, sessionId.length); System.arraycopy(secret.getBytes(), 0, combinedBuf, 41 + sessionId.length, secret.length()); MessageDigest sha256; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { throw new OtrException(ex); } byte[] combinedSecret = sha256.digest(combinedBuf); byte[] smpmsg; try { if (initiating) { smpmsg = SM.step1(smstate, combinedSecret); } else { smpmsg = SM.step2b(smstate, combinedSecret); } } catch (SMException ex) { throw new OtrException(ex); } // If we've got a question, attach it to the smpmsg if (question != null && initiating){ final byte[] bytes; try { bytes = question.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // Never thrown - all JRE's support UTF-8 throw new RuntimeException("Platform does not support encoding", e); } byte[] qsmpmsg = new byte[bytes.length + 1 + smpmsg.length]; System.arraycopy(bytes, 0, qsmpmsg, 0, bytes.length); System.arraycopy(smpmsg, 0, qsmpmsg, bytes.length + 1, smpmsg.length); smpmsg = qsmpmsg; } TLV sendtlv = new TLV(initiating ? (question != null ? TLV.SMP1Q : TLV.SMP1) : TLV.SMP2, smpmsg); smstate.nextExpected = initiating ? SM.EXPECT2 : SM.EXPECT3; smstate.approved = initiating || question == null; return makeTlvList(sendtlv); } /** * Create an abort TLV and reset our state. * * @return TLVs to send to the peer * @throws OtrException MVN_PASS_JAVADOC_INSPECTION */ public List<TLV> abortSmp() throws OtrException { TLV sendtlv = new TLV(TLV.SMP_ABORT, new byte[0]); smstate.nextExpected = SM.EXPECT1; return makeTlvList(sendtlv); } public boolean isSmpInProgress() { return smstate.nextExpected > SM.EXPECT1; } public boolean doProcessTlv(TLV tlv) throws OtrException { /* If TLVs contain SMP data, process it */ int nextMsg = smstate.nextExpected; int tlvType = tlv.getType(); PublicKey pubKey = session.getRemotePublicKey(); String fingerprint = null; try { fingerprint = new OtrCryptoEngineImpl().getFingerprint(pubKey); } catch (OtrCryptoException e) { e.printStackTrace(); } if (tlvType == TLV.SMP1Q && nextMsg == SM.EXPECT1) { /* We can only do the verification half now. * We must wait for the secret to be entered * to continue. */ byte[] question = tlv.getValue(); int qlen = 0; for(; qlen != question.length && question[qlen] != 0; qlen++) { } if (qlen == question.length) { qlen = 0; } else { qlen++; } byte[] input = new byte[question.length-qlen]; System.arraycopy(question, qlen, input, 0, question.length-qlen); try { SM.step2a(smstate, input, 1); } catch (SMException e) { throw new OtrException(e); } if (qlen != 0) qlen--; byte[] plainq = new byte[qlen]; System.arraycopy(question, 0, plainq, 0, qlen); if (smstate.smProgState != SM.PROG_CHEATED){ smstate.asked = true; String questionUTF = null; try { questionUTF = new String(plainq, "UTF-8"); } catch (UnsupportedEncodingException e) { // Never thrown - all JRE's support UTF-8 throw new RuntimeException("Platform does not support encoding", e); } engineHost.askForSecret(session.getSessionID(), session.getReceiverInstanceTag(), questionUTF); } else { engineHost.smpError(session.getSessionID(), tlvType, true); reset(); } } else if (tlvType == TLV.SMP1Q) { engineHost.smpError(session.getSessionID(), tlvType, false); } else if (tlvType == TLV.SMP1 && nextMsg == SM.EXPECT1) { /* We can only do the verification half now. * We must wait for the secret to be entered * to continue. */ try { SM.step2a(smstate, tlv.getValue(), 0); } catch (SMException e) { throw new OtrException(e); } if (smstate.smProgState != SM.PROG_CHEATED) { smstate.asked = true; engineHost.askForSecret(session.getSessionID(), session.getReceiverInstanceTag(), null); } else { engineHost.smpError(session.getSessionID(), tlvType, true); reset(); } } else if (tlvType == TLV.SMP1) { engineHost.smpError(session.getSessionID(), tlvType, false); } else if (tlvType == TLV.SMP2 && nextMsg == SM.EXPECT2) { byte[] nextmsg; try { nextmsg = SM.step3(smstate, tlv.getValue()); } catch (SMException e) { throw new OtrException(e); } if (smstate.smProgState != SM.PROG_CHEATED){ /* Send msg with next smp msg content */ TLV sendtlv = new TLV(TLV.SMP3, nextmsg); smstate.nextExpected = SM.EXPECT4; String[] msg = session.transformSending("", makeTlvList(sendtlv)); for (String part : msg) { engineHost.injectMessage(session.getSessionID(), part); } } else { engineHost.smpError(session.getSessionID(), tlvType, true); reset(); } } else if (tlvType == TLV.SMP2){ engineHost.smpError(session.getSessionID(), tlvType, false); } else if (tlvType == TLV.SMP3 && nextMsg == SM.EXPECT3) { byte[] nextmsg; try { nextmsg = SM.step4(smstate, tlv.getValue()); } catch (SMException e) { throw new OtrException(e); } /* Set trust level based on result */ if (smstate.smProgState == SM.PROG_SUCCEEDED){ engineHost.verify(session.getSessionID(), fingerprint, smstate.approved); } else { engineHost.unverify(session.getSessionID(), fingerprint); } if (smstate.smProgState != SM.PROG_CHEATED){ /* Send msg with next smp msg content */ TLV sendtlv = new TLV(TLV.SMP4, nextmsg); String[] msg = session.transformSending("", makeTlvList(sendtlv)); for (String part : msg) { engineHost.injectMessage(session.getSessionID(), part); } } else { engineHost.smpError(session.getSessionID(), tlvType, true); } reset(); } else if (tlvType == TLV.SMP3) { engineHost.smpError(session.getSessionID(), tlvType, false); } else if (tlvType == TLV.SMP4 && nextMsg == SM.EXPECT4) { try { SM.step5(smstate, tlv.getValue()); } catch (SMException e) { throw new OtrException(e); } if (smstate.smProgState == SM.PROG_SUCCEEDED) { engineHost.verify(session.getSessionID(), fingerprint, smstate.approved); } else { engineHost.unverify(session.getSessionID(), fingerprint); } if (smstate.smProgState == SM.PROG_CHEATED) { engineHost.smpError(session.getSessionID(), tlvType, true); } reset(); } else if (tlvType == TLV.SMP4) { engineHost.smpError(session.getSessionID(), tlvType, false); } else if (tlvType == TLV.SMP_ABORT){ engineHost.smpAborted(session.getSessionID()); reset(); } else return false; return true; } private List<TLV> makeTlvList(TLV sendtlv) { List<TLV> tlvs = new ArrayList<TLV>(1); tlvs.add(sendtlv); return tlvs; } }
src/main/java/net/java/otr4j/session/OtrSm.java
package net.java.otr4j.session; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.util.ArrayList; import java.util.List; import net.java.otr4j.OtrEngineHost; import net.java.otr4j.OtrException; import net.java.otr4j.crypto.OtrCryptoEngineImpl; import net.java.otr4j.crypto.OtrCryptoException; import net.java.otr4j.crypto.SM; import net.java.otr4j.crypto.SM.SMException; import net.java.otr4j.crypto.SM.SMState; import net.java.otr4j.io.OtrOutputStream; /** * Socialist Millionaire Protocol handler. */ public class OtrSm { private SMState smstate; private final OtrEngineHost engineHost; private final Session session; /** * Construct an OTR Socialist Millionaire handler object. * * @param session The session reference. * @param engineHost The host where we can present messages or ask for the shared secret. */ public OtrSm(Session session, OtrEngineHost engineHost) { this.session = session; this.engineHost = engineHost; reset(); } public void reset() { smstate = new SMState(); } /* Compute secret session ID as hash of agreed secret */ private static byte[] computeSessionId(BigInteger s) throws SMException { byte[] sdata; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); OtrOutputStream oos = new OtrOutputStream(out); oos.write(0x00); oos.writeBigInt(s); sdata = out.toByteArray(); oos.close(); } catch (IOException e1) { throw new SMException(e1); } /* Calculate the session id */ MessageDigest sha256; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new SMException("cannot find SHA-256"); } byte[] res = sha256.digest(sdata); byte[] secureSessionId = new byte[8]; System.arraycopy(res, 0, secureSessionId, 0, 8); return secureSessionId; } /** * Respond to or initiate an SMP negotiation * * @param question * The question to present to the peer, if initiating. * May be <code>null</code> for no question. * If not initiating, then it should be received question * in order to clarify whether this is shared secret verification. * @param secret The secret. * @param initiating Whether we are initiating or responding to an initial request. * * @return TLVs to send to the peer * @throws OtrException MVN_PASS_JAVADOC_INSPECTION */ public List<TLV> initRespondSmp(String question, String secret, boolean initiating) throws OtrException { if (!initiating && !smstate.asked) throw new OtrException(new IllegalStateException( "There is no question to be answered.")); /* * Construct the combined secret as a SHA256 hash of: * Version byte (0x01), Initiator fingerprint (20 bytes), * responder fingerprint (20 bytes), secure session id, input secret */ byte[] ourFp = engineHost.getLocalFingerprintRaw(session .getSessionID()); byte[] theirFp; PublicKey remotePublicKey = session.getRemotePublicKey(); try { theirFp = new OtrCryptoEngineImpl() .getFingerprintRaw(remotePublicKey); } catch (OtrCryptoException e) { throw new OtrException(e); } byte[] sessionId; try { sessionId = computeSessionId(session.getS()); } catch (SMException ex) { throw new OtrException(ex); } int combinedBufLen = 41 + sessionId.length + secret.length(); byte[] combinedBuf = new byte[combinedBufLen]; combinedBuf[0] = 1; if (initiating){ System.arraycopy(ourFp, 0, combinedBuf, 1, 20); System.arraycopy(theirFp, 0, combinedBuf, 21, 20); } else { System.arraycopy(theirFp, 0, combinedBuf, 1, 20); System.arraycopy(ourFp, 0, combinedBuf, 21, 20); } System.arraycopy(sessionId, 0, combinedBuf, 41, sessionId.length); System.arraycopy(secret.getBytes(), 0, combinedBuf, 41 + sessionId.length, secret.length()); MessageDigest sha256; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { throw new OtrException(ex); } byte[] combinedSecret = sha256.digest(combinedBuf); byte[] smpmsg; try { if (initiating) { smpmsg = SM.step1(smstate, combinedSecret); } else { smpmsg = SM.step2b(smstate, combinedSecret); } } catch (SMException ex) { throw new OtrException(ex); } // If we've got a question, attach it to the smpmsg if (question != null && initiating){ byte[] bytes; try { bytes = question.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // Never thrown - all JRE's support UTF-8 throw new RuntimeException("Platform does not support encoding", e); } byte[] qsmpmsg = new byte[bytes.length + 1 + smpmsg.length]; System.arraycopy(bytes, 0, qsmpmsg, 0, bytes.length); System.arraycopy(smpmsg, 0, qsmpmsg, bytes.length + 1, smpmsg.length); smpmsg = qsmpmsg; } TLV sendtlv = new TLV(initiating ? (question != null ? TLV.SMP1Q : TLV.SMP1) : TLV.SMP2, smpmsg); smstate.nextExpected = initiating ? SM.EXPECT2 : SM.EXPECT3; smstate.approved = initiating || question == null; return makeTlvList(sendtlv); } /** * Create an abort TLV and reset our state. * * @return TLVs to send to the peer * @throws OtrException MVN_PASS_JAVADOC_INSPECTION */ public List<TLV> abortSmp() throws OtrException { TLV sendtlv = new TLV(TLV.SMP_ABORT, new byte[0]); smstate.nextExpected = SM.EXPECT1; return makeTlvList(sendtlv); } public boolean isSmpInProgress() { return smstate.nextExpected > SM.EXPECT1; } public boolean doProcessTlv(TLV tlv) throws OtrException { /* If TLVs contain SMP data, process it */ int nextMsg = smstate.nextExpected; int tlvType = tlv.getType(); PublicKey pubKey = session.getRemotePublicKey(); String fingerprint = null; try { fingerprint = new OtrCryptoEngineImpl().getFingerprint(pubKey); } catch (OtrCryptoException e) { e.printStackTrace(); } if (tlvType == TLV.SMP1Q && nextMsg == SM.EXPECT1) { /* We can only do the verification half now. * We must wait for the secret to be entered * to continue. */ byte[] question = tlv.getValue(); int qlen = 0; for(; qlen != question.length && question[qlen] != 0; qlen++) { } if (qlen == question.length) { qlen = 0; } else { qlen++; } byte[] input = new byte[question.length-qlen]; System.arraycopy(question, qlen, input, 0, question.length-qlen); try { SM.step2a(smstate, input, 1); } catch (SMException e) { throw new OtrException(e); } if (qlen != 0) qlen--; byte[] plainq = new byte[qlen]; System.arraycopy(question, 0, plainq, 0, qlen); if (smstate.smProgState != SM.PROG_CHEATED){ smstate.asked = true; String questionUTF = null; try { questionUTF = new String(plainq, "UTF-8"); } catch (UnsupportedEncodingException e) { // Never thrown - all JRE's support UTF-8 throw new RuntimeException("Platform does not support encoding", e); } engineHost.askForSecret(session.getSessionID(), session.getReceiverInstanceTag(), questionUTF); } else { engineHost.smpError(session.getSessionID(), tlvType, true); reset(); } } else if (tlvType == TLV.SMP1Q) { engineHost.smpError(session.getSessionID(), tlvType, false); } else if (tlvType == TLV.SMP1 && nextMsg == SM.EXPECT1) { /* We can only do the verification half now. * We must wait for the secret to be entered * to continue. */ try { SM.step2a(smstate, tlv.getValue(), 0); } catch (SMException e) { throw new OtrException(e); } if (smstate.smProgState != SM.PROG_CHEATED) { smstate.asked = true; engineHost.askForSecret(session.getSessionID(), session.getReceiverInstanceTag(), null); } else { engineHost.smpError(session.getSessionID(), tlvType, true); reset(); } } else if (tlvType == TLV.SMP1) { engineHost.smpError(session.getSessionID(), tlvType, false); } else if (tlvType == TLV.SMP2 && nextMsg == SM.EXPECT2) { byte[] nextmsg; try { nextmsg = SM.step3(smstate, tlv.getValue()); } catch (SMException e) { throw new OtrException(e); } if (smstate.smProgState != SM.PROG_CHEATED){ /* Send msg with next smp msg content */ TLV sendtlv = new TLV(TLV.SMP3, nextmsg); smstate.nextExpected = SM.EXPECT4; String[] msg = session.transformSending("", makeTlvList(sendtlv)); for (String part : msg) { engineHost.injectMessage(session.getSessionID(), part); } } else { engineHost.smpError(session.getSessionID(), tlvType, true); reset(); } } else if (tlvType == TLV.SMP2){ engineHost.smpError(session.getSessionID(), tlvType, false); } else if (tlvType == TLV.SMP3 && nextMsg == SM.EXPECT3) { byte[] nextmsg; try { nextmsg = SM.step4(smstate, tlv.getValue()); } catch (SMException e) { throw new OtrException(e); } /* Set trust level based on result */ if (smstate.smProgState == SM.PROG_SUCCEEDED){ engineHost.verify(session.getSessionID(), fingerprint, smstate.approved); } else { engineHost.unverify(session.getSessionID(), fingerprint); } if (smstate.smProgState != SM.PROG_CHEATED){ /* Send msg with next smp msg content */ TLV sendtlv = new TLV(TLV.SMP4, nextmsg); String[] msg = session.transformSending("", makeTlvList(sendtlv)); for (String part : msg) { engineHost.injectMessage(session.getSessionID(), part); } } else { engineHost.smpError(session.getSessionID(), tlvType, true); } reset(); } else if (tlvType == TLV.SMP3) { engineHost.smpError(session.getSessionID(), tlvType, false); } else if (tlvType == TLV.SMP4 && nextMsg == SM.EXPECT4) { try { SM.step5(smstate, tlv.getValue()); } catch (SMException e) { throw new OtrException(e); } if (smstate.smProgState == SM.PROG_SUCCEEDED) { engineHost.verify(session.getSessionID(), fingerprint, smstate.approved); } else { engineHost.unverify(session.getSessionID(), fingerprint); } if (smstate.smProgState == SM.PROG_CHEATED) { engineHost.smpError(session.getSessionID(), tlvType, true); } reset(); } else if (tlvType == TLV.SMP4) { engineHost.smpError(session.getSessionID(), tlvType, false); } else if (tlvType == TLV.SMP_ABORT){ engineHost.smpAborted(session.getSessionID()); reset(); } else return false; return true; } private List<TLV> makeTlvList(TLV sendtlv) { List<TLV> tlvs = new ArrayList<TLV>(1); tlvs.add(sendtlv); return tlvs; } }
mark one variable as final in OtrSm (thanks @cobratbq)
src/main/java/net/java/otr4j/session/OtrSm.java
mark one variable as final in OtrSm (thanks @cobratbq)
<ide><path>rc/main/java/net/java/otr4j/session/OtrSm.java <ide> <ide> // If we've got a question, attach it to the smpmsg <ide> if (question != null && initiating){ <del> byte[] bytes; <add> final byte[] bytes; <ide> try { <ide> bytes = question.getBytes("UTF-8"); <ide> } catch (UnsupportedEncodingException e) {
Java
apache-2.0
error: pathspec 'src/com/facebook/buck/apple/ApplePlatform.java' did not match any file(s) known to git
ae224674004dae8be2826963df7dad7d03fed69d
1
Learn-Android-app/buck,pwz3n0/buck,justinmuller/buck,luiseduardohdbackup/buck,k21/buck,janicduplessis/buck,darkforestzero/buck,vschs007/buck,Dominator008/buck,Addepar/buck,zhuxiaohao/buck,rhencke/buck,LegNeato/buck,grumpyjames/buck,brettwooldridge/buck,1yvT0s/buck,k21/buck,davido/buck,rmaz/buck,clonetwin26/buck,sdwilsh/buck,OkBuilds/buck,darkforestzero/buck,raviagarwal7/buck,dsyang/buck,ilya-klyuchnikov/buck,luiseduardohdbackup/buck,zhan-xiong/buck,tgummerer/buck,stuhood/buck,neonichu/buck,dushmis/buck,shs96c/buck,Dominator008/buck,vschs007/buck,JoelMarcey/buck,1yvT0s/buck,SeleniumHQ/buck,Dominator008/buck,rowillia/buck,zhuxiaohao/buck,daedric/buck,daedric/buck,Heart2009/buck,dsyang/buck,daedric/buck,Learn-Android-app/buck,kageiit/buck,robbertvanginkel/buck,sdwilsh/buck,shs96c/buck,MarkRunWu/buck,romanoid/buck,mikekap/buck,rowillia/buck,artiya4u/buck,artiya4u/buck,siddhartharay007/buck,mogers/buck,vschs007/buck,clonetwin26/buck,lukw00/buck,Dominator008/buck,davido/buck,illicitonion/buck,justinmuller/buck,shybovycha/buck,neonichu/buck,janicduplessis/buck,justinmuller/buck,neonichu/buck,shs96c/buck,vine/buck,JoelMarcey/buck,mogers/buck,grumpyjames/buck,LegNeato/buck,dushmis/buck,nguyentruongtho/buck,darkforestzero/buck,raviagarwal7/buck,marcinkwiatkowski/buck,nguyentruongtho/buck,LegNeato/buck,zpao/buck,JoelMarcey/buck,mogers/buck,Addepar/buck,dpursehouse/buck,Dominator008/buck,lukw00/buck,vine/buck,dsyang/buck,shybovycha/buck,ilya-klyuchnikov/buck,clonetwin26/buck,Distrotech/buck,lukw00/buck,mnuessler/buck,marcinkwiatkowski/buck,shybovycha/buck,daedric/buck,ilya-klyuchnikov/buck,zhuxiaohao/buck,shs96c/buck,luiseduardohdbackup/buck,facebook/buck,Dominator008/buck,vine/buck,SeleniumHQ/buck,facebook/buck,mikekap/buck,lukw00/buck,brettwooldridge/buck,raviagarwal7/buck,grumpyjames/buck,1yvT0s/buck,grumpyjames/buck,rhencke/buck,lukw00/buck,bocon13/buck,rhencke/buck,justinmuller/buck,romanoid/buck,illicitonion/buck,luiseduardohdbackup/buck,darkforestzero/buck,dsyang/buck,marcinkwiatkowski/buck,luiseduardohdbackup/buck,robbertvanginkel/buck,grumpyjames/buck,SeleniumHQ/buck,SeleniumHQ/buck,k21/buck,dushmis/buck,vine/buck,raviagarwal7/buck,liuyang-li/buck,vine/buck,shybovycha/buck,rmaz/buck,hgl888/buck,marcinkwiatkowski/buck,kageiit/buck,illicitonion/buck,raviagarwal7/buck,hgl888/buck,LegNeato/buck,bocon13/buck,Distrotech/buck,rmaz/buck,brettwooldridge/buck,Learn-Android-app/buck,clonetwin26/buck,clonetwin26/buck,lukw00/buck,shs96c/buck,sdwilsh/buck,daedric/buck,1yvT0s/buck,kageiit/buck,zhuxiaohao/buck,shybovycha/buck,janicduplessis/buck,artiya4u/buck,liuyang-li/buck,daedric/buck,justinmuller/buck,raviagarwal7/buck,artiya4u/buck,brettwooldridge/buck,davido/buck,OkBuilds/buck,OkBuilds/buck,dushmis/buck,dsyang/buck,romanoid/buck,Dominator008/buck,mikekap/buck,sdwilsh/buck,shybovycha/buck,robbertvanginkel/buck,stuhood/buck,vschs007/buck,1yvT0s/buck,k21/buck,JoelMarcey/buck,Addepar/buck,kageiit/buck,Heart2009/buck,raviagarwal7/buck,brettwooldridge/buck,1yvT0s/buck,romanoid/buck,tgummerer/buck,lukw00/buck,grumpyjames/buck,OkBuilds/buck,shybovycha/buck,SeleniumHQ/buck,bocon13/buck,pwz3n0/buck,romanoid/buck,k21/buck,daedric/buck,artiya4u/buck,mnuessler/buck,vschs007/buck,shs96c/buck,facebook/buck,shybovycha/buck,lukw00/buck,davido/buck,mogers/buck,mogers/buck,luiseduardohdbackup/buck,davido/buck,pwz3n0/buck,zhuxiaohao/buck,liuyang-li/buck,dsyang/buck,SeleniumHQ/buck,romanoid/buck,shybovycha/buck,darkforestzero/buck,janicduplessis/buck,Heart2009/buck,dpursehouse/buck,OkBuilds/buck,siddhartharay007/buck,clonetwin26/buck,SeleniumHQ/buck,mikekap/buck,hgl888/buck,k21/buck,robbertvanginkel/buck,OkBuilds/buck,marcinkwiatkowski/buck,davido/buck,davido/buck,tgummerer/buck,luiseduardohdbackup/buck,zpao/buck,rowillia/buck,liuyang-li/buck,pwz3n0/buck,LegNeato/buck,JoelMarcey/buck,shs96c/buck,illicitonion/buck,pwz3n0/buck,Distrotech/buck,illicitonion/buck,rmaz/buck,JoelMarcey/buck,SeleniumHQ/buck,Addepar/buck,vschs007/buck,shs96c/buck,ilya-klyuchnikov/buck,raviagarwal7/buck,MarkRunWu/buck,vine/buck,facebook/buck,raviagarwal7/buck,lukw00/buck,facebook/buck,k21/buck,romanoid/buck,mikekap/buck,robbertvanginkel/buck,liuyang-li/buck,shybovycha/buck,MarkRunWu/buck,rmaz/buck,sdwilsh/buck,daedric/buck,LegNeato/buck,clonetwin26/buck,Distrotech/buck,zhan-xiong/buck,SeleniumHQ/buck,rmaz/buck,illicitonion/buck,raviagarwal7/buck,hgl888/buck,Addepar/buck,bocon13/buck,shs96c/buck,zhan-xiong/buck,pwz3n0/buck,illicitonion/buck,romanoid/buck,robbertvanginkel/buck,sdwilsh/buck,mnuessler/buck,zhuxiaohao/buck,darkforestzero/buck,siddhartharay007/buck,justinmuller/buck,dushmis/buck,rhencke/buck,vschs007/buck,illicitonion/buck,stuhood/buck,pwz3n0/buck,marcinkwiatkowski/buck,sdwilsh/buck,zhan-xiong/buck,grumpyjames/buck,sdwilsh/buck,zhan-xiong/buck,marcinkwiatkowski/buck,romanoid/buck,sdwilsh/buck,daedric/buck,brettwooldridge/buck,zhuxiaohao/buck,romanoid/buck,OkBuilds/buck,dsyang/buck,janicduplessis/buck,siddhartharay007/buck,bocon13/buck,MarkRunWu/buck,clonetwin26/buck,SeleniumHQ/buck,siddhartharay007/buck,davido/buck,rhencke/buck,marcinkwiatkowski/buck,artiya4u/buck,Addepar/buck,justinmuller/buck,mnuessler/buck,dpursehouse/buck,marcinkwiatkowski/buck,rhencke/buck,robbertvanginkel/buck,Learn-Android-app/buck,stuhood/buck,tgummerer/buck,grumpyjames/buck,dushmis/buck,dpursehouse/buck,grumpyjames/buck,rmaz/buck,stuhood/buck,shs96c/buck,Heart2009/buck,mnuessler/buck,rhencke/buck,sdwilsh/buck,robbertvanginkel/buck,shs96c/buck,dsyang/buck,1yvT0s/buck,k21/buck,Dominator008/buck,JoelMarcey/buck,OkBuilds/buck,rowillia/buck,rmaz/buck,kageiit/buck,pwz3n0/buck,Learn-Android-app/buck,mnuessler/buck,marcinkwiatkowski/buck,dushmis/buck,janicduplessis/buck,robbertvanginkel/buck,liuyang-li/buck,davido/buck,dpursehouse/buck,mogers/buck,Dominator008/buck,SeleniumHQ/buck,Dominator008/buck,Learn-Android-app/buck,dpursehouse/buck,bocon13/buck,Distrotech/buck,marcinkwiatkowski/buck,mnuessler/buck,clonetwin26/buck,brettwooldridge/buck,liuyang-li/buck,tgummerer/buck,Learn-Android-app/buck,zhan-xiong/buck,nguyentruongtho/buck,rmaz/buck,janicduplessis/buck,vine/buck,raviagarwal7/buck,davido/buck,shybovycha/buck,LegNeato/buck,artiya4u/buck,vschs007/buck,k21/buck,LegNeato/buck,shs96c/buck,Learn-Android-app/buck,darkforestzero/buck,rhencke/buck,robbertvanginkel/buck,darkforestzero/buck,rowillia/buck,illicitonion/buck,mnuessler/buck,luiseduardohdbackup/buck,ilya-klyuchnikov/buck,dsyang/buck,k21/buck,JoelMarcey/buck,k21/buck,facebook/buck,artiya4u/buck,justinmuller/buck,nguyentruongtho/buck,siddhartharay007/buck,stuhood/buck,dsyang/buck,dsyang/buck,LegNeato/buck,lukw00/buck,marcinkwiatkowski/buck,romanoid/buck,pwz3n0/buck,OkBuilds/buck,vschs007/buck,shybovycha/buck,daedric/buck,Learn-Android-app/buck,rmaz/buck,zhan-xiong/buck,brettwooldridge/buck,darkforestzero/buck,ilya-klyuchnikov/buck,janicduplessis/buck,JoelMarcey/buck,Heart2009/buck,hgl888/buck,Addepar/buck,rhencke/buck,raviagarwal7/buck,ilya-klyuchnikov/buck,illicitonion/buck,lukw00/buck,rhencke/buck,bocon13/buck,ilya-klyuchnikov/buck,artiya4u/buck,stuhood/buck,MarkRunWu/buck,zpao/buck,janicduplessis/buck,justinmuller/buck,mikekap/buck,clonetwin26/buck,romanoid/buck,dsyang/buck,brettwooldridge/buck,Distrotech/buck,OkBuilds/buck,Heart2009/buck,daedric/buck,Distrotech/buck,neonichu/buck,Heart2009/buck,dushmis/buck,zhan-xiong/buck,Distrotech/buck,Dominator008/buck,liuyang-li/buck,pwz3n0/buck,OkBuilds/buck,luiseduardohdbackup/buck,LegNeato/buck,Heart2009/buck,JoelMarcey/buck,mikekap/buck,MarkRunWu/buck,tgummerer/buck,sdwilsh/buck,mogers/buck,tgummerer/buck,k21/buck,stuhood/buck,mnuessler/buck,brettwooldridge/buck,artiya4u/buck,vine/buck,ilya-klyuchnikov/buck,nguyentruongtho/buck,OkBuilds/buck,ilya-klyuchnikov/buck,janicduplessis/buck,hgl888/buck,rowillia/buck,robbertvanginkel/buck,zhuxiaohao/buck,MarkRunWu/buck,sdwilsh/buck,tgummerer/buck,Learn-Android-app/buck,1yvT0s/buck,dsyang/buck,grumpyjames/buck,janicduplessis/buck,liuyang-li/buck,dushmis/buck,JoelMarcey/buck,Distrotech/buck,artiya4u/buck,stuhood/buck,dushmis/buck,vschs007/buck,Addepar/buck,rhencke/buck,clonetwin26/buck,Learn-Android-app/buck,illicitonion/buck,clonetwin26/buck,Addepar/buck,Addepar/buck,justinmuller/buck,mikekap/buck,vschs007/buck,zpao/buck,davido/buck,romanoid/buck,darkforestzero/buck,hgl888/buck,tgummerer/buck,zhuxiaohao/buck,siddhartharay007/buck,vschs007/buck,SeleniumHQ/buck,k21/buck,janicduplessis/buck,rowillia/buck,kageiit/buck,neonichu/buck,bocon13/buck,nguyentruongtho/buck,rmaz/buck,neonichu/buck,zhan-xiong/buck,shs96c/buck,hgl888/buck,dpursehouse/buck,rowillia/buck,MarkRunWu/buck,liuyang-li/buck,daedric/buck,Addepar/buck,neonichu/buck,clonetwin26/buck,tgummerer/buck,darkforestzero/buck,grumpyjames/buck,tgummerer/buck,JoelMarcey/buck,brettwooldridge/buck,mogers/buck,zhan-xiong/buck,facebook/buck,robbertvanginkel/buck,pwz3n0/buck,sdwilsh/buck,illicitonion/buck,siddhartharay007/buck,mogers/buck,bocon13/buck,hgl888/buck,mikekap/buck,rowillia/buck,vine/buck,davido/buck,LegNeato/buck,vschs007/buck,darkforestzero/buck,zpao/buck,mikekap/buck,ilya-klyuchnikov/buck,bocon13/buck,vine/buck,zpao/buck,Addepar/buck,mikekap/buck,robbertvanginkel/buck,justinmuller/buck,neonichu/buck,dpursehouse/buck,justinmuller/buck,1yvT0s/buck,siddhartharay007/buck,ilya-klyuchnikov/buck,nguyentruongtho/buck,zhan-xiong/buck,LegNeato/buck,mogers/buck,stuhood/buck,kageiit/buck,marcinkwiatkowski/buck,ilya-klyuchnikov/buck,mikekap/buck,liuyang-li/buck,OkBuilds/buck,Distrotech/buck,rowillia/buck,Dominator008/buck,zpao/buck,LegNeato/buck,rmaz/buck,JoelMarcey/buck,Heart2009/buck,rowillia/buck,rmaz/buck,stuhood/buck,daedric/buck,brettwooldridge/buck,davido/buck,darkforestzero/buck,vine/buck,SeleniumHQ/buck,zhan-xiong/buck,illicitonion/buck,bocon13/buck,mogers/buck,Addepar/buck,rowillia/buck,justinmuller/buck,bocon13/buck,neonichu/buck,zhan-xiong/buck,raviagarwal7/buck,Distrotech/buck,shybovycha/buck,grumpyjames/buck,brettwooldridge/buck
/* * Copyright 2014-present Facebook, 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.facebook.buck.apple; public enum ApplePlatform { MACOS("macos"), IPHONESIMULATOR("iphonesimulator"), IPHONEOS("iphoneos"), ; private final String value; private ApplePlatform(String value) { this.value = value; } @Override public String toString() { return value; } };
src/com/facebook/buck/apple/ApplePlatform.java
Easy: New enum ApplePlatform Summary: Unlike for Android, when building for Apple, we need to choose between Mac OS X, iPhone OS, or iPhone Simulator, which have separate SDKs. We also need to switch on the platform to decide whether to add `-miphoneos-version-min=...` or `-mmacosx-version-min=...` parameters to CFLAGS in `AppleCxxPlatform`. This adds a new enum `ApplePlatform` which lets us indicate the platform the user is building for. Test Plan: Used in a subsequent diff.
src/com/facebook/buck/apple/ApplePlatform.java
Easy: New enum ApplePlatform
<ide><path>rc/com/facebook/buck/apple/ApplePlatform.java <add>/* <add> * Copyright 2014-present Facebook, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may <add> * not use this file except in compliance with the License. You may obtain <add> * a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT <add> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the <add> * License for the specific language governing permissions and limitations <add> * under the License. <add> */ <add> <add>package com.facebook.buck.apple; <add> <add>public enum ApplePlatform { <add> MACOS("macos"), <add> IPHONESIMULATOR("iphonesimulator"), <add> IPHONEOS("iphoneos"), <add> ; <add> <add> private final String value; <add> <add> private ApplePlatform(String value) { <add> this.value = value; <add> } <add> <add> @Override <add> public String toString() { <add> return value; <add> } <add>};
Java
agpl-3.0
b6e35128910e808e7309136c62e950785411ce0e
0
otavanopisto/kunta-api-server,otavanopisto/kunta-api-server,Metatavu/kunta-api-server,Metatavu/kunta-api-server,Metatavu/kunta-api-server
package fi.otavanopisto.kuntaapi.server.rest; import java.util.List; import javax.ejb.Stateful; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.core.Context; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.StringUtils; import fi.otavanopisto.kuntaapi.server.controllers.ServiceController; import fi.otavanopisto.kuntaapi.server.id.ElectronicServiceChannelId; import fi.otavanopisto.kuntaapi.server.id.PhoneChannelId; import fi.otavanopisto.kuntaapi.server.id.PrintableFormChannelId; import fi.otavanopisto.kuntaapi.server.id.ServiceId; import fi.otavanopisto.kuntaapi.server.id.ServiceLocationChannelId; import fi.otavanopisto.kuntaapi.server.id.WebPageChannelId; import fi.otavanopisto.kuntaapi.server.integrations.KuntaApiConsts; import fi.otavanopisto.kuntaapi.server.rest.model.ElectronicChannel; import fi.otavanopisto.kuntaapi.server.rest.model.PhoneChannel; import fi.otavanopisto.kuntaapi.server.rest.model.PrintableFormChannel; import fi.otavanopisto.kuntaapi.server.rest.model.Service; import fi.otavanopisto.kuntaapi.server.rest.model.ServiceLocationChannel; import fi.otavanopisto.kuntaapi.server.rest.model.WebPageChannel; /** * REST Service implementation * * @author Antti Leppä */ @RequestScoped @Stateful @SuppressWarnings ("squid:S3306") public class ServicesApiImpl extends ServicesApi { private static final String MAX_RESULTS_MUST_BY_A_POSITIVE_INTEGER = "maxResults must by a positive integer"; private static final String FIRST_RESULT_MUST_BY_A_POSITIVE_INTEGER = "firstResult must by a positive integer"; private static final String INVALID_SERVICE_ID = "Invalid service id %s"; private static final String INVALID_ELECTRONIC_CHANNEL_ID = "Invalid electronic service channel id %s"; private static final String INVALID_PHONE_CHANNEL_ID = "Invalid electronic phone service channel id %s"; private static final String INVALID_SERVICE_LOCATION_CHANNEL_ID = "Invalid service location service channel id %s"; private static final String INVALID_PRINTABLE_FORM_CHANNEL_ID = "Invalid printable form service channel id %s"; private static final String INVALID_WEBPAGE_CHANNEL_ID = "Invalid webpage service channel id %s"; private static final String NOT_FOUND = "Not Found"; private static final String NOT_IMPLEMENTED = "Not implemented"; @Inject private ServiceController serviceController; @Inject private HttpCacheController httpCacheController; @Override public Response createService(Service body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response findService(String serviceIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); Response notModified = httpCacheController.getNotModified(request, serviceId); if (notModified != null) { return notModified; } Service service = serviceController.findService(serviceId); if (service != null) { return httpCacheController.sendModified(service, service.getId()); } return createNotFound(NOT_FOUND); } @Override public Response listServices(String search, Long firstResult, Long maxResults, @Context Request request) { Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } if (search == null) { return Response.ok(serviceController.listServices(firstResult, maxResults)).build(); } else { return Response.ok(serviceController.searchServices(search, firstResult, maxResults)).build(); } } @Override public Response updateService(String serviceId, Service body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response createServiceElectronicChannel(String serviceId, ElectronicChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response createServicePhoneChannel(String serviceId, PhoneChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response createServicePrintableFormChannel(String serviceId, PrintableFormChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response createServiceServiceLocationChannel(String serviceId, ServiceLocationChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response createServiceWebPageChannel(String serviceId, WebPageChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response findServiceElectronicChannel(String serviceIdParam, String electronicChannelIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } ElectronicServiceChannelId electronicChannelId = toElectronicChannelId(electronicChannelIdParam); if (electronicChannelId == null) { return createBadRequest(String.format(INVALID_ELECTRONIC_CHANNEL_ID, serviceIdParam)); } Response notModified = httpCacheController.getNotModified(request, electronicChannelId); if (notModified != null) { return notModified; } ElectronicChannel electronicChannel = serviceController.findElectronicChannel(serviceId, electronicChannelId); if (electronicChannel != null) { return httpCacheController.sendModified(electronicChannel, electronicChannel.getId()); } return Response .status(Status.NOT_FOUND) .entity(NOT_FOUND) .build(); } @Override public Response findServicePhoneChannel(String serviceIdParam, String phoneChannelIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } PhoneChannelId phoneChannelId = toPhoneChannelId(phoneChannelIdParam); if (phoneChannelId == null) { return createBadRequest(String.format(INVALID_PHONE_CHANNEL_ID, serviceIdParam)); } Response notModified = httpCacheController.getNotModified(request, phoneChannelId); if (notModified != null) { return notModified; } PhoneChannel phoneChannel = serviceController.findPhoneChannel(serviceId, phoneChannelId); if (phoneChannel != null) { return httpCacheController.sendModified(phoneChannel, phoneChannel.getId()); } return Response .status(Status.NOT_FOUND) .entity(NOT_FOUND) .build(); } @Override public Response findServicePrintableFormChannel(String serviceIdParam, String printableFormChannelIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } PrintableFormChannelId printableFormChannelId = toPrintableFormChannelId(printableFormChannelIdParam); if (printableFormChannelId == null) { return createBadRequest(String.format(INVALID_PRINTABLE_FORM_CHANNEL_ID, serviceIdParam)); } Response notModified = httpCacheController.getNotModified(request, printableFormChannelId); if (notModified != null) { return notModified; } PrintableFormChannel printableFormChannel = serviceController.findPrintableFormChannel(serviceId, printableFormChannelId); if (printableFormChannel != null) { return httpCacheController.sendModified(printableFormChannel, printableFormChannel.getId()); } return Response .status(Status.NOT_FOUND) .entity(NOT_FOUND) .build(); } @Override public Response findServiceServiceLocationChannel(String serviceIdParam, String serviceLocationChannelIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } ServiceLocationChannelId serviceLocationChannelId = toServiceLocationChannelId(serviceLocationChannelIdParam); if (serviceLocationChannelId == null) { return createBadRequest(String.format(INVALID_SERVICE_LOCATION_CHANNEL_ID, serviceIdParam)); } Response notModified = httpCacheController.getNotModified(request, serviceLocationChannelId); if (notModified != null) { return notModified; } ServiceLocationChannel serviceLocationChannel = serviceController.findServiceLocationChannel(serviceId, serviceLocationChannelId); if (serviceLocationChannel != null) { return httpCacheController.sendModified(serviceLocationChannel, serviceLocationChannel.getId()); } return Response .status(Status.NOT_FOUND) .entity(NOT_FOUND) .build(); } @Override public Response findServiceWebPageChannel(String serviceIdParam, String webPageChannelIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } WebPageChannelId webPageChannelId = toWebPageChannelId(webPageChannelIdParam); if (webPageChannelId == null) { return createBadRequest(String.format(INVALID_WEBPAGE_CHANNEL_ID, serviceIdParam)); } Response notModified = httpCacheController.getNotModified(request, webPageChannelId); if (notModified != null) { return notModified; } WebPageChannel webPageChannel = serviceController.findWebPageChannel(serviceId, webPageChannelId); if (webPageChannel != null) { return httpCacheController.sendModified(webPageChannel, webPageChannel.getId()); } return Response .status(Status.NOT_FOUND) .entity(NOT_FOUND) .build(); } @Override public Response listServiceElectronicChannels(String serviceIdParam, Long firstResult, Long maxResults, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<ElectronicChannel> result = serviceController.listElectronicChannels(firstResult, maxResults, serviceId); return Response.ok(result).build(); } @Override public Response listServicePhoneChannels(String serviceIdParam, Long firstResult, Long maxResults, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<PhoneChannel> result = serviceController.listPhoneChannels(firstResult, maxResults, serviceId); return Response.ok(result).build(); } @Override public Response listServicePrintableFormChannels(String serviceIdParam, Long firstResult, Long maxResults, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<PrintableFormChannel> result = serviceController.listPrintableFormChannels(firstResult, maxResults, serviceId); return Response.ok(result).build(); } @Override public Response listServiceServiceLocationChannels(String serviceIdParam, Long firstResult, Long maxResults, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<ServiceLocationChannel> result = serviceController.listServiceLocationChannels(firstResult, maxResults, serviceId); return Response.ok(result).build(); } @Override public Response listServiceWebPageChannels(String serviceIdParam, Long firstResult, Long maxResults, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<WebPageChannel> result = serviceController.listWebPageChannels(firstResult, maxResults, serviceId); return Response.ok(result).build(); } @Override public Response updatePhoneChannel(String serviceId, String phoneChannelId, PhoneChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response updatePrintableFormChannel(String serviceId, String printableFormChannelId, PrintableFormChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response updateServiceElectronicChannel(String serviceId, String electronicChannelId, ElectronicChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response updateServiceLocationChannel(String serviceId, String serviceLocationChannelId, ServiceLocationChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response updateWebPageChannel(String serviceId, String webPageChannelId, WebPageChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } private Response validateListLimitParams(Long firstResult, Long maxResults) { if (firstResult != null && firstResult < 0) { return createBadRequest(FIRST_RESULT_MUST_BY_A_POSITIVE_INTEGER); } if (maxResults != null && maxResults < 0) { return createBadRequest(MAX_RESULTS_MUST_BY_A_POSITIVE_INTEGER); } return null; } private ServiceId toServiceId(String id) { if (StringUtils.isNotBlank(id)) { return new ServiceId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private ElectronicServiceChannelId toElectronicChannelId(String id) { if (StringUtils.isNotBlank(id)) { return new ElectronicServiceChannelId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private PhoneChannelId toPhoneChannelId(String id) { if (StringUtils.isNotBlank(id)) { return new PhoneChannelId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private PrintableFormChannelId toPrintableFormChannelId(String id) { if (StringUtils.isNotBlank(id)) { return new PrintableFormChannelId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private ServiceLocationChannelId toServiceLocationChannelId(String id) { if (StringUtils.isNotBlank(id)) { return new ServiceLocationChannelId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private WebPageChannelId toWebPageChannelId(String id) { if (StringUtils.isNotBlank(id)) { return new WebPageChannelId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } }
src/main/java/fi/otavanopisto/kuntaapi/server/rest/ServicesApiImpl.java
package fi.otavanopisto.kuntaapi.server.rest; import java.util.List; import javax.ejb.Stateful; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.core.Context; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.StringUtils; import fi.otavanopisto.kuntaapi.server.controllers.ServiceController; import fi.otavanopisto.kuntaapi.server.id.ElectronicServiceChannelId; import fi.otavanopisto.kuntaapi.server.id.PhoneChannelId; import fi.otavanopisto.kuntaapi.server.id.PrintableFormChannelId; import fi.otavanopisto.kuntaapi.server.id.ServiceId; import fi.otavanopisto.kuntaapi.server.id.ServiceLocationChannelId; import fi.otavanopisto.kuntaapi.server.id.WebPageChannelId; import fi.otavanopisto.kuntaapi.server.integrations.KuntaApiConsts; import fi.otavanopisto.kuntaapi.server.rest.model.ElectronicChannel; import fi.otavanopisto.kuntaapi.server.rest.model.PhoneChannel; import fi.otavanopisto.kuntaapi.server.rest.model.PrintableFormChannel; import fi.otavanopisto.kuntaapi.server.rest.model.Service; import fi.otavanopisto.kuntaapi.server.rest.model.ServiceLocationChannel; import fi.otavanopisto.kuntaapi.server.rest.model.WebPageChannel; /** * REST Service implementation * * @author Antti Leppä */ @RequestScoped @Stateful @SuppressWarnings ("squid:S3306") public class ServicesApiImpl extends ServicesApi { private static final String MAX_RESULTS_MUST_BY_A_POSITIVE_INTEGER = "maxResults must by a positive integer"; private static final String FIRST_RESULT_MUST_BY_A_POSITIVE_INTEGER = "firstResult must by a positive integer"; private static final String INVALID_SERVICE_ID = "Invalid service id %s"; private static final String INVALID_ELECTRONIC_CHANNEL_ID = "Invalid electronic service channel id %s"; private static final String INVALID_PHONE_CHANNEL_ID = "Invalid electronic phone service channel id %s"; private static final String INVALID_SERVICE_LOCATION_CHANNEL_ID = "Invalid service location service channel id %s"; private static final String INVALID_PRINTABLE_FORM_CHANNEL_ID = "Invalid printable form service channel id %s"; private static final String INVALID_WEBPAGE_CHANNEL_ID = "Invalid webpage service channel id %s"; private static final String NOT_FOUND = "Not Found"; private static final String NOT_IMPLEMENTED = "Not implemented"; @Inject private ServiceController serviceController; @Inject private HttpCacheController httpCacheController; @Override public Response createService(Service body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response findService(String serviceIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); Response notModified = httpCacheController.getNotModified(request, serviceId); if (notModified != null) { return notModified; } Service service = serviceController.findService(serviceId); if (service != null) { return httpCacheController.sendModified(service, service.getId()); } return createNotFound(NOT_FOUND); } @Override public Response listServices(String search, Long firstResult, Long maxResults, @Context Request request) { Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } if (search == null) { return Response.ok(serviceController.listServices(firstResult, maxResults)).build(); } else { return Response.ok(serviceController.searchServices(search, firstResult, maxResults)).build(); } } @Override public Response updateService(String serviceId, Service body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response createServiceElectronicChannel(String serviceId, ElectronicChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response createServicePhoneChannel(String serviceId, PhoneChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response createServicePrintableFormChannel(String serviceId, PrintableFormChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response createServiceServiceLocationChannel(String serviceId, ServiceLocationChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response createServiceWebPageChannel(String serviceId, WebPageChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response findServiceElectronicChannel(String serviceIdParam, String electronicChannelIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } ElectronicServiceChannelId electronicChannelId = toElectronicChannelId(electronicChannelIdParam); if (electronicChannelId == null) { return createBadRequest(String.format(INVALID_ELECTRONIC_CHANNEL_ID, serviceIdParam)); } ElectronicChannel electronicChannel = serviceController.findElectronicChannel(serviceId, electronicChannelId); if (electronicChannel != null) { return Response.ok(electronicChannel) .build(); } return Response .status(Status.NOT_FOUND) .entity(NOT_FOUND) .build(); } @Override public Response findServicePhoneChannel(String serviceIdParam, String phoneChannelIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } PhoneChannelId phoneChannelId = toPhoneChannelId(phoneChannelIdParam); if (phoneChannelId == null) { return createBadRequest(String.format(INVALID_PHONE_CHANNEL_ID, serviceIdParam)); } PhoneChannel phoneChannel = serviceController.findPhoneChannel(serviceId, phoneChannelId); if (phoneChannel != null) { return Response.ok(phoneChannel) .build(); } return Response .status(Status.NOT_FOUND) .entity(NOT_FOUND) .build(); } @Override public Response findServicePrintableFormChannel(String serviceIdParam, String printableFormChannelIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } PrintableFormChannelId printableFormChannelId = toPrintableFormChannelId(printableFormChannelIdParam); if (printableFormChannelId == null) { return createBadRequest(String.format(INVALID_PRINTABLE_FORM_CHANNEL_ID, serviceIdParam)); } PrintableFormChannel printableFormChannel = serviceController.findPrintableFormChannel(serviceId, printableFormChannelId); if (printableFormChannel != null) { return Response.ok(printableFormChannel) .build(); } return Response .status(Status.NOT_FOUND) .entity(NOT_FOUND) .build(); } @Override public Response findServiceServiceLocationChannel(String serviceIdParam, String serviceLocationChannelIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } ServiceLocationChannelId serviceLocationChannelId = toServiceLocationChannelId(serviceLocationChannelIdParam); if (serviceLocationChannelId == null) { return createBadRequest(String.format(INVALID_SERVICE_LOCATION_CHANNEL_ID, serviceIdParam)); } ServiceLocationChannel serviceLocationChannel = serviceController.findServiceLocationChannel(serviceId, serviceLocationChannelId); if (serviceLocationChannel != null) { return Response.ok(serviceLocationChannel) .build(); } return Response .status(Status.NOT_FOUND) .entity(NOT_FOUND) .build(); } @Override public Response findServiceWebPageChannel(String serviceIdParam, String webPageChannelIdParam, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } WebPageChannelId webPageChannelId = toWebPageChannelId(webPageChannelIdParam); if (webPageChannelId == null) { return createBadRequest(String.format(INVALID_WEBPAGE_CHANNEL_ID, serviceIdParam)); } WebPageChannel webPageChannel = serviceController.findWebPageChannel(serviceId, webPageChannelId); if (webPageChannel != null) { return Response.ok(webPageChannel) .build(); } return Response .status(Status.NOT_FOUND) .entity(NOT_FOUND) .build(); } @Override public Response listServiceElectronicChannels(String serviceIdParam, Long firstResult, Long maxResults, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<ElectronicChannel> result = serviceController.listElectronicChannels(firstResult, maxResults, serviceId); return Response.ok(result).build(); } @Override public Response listServicePhoneChannels(String serviceIdParam, Long firstResult, Long maxResults, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<PhoneChannel> result = serviceController.listPhoneChannels(firstResult, maxResults, serviceId); return Response.ok(result).build(); } @Override public Response listServicePrintableFormChannels(String serviceIdParam, Long firstResult, Long maxResults, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<PrintableFormChannel> result = serviceController.listPrintableFormChannels(firstResult, maxResults, serviceId); return Response.ok(result).build(); } @Override public Response listServiceServiceLocationChannels(String serviceIdParam, Long firstResult, Long maxResults, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<ServiceLocationChannel> result = serviceController.listServiceLocationChannels(firstResult, maxResults, serviceId); return Response.ok(result).build(); } @Override public Response listServiceWebPageChannels(String serviceIdParam, Long firstResult, Long maxResults, @Context Request request) { ServiceId serviceId = toServiceId(serviceIdParam); if (serviceId == null) { return createBadRequest(String.format(INVALID_SERVICE_ID, serviceIdParam)); } Response validationResponse = validateListLimitParams(firstResult, maxResults); if (validationResponse != null) { return validationResponse; } List<WebPageChannel> result = serviceController.listWebPageChannels(firstResult, maxResults, serviceId); return Response.ok(result).build(); } @Override public Response updatePhoneChannel(String serviceId, String phoneChannelId, PhoneChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response updatePrintableFormChannel(String serviceId, String printableFormChannelId, PrintableFormChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response updateServiceElectronicChannel(String serviceId, String electronicChannelId, ElectronicChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response updateServiceLocationChannel(String serviceId, String serviceLocationChannelId, ServiceLocationChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } @Override public Response updateWebPageChannel(String serviceId, String webPageChannelId, WebPageChannel body, @Context Request request) { return createNotImplemented(NOT_IMPLEMENTED); } private Response validateListLimitParams(Long firstResult, Long maxResults) { if (firstResult != null && firstResult < 0) { return createBadRequest(FIRST_RESULT_MUST_BY_A_POSITIVE_INTEGER); } if (maxResults != null && maxResults < 0) { return createBadRequest(MAX_RESULTS_MUST_BY_A_POSITIVE_INTEGER); } return null; } private ServiceId toServiceId(String id) { if (StringUtils.isNotBlank(id)) { return new ServiceId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private ElectronicServiceChannelId toElectronicChannelId(String id) { if (StringUtils.isNotBlank(id)) { return new ElectronicServiceChannelId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private PhoneChannelId toPhoneChannelId(String id) { if (StringUtils.isNotBlank(id)) { return new PhoneChannelId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private PrintableFormChannelId toPrintableFormChannelId(String id) { if (StringUtils.isNotBlank(id)) { return new PrintableFormChannelId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private ServiceLocationChannelId toServiceLocationChannelId(String id) { if (StringUtils.isNotBlank(id)) { return new ServiceLocationChannelId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } private WebPageChannelId toWebPageChannelId(String id) { if (StringUtils.isNotBlank(id)) { return new WebPageChannelId(KuntaApiConsts.IDENTIFIER_NAME, id); } return null; } }
Enabled http cache on service channels
src/main/java/fi/otavanopisto/kuntaapi/server/rest/ServicesApiImpl.java
Enabled http cache on service channels
<ide><path>rc/main/java/fi/otavanopisto/kuntaapi/server/rest/ServicesApiImpl.java <ide> return createBadRequest(String.format(INVALID_ELECTRONIC_CHANNEL_ID, serviceIdParam)); <ide> } <ide> <add> Response notModified = httpCacheController.getNotModified(request, electronicChannelId); <add> if (notModified != null) { <add> return notModified; <add> } <add> <ide> ElectronicChannel electronicChannel = serviceController.findElectronicChannel(serviceId, electronicChannelId); <ide> if (electronicChannel != null) { <del> return Response.ok(electronicChannel) <del> .build(); <add> return httpCacheController.sendModified(electronicChannel, electronicChannel.getId()); <ide> } <ide> <ide> return Response <ide> return createBadRequest(String.format(INVALID_PHONE_CHANNEL_ID, serviceIdParam)); <ide> } <ide> <add> Response notModified = httpCacheController.getNotModified(request, phoneChannelId); <add> if (notModified != null) { <add> return notModified; <add> } <add> <ide> PhoneChannel phoneChannel = serviceController.findPhoneChannel(serviceId, phoneChannelId); <ide> if (phoneChannel != null) { <del> return Response.ok(phoneChannel) <del> .build(); <del> } <del> <add> return httpCacheController.sendModified(phoneChannel, phoneChannel.getId()); <add> } <add> <ide> return Response <ide> .status(Status.NOT_FOUND) <ide> .entity(NOT_FOUND) <ide> if (printableFormChannelId == null) { <ide> return createBadRequest(String.format(INVALID_PRINTABLE_FORM_CHANNEL_ID, serviceIdParam)); <ide> } <del> <add> <add> Response notModified = httpCacheController.getNotModified(request, printableFormChannelId); <add> if (notModified != null) { <add> return notModified; <add> } <add> <ide> PrintableFormChannel printableFormChannel = serviceController.findPrintableFormChannel(serviceId, printableFormChannelId); <ide> if (printableFormChannel != null) { <del> return Response.ok(printableFormChannel) <del> .build(); <add> return httpCacheController.sendModified(printableFormChannel, printableFormChannel.getId()); <ide> } <ide> <ide> return Response <ide> if (serviceLocationChannelId == null) { <ide> return createBadRequest(String.format(INVALID_SERVICE_LOCATION_CHANNEL_ID, serviceIdParam)); <ide> } <del> <add> <add> Response notModified = httpCacheController.getNotModified(request, serviceLocationChannelId); <add> if (notModified != null) { <add> return notModified; <add> } <add> <ide> ServiceLocationChannel serviceLocationChannel = serviceController.findServiceLocationChannel(serviceId, serviceLocationChannelId); <ide> if (serviceLocationChannel != null) { <del> return Response.ok(serviceLocationChannel) <del> .build(); <add> return httpCacheController.sendModified(serviceLocationChannel, serviceLocationChannel.getId()); <ide> } <ide> <ide> return Response <ide> if (webPageChannelId == null) { <ide> return createBadRequest(String.format(INVALID_WEBPAGE_CHANNEL_ID, serviceIdParam)); <ide> } <del> <add> <add> Response notModified = httpCacheController.getNotModified(request, webPageChannelId); <add> if (notModified != null) { <add> return notModified; <add> } <add> <ide> WebPageChannel webPageChannel = serviceController.findWebPageChannel(serviceId, webPageChannelId); <ide> if (webPageChannel != null) { <del> return Response.ok(webPageChannel) <del> .build(); <add> return httpCacheController.sendModified(webPageChannel, webPageChannel.getId()); <ide> } <ide> <ide> return Response <ide> } <ide> <ide> List<ServiceLocationChannel> result = serviceController.listServiceLocationChannels(firstResult, maxResults, serviceId); <del> <ide> return Response.ok(result).build(); <ide> } <ide>
JavaScript
mit
00ba5670f28ad07840158f430bc32a5f3e443806
0
HimanshuBCS/mt2414ui,HimanshuBCS/mt2414ui
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, browserHistory } from 'react-router'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import { createStore, applyMiddleware } from 'redux'; import SignupForm from './SignupForm'; import UploadSource from './UploadSource'; import DownloadTokens from './DownloadTokens'; import GetConcordances from './GetConcordances'; import GenerateConcordance from './GenerateConcordance'; import GetTranslationDraft from './GetTranslationDraft'; import GetLanguages from './GetLanguages'; import UploadTokens from './UploadTokens'; import HomePage from './HomePage'; import ResetPassword from './ResetPassword'; import ForgotPassword from './ForgotPassword'; const store = createStore( (state = {}) => state, applyMiddleware(thunk) ); let accessToken = JSON.parse(window.localStorage.getItem('access_token')) ReactDOM.render( <Provider path="/" store={store}> <Router history={browserHistory}> <Route path="/" component={HomePage} /> <Route path="/homepage" component={HomePage} /> { (accessToken) ? ( <Router history={browserHistory}> <Route path="/getlanguages" component={GetLanguages}/> <Route path="/uploadsource" component={UploadSource} /> <Route path="/downloadtokens" component={DownloadTokens}/> <Route path="/uploadtokens" component={UploadTokens}/> <Route path="/getconcordances" component={GetConcordances}/> <Route path="/generateconcordance" component={GenerateConcordance}/> <Route path="/gettranslationdraft" component={GetTranslationDraft}/> <Route path="/signup" component={SignupForm}/> <Route path="/resetpassword" component={ResetPassword}/> <Route path="/forgotpassword" component={ForgotPassword}/> </Router> ) : ( <Router history={browserHistory}> <Route path="/getlanguages" component={HomePage}/> <Route path="/uploadsource" component={HomePage} /> <Route path="/downloadtokens" component={HomePage}/> <Route path="/uploadtokens" component={HomePage}/> <Route path="/getconcordances" component={HomePage}/> <Route path="/generateconcordance" component={HomePage}/> <Route path="/gettranslationdraft" component={HomePage}/> <Route path="/signup" component={SignupForm}/> <Route path="/resetpassword" component={ResetPassword}/> <Route path="/forgotpassword" component={ForgotPassword}/> </Router> ) } </Router> </Provider>, document.getElementById('root') );
src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, browserHistory } from 'react-router'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import { createStore, applyMiddleware } from 'redux'; import SignupForm from './SignupForm'; import UploadSource from './UploadSource'; import DownloadTokens from './DownloadTokens'; import GetConcordances from './GetConcordances'; import GenerateConcordance from './GenerateConcordance'; import GetTranslationDraft from './GetTranslationDraft'; import GetLanguages from './GetLanguages'; import UploadTokens from './UploadTokens'; import HomePage from './HomePage'; const store = createStore( (state = {}) => state, applyMiddleware(thunk) ); let accessToken = JSON.parse(window.localStorage.getItem('access_token')) ReactDOM.render( <Provider path="/" store={store}> <Router history={browserHistory}> <Route path="/" component={HomePage} /> <Route path="/homepage" component={HomePage} /> { (accessToken) ? ( <Router history={browserHistory}> <Route path="/getlanguages" component={GetLanguages}/> <Route path="/uploadsource" component={UploadSource} /> <Route path="/downloadtokens" component={DownloadTokens}/> <Route path="/uploadtokens" component={UploadTokens}/> <Route path="/getconcordances" component={GetConcordances}/> <Route path="/generateconcordance" component={GenerateConcordance}/> <Route path="/gettranslationdraft" component={GetTranslationDraft}/> <Route path="/signup" component={SignupForm}/> </Router> ) : ( <Router history={browserHistory}> <Route path="/getlanguages" component={HomePage}/> <Route path="/uploadsource" component={HomePage} /> <Route path="/downloadtokens" component={HomePage}/> <Route path="/uploadtokens" component={HomePage}/> <Route path="/getconcordances" component={HomePage}/> <Route path="/generateconcordance" component={HomePage}/> <Route path="/gettranslationdraft" component={HomePage}/> <Route path="/signup" component={SignupForm}/> </Router> ) } </Router> </Provider>, document.getElementById('root') );
Added route for forgot & index page
src/index.js
Added route for forgot & index page
<ide><path>rc/index.js <ide> import GetLanguages from './GetLanguages'; <ide> import UploadTokens from './UploadTokens'; <ide> import HomePage from './HomePage'; <add>import ResetPassword from './ResetPassword'; <add>import ForgotPassword from './ForgotPassword'; <ide> <ide> const store = createStore( <ide> (state = {}) => state, <ide> <Route path="/generateconcordance" component={GenerateConcordance}/> <ide> <Route path="/gettranslationdraft" component={GetTranslationDraft}/> <ide> <Route path="/signup" component={SignupForm}/> <add> <Route path="/resetpassword" component={ResetPassword}/> <add> <Route path="/forgotpassword" component={ForgotPassword}/> <ide> </Router> <ide> ) : ( <ide> <Router history={browserHistory}> <ide> <Route path="/getconcordances" component={HomePage}/> <ide> <Route path="/generateconcordance" component={HomePage}/> <ide> <Route path="/gettranslationdraft" component={HomePage}/> <del> <Route path="/signup" component={SignupForm}/> <add> <Route path="/signup" component={SignupForm}/> <add> <Route path="/resetpassword" component={ResetPassword}/> <add> <Route path="/forgotpassword" component={ForgotPassword}/> <ide> </Router> <ide> ) <ide> }
Java
bsd-3-clause
aa0c8c929a68a3ac981e52f7cbcaa223c68ca989
0
smartdevicelink/sdl_android,anildahiya/sdl_android,jthrun/sdl_android,914802951/sdl_android,jthrun/sdl_android
package com.smartdevicelink.protocol; import android.util.Log; import com.smartdevicelink.util.BitConverter; public class BinaryFrameHeader { private static final String TAG = "BinaryFrameHeader"; private byte _rpcType; private int _functionID; private int _correlationID; private int _jsonSize; private byte[] _jsonData; private byte[] _bulkData; public BinaryFrameHeader() {} public static BinaryFrameHeader parseBinaryHeader(byte[] binHeader) { BinaryFrameHeader msg = new BinaryFrameHeader(); byte RPC_Type = (byte) (binHeader[0] >>> 4); msg.setRPCType(RPC_Type); int _functionID = (BitConverter.intFromByteArray(binHeader, 0) & 0x0FFFFFFF); msg.setFunctionID(_functionID); int corrID = BitConverter.intFromByteArray(binHeader, 4); msg.setCorrID(corrID); int _jsonSize = BitConverter.intFromByteArray(binHeader, 8); msg.setJsonSize(_jsonSize); try { if (_jsonSize > 0) { byte[] _jsonData = new byte[_jsonSize]; System.arraycopy(binHeader, 12, _jsonData, 0, _jsonSize); msg.setJsonData(_jsonData); } if (binHeader.length - _jsonSize - 12 > 0) { byte[] _bulkData = new byte[binHeader.length - _jsonSize - 12]; System.arraycopy(binHeader, 12 + _jsonSize, _bulkData, 0, _bulkData.length); msg.setBulkData(_bulkData); } } catch (OutOfMemoryError|ArrayIndexOutOfBoundsException e){ Log.e(TAG, "Unable to process data to form header"); return null; } return msg; } public byte[] assembleHeaderBytes() { int binHeader = _functionID; // reset the 4 leftmost bits, for _rpcType binHeader &= 0xFFFFFFFF >>> 4; binHeader |= (_rpcType << 28); byte[] ret = new byte[12]; System.arraycopy(BitConverter.intToByteArray(binHeader), 0, ret, 0, 4); System.arraycopy(BitConverter.intToByteArray(_correlationID), 0, ret, 4, 4); System.arraycopy(BitConverter.intToByteArray(_jsonSize), 0, ret, 8, 4); return ret; } public byte getRPCType() { return _rpcType; } public void setRPCType(byte _rpcType) { this._rpcType = _rpcType; } public int getFunctionID() { return _functionID; } public void setFunctionID(int _functionID) { this._functionID = _functionID; } public int getCorrID() { return _correlationID; } public void setCorrID(int _correlationID) { this._correlationID = _correlationID; } public int getJsonSize() { return _jsonSize; } public void setJsonSize(int _jsonSize) { this._jsonSize = _jsonSize; } public byte[] getJsonData() { return _jsonData; } public void setJsonData(byte[] _jsonData) { this._jsonData = new byte[this._jsonSize]; System.arraycopy(_jsonData, 0, this._jsonData, 0, _jsonSize); //this._jsonData = _jsonData; } public byte[] getBulkData() { return _bulkData; } public void setBulkData(byte[] _bulkData) { this._bulkData = _bulkData; } }
sdl_android/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java
package com.smartdevicelink.protocol; import android.util.Log; import com.smartdevicelink.util.BitConverter; public class BinaryFrameHeader { private static final String TAG = "BinaryFrameHeader"; private byte _rpcType; private int _functionID; private int _correlationID; private int _jsonSize; private byte[] _jsonData; private byte[] _bulkData; public BinaryFrameHeader() {} public static BinaryFrameHeader parseBinaryHeader(byte[] binHeader) { BinaryFrameHeader msg = new BinaryFrameHeader(); byte RPC_Type = (byte) (binHeader[0] >>> 4); msg.setRPCType(RPC_Type); int _functionID = (BitConverter.intFromByteArray(binHeader, 0) & 0x0FFFFFFF); msg.setFunctionID(_functionID); int corrID = BitConverter.intFromByteArray(binHeader, 4); msg.setCorrID(corrID); int _jsonSize = BitConverter.intFromByteArray(binHeader, 8); msg.setJsonSize(_jsonSize); try { if (_jsonSize > 0) { byte[] _jsonData = new byte[_jsonSize]; System.arraycopy(binHeader, 12, _jsonData, 0, _jsonSize); msg.setJsonData(_jsonData); } if (binHeader.length - _jsonSize - 12 > 0) { byte[] _bulkData = new byte[binHeader.length - _jsonSize - 12]; System.arraycopy(binHeader, 12 + _jsonSize, _bulkData, 0, _bulkData.length); msg.setBulkData(_bulkData); } } catch (OutOfMemoryError e){ Log.e(TAG, "Unable to process data to form header"); return null; } return msg; } public byte[] assembleHeaderBytes() { int binHeader = _functionID; // reset the 4 leftmost bits, for _rpcType binHeader &= 0xFFFFFFFF >>> 4; binHeader |= (_rpcType << 28); byte[] ret = new byte[12]; System.arraycopy(BitConverter.intToByteArray(binHeader), 0, ret, 0, 4); System.arraycopy(BitConverter.intToByteArray(_correlationID), 0, ret, 4, 4); System.arraycopy(BitConverter.intToByteArray(_jsonSize), 0, ret, 8, 4); return ret; } public byte getRPCType() { return _rpcType; } public void setRPCType(byte _rpcType) { this._rpcType = _rpcType; } public int getFunctionID() { return _functionID; } public void setFunctionID(int _functionID) { this._functionID = _functionID; } public int getCorrID() { return _correlationID; } public void setCorrID(int _correlationID) { this._correlationID = _correlationID; } public int getJsonSize() { return _jsonSize; } public void setJsonSize(int _jsonSize) { this._jsonSize = _jsonSize; } public byte[] getJsonData() { return _jsonData; } public void setJsonData(byte[] _jsonData) { this._jsonData = new byte[this._jsonSize]; System.arraycopy(_jsonData, 0, this._jsonData, 0, _jsonSize); //this._jsonData = _jsonData; } public byte[] getBulkData() { return _bulkData; } public void setBulkData(byte[] _bulkData) { this._bulkData = _bulkData; } }
Add catch for ArrayIndexOutOfBoundsException
sdl_android/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java
Add catch for ArrayIndexOutOfBoundsException
<ide><path>dl_android/src/main/java/com/smartdevicelink/protocol/BinaryFrameHeader.java <ide> System.arraycopy(binHeader, 12 + _jsonSize, _bulkData, 0, _bulkData.length); <ide> msg.setBulkData(_bulkData); <ide> } <del> } catch (OutOfMemoryError e){ <add> } catch (OutOfMemoryError|ArrayIndexOutOfBoundsException e){ <ide> Log.e(TAG, "Unable to process data to form header"); <ide> return null; <ide> }
Java
mit
1091d364b17e61f4c494b839d0a11ca0ffb9f7bf
0
eduardgamiao/textbookmania,eduardgamiao/textbookmania
package controllers; import java.util.List; import java.util.Map; import models.BuyOffer; import models.BuyOfferDB; import models.SellOfferDB; import models.StudentDB; import models.TextbookDB; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import views.formdata.BuyOfferFormData; import views.formdata.SellOfferFormData; import views.formdata.StudentFormData; import views.formdata.TextbookCondtion; import views.formdata.TextbookFormData; import views.html.Index; import views.html.ManageBuyOffer; import views.html.ManageSellOffer; import views.html.ManageStudent; import views.html.ManageTextbook; import views.html.Matches; import views.html.Students; import views.html.Textbooks; import views.html.BuyOffers; import views.html.SellOffers; /** * Implements the controllers for this application. */ public class Application extends Controller { /** * Returns the home page. * @return The resulting home page. */ public static Result index() { return ok(Index.render("Welcome to the home page.")); } /** * Returns the show students page. * @return The show students page. */ public static Result showStudents() { return ok(Students.render(StudentDB.getStudents())); } /** * Returns the show textbooks page. * @return The show textbooks page. */ public static Result showTextbooks() { return ok(Textbooks.render(TextbookDB.getTextbooks())); } /** * Returns the showBuyOffers page. * @return The showBuyOffers page. */ public static Result showBuyOffers() { return ok(BuyOffers.render(BuyOfferDB.getBuyOffers())); } /** * Returns the showSellOffers page. * @return The showSellOffers page. */ public static Result showSellOffers() { return ok(SellOffers.render(SellOfferDB.getSellOffers())); } /** * The Student data form page. * @return The Student data form page. */ public static Result newStudent() { StudentFormData data = new StudentFormData(); Form<StudentFormData> formData = Form.form(StudentFormData.class).fill(data); return ok(ManageStudent.render("Add New Surfer", formData, false)); } /** * The Textbook data form page. * @return The Textbook data form page. */ public static Result newTextbook() { TextbookFormData data = new TextbookFormData(); Form<TextbookFormData> formData = Form.form(TextbookFormData.class).fill(data); List<String> conditions = TextbookCondtion.getCondition(); return ok(ManageTextbook.render("Add New Textbook", formData, conditions, false)); } /** * Render form for creating a new BuyOffer. * @return The BuyOffer data page. */ public static Result newBuyOffer() { BuyOfferFormData data = new BuyOfferFormData(); Form<BuyOfferFormData> formData = Form.form(BuyOfferFormData.class).fill(data); Map<String, Boolean> studentMap = StudentDB.getStudentNames(); Map<String, Boolean> bookMap = TextbookDB.getTextbookNames(); return ok(ManageBuyOffer.render("Add New Buy-Offer", formData, studentMap, bookMap)); } /** * Renders page after submitting form data. * @return The BuyOffer page. */ public static Result postBuyOffer() { Form<BuyOfferFormData> formData = Form.form(BuyOfferFormData.class).bindFromRequest(); if (formData.hasErrors()) { Map<String, Boolean> studentMap = StudentDB.getStudentNames(); Map<String, Boolean> bookMap = TextbookDB.getTextbookNames(); return badRequest(ManageBuyOffer.render("Manage Buy-Offer", formData, studentMap, bookMap)); } else { BuyOfferFormData form = formData.get(); BuyOfferDB.addBuyOffer(form); Map<String, Boolean> studentMap = StudentDB.getStudentNames(form.student); Map<String, Boolean> bookMap = TextbookDB.getTextbookNames(form.textbook); return ok(ManageBuyOffer.render("Manage Student", formData, studentMap, bookMap)); } } /** * Render form for creating a new SellOffer. * @return The SellOffer data page. */ public static Result newSellOffer() { SellOfferFormData data = new SellOfferFormData(); Form<SellOfferFormData> formData = Form.form(SellOfferFormData.class).fill(data); Map<String, Boolean> studentMap = StudentDB.getStudentNames(); return ok(ManageSellOffer.render("Add New Sell-Offer", formData, studentMap)); } /** * Renders page after submitting form data. * @return The SellOffer page. */ public static Result postSellOffer() { Form<SellOfferFormData> formData = Form.form(SellOfferFormData.class).bindFromRequest(); if (formData.hasErrors()) { Map<String, Boolean> studentMap = StudentDB.getStudentNames(); return badRequest(ManageSellOffer.render("Manage Sell-Offer", formData, studentMap)); } else { SellOfferFormData form = formData.get(); SellOfferDB.addSellOffer(form); Map<String, Boolean> studentMap = StudentDB.getStudentNames(form.student.getEmail()); return ok(ManageSellOffer.render("Manage Sell-Offer", formData, studentMap)); } } /** * Renders page after submitting form data. * @return The Student page. */ public static Result postStudent() { Form<StudentFormData> formData = Form.form(StudentFormData.class).bindFromRequest(); if (formData.hasErrors()) { return badRequest(ManageStudent.render("Manage Student", formData, false)); } else { StudentFormData form = formData.get(); StudentDB.addStudent(form); return ok(Students.render(StudentDB.getStudents())); } } /** * Renders page for editing a Student. * @param email Email of the Student to edit. * @return The Student form. */ public static Result manageStudent(String email) { if (StudentDB.isEmailTaken(email)) { StudentFormData data = new StudentFormData(StudentDB.getStudent(email)); Form<StudentFormData> formData = Form.form(StudentFormData.class).fill(data); return ok(ManageStudent.render("Manage Student", formData, true)); } else { return badRequest(Index.render("nope.avi")); } } /** * Renders page after submitting form data. * @return The Textbook page. */ public static Result postTextbook() { Form<TextbookFormData> formData = Form.form(TextbookFormData.class).bindFromRequest(); List<String> conditions = TextbookCondtion.getCondition(); if (formData.hasErrors()) { return badRequest(ManageTextbook.render("Manage Textbook", formData, conditions, false)); } else { TextbookFormData form = formData.get(); TextbookDB.addTextbook(form); return ok(Textbooks.render(TextbookDB.getTextbooks())); } } /** * Renders page for editing a Textbook. * @param isbn ISBN of textbook to edit. * @return The Textbook form. */ public static Result manageTextbook(String isbn) { TextbookFormData data = new TextbookFormData(TextbookDB.getTextbook(isbn)); Form<TextbookFormData> formData = Form.form(TextbookFormData.class).fill(data); List<String> conditions = TextbookCondtion.getCondition(); return ok(ManageTextbook.render("Manage Textbook", formData, conditions, true)); } public static Result matches() { Map<String, Boolean> studentMap = StudentDB.getStudentNames(); List<BuyOffer> buyOffers = BuyOfferDB.getBuyOffers(); return ok(Matches.render(studentMap, buyOffers)); } }
app/controllers/Application.java
package controllers; import java.util.List; import java.util.Map; import models.BuyOffer; import models.BuyOfferDB; import models.SellOfferDB; import models.StudentDB; import models.TextbookDB; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import views.formdata.BuyOfferFormData; import views.formdata.SellOfferFormData; import views.formdata.StudentFormData; import views.formdata.TextbookCondtion; import views.formdata.TextbookFormData; import views.html.Index; import views.html.ManageBuyOffer; import views.html.ManageSellOffer; import views.html.ManageStudent; import views.html.ManageTextbook; import views.html.Matches; import views.html.Students; import views.html.Textbooks; import views.html.BuyOffers; import views.html.SellOffers; /** * Implements the controllers for this application. */ public class Application extends Controller { /** * Returns the home page. * @return The resulting home page. */ public static Result index() { return ok(Index.render("Welcome to the home page.")); } /** * Returns the show students page. * @return The show students page. */ public static Result showStudents() { return ok(Students.render(StudentDB.getStudents())); } /** * Returns the show textbooks page. * @return The show textbooks page. */ public static Result showTextbooks() { return ok(Textbooks.render(TextbookDB.getTextbooks())); } /** * Returns the showBuyOffers page. * @return The showBuyOffers page. */ public static Result showBuyOffers() { return ok(BuyOffers.render(BuyOfferDB.getBuyOffers())); } /** * Returns the showSellOffers page. * @return The showSellOffers page. */ public static Result showSellOffers() { return ok(SellOffers.render(SellOfferDB.getSellOffers())); } /** * The Student data form page. * @return The Student data form page. */ public static Result newStudent() { StudentFormData data = new StudentFormData(); Form<StudentFormData> formData = Form.form(StudentFormData.class).fill(data); return ok(ManageStudent.render("Add New Surfer", formData, false)); } /** * The Textbook data form page. * @return The Textbook data form page. */ public static Result newTextbook() { TextbookFormData data = new TextbookFormData(); Form<TextbookFormData> formData = Form.form(TextbookFormData.class).fill(data); List<String> conditions = TextbookCondtion.getCondition(); return ok(ManageTextbook.render("Add New Textbook", formData, conditions, false)); } /** * Render form for creating a new BuyOffer. * @return The BuyOffer data page. */ public static Result newBuyOffer() { BuyOfferFormData data = new BuyOfferFormData(); Form<BuyOfferFormData> formData = Form.form(BuyOfferFormData.class).fill(data); Map<String, Boolean> studentMap = StudentDB.getStudentNames(); Map<String, Boolean> bookMap = TextbookDB.getTextbookNames(); return ok(ManageBuyOffer.render("Add New Buy-Offer", formData, studentMap, bookMap)); } /** * Renders page after submitting form data. * @return The BuyOffer page. */ public static Result postBuyOffer() { Form<BuyOfferFormData> formData = Form.form(BuyOfferFormData.class).bindFromRequest(); if (formData.hasErrors()) { Map<String, Boolean> studentMap = StudentDB.getStudentNames(); Map<String, Boolean> bookMap = TextbookDB.getTextbookNames(); return badRequest(ManageBuyOffer.render("Manage Buy-Offer", formData, studentMap, bookMap)); } else { BuyOfferFormData form = formData.get(); BuyOfferDB.addBuyOffer(form); Map<String, Boolean> studentMap = StudentDB.getStudentNames(form.student); Map<String, Boolean> bookMap = TextbookDB.getTextbookNames(form.textbook); return ok(ManageBuyOffer.render("Manage Student", formData, studentMap, bookMap)); } } /** * Render form for creating a new SellOffer. * @return The SellOffer data page. */ public static Result newSellOffer() { SellOfferFormData data = new SellOfferFormData(); Form<SellOfferFormData> formData = Form.form(SellOfferFormData.class).fill(data); Map<String, Boolean> studentMap = StudentDB.getStudentNames(); return ok(ManageSellOffer.render("Add New Sell-Offer", formData, studentMap)); } /** * Renders page after submitting form data. * @return The SellOffer page. */ public static Result postSellOffer() { Form<SellOfferFormData> formData = Form.form(SellOfferFormData.class).bindFromRequest(); if (formData.hasErrors()) { Map<String, Boolean> studentMap = StudentDB.getStudentNames(); return badRequest(ManageSellOffer.render("Manage Sell-Offer", formData, studentMap)); } else { SellOfferFormData form = formData.get(); SellOfferDB.addSellOffer(form); Map<String, Boolean> studentMap = StudentDB.getStudentNames(form.student.getEmail()); return ok(ManageSellOffer.render("Manage Sell-Offer", formData, studentMap)); } } /** * Renders page after submitting form data. * @return The Student page. */ public static Result postStudent() { Form<StudentFormData> formData = Form.form(StudentFormData.class).bindFromRequest(); if (formData.hasErrors()) { return badRequest(ManageStudent.render("Manage Student", formData, true)); } else { StudentFormData form = formData.get(); StudentDB.addStudent(form); return ok(ManageStudent.render("Manage Student", formData, false)); } } /** * Renders page for editing a Student. * @param email Email of the Student to edit. * @return The Student form. */ public static Result manageStudent(String email) { if (StudentDB.isEmailTaken(email)) { StudentFormData data = new StudentFormData(StudentDB.getStudent(email)); Form<StudentFormData> formData = Form.form(StudentFormData.class).fill(data); return ok(ManageStudent.render("Manage Student", formData, true)); } else { return badRequest(Index.render("nope.avi")); } } /** * Renders page after submitting form data. * @return The Textbook page. */ public static Result postTextbook() { Form<TextbookFormData> formData = Form.form(TextbookFormData.class).bindFromRequest(); List<String> conditions = TextbookCondtion.getCondition(); if (formData.hasErrors()) { return badRequest(ManageTextbook.render("Manage Textbook", formData, conditions, true)); } else { TextbookFormData form = formData.get(); TextbookDB.addTextbook(form); return ok(ManageTextbook.render("Manage Textbook", formData, conditions, false)); } } /** * Renders page for editing a Textbook. * @param isbn ISBN of textbook to edit. * @return The Textbook form. */ public static Result manageTextbook(String isbn) { TextbookFormData data = new TextbookFormData(TextbookDB.getTextbook(isbn)); Form<TextbookFormData> formData = Form.form(TextbookFormData.class).fill(data); List<String> conditions = TextbookCondtion.getCondition(); return ok(ManageTextbook.render("Manage Textbook", formData, conditions, true)); } public static Result matches() { Map<String, Boolean> studentMap = StudentDB.getStudentNames(); List<BuyOffer> buyOffers = BuyOfferDB.getBuyOffers(); return ok(Matches.render(studentMap, buyOffers)); } }
Possible fix for adding error.
app/controllers/Application.java
Possible fix for adding error.
<ide><path>pp/controllers/Application.java <ide> public static Result postStudent() { <ide> Form<StudentFormData> formData = Form.form(StudentFormData.class).bindFromRequest(); <ide> if (formData.hasErrors()) { <del> return badRequest(ManageStudent.render("Manage Student", formData, true)); <add> return badRequest(ManageStudent.render("Manage Student", formData, false)); <ide> } <ide> else { <ide> StudentFormData form = formData.get(); <ide> StudentDB.addStudent(form); <del> return ok(ManageStudent.render("Manage Student", formData, false)); <add> return ok(Students.render(StudentDB.getStudents())); <ide> } <ide> } <ide> <ide> Form<TextbookFormData> formData = Form.form(TextbookFormData.class).bindFromRequest(); <ide> List<String> conditions = TextbookCondtion.getCondition(); <ide> if (formData.hasErrors()) { <del> return badRequest(ManageTextbook.render("Manage Textbook", formData, conditions, true)); <add> return badRequest(ManageTextbook.render("Manage Textbook", formData, conditions, false)); <ide> } <ide> else { <ide> TextbookFormData form = formData.get(); <ide> TextbookDB.addTextbook(form); <del> return ok(ManageTextbook.render("Manage Textbook", formData, conditions, false)); <add> return ok(Textbooks.render(TextbookDB.getTextbooks())); <ide> } <ide> } <ide>
Java
apache-2.0
dceccc4e72d5e8af76c56541b40395890f3eba6b
0
dell-oss/Doradus,shaunstanislaus/Doradus,kod3r/Doradus,dell-oss/Doradus,kod3r/Doradus,shaunstanislaus/Doradus,dell-oss/Doradus,shaunstanislaus/Doradus,kod3r/Doradus
/* * Copyright (C) 2014 Dell, 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.dell.doradus.service.spider; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.cassandra.utils.Pair; import com.dell.doradus.common.AggregateResult; import com.dell.doradus.common.ApplicationDefinition; import com.dell.doradus.common.BatchResult; import com.dell.doradus.common.CommonDefs; import com.dell.doradus.common.DBObject; import com.dell.doradus.common.DBObjectBatch; import com.dell.doradus.common.FieldDefinition; import com.dell.doradus.common.FieldType; import com.dell.doradus.common.RetentionAge; import com.dell.doradus.common.TableDefinition; import com.dell.doradus.common.UNode; import com.dell.doradus.common.Utils; import com.dell.doradus.common.TableDefinition.ShardingGranularity; import com.dell.doradus.fieldanalyzer.FieldAnalyzer; import com.dell.doradus.search.SearchResultList; import com.dell.doradus.search.aggregate.Aggregate; import com.dell.doradus.service.StorageService; import com.dell.doradus.service.db.DBService; import com.dell.doradus.service.db.DColumn; import com.dell.doradus.service.db.DRow; import com.dell.doradus.service.db.Tenant; import com.dell.doradus.service.schema.SchemaService; import com.dell.doradus.service.taskmanager.Task; import com.dell.doradus.service.taskmanager.TaskFrequency; /** * The main class for the SpiderService storage service. The Spider service stores objects * in a tabular database (currently Cassandra), providing fully inverted indexing, data * aging, and other features. */ public class SpiderService extends StorageService { // Maximum length of a ColumnFamily name: private static final int MAX_CF_NAME_LENGTH = 48; // Singleton object: private static final SpiderService INSTANCE = new SpiderService(); private final ShardCache m_shardCache = new ShardCache(); /** * Get the singleton instance of this service. The service may or may not have been * initialized yet. * * @return The singleton instance of this service. */ public static SpiderService instance() { return INSTANCE; } // instance //----- Service methods @Override public void initService() { } // initService @Override public void startService() { SchemaService.instance().waitForFullService(); } // startService @Override public void stopService() { m_shardCache.clearAll(); } // stopService //----- StorageService schema update methods // Delete all CFs used by the given application. @Override public void deleteApplication(ApplicationDefinition appDef) { checkServiceState(); deleteApplicationCFs(appDef); m_shardCache.clear(appDef); } // deleteApplication // Create all CFs needed for the given application. @Override public void initializeApplication(ApplicationDefinition oldAppDef, ApplicationDefinition appDef) { checkServiceState(); Tenant tenant = Tenant.getTenant(appDef); verifyApplicationCFs(tenant.getKeyspace(), oldAppDef, appDef); } // initializeApplication // Verify that the given application's options are valid for the Spider service. @Override public void validateSchema(ApplicationDefinition appDef) { checkServiceState(); validateApplication(appDef); } // validateSchema @Override public Collection<Task> getAppTasks(ApplicationDefinition appDef) { List<Task> appTasks = new ArrayList<>(); for (TableDefinition tableDef : appDef.getTableDefinitions().values()) { String agingFreq = tableDef.getOption(CommonDefs.OPT_AGING_CHECK_FREQ); if (agingFreq != null) { Task task = new Task(appDef.getAppName(), tableDef.getTableName(), "data-aging", agingFreq, SpiderDataAger.class); appTasks.add(task); } } return appTasks; } // getAppTasks //----- StorageService object query methods /** * Get all scalar and link fields for the object in the given table with the given ID. * * @param tableDef {@link TableDefinition} in which object resides. * @param objID Object ID. * @return {@link DBObject} containing all object scalar and link fields, or * null if there is no such object. */ @Override public DBObject getObject(TableDefinition tableDef, String objID) { checkServiceState(); String storeName = objectsStoreName(tableDef); Iterator<DColumn> colIter = DBService.instance().getAllColumns(Tenant.getTenant(tableDef), storeName, objID); if (colIter == null) { return null; } DBObject dbObj = createObject(tableDef, objID, colIter); addShardedLinkValues(tableDef, dbObj); return dbObj; } // getObject @Override public SearchResultList objectQueryURI(TableDefinition tableDef, String uriQuery) { checkServiceState(); return new ObjectQuery(tableDef, uriQuery).query(); } // objectQueryURI @Override public SearchResultList objectQueryDoc(TableDefinition tableDef, UNode rootNode) { checkServiceState(); return new ObjectQuery(tableDef, rootNode).query(); } // objectQueryDoc @Override public AggregateResult aggregateQueryURI(TableDefinition tableDef, String uriQuery) { checkServiceState(); Aggregate aggregate = new Aggregate(tableDef); aggregate.parseParameters(uriQuery); try { aggregate.execute(); } catch (IOException e) { throw new RuntimeException("Aggregation failed with " + e); } return aggregate.getResult(); } // aggregateQuery @Override public AggregateResult aggregateQueryDoc(TableDefinition tableDef, UNode rootNode) { checkServiceState(); Aggregate aggregate = new Aggregate(tableDef); aggregate.parseParameters(rootNode); try { aggregate.execute(); } catch (IOException e) { throw new RuntimeException("Aggregation failed with " + e); } return aggregate.getResult(); } // aggregateQuery //----- StorageService object update methods // Add and/or update a batch of objects. For a Spider application, the store name must // be a table name. @Override public BatchResult addBatch(ApplicationDefinition appDef, String tableName, DBObjectBatch batch) { return addBatch(appDef, tableName, batch, null); } // addBatch // Add and/or update a batch of objects. For a Spider application, the store name must // be a table name. @Override public BatchResult addBatch(ApplicationDefinition appDef, String tableName, DBObjectBatch batch, Map<String, String> options) { checkServiceState(); TableDefinition tableDef = appDef.getTableDef(tableName); Utils.require(tableDef != null || appDef.allowsAutoTables(), "Unknown table for application '%s': %s", appDef.getAppName(), tableName); Utils.require(options == null || options.size() == 0, "No parameters expected"); if (tableDef == null && appDef.allowsAutoTables()) { tableDef = addAutoTable(appDef, tableName); } BatchObjectUpdater batchUpdater = new BatchObjectUpdater(tableDef); return batchUpdater.addBatch(batch); } // addBatch // Delete a batch of objects. For a Spider application, the store name must be a table // name, and (for now) all objects in the batch must belong to that table. @Override public BatchResult deleteBatch(ApplicationDefinition appDef, String tableName, DBObjectBatch batch) { checkServiceState(); TableDefinition tableDef = appDef.getTableDef(tableName); Utils.require(tableDef != null, "Unknown table for application '%s': %s", appDef.getAppName(), tableName); Set<String> objIDSet = new HashSet<>(); for (DBObject dbObj : batch.getObjects()) { Utils.require(!Utils.isEmpty(dbObj.getObjectID()), "All objects must have _ID defined"); objIDSet.add(dbObj.getObjectID()); } BatchObjectUpdater batchUpdater = new BatchObjectUpdater(tableDef); return batchUpdater.deleteBatch(objIDSet); } // deleteBatch // Same as addBatch() @Override public BatchResult updateBatch(ApplicationDefinition appDef, String storeName, DBObjectBatch batch) { return addBatch(appDef, storeName, batch, null); } // updateBatch // Same as addBatch() @Override public BatchResult updateBatch(ApplicationDefinition appDef, String storeName, DBObjectBatch batch, Map<String, String> paramMap) { return addBatch(appDef, storeName, batch, paramMap); } // updateBatch //----- SpiderService-specific public static methods /** * Return the column name used to store the given value for the given link. The column * name uses the format: * <pre> * ~{link name}/{object ID} * </pre> * This method should be used for unsharded links or link values to that refer to an * object whose shard number is 0. * * @param linkDef {@link FieldDefinition} of a link. * @param objID ID of an object referenced by the link. * @return Column name that is used to store a value for the given link and * object ID. * @see #shardedLinkTermRowKey(FieldDefinition, String, int) */ public static String linkColumnName(FieldDefinition linkDef, String objID) { assert linkDef.isLinkField(); StringBuilder buffer = new StringBuilder(); buffer.append("~"); buffer.append(linkDef.getName()); buffer.append("/"); buffer.append(objID); return buffer.toString(); } // linkColumnName /** * Return the store name (ColumnFamily) in which objects are stored for the given table. * This name is either {table name} or {application name}_{table name} truncated to * {@link #MAX_CF_NAME_LENGTH} if needed. * * @param tableDef {@link TableDefinition} of a table. * @return Store name (ColumnFamily) in which objects are stored for the given * table. */ public static String objectsStoreName(TableDefinition tableDef) { String storeName = null; storeName = tableDef.getAppDef().getAppName() + "_" + tableDef.getTableName(); return Utils.truncateTo(storeName, MAX_CF_NAME_LENGTH); } // objectsStoreName /** * Convert the given scalar value to binary form. This method returns the appropriate * format for storage based on the scalar's type. This method is the twin of * {@link #scalarValueToString(TableDefinition, String, byte[])} * * @param tableDef {@link TableDefinition} of table in which field resides. * @param fieldName Scalar field name. * @param fieldValue Field value in string form (may be null). * @return Binary storage format. */ public static byte[] scalarValueToBinary(TableDefinition tableDef, String fieldName, String fieldValue) { if (fieldValue == null || fieldValue.length() == 0) { return null; // means "don't store". } FieldDefinition fieldDef = tableDef.getFieldDef(fieldName); if (fieldDef != null && fieldDef.isBinaryField()) { return fieldDef.getEncoding().decode(fieldValue); } else { return Utils.toBytes(fieldValue); } } // scalarValueToBinary /** * Convert the given binary scalar field value to string form based on its definition. * This method is the twin of * {@link #scalarValueToBinary(TableDefinition, String, String)}. * * @param tableDef TableDefinition that defines field. * @param fieldName Name of a scalar field. * @param colValue Binary column value. * @return Scalar value as a string. */ public static String scalarValueToString(TableDefinition tableDef, String fieldName, byte[] colValue) { // Only binary fields are treated specially. FieldDefinition fieldDef = tableDef.getFieldDef(fieldName); if (fieldDef != null && fieldDef.isBinaryField()) { return fieldDef.getEncoding().encode(colValue); } else { return Utils.toString(colValue); } } // scalarValueToString /** * Return the row key for the Terms record that represents a link shard record for the * given link, owned by the given object ID, referencing target objects in the given * shard. The key format is: * <pre> * {shard number}/{link name}/{object ID} * </pre> * * @param linkDef {@link FieldDefinition} of a sharded link. * @param objID ID of object that owns link field. * @param shardNumber Shard number in the link's extent table. * @return */ public static String shardedLinkTermRowKey(FieldDefinition linkDef, String objID, int shardNumber) { assert linkDef.isLinkField() && linkDef.isSharded() && shardNumber > 0; StringBuilder shardPrefix = new StringBuilder(); shardPrefix.append(shardNumber); shardPrefix.append("/"); shardPrefix.append(linkColumnName(linkDef, objID)); return shardPrefix.toString(); } // shardedLinkTermRowKey /** * Create the Terms row key for the given table, object, field name, and term. * * @param tableDef {@link TableDefinition} of table that owns object. * @param dbObj DBObject that owns field. * @param fieldName Field name. * @param term Term to be indexed. * @return */ public static String termIndexRowKey(TableDefinition tableDef, DBObject dbObj, String fieldName, String term) { StringBuilder termRecKey = new StringBuilder(); int shardNumber = tableDef.getShardNumber(dbObj); if (shardNumber > 0) { termRecKey.append(shardNumber); termRecKey.append("/"); } termRecKey.append(FieldAnalyzer.makeTermKey(fieldName, term)); return termRecKey.toString(); } // termIndexRowKey /** * Return the store name (ColumnFamily) in which terms are stored for the given table. * This name is the object store name appended with "_terms". If the object store name * is too long, it is truncated so that the terms store name is less than * {@link #MAX_CF_NAME_LENGTH}. * * @param tableDef {@link TableDefinition} of a table. * @return Store name (ColumnFamily) in which terms are stored for the given * table. */ public static String termsStoreName(TableDefinition tableDef) { String objStoreName = Utils.truncateTo(objectsStoreName(tableDef), MAX_CF_NAME_LENGTH - "_Terms".length()); return objStoreName + "_Terms"; } // termsStoreName //----- SpiderService public methods /** * Retrieve the requested scalar fields for the given object IDs in the given table. * The map returned is object IDs -> field names -> field values. The map will be * empty (but not null) if (1) objIDs is empty, (2) fieldNames is empty, or (3) none * of the requested object IDs were found. An entry in the outer map may exist with an * empty field map if none of the requested fields were found for the corresponding * object. * * @param tableDef {@link TableDefinition} of table to query. * @param objIDs Collection of object IDs to fetch. * @param fieldNames Collection of field names to fetch. * @return Map of object IDs -> field names -> field values for all * objects found. Objects not found will have no entry in the * outer map. The map will be empty if no objects were found. */ public Map<String, Map<String, String>> getObjectScalars(TableDefinition tableDef, Collection<String> objIDs, Collection<String> fieldNames) { checkServiceState(); Map<String, Map<String, String>> objScalarMap = new HashMap<>(); if (objIDs.size() > 0 && fieldNames.size() > 0) { String storeName = objectsStoreName(tableDef); Iterator<DRow> rowIter = DBService.instance().getRowsColumns(Tenant.getTenant(tableDef), storeName, objIDs, fieldNames); while (rowIter.hasNext()) { DRow row = rowIter.next(); Map<String, String> scalarMap = new HashMap<>(); objScalarMap.put(row.getKey(), scalarMap); Iterator<DColumn> colIter = row.getColumns(); while (colIter.hasNext()) { DColumn col = colIter.next(); String fieldValue = scalarValueToString(tableDef, col.getName(), col.getRawValue()); scalarMap.put(col.getName(), fieldValue); } } } return objScalarMap; } // getObjectScalars /** * Retrieve a single scalar field for the given object IDs in the given table. * The map returned is object IDs -> field value. The map will be empty (but not null) * if objIDs is empty or none of the requested object IDs have a value for the * requested field name. * * @param tableDef {@link TableDefinition} of table to query. * @param objIDs Collection of object IDs to fetch. * @param fieldName Scalar field name to get values for. * @return Map of object IDs -> field values for values found. */ public Map<String, String> getObjectScalar(TableDefinition tableDef, Collection<String> objIDs, String fieldName) { checkServiceState(); Map<String, String> objScalarMap = new HashMap<>(); if (objIDs.size() > 0) { String storeName = objectsStoreName(tableDef); Iterator<DRow> rowIter = DBService.instance().getRowsColumns(Tenant.getTenant(tableDef), storeName, objIDs, Arrays.asList(fieldName)); while (rowIter.hasNext()) { DRow row = rowIter.next(); Iterator<DColumn> colIter = row.getColumns(); while (colIter.hasNext()) { DColumn col = colIter.next(); if (col.getName().equals(fieldName)) { String fieldValue = scalarValueToString(tableDef, col.getName(), col.getRawValue()); objScalarMap.put(row.getKey(), fieldValue); } } } } return objScalarMap; } // getObjectScalar /** * Get the starting date of the shard with the given number in the given sharded * table. If the given table has not yet started the given shard, null is returned. * * @param tableDef {@link TableDefinition} of a sharded table. * @param shardNumber Shard number (must be > 0). * @return Start date of the given shard or null if no objects have been * stored in the given shard yet. */ public void verifyShard(TableDefinition tableDef, int shardNumber) { assert tableDef.isSharded(); assert shardNumber > 0; checkServiceState(); m_shardCache.verifyShard(tableDef, shardNumber); } // verifyShard /** * Get all known shards for the given table. Each shard is defined in a column in the * "_shards" row of the table's Terms store. If the given table is not sharded, an * empty map is returned. * * @param tableDef Sharded table to get current shards for. * @return Map of shard numbers to shard start dates. May be empty but will * not be null. */ public Map<Integer, Date> getShards(TableDefinition tableDef) { checkServiceState(); if (tableDef.isSharded()) { return m_shardCache.getShardMap(tableDef); } else { return new HashMap<>(); } } // getShards //----- Private methods // Singleton creation only private SpiderService() {} // Add an implicit table to the given application and return its new TableDefinition. private TableDefinition addAutoTable(ApplicationDefinition appDef, String tableName) { m_logger.debug("Adding implicit table '{}' to application '{}'", tableName, appDef.getAppName()); Tenant tenant = Tenant.getTenant(appDef); TableDefinition tableDef = new TableDefinition(appDef); tableDef.setTableName(tableName); appDef.addTable(tableDef); SchemaService.instance().defineApplication(appDef); appDef = SchemaService.instance().getApplication(tenant, appDef.getAppName()); return appDef.getTableDef(tableName); } // addAutoTable // Add sharded link values, if any, to the given DBObject. private void addShardedLinkValues(TableDefinition tableDef, DBObject dbObj) { for (FieldDefinition fieldDef : tableDef.getFieldDefinitions()) { if (fieldDef.isLinkField() && fieldDef.isSharded()) { TableDefinition extentTableDef = tableDef.getLinkExtentTableDef(fieldDef); Set<Integer> shardNums = getShards(extentTableDef).keySet(); Set<String> values = getShardedLinkValues(dbObj.getObjectID(), fieldDef, shardNums); dbObj.addFieldValues(fieldDef.getName(), values); } } } // addShardedlinkValues // Create a DBObject from the given scalar/link column values. private DBObject createObject(TableDefinition tableDef, String objID, Iterator<DColumn> colIter) { DBObject dbObj = new DBObject(); dbObj.setObjectID(objID); while (colIter.hasNext()) { DColumn col = colIter.next(); Pair<String, String> linkCol = extractLinkValue(tableDef, col.getName()); if (linkCol == null) { String fieldName = col.getName(); String fieldValue = scalarValueToString(tableDef, col.getName(), col.getRawValue()); FieldDefinition fieldDef = tableDef.getFieldDef(fieldName); if (fieldDef != null && fieldDef.isCollection()) { // MV scalar field Set<String> values = Utils.split(fieldValue, CommonDefs.MV_SCALAR_SEP_CHAR); dbObj.addFieldValues(fieldName, values); } else { dbObj.addFieldValue(col.getName(), fieldValue); } // Skip links no longer present in schema } else if (tableDef.isLinkField(linkCol.left)) { dbObj.addFieldValue(linkCol.left, linkCol.right); } } return dbObj; } // createObject // Delete all ColumnFamilies used by the given application. Only delete the ones that // actually exist in case a previous delete-app failed. private void deleteApplicationCFs(ApplicationDefinition appDef) { // Table-level CFs: Tenant tenant = Tenant.getTenant(appDef); for (TableDefinition tableDef : appDef.getTableDefinitions().values()) { DBService.instance().deleteStoreIfPresent(tenant, objectsStoreName(tableDef)); DBService.instance().deleteStoreIfPresent(tenant, termsStoreName(tableDef)); } } // deleteApplicationCFs // Get all target object IDs for the given sharded link. private Set<String> getShardedLinkValues(String objID, FieldDefinition linkDef, Set<Integer> shardNums) { Set<String> values = new HashSet<String>(); if (shardNums.size() == 0) { return values; } // Construct row keys for the link's possible Terms records. Set<String> termRowKeys = new HashSet<String>(); for (Integer shardNumber : shardNums) { termRowKeys.add(shardedLinkTermRowKey(linkDef, objID, shardNumber)); } TableDefinition tableDef = linkDef.getTableDef(); String termStore = termsStoreName(linkDef.getTableDef()); Iterator<DRow> rowIter = DBService.instance().getRowsAllColumns(Tenant.getTenant(tableDef), termStore, termRowKeys); // We only need the column names from each row. while (rowIter.hasNext()) { DRow row = rowIter.next(); Iterator<DColumn> colIter = row.getColumns(); while (colIter.hasNext()) { values.add(colIter.next().getName()); } } return values; } // getShardedLinkValues // If the given column name represents a link value, return the link's field name and // target object ID as a Pair<String, String> private Pair<String, String> extractLinkValue(TableDefinition tableDef, String colName) { if (colName.length() < 3 || colName.charAt(0) != '~') { return null; } // A '/' should separate the field name and object ID value. Example: ~foo/xyz int slashInx = 1; while (slashInx < colName.length() && colName.charAt(slashInx) != '/') { slashInx++; } if (slashInx >= colName.length()) { return null; } String fieldName = colName.substring(1, slashInx); String objID = colName.substring(slashInx + 1); return Pair.create(fieldName, objID); } // extractLinkValue // Verify that the given shard-starting date is in the format YYYY-MM-DD. If the format // is bad, just return false. private boolean isValidShardDate(String shardDate) { try { // If the format is invalid, a ParseException is thrown. Utils.dateFromString(shardDate); return true; } catch (IllegalArgumentException ex) { return false; } } // isValidShardDate // Validate the given application against SpiderService-specific constraints. private void validateApplication(ApplicationDefinition appDef) { boolean bAutoTablesSet = false; for (String optName : appDef.getOptionNames()) { String optValue = appDef.getOption(optName); switch (optName) { case CommonDefs.AUTO_TABLES: validateBooleanOption(optName, optValue); bAutoTablesSet = true; break; case CommonDefs.OPT_STORAGE_SERVICE: assert optValue.equals(this.getClass().getSimpleName()); break; case CommonDefs.OPT_TENANT: // Ignore break; default: throw new IllegalArgumentException("Unknown option for SpiderService application: " + optName); } } if (!bAutoTablesSet) { // For backwards compatibility, default AutoTables to true. appDef.setOption(CommonDefs.AUTO_TABLES, "true"); } for (TableDefinition tableDef : appDef.getTableDefinitions().values()) { validateTable(tableDef); } } // validateApplication // Validate that the given string is a valid Booleab value. private void validateBooleanOption(String optName, String optValue) { if (!optValue.equalsIgnoreCase("true") && !optValue.equalsIgnoreCase("false")) { throw new IllegalArgumentException("Boolean value expected for '" + optName + "' option: " + optValue); } } // validateBooleanOption // Validate the given field against SpiderService-specific constraints. private void validateField(FieldDefinition fieldDef) { Utils.require(!fieldDef.isXLinkField(), "Xlink fields are not allowed in Spider applications"); // Validate scalar field analyzer. if (fieldDef.isScalarField()) { String analyzerName = fieldDef.getAnalyzerName(); if (Utils.isEmpty(analyzerName)) { analyzerName = FieldType.getDefaultAnalyzer(fieldDef.getType()); fieldDef.setAnalyzer(analyzerName); } FieldAnalyzer.verifyAnalyzer(fieldDef); } } // validateField // Validate the given table against SpiderService-specific constraints. private void validateTable(TableDefinition tableDef) { boolean bSawDataAging = false; for (String optName : tableDef.getOptionNames()) { String optValue = tableDef.getOption(optName); switch (optName) { case CommonDefs.OPT_AGING_FIELD: validateTableOptionAgingField(tableDef, optValue); break; case CommonDefs.OPT_RETENTION_AGE: validateTableOptionRetentionAge(tableDef, optValue); break; case CommonDefs.OPT_SHARDING_FIELD: validateTableOptionShardingField(tableDef, optValue); break; case CommonDefs.OPT_SHARDING_GRANULARITY: validateTableOptionShardingGranularity(tableDef, optValue); break; case CommonDefs.OPT_SHARDING_START: validateTableOptionShardingStart(tableDef, optValue); break; case CommonDefs.OPT_AGING_CHECK_FREQ: validateTableOptionAgingCheckFrequency(tableDef, optValue); bSawDataAging = true; break; default: Utils.require(false, "Unknown option for SpiderService table: " + optName); } } for (FieldDefinition fieldDef : tableDef.getFieldDefinitions()) { validateField(fieldDef); } if (!bSawDataAging && tableDef.isOptionSet(CommonDefs.OPT_AGING_FIELD)) { tableDef.setOption(CommonDefs.OPT_AGING_CHECK_FREQ, "1 DAY"); } } // validateTable // Validate the table option "aging-check-frequency" private void validateTableOptionAgingCheckFrequency(TableDefinition tableDef, String optValue) { new TaskFrequency(optValue); Utils.require(tableDef.getOption(CommonDefs.OPT_AGING_FIELD) != null, "Option 'aging-check-frequency' requires option 'aging-field'"); } // validateTableOptionAgingCheckFrequency // Validate the table option "aging-field". private void validateTableOptionAgingField(TableDefinition tableDef, String optValue) { FieldDefinition agingFieldDef = tableDef.getFieldDef(optValue); Utils.require(agingFieldDef != null, "Aging field has not been defined: " + optValue); assert agingFieldDef != null; // Make FindBugs happy Utils.require(agingFieldDef.getType() == FieldType.TIMESTAMP, "Aging field must be a timestamp field: " + optValue); Utils.require(tableDef.getOption(CommonDefs.OPT_RETENTION_AGE) != null, "Option 'aging-field' requires option 'retention-age'"); } // validateTableOptionAgingField // Validate the table option "retention-age". private void validateTableOptionRetentionAge(TableDefinition tableDef, String optValue) { RetentionAge retAge = new RetentionAge(optValue); // throws if invalid format optValue = retAge.toString(); tableDef.setOption(CommonDefs.OPT_RETENTION_AGE, optValue); // rewrite value Utils.require(tableDef.getOption(CommonDefs.OPT_AGING_FIELD) != null, "Option 'retention-age' requires option 'aging-field'"); } // validateTableOptionRetentionAge // Validate the table option "sharding-field". private void validateTableOptionShardingField(TableDefinition tableDef, String optValue) { // Verify that the sharding-field exists and is a timestamp field. FieldDefinition shardingFieldDef = tableDef.getFieldDef(optValue); Utils.require(shardingFieldDef != null, "Sharding field has not been defined: " + optValue); assert shardingFieldDef != null; // Make FindBugs happy Utils.require(shardingFieldDef.getType() == FieldType.TIMESTAMP, "Sharding field must be a timestamp field: " + optValue); Utils.require(!shardingFieldDef.isCollection(), "Sharding field cannot be a collection: " + optValue); // Default sharding-granularity to MONTH. if (tableDef.getOption(CommonDefs.OPT_SHARDING_GRANULARITY) == null) { tableDef.setOption(CommonDefs.OPT_SHARDING_GRANULARITY, "MONTH"); } // Default sharding-start to "tomorrow". if (tableDef.getOption(CommonDefs.OPT_SHARDING_START) == null) { GregorianCalendar startDate = new GregorianCalendar(Utils.UTC_TIMEZONE); startDate.add(Calendar.DAY_OF_MONTH, 1); // adds 1 day String startOpt = String.format("%04d-%02d-%02d", startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH)+1, // 0-relative! startDate.get(Calendar.DAY_OF_MONTH)); tableDef.setOption(CommonDefs.OPT_SHARDING_START, startOpt); } } // validateTableOptionShardingField // Validate the table option "sharding-granularity". private void validateTableOptionShardingGranularity(TableDefinition tableDef, String optValue) { ShardingGranularity shardingGranularity = ShardingGranularity.fromString(optValue); Utils.require(shardingGranularity != null, "Unrecognized 'sharding-granularity' value: " + optValue); // 'sharding-granularity' requires 'sharding-field' Utils.require(tableDef.getOption(CommonDefs.OPT_SHARDING_FIELD) != null, "Option 'sharding-granularity' requires option 'sharding-field'"); } // validateTableOptionShardingGranularity // Validate the table option "sharding-start". private void validateTableOptionShardingStart(TableDefinition tableDef, String optValue) { Utils.require(isValidShardDate(optValue), "'sharding-start' must be YYYY-MM-DD: " + optValue); GregorianCalendar shardingStartDate = new GregorianCalendar(Utils.UTC_TIMEZONE); shardingStartDate.setTime(Utils.dateFromString(optValue)); // 'sharding-start' requires 'sharding-field' Utils.require(tableDef.getOption(CommonDefs.OPT_SHARDING_FIELD) != null, "Option 'sharding-start' requires option 'sharding-field'"); } // validateTableOptionShardingStart // Verify that all ColumnFamilies needed for the given application exist. private void verifyApplicationCFs(String keyspace, ApplicationDefinition oldAppDef, ApplicationDefinition appDef) { // Add new table-level CFs: DBService dbService = DBService.instance(); Tenant tenant = Tenant.getTenant(appDef); for (TableDefinition tableDef : appDef.getTableDefinitions().values()) { dbService.createStoreIfAbsent(tenant, objectsStoreName(tableDef), true); dbService.createStoreIfAbsent(tenant, termsStoreName(tableDef), true); } // Delete obsolete table-level CFs: if (oldAppDef != null) { for (TableDefinition oldTableDef : oldAppDef.getTableDefinitions().values()) { if (appDef.getTableDef(oldTableDef.getTableName()) == null) { dbService.deleteStoreIfPresent(tenant, objectsStoreName(oldTableDef)); dbService.deleteStoreIfPresent(tenant, termsStoreName(oldTableDef)); } } } } // verifyApplicationCFs } // class SpiderService
doradus-server/src/com/dell/doradus/service/spider/SpiderService.java
/* * Copyright (C) 2014 Dell, 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.dell.doradus.service.spider; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.cassandra.utils.Pair; import com.dell.doradus.common.AggregateResult; import com.dell.doradus.common.ApplicationDefinition; import com.dell.doradus.common.BatchResult; import com.dell.doradus.common.CommonDefs; import com.dell.doradus.common.DBObject; import com.dell.doradus.common.DBObjectBatch; import com.dell.doradus.common.FieldDefinition; import com.dell.doradus.common.FieldType; import com.dell.doradus.common.RetentionAge; import com.dell.doradus.common.TableDefinition; import com.dell.doradus.common.UNode; import com.dell.doradus.common.Utils; import com.dell.doradus.common.TableDefinition.ShardingGranularity; import com.dell.doradus.fieldanalyzer.FieldAnalyzer; import com.dell.doradus.search.SearchResultList; import com.dell.doradus.search.aggregate.Aggregate; import com.dell.doradus.service.StorageService; import com.dell.doradus.service.db.DBService; import com.dell.doradus.service.db.DColumn; import com.dell.doradus.service.db.DRow; import com.dell.doradus.service.db.Tenant; import com.dell.doradus.service.schema.SchemaService; import com.dell.doradus.service.taskmanager.Task; import com.dell.doradus.service.taskmanager.TaskFrequency; /** * The main class for the SpiderService storage service. The Spider service stores objects * in a tabular database (currently Cassandra), providing fully inverted indexing, data * aging, and other features. */ public class SpiderService extends StorageService { // Maximum length of a ColumnFamily name: private static final int MAX_CF_NAME_LENGTH = 48; // Singleton object: private static final SpiderService INSTANCE = new SpiderService(); private final ShardCache m_shardCache = new ShardCache(); /** * Get the singleton instance of this service. The service may or may not have been * initialized yet. * * @return The singleton instance of this service. */ public static SpiderService instance() { return INSTANCE; } // instance //----- Service methods @Override public void initService() { } // initService @Override public void startService() { SchemaService.instance().waitForFullService(); } // startService @Override public void stopService() { m_shardCache.clearAll(); } // stopService //----- StorageService schema update methods // Delete all CFs used by the given application. @Override public void deleteApplication(ApplicationDefinition appDef) { checkServiceState(); deleteApplicationCFs(appDef); m_shardCache.clear(appDef); } // deleteApplication // Create all CFs needed for the given application. @Override public void initializeApplication(ApplicationDefinition oldAppDef, ApplicationDefinition appDef) { checkServiceState(); Tenant tenant = Tenant.getTenant(appDef); verifyApplicationCFs(tenant.getKeyspace(), oldAppDef, appDef); } // initializeApplication // Verify that the given application's options are valid for the Spider service. @Override public void validateSchema(ApplicationDefinition appDef) { checkServiceState(); validateApplication(appDef); } // validateSchema @Override public Collection<Task> getAppTasks(ApplicationDefinition appDef) { List<Task> appTasks = new ArrayList<>(); for (TableDefinition tableDef : appDef.getTableDefinitions().values()) { String agingFreq = tableDef.getOption(CommonDefs.OPT_AGING_CHECK_FREQ); if (agingFreq != null) { Task task = new Task(appDef.getAppName(), tableDef.getTableName(), "data-aging", agingFreq, SpiderDataAger.class); appTasks.add(task); } } return appTasks; } // getAppTasks //----- StorageService object query methods /** * Get all scalar and link fields for the object in the given table with the given ID. * * @param tableDef {@link TableDefinition} in which object resides. * @param objID Object ID. * @return {@link DBObject} containing all object scalar and link fields, or * null if there is no such object. */ @Override public DBObject getObject(TableDefinition tableDef, String objID) { checkServiceState(); String storeName = objectsStoreName(tableDef); Iterator<DColumn> colIter = DBService.instance().getAllColumns(Tenant.getTenant(tableDef), storeName, objID); if (colIter == null) { return null; } DBObject dbObj = createObject(tableDef, objID, colIter); addShardedLinkValues(tableDef, dbObj); return dbObj; } // getObject @Override public SearchResultList objectQueryURI(TableDefinition tableDef, String uriQuery) { checkServiceState(); return new ObjectQuery(tableDef, uriQuery).query(); } // objectQueryURI @Override public SearchResultList objectQueryDoc(TableDefinition tableDef, UNode rootNode) { checkServiceState(); return new ObjectQuery(tableDef, rootNode).query(); } // objectQueryDoc @Override public AggregateResult aggregateQueryURI(TableDefinition tableDef, String uriQuery) { checkServiceState(); Aggregate aggregate = new Aggregate(tableDef); aggregate.parseParameters(uriQuery); try { aggregate.execute(); } catch (IOException e) { throw new RuntimeException("Aggregation failed with " + e); } return aggregate.getResult(); } // aggregateQuery @Override public AggregateResult aggregateQueryDoc(TableDefinition tableDef, UNode rootNode) { checkServiceState(); Aggregate aggregate = new Aggregate(tableDef); aggregate.parseParameters(rootNode); try { aggregate.execute(); } catch (IOException e) { throw new RuntimeException("Aggregation failed with " + e); } return aggregate.getResult(); } // aggregateQuery //----- StorageService object update methods // Add and/or update a batch of objects. For a Spider application, the store name must // be a table name. @Override public BatchResult addBatch(ApplicationDefinition appDef, String tableName, DBObjectBatch batch) { return addBatch(appDef, tableName, batch, null); } // addBatch // Add and/or update a batch of objects. For a Spider application, the store name must // be a table name. @Override public BatchResult addBatch(ApplicationDefinition appDef, String tableName, DBObjectBatch batch, Map<String, String> options) { checkServiceState(); TableDefinition tableDef = appDef.getTableDef(tableName); Utils.require(tableDef != null || appDef.allowsAutoTables(), "Unknown table for application '%s': %s", appDef.getAppName(), tableName); Utils.require(options == null || options.size() == 0, "No parameters expected"); if (tableDef == null && appDef.allowsAutoTables()) { tableDef = addAutoTable(appDef, tableName); } BatchObjectUpdater batchUpdater = new BatchObjectUpdater(tableDef); return batchUpdater.addBatch(batch); } // addBatch // Delete a batch of objects. For a Spider application, the store name must be a table // name, and (for now) all objects in the batch must belong to that table. @Override public BatchResult deleteBatch(ApplicationDefinition appDef, String tableName, DBObjectBatch batch) { checkServiceState(); TableDefinition tableDef = appDef.getTableDef(tableName); Utils.require(tableDef != null, "Unknown table for application '%s': %s", appDef.getAppName(), tableName); Set<String> objIDSet = new HashSet<>(); for (DBObject dbObj : batch.getObjects()) { Utils.require(!Utils.isEmpty(dbObj.getObjectID()), "All objects must have _ID defined"); objIDSet.add(dbObj.getObjectID()); } BatchObjectUpdater batchUpdater = new BatchObjectUpdater(tableDef); return batchUpdater.deleteBatch(objIDSet); } // deleteBatch // Same as addBatch() @Override public BatchResult updateBatch(ApplicationDefinition appDef, String storeName, DBObjectBatch batch) { return addBatch(appDef, storeName, batch, null); } // updateBatch // Same as addBatch() @Override public BatchResult updateBatch(ApplicationDefinition appDef, String storeName, DBObjectBatch batch, Map<String, String> paramMap) { return addBatch(appDef, storeName, batch, paramMap); } // updateBatch //----- SpiderService-specific public static methods /** * Return the column name used to store the given value for the given link. The column * name uses the format: * <pre> * ~{link name}/{object ID} * </pre> * This method should be used for unsharded links or link values to that refer to an * object whose shard number is 0. * * @param linkDef {@link FieldDefinition} of a link. * @param objID ID of an object referenced by the link. * @return Column name that is used to store a value for the given link and * object ID. * @see #shardedLinkTermRowKey(FieldDefinition, String, int) */ public static String linkColumnName(FieldDefinition linkDef, String objID) { assert linkDef.isLinkField(); StringBuilder buffer = new StringBuilder(); buffer.append("~"); buffer.append(linkDef.getName()); buffer.append("/"); buffer.append(objID); return buffer.toString(); } // linkColumnName /** * Return the store name (ColumnFamily) in which objects are stored for the given table. * This name is either {table name} or {application name}_{table name} truncated to * {@link #MAX_CF_NAME_LENGTH} if needed. * * @param tableDef {@link TableDefinition} of a table. * @return Store name (ColumnFamily) in which objects are stored for the given * table. */ public static String objectsStoreName(TableDefinition tableDef) { String storeName = null; storeName = tableDef.getAppDef().getAppName() + "_" + tableDef.getTableName(); return Utils.truncateTo(storeName, MAX_CF_NAME_LENGTH); } // objectsStoreName /** * Convert the given scalar value to binary form. This method returns the appropriate * format for storage based on the scalar's type. This method is the twin of * {@link #scalarValueToString(TableDefinition, String, byte[])} * * @param tableDef {@link TableDefinition} of table in which field resides. * @param fieldName Scalar field name. * @param fieldValue Field value in string form (may be null). * @return Binary storage format. */ public static byte[] scalarValueToBinary(TableDefinition tableDef, String fieldName, String fieldValue) { if (fieldValue == null || fieldValue.length() == 0) { return null; // means "don't store". } FieldDefinition fieldDef = tableDef.getFieldDef(fieldName); if (fieldDef != null && fieldDef.isBinaryField()) { return fieldDef.getEncoding().decode(fieldValue); } else { return Utils.toBytes(fieldValue); } } // scalarValueToBinary /** * Convert the given binary scalar field value to string form based on its definition. * This method is the twin of * {@link #scalarValueToBinary(TableDefinition, String, String)}. * * @param tableDef TableDefinition that defines field. * @param fieldName Name of a scalar field. * @param colValue Binary column value. * @return Scalar value as a string. */ public static String scalarValueToString(TableDefinition tableDef, String fieldName, byte[] colValue) { // Only binary fields are treated specially. FieldDefinition fieldDef = tableDef.getFieldDef(fieldName); if (fieldDef != null && fieldDef.isBinaryField()) { return fieldDef.getEncoding().encode(colValue); } else { return Utils.toString(colValue); } } // scalarValueToString /** * Return the row key for the Terms record that represents a link shard record for the * given link, owned by the given object ID, referencing target objects in the given * shard. The key format is: * <pre> * {shard number}/{link name}/{object ID} * </pre> * * @param linkDef {@link FieldDefinition} of a sharded link. * @param objID ID of object that owns link field. * @param shardNumber Shard number in the link's extent table. * @return */ public static String shardedLinkTermRowKey(FieldDefinition linkDef, String objID, int shardNumber) { assert linkDef.isLinkField() && linkDef.isSharded() && shardNumber > 0; StringBuilder shardPrefix = new StringBuilder(); shardPrefix.append(shardNumber); shardPrefix.append("/"); shardPrefix.append(linkColumnName(linkDef, objID)); return shardPrefix.toString(); } // shardedLinkTermRowKey /** * Create the Terms row key for the given table, object, field name, and term. * * @param tableDef {@link TableDefinition} of table that owns object. * @param dbObj DBObject that owns field. * @param fieldName Field name. * @param term Term to be indexed. * @return */ public static String termIndexRowKey(TableDefinition tableDef, DBObject dbObj, String fieldName, String term) { StringBuilder termRecKey = new StringBuilder(); int shardNumber = tableDef.getShardNumber(dbObj); if (shardNumber > 0) { termRecKey.append(shardNumber); termRecKey.append("/"); } termRecKey.append(FieldAnalyzer.makeTermKey(fieldName, term)); return termRecKey.toString(); } // termIndexRowKey /** * Return the store name (ColumnFamily) in which terms are stored for the given table. * This name is the object store name appended with "_terms". If the object store name * is too long, it is truncated so that the terms store name is less than * {@link #MAX_CF_NAME_LENGTH}. * * @param tableDef {@link TableDefinition} of a table. * @return Store name (ColumnFamily) in which terms are stored for the given * table. */ public static String termsStoreName(TableDefinition tableDef) { String objStoreName = Utils.truncateTo(objectsStoreName(tableDef), MAX_CF_NAME_LENGTH - "_Terms".length()); return objStoreName + "_Terms"; } // termsStoreName //----- SpiderService public methods /** * Retrieve the requested scalar fields for the given object IDs in the given table. * The map returned is object IDs -> field names -> field values. The map will be * empty (but not null) if (1) objIDs is empty, (2) fieldNames is empty, or (3) none * of the requested object IDs were found. An entry in the outer map may exist with an * empty field map if none of the requested fields were found for the corresponding * object. * * @param tableDef {@link TableDefinition} of table to query. * @param objIDs Collection of object IDs to fetch. * @param fieldNames Collection of field names to fetch. * @return Map of object IDs -> field names -> field values for all * objects found. Objects not found will have no entry in the * outer map. The map will be empty if no objects were found. */ public Map<String, Map<String, String>> getObjectScalars(TableDefinition tableDef, Collection<String> objIDs, Collection<String> fieldNames) { checkServiceState(); Map<String, Map<String, String>> objScalarMap = new HashMap<>(); if (objIDs.size() > 0 && fieldNames.size() > 0) { String storeName = objectsStoreName(tableDef); Iterator<DRow> rowIter = DBService.instance().getRowsColumns(Tenant.getTenant(tableDef), storeName, objIDs, fieldNames); while (rowIter.hasNext()) { DRow row = rowIter.next(); Map<String, String> scalarMap = new HashMap<>(); objScalarMap.put(row.getKey(), scalarMap); Iterator<DColumn> colIter = row.getColumns(); while (colIter.hasNext()) { DColumn col = colIter.next(); String fieldValue = scalarValueToString(tableDef, col.getName(), col.getRawValue()); scalarMap.put(col.getName(), fieldValue); } } } return objScalarMap; } // getObjectScalars /** * Retrieve a single scalar field for the given object IDs in the given table. * The map returned is object IDs -> field value. The map will be empty (but not null) * if objIDs is empty or none of the requested object IDs have a value for the * requested field name. * * @param tableDef {@link TableDefinition} of table to query. * @param objIDs Collection of object IDs to fetch. * @param fieldName Scalar field name to get values for. * @return Map of object IDs -> field values for values found. */ public Map<String, String> getObjectScalar(TableDefinition tableDef, Collection<String> objIDs, String fieldName) { checkServiceState(); Map<String, String> objScalarMap = new HashMap<>(); if (objIDs.size() > 0) { String storeName = objectsStoreName(tableDef); Iterator<DRow> rowIter = DBService.instance().getRowsColumns(Tenant.getTenant(tableDef), storeName, objIDs, Arrays.asList(fieldName)); while (rowIter.hasNext()) { DRow row = rowIter.next(); Iterator<DColumn> colIter = row.getColumns(); while (colIter.hasNext()) { DColumn col = colIter.next(); if (col.getName().equals(fieldName)) { String fieldValue = scalarValueToString(tableDef, col.getName(), col.getRawValue()); objScalarMap.put(row.getKey(), fieldValue); } } } } return objScalarMap; } // getObjectScalar /** * Get the starting date of the shard with the given number in the given sharded * table. If the given table has not yet started the given shard, null is returned. * * @param tableDef {@link TableDefinition} of a sharded table. * @param shardNumber Shard number (must be > 0). * @return Start date of the given shard or null if no objects have been * stored in the given shard yet. */ public void verifyShard(TableDefinition tableDef, int shardNumber) { assert tableDef.isSharded(); assert shardNumber > 0; checkServiceState(); m_shardCache.verifyShard(tableDef, shardNumber); } // verifyShard /** * Get all known shards for the given table. Each shard is defined in a column in the * "_shards" row of the table's Terms store. If the given table is not sharded, an * empty map is returned. * * @param tableDef Sharded table to get current shards for. * @return Map of shard numbers to shard start dates. May be empty but will * not be null. */ public Map<Integer, Date> getShards(TableDefinition tableDef) { checkServiceState(); if (tableDef.isSharded()) { return m_shardCache.getShardMap(tableDef); } else { return new HashMap<>(); } } // getShards //----- Private methods // Singleton creation only private SpiderService() {} // Add an implicit table to the given application and return its new TableDefinition. private TableDefinition addAutoTable(ApplicationDefinition appDef, String tableName) { m_logger.debug("Adding implicit table '{}' to application '{}'", tableName, appDef.getAppName()); Tenant tenant = Tenant.getTenant(appDef); TableDefinition tableDef = new TableDefinition(appDef); tableDef.setTableName(tableName); appDef.addTable(tableDef); SchemaService.instance().defineApplication(appDef); appDef = SchemaService.instance().getApplication(tenant, appDef.getAppName()); return appDef.getTableDef(tableName); } // addAutoTable // Add sharded link values, if any, to the given DBObject. private void addShardedLinkValues(TableDefinition tableDef, DBObject dbObj) { for (FieldDefinition fieldDef : tableDef.getFieldDefinitions()) { if (fieldDef.isLinkField() && fieldDef.isSharded()) { TableDefinition extentTableDef = tableDef.getLinkExtentTableDef(fieldDef); Set<Integer> shardNums = getShards(extentTableDef).keySet(); Set<String> values = getShardedLinkValues(dbObj.getObjectID(), fieldDef, shardNums); dbObj.addFieldValues(fieldDef.getName(), values); } } } // addShardedlinkValues // Create a DBObject from the given scalar/link column values. private DBObject createObject(TableDefinition tableDef, String objID, Iterator<DColumn> colIter) { DBObject dbObj = new DBObject(); dbObj.setObjectID(objID); while (colIter.hasNext()) { DColumn col = colIter.next(); Pair<String, String> linkCol = extractLinkValue(tableDef, col.getName()); if (linkCol == null) { String fieldName = col.getName(); String fieldValue = scalarValueToString(tableDef, col.getName(), col.getRawValue()); FieldDefinition fieldDef = tableDef.getFieldDef(fieldName); if (fieldDef != null && fieldDef.isCollection()) { // MV scalar field Set<String> values = Utils.split(fieldValue, CommonDefs.MV_SCALAR_SEP_CHAR); dbObj.addFieldValues(fieldName, values); } else { dbObj.addFieldValue(col.getName(), fieldValue); } // Skip links no longer present in schema } else if (tableDef.isLinkField(linkCol.left)) { dbObj.addFieldValue(linkCol.left, linkCol.right); } } return dbObj; } // createObject // Delete all ColumnFamilies used by the given application. Only delete the ones that // actually exist in case a previous delete-app failed. private void deleteApplicationCFs(ApplicationDefinition appDef) { // Table-level CFs: Tenant tenant = Tenant.getTenant(appDef); for (TableDefinition tableDef : appDef.getTableDefinitions().values()) { DBService.instance().deleteStoreIfPresent(tenant, objectsStoreName(tableDef)); DBService.instance().deleteStoreIfPresent(tenant, termsStoreName(tableDef)); } } // deleteApplicationCFs // Get all target object IDs for the given sharded link. private Set<String> getShardedLinkValues(String objID, FieldDefinition linkDef, Set<Integer> shardNums) { Set<String> values = new HashSet<String>(); if (shardNums.size() == 0) { return values; } // Construct row keys for the link's possible Terms records. Set<String> termRowKeys = new HashSet<String>(); for (Integer shardNumber : shardNums) { termRowKeys.add(shardedLinkTermRowKey(linkDef, objID, shardNumber)); } TableDefinition tableDef = linkDef.getTableDef(); String termStore = termsStoreName(linkDef.getTableDef()); Iterator<DRow> rowIter = DBService.instance().getRowsAllColumns(Tenant.getTenant(tableDef), termStore, termRowKeys); // We only need the column names from each row. while (rowIter.hasNext()) { DRow row = rowIter.next(); Iterator<DColumn> colIter = row.getColumns(); while (colIter.hasNext()) { values.add(colIter.next().getName()); } } return values; } // getShardedLinkValues // If the given column name represents a link value, return the link's field name and // target object ID as a Pair<String, String> private Pair<String, String> extractLinkValue(TableDefinition tableDef, String colName) { if (colName.length() < 3 || colName.charAt(0) != '~') { return null; } // A '/' should separate the field name and object ID value. Example: ~foo/xyz int slashInx = 1; while (slashInx < colName.length() && colName.charAt(slashInx) != '/') { slashInx++; } if (slashInx >= colName.length()) { return null; } String fieldName = colName.substring(1, slashInx); String objID = colName.substring(slashInx + 1); return Pair.create(fieldName, objID); } // extractLinkValue // Verify that the given shard-starting date is in the format YYYY-MM-DD. If the format // is bad, just return false. private boolean isValidShardDate(String shardDate) { try { // If the format is invalid, a ParseException is thrown. Utils.dateFromString(shardDate); return true; } catch (IllegalArgumentException ex) { return false; } } // isValidShardDate // Validate the given application against SpiderService-specific constraints. private void validateApplication(ApplicationDefinition appDef) { boolean bAutoTablesSet = false; for (String optName : appDef.getOptionNames()) { String optValue = appDef.getOption(optName); switch (optName) { case CommonDefs.AUTO_TABLES: validateBooleanOption(optName, optValue); bAutoTablesSet = true; break; case CommonDefs.OPT_STORAGE_SERVICE: assert optValue.equals(this.getClass().getSimpleName()); break; case CommonDefs.OPT_TENANT: // Ignore break; default: throw new IllegalArgumentException("Unknown option for SpiderService application: " + optName); } } if (!bAutoTablesSet) { // For backwards compatibility, default AutoTables to true. appDef.setOption(CommonDefs.AUTO_TABLES, "true"); } for (TableDefinition tableDef : appDef.getTableDefinitions().values()) { validateTable(tableDef); } } // validateApplication // Validate that the given string is a valid Booleab value. private void validateBooleanOption(String optName, String optValue) { if (!optValue.equalsIgnoreCase("true") && !optValue.equalsIgnoreCase("false")) { throw new IllegalArgumentException("Boolean value expected for '" + optName + "' option: " + optValue); } } // validateBooleanOption // Validate the given field against SpiderService-specific constraints. private void validateField(FieldDefinition fieldDef) { Utils.require(!fieldDef.isXLinkField(), "Xlink fields are not allowed in Spider applications"); // Validate scalar field analyzer. if (fieldDef.isScalarField()) { String analyzerName = fieldDef.getAnalyzerName(); if (Utils.isEmpty(analyzerName)) { analyzerName = FieldType.getDefaultAnalyzer(fieldDef.getType()); fieldDef.setAnalyzer(analyzerName); } FieldAnalyzer.verifyAnalyzer(fieldDef); } } // validateField // Validate the given table against SpiderService-specific constraints. private void validateTable(TableDefinition tableDef) { boolean bSawDataAging = false; for (String optName : tableDef.getOptionNames()) { String optValue = tableDef.getOption(optName); switch (optName) { case CommonDefs.OPT_AGING_FIELD: validateTableOptionAgingField(tableDef, optValue); break; case CommonDefs.OPT_RETENTION_AGE: validateTableOptionRetentionAge(tableDef, optValue); break; case CommonDefs.OPT_SHARDING_FIELD: validateTableOptionShardingField(tableDef, optValue); break; case CommonDefs.OPT_SHARDING_GRANULARITY: validateTableOptionShardingGranularity(tableDef, optValue); break; case CommonDefs.OPT_SHARDING_START: validateTableOptionShardingStart(tableDef, optValue); break; case CommonDefs.OPT_AGING_CHECK_FREQ: validateTableOptionAgingCheckFrequency(tableDef, optValue); bSawDataAging = true; break; default: Utils.require(false, "Unknown option for SpiderService table: " + optName); } } for (FieldDefinition fieldDef : tableDef.getFieldDefinitions()) { validateField(fieldDef); } if (!bSawDataAging && tableDef.isOptionSet(CommonDefs.OPT_AGING_FIELD)) { tableDef.setOption(CommonDefs.OPT_AGING_CHECK_FREQ, "1 DAY"); } } // validateTable // Validate the table option "aging-check-frequency" private void validateTableOptionAgingCheckFrequency(TableDefinition tableDef, String optValue) { new TaskFrequency(optValue); Utils.require(tableDef.getOption(CommonDefs.OPT_AGING_FIELD) != null, "Option 'aging-check-frequency' requires option 'aging-field'"); } // validateTableOptionAgingCheckFrequency // Validate the table option "aging-field". private void validateTableOptionAgingField(TableDefinition tableDef, String optValue) { FieldDefinition agingFieldDef = tableDef.getFieldDef(optValue); Utils.require(agingFieldDef != null, "Aging field has not been defined: " + optValue); assert agingFieldDef != null; // Make FindBugs happy Utils.require(agingFieldDef.getType() == FieldType.TIMESTAMP, "Aging field must be a timestamp field: " + optValue); } // validateTableOptionAgingField // Validate the table option "retention-age". private void validateTableOptionRetentionAge(TableDefinition tableDef, String optValue) { RetentionAge retAge = new RetentionAge(optValue); // throws if invalid format optValue = retAge.toString(); tableDef.setOption(CommonDefs.OPT_RETENTION_AGE, optValue); // rewrite value } // validateTableOptionRetentionAge // Validate the table option "sharding-field". private void validateTableOptionShardingField(TableDefinition tableDef, String optValue) { // Verify that the sharding-field exists and is a timestamp field. FieldDefinition shardingFieldDef = tableDef.getFieldDef(optValue); Utils.require(shardingFieldDef != null, "Sharding field has not been defined: " + optValue); assert shardingFieldDef != null; // Make FindBugs happy Utils.require(shardingFieldDef.getType() == FieldType.TIMESTAMP, "Sharding field must be a timestamp field: " + optValue); Utils.require(!shardingFieldDef.isCollection(), "Sharding field cannot be a collection: " + optValue); // Default sharding-granularity to MONTH. if (tableDef.getOption(CommonDefs.OPT_SHARDING_GRANULARITY) == null) { tableDef.setOption(CommonDefs.OPT_SHARDING_GRANULARITY, "MONTH"); } // Default sharding-start to "tomorrow". if (tableDef.getOption(CommonDefs.OPT_SHARDING_START) == null) { GregorianCalendar startDate = new GregorianCalendar(Utils.UTC_TIMEZONE); startDate.add(Calendar.DAY_OF_MONTH, 1); // adds 1 day String startOpt = String.format("%04d-%02d-%02d", startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH)+1, // 0-relative! startDate.get(Calendar.DAY_OF_MONTH)); tableDef.setOption(CommonDefs.OPT_SHARDING_START, startOpt); } } // validateTableOptionShardingField // Validate the table option "sharding-granularity". private void validateTableOptionShardingGranularity(TableDefinition tableDef, String optValue) { ShardingGranularity shardingGranularity = ShardingGranularity.fromString(optValue); Utils.require(shardingGranularity != null, "Unrecognized 'sharding-granularity' value: " + optValue); // 'sharding-granularity' requires 'sharding-field' Utils.require(tableDef.getOption(CommonDefs.OPT_SHARDING_FIELD) != null, "Option 'sharding-granularity' requires option 'sharding-field'"); } // validateTableOptionShardingGranularity // Validate the table option "sharding-start". private void validateTableOptionShardingStart(TableDefinition tableDef, String optValue) { Utils.require(isValidShardDate(optValue), "'sharding-start' must be YYYY-MM-DD: " + optValue); GregorianCalendar shardingStartDate = new GregorianCalendar(Utils.UTC_TIMEZONE); shardingStartDate.setTime(Utils.dateFromString(optValue)); // 'sharding-start' requires 'sharding-field' Utils.require(tableDef.getOption(CommonDefs.OPT_SHARDING_FIELD) != null, "Option 'sharding-start' requires option 'sharding-field'"); } // validateTableOptionShardingStart // Verify that all ColumnFamilies needed for the given application exist. private void verifyApplicationCFs(String keyspace, ApplicationDefinition oldAppDef, ApplicationDefinition appDef) { // Add new table-level CFs: DBService dbService = DBService.instance(); Tenant tenant = Tenant.getTenant(appDef); for (TableDefinition tableDef : appDef.getTableDefinitions().values()) { dbService.createStoreIfAbsent(tenant, objectsStoreName(tableDef), true); dbService.createStoreIfAbsent(tenant, termsStoreName(tableDef), true); } // Delete obsolete table-level CFs: if (oldAppDef != null) { for (TableDefinition oldTableDef : oldAppDef.getTableDefinitions().values()) { if (appDef.getTableDef(oldTableDef.getTableName()) == null) { dbService.deleteStoreIfPresent(tenant, objectsStoreName(oldTableDef)); dbService.deleteStoreIfPresent(tenant, termsStoreName(oldTableDef)); } } } } // verifyApplicationCFs } // class SpiderService
Check that 'retention-age' and 'aging-field' options are mutually defined.
doradus-server/src/com/dell/doradus/service/spider/SpiderService.java
Check that 'retention-age' and 'aging-field' options are mutually defined.
<ide><path>oradus-server/src/com/dell/doradus/service/spider/SpiderService.java <ide> assert agingFieldDef != null; // Make FindBugs happy <ide> Utils.require(agingFieldDef.getType() == FieldType.TIMESTAMP, <ide> "Aging field must be a timestamp field: " + optValue); <add> Utils.require(tableDef.getOption(CommonDefs.OPT_RETENTION_AGE) != null, <add> "Option 'aging-field' requires option 'retention-age'"); <ide> } // validateTableOptionAgingField <ide> <ide> // Validate the table option "retention-age". <ide> RetentionAge retAge = new RetentionAge(optValue); // throws if invalid format <ide> optValue = retAge.toString(); <ide> tableDef.setOption(CommonDefs.OPT_RETENTION_AGE, optValue); // rewrite value <add> Utils.require(tableDef.getOption(CommonDefs.OPT_AGING_FIELD) != null, <add> "Option 'retention-age' requires option 'aging-field'"); <ide> } // validateTableOptionRetentionAge <ide> <ide> // Validate the table option "sharding-field".
Java
mit
c8ed2039db5d66e20291b64a58487df3c3f19f9a
0
flutter-webrtc/flutter-webrtc,flutter-webrtc/flutter-webrtc,flutter-webrtc/flutter-webrtc,flutter-webrtc/flutter-webrtc,flutter-webrtc/flutter-webrtc,flutter-webrtc/flutter-webrtc,flutter-webrtc/flutter-webrtc,flutter-webrtc/flutter-webrtc
package com.cloudwebrtc.webrtc.record; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.media.MediaMuxer; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.view.Surface; import org.webrtc.EglBase; import org.webrtc.GlRectDrawer; import org.webrtc.ThreadUtils; import org.webrtc.VideoFrame; import org.webrtc.VideoFrameDrawer; import org.webrtc.VideoSink; import org.webrtc.audio.JavaAudioDeviceModule; import org.webrtc.audio.JavaAudioDeviceModule.SamplesReadyCallback; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; class VideoFileRenderer implements VideoSink, SamplesReadyCallback { private static final String TAG = "VideoFileRenderer"; private final HandlerThread renderThread; private final Handler renderThreadHandler; private final HandlerThread fileThread; private final Handler fileThreadHandler; private final HandlerThread audioThread; private final Handler audioThreadHandler; private final FileOutputStream videoOutFile; private final String outputFileName; private int outputFileWidth = -1; private int outputFileHeight = -1; private ByteBuffer[] encoderOutputBuffers; private ByteBuffer[] audioInputBuffers; private ByteBuffer[] audioOutputBuffers; private EglBase eglBase; private EglBase.Context sharedContext; private VideoFrameDrawer frameDrawer; // TODO: these ought to be configurable as well private static final String MIME_TYPE = "video/avc"; // H.264 Advanced Video Coding private static final int FRAME_RATE = 30; // 30fps private static final int IFRAME_INTERVAL = 5; // 5 seconds between I-frames private MediaMuxer mediaMuxer; private MediaCodec encoder; private MediaCodec.BufferInfo bufferInfo, audioBufferInfo; private int trackIndex = -1; private int audioTrackIndex; private boolean isRunning = true; private GlRectDrawer drawer; private Surface surface; private MediaCodec audioEncoder; VideoFileRenderer(String outputFile, final EglBase.Context sharedContext, boolean withAudio) throws IOException { this.outputFileName = outputFile; videoOutFile = new FileOutputStream(outputFile); renderThread = new HandlerThread(TAG + "RenderThread"); renderThread.start(); renderThreadHandler = new Handler(renderThread.getLooper()); fileThread = new HandlerThread(TAG + "FileThread"); fileThread.start(); if (withAudio) { audioThread = new HandlerThread(TAG + "AudioThread"); audioThread.start(); audioThreadHandler = new Handler(audioThread.getLooper()); } else { audioThread = null; audioThreadHandler = null; } fileThreadHandler = new Handler(fileThread.getLooper()); bufferInfo = new MediaCodec.BufferInfo(); this.sharedContext = sharedContext; // Create a MediaMuxer. We can't add the video track and start() the muxer here, // because our MediaFormat doesn't have the Magic Goodies. These can only be // obtained from the encoder after it has started processing data. mediaMuxer = new MediaMuxer(outputFile, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4); audioTrackIndex = withAudio ? -1 : 0; } private void initVideoEncoder() { MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, outputFileWidth, outputFileHeight); // Set some properties. Failing to specify some of these can cause the MediaCodec // configure() call to throw an unhelpful exception. format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); format.setInteger(MediaFormat.KEY_BIT_RATE, 6000000); format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL); // Create a MediaCodec encoder, and configure it with our format. Get a Surface // we can use for input and wrap it with a class that handles the EGL work. try { encoder = MediaCodec.createEncoderByType(MIME_TYPE); encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); renderThreadHandler.post(() -> { eglBase = EglBase.create(sharedContext, EglBase.CONFIG_RECORDABLE); surface = encoder.createInputSurface(); eglBase.createSurface(surface); eglBase.makeCurrent(); drawer = new GlRectDrawer(); }); } catch (Exception e) { Log.wtf(TAG, e); } } @Override public void onFrame(VideoFrame frame) { frame.retain(); if (outputFileWidth == -1) { outputFileWidth = frame.getRotatedWidth(); outputFileHeight = frame.getRotatedHeight(); initVideoEncoder(); } renderThreadHandler.post(() -> renderFrameOnRenderThread(frame)); } private void renderFrameOnRenderThread(VideoFrame frame) { if (frameDrawer == null) { frameDrawer = new VideoFrameDrawer(); } frameDrawer.drawFrame(frame, drawer, null, 0, 0, outputFileWidth, outputFileHeight); frame.release(); drainEncoder(); eglBase.swapBuffers(); } /** * Release all resources. All already posted frames will be rendered first. */ void release() { final CountDownLatch cleanupBarrier = new CountDownLatch(2); isRunning = false; renderThreadHandler.post(() -> { encoder.stop(); encoder.release(); eglBase.release(); renderThread.quit(); cleanupBarrier.countDown(); }); if (audioThreadHandler != null) { audioThreadHandler.post(() -> { audioEncoder.stop(); audioEncoder.release(); audioThread.quit(); cleanupBarrier.countDown(); }); } else { cleanupBarrier.countDown(); } ThreadUtils.awaitUninterruptibly(cleanupBarrier); fileThreadHandler.post(() -> { mediaMuxer.stop(); mediaMuxer.release(); try { videoOutFile.close(); Log.d(TAG, "Video written to disk as " + outputFileName); } catch (IOException e) { throw new RuntimeException("Error closing output file", e); } fileThread.quit(); }); try { fileThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.e(TAG, "Interrupted while waiting for the write to disk to complete.", e); } } private boolean encoderStarted = false; private volatile boolean muxerStarted = false; private long videoFrameStart = 0; private void drainEncoder() { if (!encoderStarted) { encoder.start(); encoderOutputBuffers = encoder.getOutputBuffers(); encoderStarted = true; return; } while (true) { int encoderStatus = encoder.dequeueOutputBuffer(bufferInfo, 10000); if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { break; } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { // not expected for an encoder encoderOutputBuffers = encoder.getOutputBuffers(); Log.e(TAG, "encoder output buffers changed"); } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { // not expected for an encoder MediaFormat newFormat = encoder.getOutputFormat(); Log.e(TAG, "encoder output format changed: " + newFormat); trackIndex = mediaMuxer.addTrack(newFormat); if (audioTrackIndex != -1 && !muxerStarted) { mediaMuxer.start(); muxerStarted = true; } if (!muxerStarted) break; } else if (encoderStatus < 0) { Log.e(TAG, "unexpected result fr om encoder.dequeueOutputBuffer: " + encoderStatus); } else { // encoderStatus >= 0 try { ByteBuffer encodedData = encoderOutputBuffers[encoderStatus]; if (encodedData == null) { Log.e(TAG, "encoderOutputBuffer " + encoderStatus + " was null"); break; } // It's usually necessary to adjust the ByteBuffer values to match BufferInfo. encodedData.position(bufferInfo.offset); encodedData.limit(bufferInfo.offset + bufferInfo.size); if (videoFrameStart == 0 && bufferInfo.presentationTimeUs != 0) { videoFrameStart = bufferInfo.presentationTimeUs; } bufferInfo.presentationTimeUs -= videoFrameStart; if (muxerStarted) mediaMuxer.writeSampleData(trackIndex, encodedData, bufferInfo); isRunning = isRunning && (bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) == 0; Log.d(TAG, "passed " + bufferInfo.size + " bytes to file" + (!isRunning ? " (EOS)" : "")); encoder.releaseOutputBuffer(encoderStatus, false); if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } } catch (Exception e) { Log.wtf(TAG, e); break; } } } } private long presTime = 0L; private void drainAudio() { if (audioBufferInfo == null) audioBufferInfo = new MediaCodec.BufferInfo(); while (true) { int encoderStatus = audioEncoder.dequeueOutputBuffer(audioBufferInfo, 10000); if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { break; } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { // not expected for an encoder audioOutputBuffers = audioEncoder.getOutputBuffers(); Log.w(TAG, "encoder output buffers changed"); } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { // not expected for an encoder MediaFormat newFormat = audioEncoder.getOutputFormat(); Log.w(TAG, "encoder output format changed: " + newFormat); audioTrackIndex = mediaMuxer.addTrack(newFormat); if (trackIndex != -1 && !muxerStarted) { mediaMuxer.start(); muxerStarted = true; } if (!muxerStarted) break; } else if (encoderStatus < 0) { Log.e(TAG, "unexpected result fr om encoder.dequeueOutputBuffer: " + encoderStatus); } else { // encoderStatus >= 0 try { ByteBuffer encodedData = audioOutputBuffers[encoderStatus]; if (encodedData == null) { Log.e(TAG, "encoderOutputBuffer " + encoderStatus + " was null"); break; } // It's usually necessary to adjust the ByteBuffer values to match BufferInfo. encodedData.position(audioBufferInfo.offset); encodedData.limit(audioBufferInfo.offset + audioBufferInfo.size); if (muxerStarted) mediaMuxer.writeSampleData(audioTrackIndex, encodedData, audioBufferInfo); isRunning = isRunning && (audioBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) == 0; Log.d(TAG, "passed " + audioBufferInfo.size + " bytes to file" + (!isRunning ? " (EOS)" : "")); audioEncoder.releaseOutputBuffer(encoderStatus, false); if ((audioBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } } catch (Exception e) { Log.wtf(TAG, e); break; } } } } @Override public void onWebRtcAudioRecordSamplesReady(JavaAudioDeviceModule.AudioSamples audioSamples) { if (!isRunning) return; audioThreadHandler.post(() -> { if (audioEncoder == null) try { audioEncoder = MediaCodec.createEncoderByType("audio/mp4a-latm"); MediaFormat format = new MediaFormat(); format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm"); format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, audioSamples.getChannelCount()); format.setInteger(MediaFormat.KEY_SAMPLE_RATE, audioSamples.getSampleRate()); format.setInteger(MediaFormat.KEY_BIT_RATE, 64 * 1024); format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectMain); audioEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); audioEncoder.start(); audioInputBuffers = audioEncoder.getInputBuffers(); audioOutputBuffers = audioEncoder.getOutputBuffers(); } catch (IOException exception) { Log.wtf(TAG, exception); } int bufferIndex = audioEncoder.dequeueInputBuffer(0); if (bufferIndex >= 0) { ByteBuffer buffer = audioInputBuffers[bufferIndex]; buffer.clear(); byte[] data = audioSamples.getData(); buffer.put(data); audioEncoder.queueInputBuffer(bufferIndex, 0, data.length, presTime, 0); presTime += data.length * 125 / 12; // 1000000 microseconds / 48000hz / 2 bytes } drainAudio(); }); } }
android/src/main/java/com/cloudwebrtc/webrtc/record/VideoFileRenderer.java
package com.cloudwebrtc.webrtc.record; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaFormat; import android.media.MediaMuxer; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import android.view.Surface; import org.webrtc.EglBase; import org.webrtc.GlRectDrawer; import org.webrtc.ThreadUtils; import org.webrtc.VideoFrame; import org.webrtc.VideoFrameDrawer; import org.webrtc.VideoSink; import org.webrtc.audio.JavaAudioDeviceModule; import org.webrtc.audio.JavaAudioDeviceModule.SamplesReadyCallback; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; class VideoFileRenderer implements VideoSink, SamplesReadyCallback { private static final String TAG = "VideoFileRenderer"; private final HandlerThread renderThread; private final Handler renderThreadHandler; private final HandlerThread fileThread; private final Handler fileThreadHandler; private final HandlerThread audioThread; private final Handler audioThreadHandler; private final FileOutputStream videoOutFile; private final String outputFileName; private int outputFileWidth = -1; private int outputFileHeight = -1; private ByteBuffer[] encoderOutputBuffers; private ByteBuffer[] audioInputBuffers; private ByteBuffer[] audioOutputBuffers; private EglBase eglBase; private EglBase.Context sharedContext; private VideoFrameDrawer frameDrawer; // TODO: these ought to be configurable as well private static final String MIME_TYPE = "video/avc"; // H.264 Advanced Video Coding private static final int FRAME_RATE = 30; // 30fps private static final int IFRAME_INTERVAL = 5; // 5 seconds between I-frames private MediaMuxer mediaMuxer; private MediaCodec encoder; private MediaCodec.BufferInfo bufferInfo; private int trackIndex = -1; private int audioTrackIndex; private boolean isRunning = true; private GlRectDrawer drawer; private Surface surface; private MediaCodec audioEncoder; VideoFileRenderer(String outputFile, final EglBase.Context sharedContext, boolean withAudio) throws IOException { this.outputFileName = outputFile; videoOutFile = new FileOutputStream(outputFile); renderThread = new HandlerThread(TAG + "RenderThread"); renderThread.start(); renderThreadHandler = new Handler(renderThread.getLooper()); fileThread = new HandlerThread(TAG + "FileThread"); fileThread.start(); audioThread = new HandlerThread(TAG + "AudioThread"); audioThread.start(); audioThreadHandler = new Handler(audioThread.getLooper()); fileThreadHandler = new Handler(fileThread.getLooper()); bufferInfo = new MediaCodec.BufferInfo(); this.sharedContext = sharedContext; // Create a MediaMuxer. We can't add the video track and start() the muxer here, // because our MediaFormat doesn't have the Magic Goodies. These can only be // obtained from the encoder after it has started processing data. mediaMuxer = new MediaMuxer(outputFile, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4); audioTrackIndex = withAudio ? 0 : -1; } private void initVideoEncoder() { MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, outputFileWidth, outputFileHeight); // Set some properties. Failing to specify some of these can cause the MediaCodec // configure() call to throw an unhelpful exception. format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface); format.setInteger(MediaFormat.KEY_BIT_RATE, 6000000); format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE); format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL); // Create a MediaCodec encoder, and configure it with our format. Get a Surface // we can use for input and wrap it with a class that handles the EGL work. try { encoder = MediaCodec.createEncoderByType(MIME_TYPE); encoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); renderThreadHandler.post(() -> { eglBase = EglBase.create(sharedContext, EglBase.CONFIG_RECORDABLE); surface = encoder.createInputSurface(); eglBase.createSurface(surface); eglBase.makeCurrent(); drawer = new GlRectDrawer(); }); } catch (Exception e) { Log.wtf(TAG, e); } } @Override public void onFrame(VideoFrame frame) { frame.retain(); if (outputFileWidth == -1) { outputFileWidth = frame.getRotatedWidth(); outputFileHeight = frame.getRotatedHeight(); initVideoEncoder(); } renderThreadHandler.post(() -> renderFrameOnRenderThread(frame)); } private void renderFrameOnRenderThread(VideoFrame frame) { if (frameDrawer == null) { frameDrawer = new VideoFrameDrawer(); } frameDrawer.drawFrame(frame, drawer, null, 0, 0, outputFileWidth, outputFileHeight); frame.release(); drainEncoder(); eglBase.swapBuffers(); } /** * Release all resources. All already posted frames will be rendered first. */ void release() { final CountDownLatch cleanupBarrier = new CountDownLatch(2); isRunning = false; renderThreadHandler.post(() -> { encoder.stop(); encoder.release(); eglBase.release(); renderThread.quit(); cleanupBarrier.countDown(); }); audioThreadHandler.post(() -> { audioEncoder.stop(); audioEncoder.release(); audioThread.quit(); cleanupBarrier.countDown(); }); ThreadUtils.awaitUninterruptibly(cleanupBarrier); fileThreadHandler.post(() -> { mediaMuxer.stop(); mediaMuxer.release(); try { videoOutFile.close(); Log.d(TAG, "Video written to disk as " + outputFileName); } catch (IOException e) { throw new RuntimeException("Error closing output file", e); } fileThread.quit(); }); try { fileThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); Log.e(TAG, "Interrupted while waiting for the write to disk to complete.", e); } } private boolean encoderStarted = false; private volatile boolean muxerStarted = false; private long videoFrameStart = 0; private void drainEncoder() { if (!encoderStarted) { encoder.start(); encoderOutputBuffers = encoder.getOutputBuffers(); encoderStarted = true; return; } while (true) { int encoderStatus = encoder.dequeueOutputBuffer(bufferInfo, 10000); if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { break; } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { // not expected for an encoder encoderOutputBuffers = encoder.getOutputBuffers(); Log.e(TAG, "encoder output buffers changed"); } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { // not expected for an encoder MediaFormat newFormat = encoder.getOutputFormat(); Log.e(TAG, "encoder output format changed: " + newFormat); trackIndex = mediaMuxer.addTrack(newFormat); if (audioTrackIndex != -1 && !muxerStarted) { mediaMuxer.start(); muxerStarted = true; } if (!muxerStarted) break; } else if (encoderStatus < 0) { Log.e(TAG, "unexpected result fr om encoder.dequeueOutputBuffer: " + encoderStatus); } else { // encoderStatus >= 0 try { ByteBuffer encodedData = encoderOutputBuffers[encoderStatus]; if (encodedData == null) { Log.e(TAG, "encoderOutputBuffer " + encoderStatus + " was null"); break; } // It's usually necessary to adjust the ByteBuffer values to match BufferInfo. encodedData.position(bufferInfo.offset); encodedData.limit(bufferInfo.offset + bufferInfo.size); if (videoFrameStart == 0 && bufferInfo.presentationTimeUs != 0) { videoFrameStart = bufferInfo.presentationTimeUs; } bufferInfo.presentationTimeUs -= videoFrameStart; if (muxerStarted) mediaMuxer.writeSampleData(trackIndex, encodedData, bufferInfo); isRunning = isRunning && (bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) == 0; Log.d(TAG, "passed " + bufferInfo.size + " bytes to file" + (!isRunning ? " (EOS)" : "")); encoder.releaseOutputBuffer(encoderStatus, false); if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } } catch (Exception e) { Log.wtf(TAG, e); break; } } } } private long presTime = 0L; private void drainAudio() { while (true) { int encoderStatus = audioEncoder.dequeueOutputBuffer(bufferInfo, 10000); if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { break; } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { // not expected for an encoder audioOutputBuffers = audioEncoder.getOutputBuffers(); Log.w(TAG, "encoder output buffers changed"); } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) { // not expected for an encoder MediaFormat newFormat = audioEncoder.getOutputFormat(); Log.w(TAG, "encoder output format changed: " + newFormat); audioTrackIndex = mediaMuxer.addTrack(newFormat); if (trackIndex != -1 && !muxerStarted) { mediaMuxer.start(); muxerStarted = true; } if (!muxerStarted) break; } else if (encoderStatus < 0) { Log.e(TAG, "unexpected result fr om encoder.dequeueOutputBuffer: " + encoderStatus); } else { // encoderStatus >= 0 try { ByteBuffer encodedData = audioOutputBuffers[encoderStatus]; if (encodedData == null) { Log.e(TAG, "encoderOutputBuffer " + encoderStatus + " was null"); break; } // It's usually necessary to adjust the ByteBuffer values to match BufferInfo. encodedData.position(bufferInfo.offset); encodedData.limit(bufferInfo.offset + bufferInfo.size); if (muxerStarted) mediaMuxer.writeSampleData(audioTrackIndex, encodedData, bufferInfo); isRunning = isRunning && (bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) == 0; Log.d(TAG, "passed " + bufferInfo.size + " bytes to file" + (!isRunning ? " (EOS)" : "")); audioEncoder.releaseOutputBuffer(encoderStatus, false); if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { break; } } catch (Exception e) { Log.wtf(TAG, e); break; } } } } @Override public void onWebRtcAudioRecordSamplesReady(JavaAudioDeviceModule.AudioSamples audioSamples) { if (!isRunning) return; audioThreadHandler.post(() -> { if (audioEncoder == null) try { audioEncoder = MediaCodec.createEncoderByType("audio/mp4a-latm"); MediaFormat format = new MediaFormat(); format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm"); format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, audioSamples.getChannelCount()); format.setInteger(MediaFormat.KEY_SAMPLE_RATE, audioSamples.getSampleRate()); format.setInteger(MediaFormat.KEY_BIT_RATE, 64 * 1024); format.setInteger(MediaFormat.KEY_AAC_PROFILE, MediaCodecInfo.CodecProfileLevel.AACObjectMain); audioEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); audioEncoder.start(); audioInputBuffers = audioEncoder.getInputBuffers(); audioOutputBuffers = audioEncoder.getOutputBuffers(); } catch (IOException exception) { Log.wtf(TAG, exception); } int bufferIndex = audioEncoder.dequeueInputBuffer(0); if (bufferIndex >= 0) { ByteBuffer buffer = audioInputBuffers[bufferIndex]; buffer.clear(); byte[] data = audioSamples.getData(); buffer.put(data); audioEncoder.queueInputBuffer(bufferIndex, 0, data.length, presTime, 0); presTime += data.length * 125 / 12; // 1000000 microseconds / 48000hz / 2 bytes } drainAudio(); }); } }
Fix video-only recording and audio encoder crashes
android/src/main/java/com/cloudwebrtc/webrtc/record/VideoFileRenderer.java
Fix video-only recording and audio encoder crashes
<ide><path>ndroid/src/main/java/com/cloudwebrtc/webrtc/record/VideoFileRenderer.java <ide> <ide> private MediaMuxer mediaMuxer; <ide> private MediaCodec encoder; <del> private MediaCodec.BufferInfo bufferInfo; <add> private MediaCodec.BufferInfo bufferInfo, audioBufferInfo; <ide> private int trackIndex = -1; <ide> private int audioTrackIndex; <ide> private boolean isRunning = true; <ide> renderThreadHandler = new Handler(renderThread.getLooper()); <ide> fileThread = new HandlerThread(TAG + "FileThread"); <ide> fileThread.start(); <del> audioThread = new HandlerThread(TAG + "AudioThread"); <del> audioThread.start(); <del> audioThreadHandler = new Handler(audioThread.getLooper()); <add> if (withAudio) { <add> audioThread = new HandlerThread(TAG + "AudioThread"); <add> audioThread.start(); <add> audioThreadHandler = new Handler(audioThread.getLooper()); <add> } else { <add> audioThread = null; <add> audioThreadHandler = null; <add> } <ide> fileThreadHandler = new Handler(fileThread.getLooper()); <ide> bufferInfo = new MediaCodec.BufferInfo(); <ide> this.sharedContext = sharedContext; <ide> mediaMuxer = new MediaMuxer(outputFile, <ide> MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4); <ide> <del> audioTrackIndex = withAudio ? 0 : -1; <add> audioTrackIndex = withAudio ? -1 : 0; <ide> } <ide> <ide> private void initVideoEncoder() { <ide> renderThread.quit(); <ide> cleanupBarrier.countDown(); <ide> }); <del> audioThreadHandler.post(() -> { <del> audioEncoder.stop(); <del> audioEncoder.release(); <del> audioThread.quit(); <add> if (audioThreadHandler != null) { <add> audioThreadHandler.post(() -> { <add> audioEncoder.stop(); <add> audioEncoder.release(); <add> audioThread.quit(); <add> cleanupBarrier.countDown(); <add> }); <add> } else { <ide> cleanupBarrier.countDown(); <del> }); <add> } <ide> ThreadUtils.awaitUninterruptibly(cleanupBarrier); <ide> fileThreadHandler.post(() -> { <ide> mediaMuxer.stop(); <ide> private long presTime = 0L; <ide> <ide> private void drainAudio() { <add> if (audioBufferInfo == null) <add> audioBufferInfo = new MediaCodec.BufferInfo(); <ide> while (true) { <del> int encoderStatus = audioEncoder.dequeueOutputBuffer(bufferInfo, 10000); <add> int encoderStatus = audioEncoder.dequeueOutputBuffer(audioBufferInfo, 10000); <ide> if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) { <ide> break; <ide> } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) { <ide> break; <ide> } <ide> // It's usually necessary to adjust the ByteBuffer values to match BufferInfo. <del> encodedData.position(bufferInfo.offset); <del> encodedData.limit(bufferInfo.offset + bufferInfo.size); <add> encodedData.position(audioBufferInfo.offset); <add> encodedData.limit(audioBufferInfo.offset + audioBufferInfo.size); <ide> if (muxerStarted) <del> mediaMuxer.writeSampleData(audioTrackIndex, encodedData, bufferInfo); <del> isRunning = isRunning && (bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) == 0; <del> Log.d(TAG, "passed " + bufferInfo.size + " bytes to file" <add> mediaMuxer.writeSampleData(audioTrackIndex, encodedData, audioBufferInfo); <add> isRunning = isRunning && (audioBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) == 0; <add> Log.d(TAG, "passed " + audioBufferInfo.size + " bytes to file" <ide> + (!isRunning ? " (EOS)" : "")); <ide> audioEncoder.releaseOutputBuffer(encoderStatus, false); <del> if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { <add> if ((audioBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { <ide> break; <ide> } <ide> } catch (Exception e) {
Java
agpl-3.0
d7b2023c17ee3c20ee3161f6dd001cb46b2908b0
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
ee8ff3c2-2e60-11e5-9284-b827eb9e62be
hello.java
ee8a85cc-2e60-11e5-9284-b827eb9e62be
ee8ff3c2-2e60-11e5-9284-b827eb9e62be
hello.java
ee8ff3c2-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>ee8a85cc-2e60-11e5-9284-b827eb9e62be <add>ee8ff3c2-2e60-11e5-9284-b827eb9e62be
Java
apache-2.0
bad85ce49966eb7139457f622eb8f5aa2cf5732b
0
jonaswagner/TomP2P,jonaswagner/TomP2P,thirdy/TomP2P,tomp2p/TomP2P,jonaswagner/TomP2P,thirdy/TomP2P,tomp2p/TomP2P,jonaswagner/TomP2P,jonaswagner/TomP2P,jonaswagner/TomP2P
/* * Copyright 2013 Thomas Bocek * * 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.tomp2p.connection; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.GenericFutureListener; import java.net.ConnectException; import java.net.InetSocketAddress; import java.nio.channels.ClosedChannelException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReferenceArray; import net.tomp2p.futures.BaseFutureAdapter; import net.tomp2p.futures.Cancel; import net.tomp2p.futures.FutureDone; import net.tomp2p.futures.FutureForkJoin; import net.tomp2p.futures.FuturePing; import net.tomp2p.futures.FutureResponse; import net.tomp2p.message.Message; import net.tomp2p.message.Message.Type; import net.tomp2p.message.TomP2PCumulationTCP; import net.tomp2p.message.TomP2POutbound; import net.tomp2p.message.TomP2PSinglePacketUDP; import net.tomp2p.p2p.builder.PingBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; import net.tomp2p.peers.PeerSocketAddress; import net.tomp2p.peers.PeerStatusListener; import net.tomp2p.rpc.RPC; import net.tomp2p.rpc.RPC.Commands; import net.tomp2p.utils.Pair; import net.tomp2p.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class that sends out messages. * * @author Thomas Bocek * */ public class Sender { private static final Logger LOG = LoggerFactory.getLogger(Sender.class); private final List<PeerStatusListener> peerStatusListeners; private final ChannelClientConfiguration channelClientConfiguration; private final Dispatcher dispatcher; private final Random random; // this map caches all messages which are meant to be sent by a reverse // connection setup or TODO jwa a hole punch private final ConcurrentHashMap<Integer, FutureResponse> cachedRequests = new ConcurrentHashMap<Integer, FutureResponse>(); // this map caches all messages which are meant to be sent by a reverse // connection setup private final ConcurrentHashMap<Integer, Message> cachedMessages = new ConcurrentHashMap<Integer, Message>(); private PingBuilderFactory pingBuilderFactory; /** * Creates a new sender with the listeners for offline peers. * * @param peerStatusListeners * The listener for offline peers * @param channelClientConfiguration * The configuration used to get the signature factory * @param dispatcher */ public Sender(final Number160 peerId, final List<PeerStatusListener> peerStatusListeners, final ChannelClientConfiguration channelClientConfiguration, Dispatcher dispatcher) { this.peerStatusListeners = peerStatusListeners; this.channelClientConfiguration = channelClientConfiguration; this.dispatcher = dispatcher; this.random = new Random(peerId.hashCode()); } public ChannelClientConfiguration channelClientConfiguration() { return channelClientConfiguration; } public PingBuilderFactory pingBuilderFactory() { return pingBuilderFactory; } public Sender pingBuilderFactory(PingBuilderFactory pingBuilderFactory) { this.pingBuilderFactory = pingBuilderFactory; return this; } /** * Send a message via TCP. * * @param handler * The handler to deal with a reply message * @param futureResponse * The future to set the response * @param message * The message to send * @param channelCreator * The channel creator for the UPD channel * @param idleTCPSeconds * The idle time of a message until we fail * @param connectTimeoutMillis * The idle we set for the connection setup */ public void sendTCP(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final Message message, final ChannelCreator channelCreator, final int idleTCPSeconds, final int connectTimeoutMillis, final PeerConnection peerConnection) { // no need to continue if we already finished if (futureResponse.isCompleted()) { return; } removePeerIfFailed(futureResponse, message); // we need to set the neighbors if we use relays if (message.sender().isRelayed() && !message.sender().peerSocketAddresses().isEmpty()) { message.peerSocketAddresses(message.sender().peerSocketAddresses()); } final ChannelFuture channelFuture; if (peerConnection != null && peerConnection.channelFuture() != null && peerConnection.channelFuture().channel().isActive()) { channelFuture = sendTCPPeerConnection(peerConnection, handler, channelCreator, futureResponse); afterConnect(futureResponse, message, channelFuture, handler == null); } else if (channelCreator != null) { final TimeoutFactory timeoutHandler = createTimeoutHandler(futureResponse, idleTCPSeconds, handler == null); // check relay if (message.recipient().isRelayed()) { // check if reverse connection is possible if (!message.sender().isRelayed()) { handleRcon(handler, futureResponse, message, channelCreator, connectTimeoutMillis, peerConnection, timeoutHandler); } else { handleRelay(handler, futureResponse, message, channelCreator, idleTCPSeconds, connectTimeoutMillis, peerConnection, timeoutHandler); } } else { connectAndSend(handler, futureResponse, channelCreator, connectTimeoutMillis, peerConnection, timeoutHandler, message); } } } /** * This method initiates the reverse connection setup (or short: rconSetup). * It creates a new Message and sends it via relay to the unreachable peer * which then connects to this peer again. After the connectMessage from the * unreachable peer this peer will send the original Message and its content * directly. * * @param handler * @param futureResponse * @param message * @param channelCreator * @param connectTimeoutMillis * @param peerConnection * @param timeoutHandler */ private void handleRcon(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final Message message, final ChannelCreator channelCreator, final int connectTimeoutMillis, final PeerConnection peerConnection, final TimeoutFactory timeoutHandler) { message.keepAlive(true); LOG.debug("initiate reverse connection setup to peer with peerAddress {}", message.recipient()); Message rconMessage = createRconMessage(message); // cache the original message until the connection is established cachedRequests.put(message.messageId(), futureResponse); // wait for response (whether the reverse connection setup was // successful) final FutureResponse rconResponse = new FutureResponse(rconMessage); // TODO: expose peer somehow in sender to be able to notify on automatic // requests // peer.notifyAutomaticFutures(rconResponse); SimpleChannelInboundHandler<Message> rconInboundHandler = new SimpleChannelInboundHandler<Message>() { @Override protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception { if (msg.command() == Commands.RCON.getNr() && msg.type() == Type.OK) { LOG.debug("Successfully set up the reverse connection to peer {}", message.recipient().peerId()); rconResponse.response(msg); } else { LOG.debug("Could not acquire a reverse connection to peer {}", message.recipient().peerId()); rconResponse.failed("Could not acquire a reverse connection, got: " + msg); futureResponse.failed(rconResponse.failedReason()); } } }; // send reverse connection request instead of normal message sendTCP(rconInboundHandler, rconResponse, rconMessage, channelCreator, connectTimeoutMillis, connectTimeoutMillis, peerConnection); } /** * This method makes a copy of the original Message and prepares it for * sending it to the relay. * * @param message * @return rconMessage */ private static Message createRconMessage(final Message message) { // get Relay InetAddress from unreachable peer Object[] relayInetAdresses = message.recipient().peerSocketAddresses().toArray(); PeerSocketAddress socketAddress = null; if (relayInetAdresses.length > 0) { // we should be fair and choose one of the relays randomly socketAddress = (PeerSocketAddress) relayInetAdresses[Utils.randomPositiveInt(relayInetAdresses.length)]; } else { throw new IllegalArgumentException( "There are no PeerSocketAdresses available for this relayed Peer. This should not be possible!"); } // we need to make a copy of the original message Message rconMessage = new Message(); rconMessage.sender(message.sender()); rconMessage.version(message.version()); rconMessage.intValue(message.messageId()); // making the message ready to send PeerAddress recipient = message.recipient().changeAddress(socketAddress.inetAddress()) .changePorts(socketAddress.tcpPort(), socketAddress.udpPort()).changeRelayed(false); rconMessage.recipient(recipient); rconMessage.command(RPC.Commands.RCON.getNr()); rconMessage.type(Message.Type.REQUEST_1); return rconMessage; } /** * This method is extracted by @author jonaswagner to ensure that no * duplicate code exist. * * @param handler * @param futureResponse * @param channelCreator * @param connectTimeoutMillis * @param peerConnection * @param timeoutHandler * @param message */ private void connectAndSend(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final ChannelCreator channelCreator, final int connectTimeoutMillis, final PeerConnection peerConnection, final TimeoutFactory timeoutHandler, final Message message) { InetSocketAddress recipient = message.recipient().createSocketTCP(); final ChannelFuture channelFuture = sendTCPCreateChannel(recipient, channelCreator, peerConnection, handler, timeoutHandler, connectTimeoutMillis, futureResponse); afterConnect(futureResponse, message, channelFuture, handler == null); } /** * TODO: document what is done here * * @param handler * @param futureResponse * @param message * @param channelCreator * @param idleTCPSeconds * @param connectTimeoutMillis * @param peerConnection * @param timeoutHandler */ private void handleRelay(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final Message message, final ChannelCreator channelCreator, final int idleTCPSeconds, final int connectTimeoutMillis, final PeerConnection peerConnection, final TimeoutFactory timeoutHandler) { FutureDone<PeerSocketAddress> futurePing = pingFirst(message.recipient().peerSocketAddresses(), pingBuilderFactory); futurePing.addListener(new BaseFutureAdapter<FutureDone<PeerSocketAddress>>() { @Override public void operationComplete(final FutureDone<PeerSocketAddress> futureDone) throws Exception { if (futureDone.isSuccess()) { InetSocketAddress recipient = PeerSocketAddress.createSocketTCP(futureDone.object()); ChannelFuture channelFuture = sendTCPCreateChannel(recipient, channelCreator, peerConnection, handler, timeoutHandler, connectTimeoutMillis, futureResponse); afterConnect(futureResponse, message, channelFuture, handler == null); futureResponse.addListener(new BaseFutureAdapter<FutureResponse>() { @Override public void operationComplete(FutureResponse future) throws Exception { if (future.isFailed()) { if (future.responseMessage() != null && future.responseMessage().type() != Message.Type.USER1) { clearInactivePeerSocketAddress(futureDone); sendTCP(handler, futureResponse, message, channelCreator, idleTCPSeconds, connectTimeoutMillis, peerConnection); } } } private void clearInactivePeerSocketAddress(final FutureDone<PeerSocketAddress> futureDone) { Collection<PeerSocketAddress> tmp = new ArrayList<PeerSocketAddress>(); for (PeerSocketAddress psa : message.recipient().peerSocketAddresses()) { if (psa != null) { if (!psa.equals(futureDone.object())) { tmp.add(psa); } } } message.peerSocketAddresses(tmp); } }); } else { futureResponse.failed("no relay could be contacted", futureDone); } } }); } /** * TODO: say what we are doing here * * @param peerSocketAddresses * @param pingBuilder * @return */ private FutureDone<PeerSocketAddress> pingFirst(Collection<PeerSocketAddress> peerSocketAddresses, PingBuilderFactory pingBuilderFactory) { final FutureDone<PeerSocketAddress> futureDone = new FutureDone<PeerSocketAddress>(); FuturePing[] forks = new FuturePing[peerSocketAddresses.size()]; int index = 0; for (PeerSocketAddress psa : peerSocketAddresses) { if (psa != null) { InetSocketAddress inetSocketAddress = PeerSocketAddress.createSocketUDP(psa); PingBuilder pingBuilder = pingBuilderFactory.create(); forks[index++] = pingBuilder.inetAddress(inetSocketAddress.getAddress()).port(inetSocketAddress.getPort()).start(); } } FutureForkJoin<FuturePing> ffk = new FutureForkJoin<FuturePing>(1, true, new AtomicReferenceArray<FuturePing>(forks)); ffk.addListener(new BaseFutureAdapter<FutureForkJoin<FuturePing>>() { @Override public void operationComplete(FutureForkJoin<FuturePing> future) throws Exception { if (future.isSuccess()) { futureDone.done(future.first().remotePeer().peerSocketAddress()); } else { futureDone.failed(future); } } }); return futureDone; } private ChannelFuture sendTCPCreateChannel(InetSocketAddress recipient, ChannelCreator channelCreator, PeerConnection peerConnection, ChannelHandler handler, TimeoutFactory timeoutHandler, int connectTimeoutMillis, FutureResponse futureResponse) { final Map<String, Pair<EventExecutorGroup, ChannelHandler>> handlers; if (timeoutHandler != null) { handlers = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(); handlers.put("timeout0", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.idleStateHandlerTomP2P())); handlers.put("timeout1", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.timeHandler())); } else { handlers = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(); } handlers.put("decoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2PCumulationTCP(channelClientConfiguration.signatureFactory()))); handlers.put( "encoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2POutbound(false, channelClientConfiguration.signatureFactory()))); if (peerConnection != null) { // we expect replies on this connection handlers.put("dispatcher", new Pair<EventExecutorGroup, ChannelHandler>(null, dispatcher)); } if (timeoutHandler != null) { handlers.put("handler", new Pair<EventExecutorGroup, ChannelHandler>(null, handler)); } HeartBeat heartBeat = null; if (peerConnection != null) { heartBeat = new HeartBeat(peerConnection.heartBeatMillis(), TimeUnit.MILLISECONDS, pingBuilderFactory); handlers.put("heartbeat", new Pair<EventExecutorGroup, ChannelHandler>(null, heartBeat)); } ChannelFuture channelFuture = channelCreator.createTCP(recipient, connectTimeoutMillis, handlers, futureResponse); if (peerConnection != null && channelFuture != null) { peerConnection.channelFuture(channelFuture); heartBeat.peerConnection(peerConnection); } return channelFuture; } private ChannelFuture sendTCPPeerConnection(PeerConnection peerConnection, ChannelHandler handler, final ChannelCreator channelCreator, final FutureResponse futureResponse) { // if the channel gets closed, the future should get notified ChannelFuture channelFuture = peerConnection.channelFuture(); // channelCreator can be null if we don't need to create any channels if (channelCreator != null) { channelCreator.setupCloseListener(channelFuture, futureResponse); } ChannelPipeline pipeline = channelFuture.channel().pipeline(); // we need to replace the handler if this comes from the peer that // create a peerconnection, otherwise we // need to add a handler addOrReplace(pipeline, "dispatcher", "handler", handler); // uncomment this if the recipient should also heartbeat // addIfAbsent(pipeline, "handler", "heartbeat", // new HeartBeat(2, pingBuilder).peerConnection(peerConnection)); return channelFuture; } // private boolean addIfAbsent(ChannelPipeline pipeline, String before, // String name, // ChannelHandler channelHandler) { // List<String> names = pipeline.names(); // if (names.contains(name)) { // return false; // } else { // if (before == null) { // pipeline.addFirst(name, channelHandler); // } else { // pipeline.addBefore(before, name, channelHandler); // } // return true; // } // } private boolean addOrReplace(ChannelPipeline pipeline, String before, String name, ChannelHandler channelHandler) { List<String> names = pipeline.names(); if (names.contains(name)) { pipeline.replace(name, name, channelHandler); return false; } else { if (before == null) { pipeline.addFirst(name, channelHandler); } else { pipeline.addBefore(before, name, channelHandler); } return true; } } /** * Send a message via UDP. * * @param handler * The handler to deal with a reply message * @param futureResponse * The future to set the response * @param message * The message to send * @param channelCreator * The channel creator for the UPD channel * @param idleUDPSeconds * The idle time of a message until we fail * @param broadcast * True to send via layer 2 broadcast */ // TODO: if message.getRecipient() is me, than call dispatcher directly // without sending over Internet. public void sendUDP(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final Message message, final ChannelCreator channelCreator, final int idleUDPSeconds, final boolean broadcast) { // no need to continue if we already finished if (futureResponse.isCompleted()) { return; } removePeerIfFailed(futureResponse, message); if (message.sender().isRelayed()) { message.peerSocketAddresses(message.sender().peerSocketAddresses()); } if (message.recipient().isRelayed() && message.sender().isRelayed()) { prepareHolePunch(handler, futureResponse, message, channelCreator, idleUDPSeconds, broadcast); return; } boolean isFireAndForget = handler == null; final Map<String, Pair<EventExecutorGroup, ChannelHandler>> handlers; if (isFireAndForget) { final int nrTCPHandlers = 3; // 2 / 0.75 handlers = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(nrTCPHandlers); } else { final int nrTCPHandlers = 7; // 5 / 0.75 handlers = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(nrTCPHandlers); final TimeoutFactory timeoutHandler = createTimeoutHandler(futureResponse, idleUDPSeconds, isFireAndForget); handlers.put("timeout0", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.idleStateHandlerTomP2P())); handlers.put("timeout1", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.timeHandler())); } handlers.put( "decoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2PSinglePacketUDP(channelClientConfiguration.signatureFactory()))); handlers.put( "encoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2POutbound(false, channelClientConfiguration.signatureFactory()))); if (!isFireAndForget) { handlers.put("handler", new Pair<EventExecutorGroup, ChannelHandler>(null, handler)); } if (message.recipient().isRelayed() && message.command() != RPC.Commands.NEIGHBOR.getNr() && message.command() != RPC.Commands.PING.getNr()) { LOG.warn("Tried to send UDP message to unreachable peers. Only TCP messages can be sent to unreachable peers: {}", message); futureResponse.failed("Tried to send UDP message to unreachable peers. Only TCP messages can be sent to unreachable peers"); } else { final ChannelFuture channelFuture; if (message.recipient().isRelayed()) { List<PeerSocketAddress> psa = new ArrayList<PeerSocketAddress>(message.recipient().peerSocketAddresses()); LOG.debug("send neighbor request to random relay peer {}", psa); if (psa.size() > 0) { PeerSocketAddress ps = psa.get(random.nextInt(psa.size())); message.recipientRelay(message.recipient().changePeerSocketAddress(ps).changeRelayed(true)); channelFuture = channelCreator.createUDP(broadcast, handlers, futureResponse); } else { futureResponse.failed("Peer is relayed, but no relay given"); return; } } else { channelFuture = channelCreator.createUDP(broadcast, handlers, futureResponse); } afterConnect(futureResponse, message, channelFuture, handler == null); } } private void prepareHolePunch(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final Message message, final ChannelCreator channelCreator, final int idleUDPSeconds, final boolean broadcast) { // TODO jwa notify rendez-vous server // TODO jwa punch a hole into firewall // TODO jwa store message to chachedRequests cachedRequests.put(message.messageId(), futureResponse); // get Relay InetAddress from unreachable peer Object[] relayInetAdresses = message.recipient().peerSocketAddresses().toArray(); PeerSocketAddress socketAddress = null; if (relayInetAdresses.length > 0) { // we should be fair and choose one of the relays randomly socketAddress = (PeerSocketAddress) relayInetAdresses[Utils.randomPositiveInt(relayInetAdresses.length)]; } else { throw new IllegalArgumentException( "There are no PeerSocketAdresses available for this relayed Peer. This should not be possible!"); } Message holePMessage = new Message(); holePMessage.sender(message.sender()); holePMessage.version(message.version()); holePMessage.intValue(message.messageId()); // making the message ready to send PeerAddress recipient = message.recipient().changeAddress(socketAddress.inetAddress()) .changePorts(socketAddress.tcpPort(), socketAddress.udpPort()).changeRelayed(false); holePMessage.recipient(recipient); holePMessage.command(RPC.Commands.HOLEP.getNr()); holePMessage.type(Message.Type.REQUEST_1); final FutureResponse holePResponse = new FutureResponse(holePMessage); final Map<String, Pair<EventExecutorGroup, ChannelHandler>> handlers; final int nrTCPHandlers = 7; // 5 / 0.75 handlers = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(nrTCPHandlers); final TimeoutFactory timeoutHandler = createTimeoutHandler(futureResponse, idleUDPSeconds, false); handlers.put("timeout0", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.idleStateHandlerTomP2P())); handlers.put("timeout1", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.timeHandler())); handlers.put( "decoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2PSinglePacketUDP(channelClientConfiguration.signatureFactory()))); handlers.put( "encoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2POutbound(false, channelClientConfiguration.signatureFactory()))); ChannelFuture channelFuture = channelCreator.createUDP(false, handlers, futureResponse); afterConnect(futureResponse, holePMessage, channelFuture, false); } /** * Create a timeout handler or null if its a fire and forget. In this case * we don't expect a reply and we don't need a timeout. * * @param futureResponse * The future to set the response * @param idleMillis * The timeout * @param fireAndForget * True, if we don't expect a message * @return The timeout creator that will create timeout handlers */ private TimeoutFactory createTimeoutHandler(final FutureResponse futureResponse, final int idleMillis, final boolean fireAndForget) { return fireAndForget ? null : new TimeoutFactory(futureResponse, idleMillis, peerStatusListeners, "Sender"); } /** * After connecting, we check if the connect was successful. * * @param futureResponse * The future to set the response * @param message * The message to send * @param channelFuture * the future of the connect * @param fireAndForget * True, if we don't expect a message */ private void afterConnect(final FutureResponse futureResponse, final Message message, final ChannelFuture channelFuture, final boolean fireAndForget) { if (channelFuture == null) { futureResponse.failed("could not create a " + (message.isUdp() ? "UDP" : "TCP") + " channel"); return; } LOG.debug("about to connect to {} with channel {}, ff={}", message.recipient(), channelFuture.channel(), fireAndForget); final Cancel connectCancel = createCancel(channelFuture); futureResponse.addCancel(connectCancel); channelFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { futureResponse.removeCancel(connectCancel); if (future.isSuccess()) { futureResponse.progressHandler(new ProgresHandler() { @Override public void progres() { final ChannelFuture writeFuture = future.channel().writeAndFlush(message); afterSend(writeFuture, futureResponse, fireAndForget); } }); // this needs to be called first before all other progress futureResponse.progressFirst(); } else { LOG.debug("Channel creation failed", future.cause()); futureResponse.failed("Channel creation failed " + future.channel() + "/" + future.cause()); // may have been closed by the other side, // or it may have been canceled from this side if (!(future.cause() instanceof CancellationException) && !(future.cause() instanceof ClosedChannelException) && !(future.cause() instanceof ConnectException)) { LOG.warn("Channel creation failed to {} for {}", future.channel(), message); } } } }); } /** * After sending, we check if the write was successful or if it was a fire * and forget. * * @param writeFuture * The future of the write operation. Can be UDP or TCP * @param futureResponse * The future to set the response * @param fireAndForget * True, if we don't expect a message */ private void afterSend(final ChannelFuture writeFuture, final FutureResponse futureResponse, final boolean fireAndForget) { final Cancel writeCancel = createCancel(writeFuture); writeFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { futureResponse.removeCancel(writeCancel); if (!future.isSuccess()) { futureResponse.failedLater(future.cause()); reportFailed(futureResponse, future.channel().close()); LOG.warn("Failed to write channel the request {} {}", futureResponse.request(), future.cause()); } if (fireAndForget) { futureResponse.responseLater(null); LOG.debug("fire and forget, close channel now {}, {}", futureResponse.request(), future.channel()); reportMessage(futureResponse, future.channel().close()); } } }); } /** * Report a failure after the channel was closed. * * @param futureResponse * The future to set the response * @param close * The close future * @param cause * The response message */ private void reportFailed(final FutureResponse futureResponse, final ChannelFuture close) { close.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture arg0) throws Exception { futureResponse.responseNow(); } }); } /** * Report a successful response after the channel was closed. * * @param futureResponse * The future to set the response * @param close * The close future * @param responseMessage * The response message */ private void reportMessage(final FutureResponse futureResponse, final ChannelFuture close) { close.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture arg0) throws Exception { futureResponse.responseNow(); } }); } /** * @param channelFuture * The channel future that can be canceled * @return Create a cancel class for the channel future */ private static Cancel createCancel(final ChannelFuture channelFuture) { return new Cancel() { @Override public void cancel() { channelFuture.cancel(true); } }; } private void removePeerIfFailed(final FutureResponse futureResponse, final Message message) { futureResponse.addListener(new BaseFutureAdapter<FutureResponse>() { @Override public void operationComplete(FutureResponse future) throws Exception { if (future.isFailed()) { if (message.recipient().isRelayed()) { // TODO: make the relay go away if failed } else { synchronized (peerStatusListeners) { for (PeerStatusListener peerStatusListener : peerStatusListeners) { peerStatusListener.peerFailed(message.recipient(), new PeerException(future)); } } } } } }); } public ConcurrentHashMap<Integer, FutureResponse> cachedRequests() { return cachedRequests; } }
core/src/main/java/net/tomp2p/connection/Sender.java
/* * Copyright 2013 Thomas Bocek * * 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.tomp2p.connection; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.GenericFutureListener; import java.net.ConnectException; import java.net.InetSocketAddress; import java.nio.channels.ClosedChannelException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReferenceArray; import net.tomp2p.futures.BaseFutureAdapter; import net.tomp2p.futures.Cancel; import net.tomp2p.futures.FutureDone; import net.tomp2p.futures.FutureForkJoin; import net.tomp2p.futures.FuturePing; import net.tomp2p.futures.FutureResponse; import net.tomp2p.message.Message; import net.tomp2p.message.Message.Type; import net.tomp2p.message.TomP2PCumulationTCP; import net.tomp2p.message.TomP2POutbound; import net.tomp2p.message.TomP2PSinglePacketUDP; import net.tomp2p.p2p.builder.PingBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; import net.tomp2p.peers.PeerSocketAddress; import net.tomp2p.peers.PeerStatusListener; import net.tomp2p.rpc.RPC; import net.tomp2p.rpc.RPC.Commands; import net.tomp2p.utils.Pair; import net.tomp2p.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class that sends out messages. * * @author Thomas Bocek * */ public class Sender { private static final Logger LOG = LoggerFactory.getLogger(Sender.class); private final List<PeerStatusListener> peerStatusListeners; private final ChannelClientConfiguration channelClientConfiguration; private final Dispatcher dispatcher; private final Random random; // this map caches all messages which are meant to be sent by a reverse // connection setup or TODO jwa a hole punch private final ConcurrentHashMap<Integer, FutureResponse> cachedRequests = new ConcurrentHashMap<Integer, FutureResponse>(); // this map caches all messages which are meant to be sent by a reverse // connection setup private final ConcurrentHashMap<Integer, Message> cachedMessages = new ConcurrentHashMap<Integer, Message>(); private PingBuilderFactory pingBuilderFactory; /** * Creates a new sender with the listeners for offline peers. * * @param peerStatusListeners * The listener for offline peers * @param channelClientConfiguration * The configuration used to get the signature factory * @param dispatcher */ public Sender(final Number160 peerId, final List<PeerStatusListener> peerStatusListeners, final ChannelClientConfiguration channelClientConfiguration, Dispatcher dispatcher) { this.peerStatusListeners = peerStatusListeners; this.channelClientConfiguration = channelClientConfiguration; this.dispatcher = dispatcher; this.random = new Random(peerId.hashCode()); } public ChannelClientConfiguration channelClientConfiguration() { return channelClientConfiguration; } public PingBuilderFactory pingBuilderFactory() { return pingBuilderFactory; } public Sender pingBuilderFactory(PingBuilderFactory pingBuilderFactory) { this.pingBuilderFactory = pingBuilderFactory; return this; } /** * Send a message via TCP. * * @param handler * The handler to deal with a reply message * @param futureResponse * The future to set the response * @param message * The message to send * @param channelCreator * The channel creator for the UPD channel * @param idleTCPSeconds * The idle time of a message until we fail * @param connectTimeoutMillis * The idle we set for the connection setup */ public void sendTCP(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final Message message, final ChannelCreator channelCreator, final int idleTCPSeconds, final int connectTimeoutMillis, final PeerConnection peerConnection) { // no need to continue if we already finished if (futureResponse.isCompleted()) { return; } removePeerIfFailed(futureResponse, message); // we need to set the neighbors if we use relays if (message.sender().isRelayed() && !message.sender().peerSocketAddresses().isEmpty()) { message.peerSocketAddresses(message.sender().peerSocketAddresses()); } final ChannelFuture channelFuture; if (peerConnection != null && peerConnection.channelFuture() != null && peerConnection.channelFuture().channel().isActive()) { channelFuture = sendTCPPeerConnection(peerConnection, handler, channelCreator, futureResponse); afterConnect(futureResponse, message, channelFuture, handler == null); } else if (channelCreator != null) { final TimeoutFactory timeoutHandler = createTimeoutHandler(futureResponse, idleTCPSeconds, handler == null); // check relay if (message.recipient().isRelayed()) { // check if reverse connection is possible if (!message.sender().isRelayed()) { handleRcon(handler, futureResponse, message, channelCreator, connectTimeoutMillis, peerConnection, timeoutHandler); } else { handleRelay(handler, futureResponse, message, channelCreator, idleTCPSeconds, connectTimeoutMillis, peerConnection, timeoutHandler); } } else { connectAndSend(handler, futureResponse, channelCreator, connectTimeoutMillis, peerConnection, timeoutHandler, message); } } } /** * This method initiates the reverse connection setup (or short: rconSetup). * It creates a new Message and sends it via relay to the unreachable peer * which then connects to this peer again. After the connectMessage from the * unreachable peer this peer will send the original Message and its content * directly. * * @param handler * @param futureResponse * @param message * @param channelCreator * @param connectTimeoutMillis * @param peerConnection * @param timeoutHandler */ private void handleRcon(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final Message message, final ChannelCreator channelCreator, final int connectTimeoutMillis, final PeerConnection peerConnection, final TimeoutFactory timeoutHandler) { message.keepAlive(true); LOG.debug("initiate reverse connection setup to peer with peerAddress {}", message.recipient()); Message rconMessage = createRconMessage(message); // cache the original message until the connection is established cachedRequests.put(message.messageId(), futureResponse); // wait for response (whether the reverse connection setup was // successful) final FutureResponse rconResponse = new FutureResponse(rconMessage); // TODO: expose peer somehow in sender to be able to notify on automatic // requests // peer.notifyAutomaticFutures(rconResponse); SimpleChannelInboundHandler<Message> rconInboundHandler = new SimpleChannelInboundHandler<Message>() { @Override protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception { if (msg.command() == Commands.RCON.getNr() && msg.type() == Type.OK) { LOG.debug("Successfully set up the reverse connection to peer {}", message.recipient().peerId()); rconResponse.response(msg); } else { LOG.debug("Could not acquire a reverse connection to peer {}", message.recipient().peerId()); rconResponse.failed("Could not acquire a reverse connection, got: " + msg); futureResponse.failed(rconResponse.failedReason()); } } }; // send reverse connection request instead of normal message sendTCP(rconInboundHandler, rconResponse, rconMessage, channelCreator, connectTimeoutMillis, connectTimeoutMillis, peerConnection); } /** * This method makes a copy of the original Message and prepares it for * sending it to the relay. * * @param message * @return rconMessage */ private static Message createRconMessage(final Message message) { // get Relay InetAddress from unreachable peer Object[] relayInetAdresses = message.recipient().peerSocketAddresses().toArray(); PeerSocketAddress socketAddress = null; if (relayInetAdresses.length > 0) { // we should be fair and choose one of the relays randomly socketAddress = (PeerSocketAddress) relayInetAdresses[Utils.randomPositiveInt(relayInetAdresses.length)]; } else { throw new IllegalArgumentException( "There are no PeerSocketAdresses available for this relayed Peer. This should not be possible!"); } // we need to make a copy of the original message Message rconMessage = new Message(); rconMessage.sender(message.sender()); rconMessage.version(message.version()); rconMessage.intValue(message.messageId()); // making the message ready to send PeerAddress recipient = message.recipient().changeAddress(socketAddress.inetAddress()) .changePorts(socketAddress.tcpPort(), socketAddress.udpPort()).changeRelayed(false); rconMessage.recipient(recipient); rconMessage.command(RPC.Commands.RCON.getNr()); rconMessage.type(Message.Type.REQUEST_1); return rconMessage; } /** * This method is extracted by @author jonaswagner to ensure that no * duplicate code exist. * * @param handler * @param futureResponse * @param channelCreator * @param connectTimeoutMillis * @param peerConnection * @param timeoutHandler * @param message */ private void connectAndSend(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final ChannelCreator channelCreator, final int connectTimeoutMillis, final PeerConnection peerConnection, final TimeoutFactory timeoutHandler, final Message message) { InetSocketAddress recipient = message.recipient().createSocketTCP(); final ChannelFuture channelFuture = sendTCPCreateChannel(recipient, channelCreator, peerConnection, handler, timeoutHandler, connectTimeoutMillis, futureResponse); afterConnect(futureResponse, message, channelFuture, handler == null); } /** * TODO: document what is done here * * @param handler * @param futureResponse * @param message * @param channelCreator * @param idleTCPSeconds * @param connectTimeoutMillis * @param peerConnection * @param timeoutHandler */ private void handleRelay(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final Message message, final ChannelCreator channelCreator, final int idleTCPSeconds, final int connectTimeoutMillis, final PeerConnection peerConnection, final TimeoutFactory timeoutHandler) { FutureDone<PeerSocketAddress> futurePing = pingFirst(message.recipient().peerSocketAddresses(), pingBuilderFactory); futurePing.addListener(new BaseFutureAdapter<FutureDone<PeerSocketAddress>>() { @Override public void operationComplete(final FutureDone<PeerSocketAddress> futureDone) throws Exception { if (futureDone.isSuccess()) { InetSocketAddress recipient = PeerSocketAddress.createSocketTCP(futureDone.object()); ChannelFuture channelFuture = sendTCPCreateChannel(recipient, channelCreator, peerConnection, handler, timeoutHandler, connectTimeoutMillis, futureResponse); afterConnect(futureResponse, message, channelFuture, handler == null); futureResponse.addListener(new BaseFutureAdapter<FutureResponse>() { @Override public void operationComplete(FutureResponse future) throws Exception { if (future.isFailed()) { if (future.responseMessage() != null && future.responseMessage().type() != Message.Type.USER1) { clearInactivePeerSocketAddress(futureDone); sendTCP(handler, futureResponse, message, channelCreator, idleTCPSeconds, connectTimeoutMillis, peerConnection); } } } private void clearInactivePeerSocketAddress(final FutureDone<PeerSocketAddress> futureDone) { Collection<PeerSocketAddress> tmp = new ArrayList<PeerSocketAddress>(); for (PeerSocketAddress psa : message.recipient().peerSocketAddresses()) { if (psa != null) { if (!psa.equals(futureDone.object())) { tmp.add(psa); } } } message.peerSocketAddresses(tmp); } }); } else { futureResponse.failed("no relay could be contacted", futureDone); } } }); } /** * TODO: say what we are doing here * * @param peerSocketAddresses * @param pingBuilder * @return */ private FutureDone<PeerSocketAddress> pingFirst(Collection<PeerSocketAddress> peerSocketAddresses, PingBuilderFactory pingBuilderFactory) { final FutureDone<PeerSocketAddress> futureDone = new FutureDone<PeerSocketAddress>(); FuturePing[] forks = new FuturePing[peerSocketAddresses.size()]; int index = 0; for (PeerSocketAddress psa : peerSocketAddresses) { if (psa != null) { InetSocketAddress inetSocketAddress = PeerSocketAddress.createSocketUDP(psa); PingBuilder pingBuilder = pingBuilderFactory.create(); forks[index++] = pingBuilder.inetAddress(inetSocketAddress.getAddress()).port(inetSocketAddress.getPort()).start(); } } FutureForkJoin<FuturePing> ffk = new FutureForkJoin<FuturePing>(1, true, new AtomicReferenceArray<FuturePing>(forks)); ffk.addListener(new BaseFutureAdapter<FutureForkJoin<FuturePing>>() { @Override public void operationComplete(FutureForkJoin<FuturePing> future) throws Exception { if (future.isSuccess()) { futureDone.done(future.first().remotePeer().peerSocketAddress()); } else { futureDone.failed(future); } } }); return futureDone; } private ChannelFuture sendTCPCreateChannel(InetSocketAddress recipient, ChannelCreator channelCreator, PeerConnection peerConnection, ChannelHandler handler, TimeoutFactory timeoutHandler, int connectTimeoutMillis, FutureResponse futureResponse) { final Map<String, Pair<EventExecutorGroup, ChannelHandler>> handlers; if (timeoutHandler != null) { handlers = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(); handlers.put("timeout0", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.idleStateHandlerTomP2P())); handlers.put("timeout1", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.timeHandler())); } else { handlers = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(); } handlers.put("decoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2PCumulationTCP(channelClientConfiguration.signatureFactory()))); handlers.put( "encoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2POutbound(false, channelClientConfiguration.signatureFactory()))); if (peerConnection != null) { // we expect replies on this connection handlers.put("dispatcher", new Pair<EventExecutorGroup, ChannelHandler>(null, dispatcher)); } if (timeoutHandler != null) { handlers.put("handler", new Pair<EventExecutorGroup, ChannelHandler>(null, handler)); } HeartBeat heartBeat = null; if (peerConnection != null) { heartBeat = new HeartBeat(peerConnection.heartBeatMillis(), TimeUnit.MILLISECONDS, pingBuilderFactory); handlers.put("heartbeat", new Pair<EventExecutorGroup, ChannelHandler>(null, heartBeat)); } ChannelFuture channelFuture = channelCreator.createTCP(recipient, connectTimeoutMillis, handlers, futureResponse); if (peerConnection != null && channelFuture != null) { peerConnection.channelFuture(channelFuture); heartBeat.peerConnection(peerConnection); } return channelFuture; } private ChannelFuture sendTCPPeerConnection(PeerConnection peerConnection, ChannelHandler handler, final ChannelCreator channelCreator, final FutureResponse futureResponse) { // if the channel gets closed, the future should get notified ChannelFuture channelFuture = peerConnection.channelFuture(); // channelCreator can be null if we don't need to create any channels if (channelCreator != null) { channelCreator.setupCloseListener(channelFuture, futureResponse); } ChannelPipeline pipeline = channelFuture.channel().pipeline(); // we need to replace the handler if this comes from the peer that // create a peerconnection, otherwise we // need to add a handler addOrReplace(pipeline, "dispatcher", "handler", handler); // uncomment this if the recipient should also heartbeat // addIfAbsent(pipeline, "handler", "heartbeat", // new HeartBeat(2, pingBuilder).peerConnection(peerConnection)); return channelFuture; } // private boolean addIfAbsent(ChannelPipeline pipeline, String before, // String name, // ChannelHandler channelHandler) { // List<String> names = pipeline.names(); // if (names.contains(name)) { // return false; // } else { // if (before == null) { // pipeline.addFirst(name, channelHandler); // } else { // pipeline.addBefore(before, name, channelHandler); // } // return true; // } // } private boolean addOrReplace(ChannelPipeline pipeline, String before, String name, ChannelHandler channelHandler) { List<String> names = pipeline.names(); if (names.contains(name)) { pipeline.replace(name, name, channelHandler); return false; } else { if (before == null) { pipeline.addFirst(name, channelHandler); } else { pipeline.addBefore(before, name, channelHandler); } return true; } } /** * Send a message via UDP. * * @param handler * The handler to deal with a reply message * @param futureResponse * The future to set the response * @param message * The message to send * @param channelCreator * The channel creator for the UPD channel * @param idleUDPSeconds * The idle time of a message until we fail * @param broadcast * True to send via layer 2 broadcast */ // TODO: if message.getRecipient() is me, than call dispatcher directly // without sending over Internet. public void sendUDP(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final Message message, final ChannelCreator channelCreator, final int idleUDPSeconds, final boolean broadcast) { // no need to continue if we already finished if (futureResponse.isCompleted()) { return; } removePeerIfFailed(futureResponse, message); boolean isFireAndForget = handler == null; final Map<String, Pair<EventExecutorGroup, ChannelHandler>> handlers; if (isFireAndForget) { final int nrTCPHandlers = 3; // 2 / 0.75 handlers = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(nrTCPHandlers); } else { final int nrTCPHandlers = 7; // 5 / 0.75 handlers = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(nrTCPHandlers); final TimeoutFactory timeoutHandler = createTimeoutHandler(futureResponse, idleUDPSeconds, isFireAndForget); handlers.put("timeout0", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.idleStateHandlerTomP2P())); handlers.put("timeout1", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.timeHandler())); } handlers.put( "decoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2PSinglePacketUDP(channelClientConfiguration.signatureFactory()))); handlers.put( "encoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2POutbound(false, channelClientConfiguration.signatureFactory()))); if (!isFireAndForget) { handlers.put("handler", new Pair<EventExecutorGroup, ChannelHandler>(null, handler)); } if (message.recipient().isRelayed() && message.command() != RPC.Commands.NEIGHBOR.getNr() && message.command() != RPC.Commands.PING.getNr()) { LOG.warn("Tried to send UDP message to unreachable peers. Only TCP messages can be sent to unreachable peers: {}", message); futureResponse.failed("Tried to send UDP message to unreachable peers. Only TCP messages can be sent to unreachable peers"); } else { final ChannelFuture channelFuture; if (message.recipient().isRelayed()) { List<PeerSocketAddress> psa = new ArrayList<PeerSocketAddress>(message.recipient().peerSocketAddresses()); LOG.debug("send neighbor request to random relay peer {}", psa); if (psa.size() > 0) { PeerSocketAddress ps = psa.get(random.nextInt(psa.size())); message.recipientRelay(message.recipient().changePeerSocketAddress(ps).changeRelayed(true)); channelFuture = channelCreator.createUDP(broadcast, handlers, futureResponse); } else { futureResponse.failed("Peer is relayed, but no relay given"); return; } } else { channelFuture = channelCreator.createUDP(broadcast, handlers, futureResponse); } afterConnect(futureResponse, message, channelFuture, handler == null); } } private void prepareHolePunch(final SimpleChannelInboundHandler<Message> handler, final FutureResponse futureResponse, final Message message, final ChannelCreator channelCreator, final int idleUDPSeconds, final boolean broadcast) { // TODO jwa notify rendez-vous server // TODO jwa punch a hole into firewall // TODO jwa store message to chachedRequests cachedRequests.put(message.messageId(), futureResponse); // get Relay InetAddress from unreachable peer Object[] relayInetAdresses = message.recipient().peerSocketAddresses().toArray(); PeerSocketAddress socketAddress = null; if (relayInetAdresses.length > 0) { // we should be fair and choose one of the relays randomly socketAddress = (PeerSocketAddress) relayInetAdresses[Utils.randomPositiveInt(relayInetAdresses.length)]; } else { throw new IllegalArgumentException( "There are no PeerSocketAdresses available for this relayed Peer. This should not be possible!"); } Message holePMessage = new Message(); holePMessage.sender(message.sender()); holePMessage.version(message.version()); holePMessage.intValue(message.messageId()); // making the message ready to send PeerAddress recipient = message.recipient().changeAddress(socketAddress.inetAddress()) .changePorts(socketAddress.tcpPort(), socketAddress.udpPort()).changeRelayed(false); holePMessage.recipient(recipient); holePMessage.command(RPC.Commands.HOLEP.getNr()); holePMessage.type(Message.Type.REQUEST_1); final FutureResponse holePResponse = new FutureResponse(holePMessage); final Map<String, Pair<EventExecutorGroup, ChannelHandler>> handlers; final int nrTCPHandlers = 7; // 5 / 0.75 handlers = new LinkedHashMap<String, Pair<EventExecutorGroup, ChannelHandler>>(nrTCPHandlers); final TimeoutFactory timeoutHandler = createTimeoutHandler(futureResponse, idleUDPSeconds, false); handlers.put("timeout0", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.idleStateHandlerTomP2P())); handlers.put("timeout1", new Pair<EventExecutorGroup, ChannelHandler>(null, timeoutHandler.timeHandler())); handlers.put( "decoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2PSinglePacketUDP(channelClientConfiguration.signatureFactory()))); handlers.put( "encoder", new Pair<EventExecutorGroup, ChannelHandler>(null, new TomP2POutbound(false, channelClientConfiguration.signatureFactory()))); ChannelFuture channelFuture = channelCreator.createUDP(false, handlers, futureResponse); afterConnect(futureResponse, holePMessage, channelFuture, false); } /** * Create a timeout handler or null if its a fire and forget. In this case * we don't expect a reply and we don't need a timeout. * * @param futureResponse * The future to set the response * @param idleMillis * The timeout * @param fireAndForget * True, if we don't expect a message * @return The timeout creator that will create timeout handlers */ private TimeoutFactory createTimeoutHandler(final FutureResponse futureResponse, final int idleMillis, final boolean fireAndForget) { return fireAndForget ? null : new TimeoutFactory(futureResponse, idleMillis, peerStatusListeners, "Sender"); } /** * After connecting, we check if the connect was successful. * * @param futureResponse * The future to set the response * @param message * The message to send * @param channelFuture * the future of the connect * @param fireAndForget * True, if we don't expect a message */ private void afterConnect(final FutureResponse futureResponse, final Message message, final ChannelFuture channelFuture, final boolean fireAndForget) { if (channelFuture == null) { futureResponse.failed("could not create a " + (message.isUdp() ? "UDP" : "TCP") + " channel"); return; } LOG.debug("about to connect to {} with channel {}, ff={}", message.recipient(), channelFuture.channel(), fireAndForget); final Cancel connectCancel = createCancel(channelFuture); futureResponse.addCancel(connectCancel); channelFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { futureResponse.removeCancel(connectCancel); if (future.isSuccess()) { futureResponse.progressHandler(new ProgresHandler() { @Override public void progres() { final ChannelFuture writeFuture = future.channel().writeAndFlush(message); afterSend(writeFuture, futureResponse, fireAndForget); } }); // this needs to be called first before all other progress futureResponse.progressFirst(); } else { LOG.debug("Channel creation failed", future.cause()); futureResponse.failed("Channel creation failed " + future.channel() + "/" + future.cause()); // may have been closed by the other side, // or it may have been canceled from this side if (!(future.cause() instanceof CancellationException) && !(future.cause() instanceof ClosedChannelException) && !(future.cause() instanceof ConnectException)) { LOG.warn("Channel creation failed to {} for {}", future.channel(), message); } } } }); } /** * After sending, we check if the write was successful or if it was a fire * and forget. * * @param writeFuture * The future of the write operation. Can be UDP or TCP * @param futureResponse * The future to set the response * @param fireAndForget * True, if we don't expect a message */ private void afterSend(final ChannelFuture writeFuture, final FutureResponse futureResponse, final boolean fireAndForget) { final Cancel writeCancel = createCancel(writeFuture); writeFuture.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { futureResponse.removeCancel(writeCancel); if (!future.isSuccess()) { futureResponse.failedLater(future.cause()); reportFailed(futureResponse, future.channel().close()); LOG.warn("Failed to write channel the request {} {}", futureResponse.request(), future.cause()); } if (fireAndForget) { futureResponse.responseLater(null); LOG.debug("fire and forget, close channel now {}, {}", futureResponse.request(), future.channel()); reportMessage(futureResponse, future.channel().close()); } } }); } /** * Report a failure after the channel was closed. * * @param futureResponse * The future to set the response * @param close * The close future * @param cause * The response message */ private void reportFailed(final FutureResponse futureResponse, final ChannelFuture close) { close.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture arg0) throws Exception { futureResponse.responseNow(); } }); } /** * Report a successful response after the channel was closed. * * @param futureResponse * The future to set the response * @param close * The close future * @param responseMessage * The response message */ private void reportMessage(final FutureResponse futureResponse, final ChannelFuture close) { close.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture arg0) throws Exception { futureResponse.responseNow(); } }); } /** * @param channelFuture * The channel future that can be canceled * @return Create a cancel class for the channel future */ private static Cancel createCancel(final ChannelFuture channelFuture) { return new Cancel() { @Override public void cancel() { channelFuture.cancel(true); } }; } private void removePeerIfFailed(final FutureResponse futureResponse, final Message message) { futureResponse.addListener(new BaseFutureAdapter<FutureResponse>() { @Override public void operationComplete(FutureResponse future) throws Exception { if (future.isFailed()) { if (message.recipient().isRelayed()) { // TODO: make the relay go away if failed } else { synchronized (peerStatusListeners) { for (PeerStatusListener peerStatusListener : peerStatusListeners) { peerStatusListener.peerFailed(message.recipient(), new PeerException(future)); } } } } } }); } public ConcurrentHashMap<Integer, FutureResponse> cachedRequests() { return cachedRequests; } }
sender fix
core/src/main/java/net/tomp2p/connection/Sender.java
sender fix
<ide><path>ore/src/main/java/net/tomp2p/connection/Sender.java <ide> } <ide> removePeerIfFailed(futureResponse, message); <ide> <add> if (message.sender().isRelayed()) { <add> message.peerSocketAddresses(message.sender().peerSocketAddresses()); <add> } <add> <add> if (message.recipient().isRelayed() && message.sender().isRelayed()) { <add> prepareHolePunch(handler, futureResponse, message, channelCreator, idleUDPSeconds, broadcast); <add> return; <add> } <add> <ide> boolean isFireAndForget = handler == null; <ide> <ide> final Map<String, Pair<EventExecutorGroup, ChannelHandler>> handlers;
Java
agpl-3.0
e2589dd4f50605212d006f3988b61e0e25d4ee4d
0
UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,ua-eas/kfs,kuali/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,kuali/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,kkronenb/kfs,ua-eas/kfs,ua-eas/kfs-devops-automation-fork,smith750/kfs,kuali/kfs,smith750/kfs,kuali/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,smith750/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,ua-eas/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,bhutchinson/kfs,kuali/kfs,quikkian-ua-devops/will-financials,kkronenb/kfs,ua-eas/kfs,smith750/kfs,kkronenb/kfs,kkronenb/kfs,quikkian-ua-devops/kfs
/* * Copyright (c) 2004, 2005 The National Association of College and University Business Officers, * Cornell University, Trustees of Indiana University, Michigan State University Board of Trustees, * Trustees of San Joaquin Delta College, University of Hawai'i, The Arizona Board of Regents on * behalf of the University of Arizona, and the r*smart group. * * Licensed under the Educational Community License Version 1.0 (the "License"); By obtaining, * using and/or copying this Original Work, you agree that you have read, understand, and will * comply with the terms and conditions of the Educational Community License. * * You may obtain a copy of the License at: * * http://kualiproject.org/license.html * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.kuali.module.financial.document; import org.kuali.Constants; import org.kuali.module.financial.YearEndDocument; /** * This is the business object that represents the <code>{@link YearEndDocument}</code> version of <code>{@link GeneralErrorCorrectionDocument}</code> in Kuali. * This is a transactional document that will eventually post transactions to the G/L. It integrates with workflow and also contains two groupings of accounting * lines: from and to. From lines are the source lines, to lines are the target lines. This document is exactly the same as the * non-<code>{@link YearEndDocument}</code> version except that it has slightly different routing and that it only allows posting to the year end accounting * period for a year. * * @author Kuali Financial Transactions Team ([email protected]) */ public class YearEndGeneralErrorCorrectionDocument extends GeneralErrorCorrectionDocument implements YearEndDocument { private static final long serialVersionUID = -8182003625909239560L; private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(YearEndGeneralErrorCorrectionDocument.class); /** * Initializes the array lists and some basic info. */ public YearEndGeneralErrorCorrectionDocument() { super(); } }
work/src/org/kuali/kfs/fp/document/YearEndGeneralErrorCorrectionDocument.java
/* * Copyright (c) 2004, 2005 The National Association of College and University Business Officers, * Cornell University, Trustees of Indiana University, Michigan State University Board of Trustees, * Trustees of San Joaquin Delta College, University of Hawai'i, The Arizona Board of Regents on * behalf of the University of Arizona, and the r*smart group. * * Licensed under the Educational Community License Version 1.0 (the "License"); By obtaining, * using and/or copying this Original Work, you agree that you have read, understand, and will * comply with the terms and conditions of the Educational Community License. * * You may obtain a copy of the License at: * * http://kualiproject.org/license.html * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.kuali.module.financial.document; import org.kuali.Constants; /** * This is the business object that represents the YearEndGeneralErrorCorrectionDocument in Kuali. This is a transactional document * that will eventually post transactions to the G/L. It integrates with workflow and also contains two groupings of accounting * lines: from and to. From lines are the source lines, to lines are the target lines. This document is exactly the same as the * non-Year End version except that it has slightly different routing and that it only allows posting to the year end accounting * period for a year. * * @author Kuali Financial Transactions Team ([email protected]) */ public class YearEndGeneralErrorCorrectionDocument extends GeneralErrorCorrectionDocument { private static final long serialVersionUID = -8182003625909239560L; private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(YearEndGeneralErrorCorrectionDocument.class); /** * Initializes the array lists and some basic info. */ public YearEndGeneralErrorCorrectionDocument() { super(); } /** * Overrides the base implementation to return "From". */ public String getSourceAccountingLinesSectionTitle() { return Constants.FROM; } /** * Overrides the base implementation to return "To". */ public String getTargetAccountingLinesSectionTitle() { return Constants.TO; } }
KULEDOCS-1353 Cleaned up YearEndGeneralErrorCorrectionDocument. Also, now implements YearEndDocument.
work/src/org/kuali/kfs/fp/document/YearEndGeneralErrorCorrectionDocument.java
KULEDOCS-1353
<ide><path>ork/src/org/kuali/kfs/fp/document/YearEndGeneralErrorCorrectionDocument.java <ide> <ide> import org.kuali.Constants; <ide> <add>import org.kuali.module.financial.YearEndDocument; <add> <ide> <ide> /** <del> * This is the business object that represents the YearEndGeneralErrorCorrectionDocument in Kuali. This is a transactional document <del> * that will eventually post transactions to the G/L. It integrates with workflow and also contains two groupings of accounting <add> * This is the business object that represents the <code>{@link YearEndDocument}</code> version of <code>{@link GeneralErrorCorrectionDocument}</code> in Kuali. <add> * This is a transactional document that will eventually post transactions to the G/L. It integrates with workflow and also contains two groupings of accounting <ide> * lines: from and to. From lines are the source lines, to lines are the target lines. This document is exactly the same as the <del> * non-Year End version except that it has slightly different routing and that it only allows posting to the year end accounting <add> * non-<code>{@link YearEndDocument}</code> version except that it has slightly different routing and that it only allows posting to the year end accounting <ide> * period for a year. <ide> * <ide> * @author Kuali Financial Transactions Team ([email protected]) <ide> */ <del>public class YearEndGeneralErrorCorrectionDocument extends GeneralErrorCorrectionDocument { <add>public class YearEndGeneralErrorCorrectionDocument extends GeneralErrorCorrectionDocument implements YearEndDocument { <ide> private static final long serialVersionUID = -8182003625909239560L; <ide> private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(YearEndGeneralErrorCorrectionDocument.class); <ide> <ide> public YearEndGeneralErrorCorrectionDocument() { <ide> super(); <ide> } <del> <del> /** <del> * Overrides the base implementation to return "From". <del> */ <del> public String getSourceAccountingLinesSectionTitle() { <del> return Constants.FROM; <del> } <del> <del> /** <del> * Overrides the base implementation to return "To". <del> */ <del> public String getTargetAccountingLinesSectionTitle() { <del> return Constants.TO; <del> } <ide> }
Java
mit
2165c2d550a0be023d78bf152c30b9a5c26156a3
0
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
package org.innovateuk.ifs.async.generation; import org.innovateuk.ifs.commons.BaseIntegrationTest; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; /** * Tests for the {@link AsyncFuturesGenerator#awaitAll} methods. These methods allow us to await the completion of other * Futures before performing another Future piece of work. Above and beyond {@link CompletableFuture#allOf(CompletableFuture[])}, * these methods also register the newly generated Future with {@link AsyncFuturesHolder} so that we can await its completion * during the execution of Controller methods (to prevent Thymeleaf form attempting to render pages before all Futures * have completed writing data to the model. */ public class AsyncFuturesGeneratorAwaitAllIntegrationTest extends BaseIntegrationTest { @Autowired private AsyncFuturesGenerator generator; @Before public void clearRegisteredFutures() { AsyncFuturesHolder.clearFutures(); } /** * This is a simple test for the {@link AsyncFuturesGenerator#awaitAll(CompletableFuture)} method that checks that * the awaiting Future successfully waits for the first Future to complete and then uses its value to perform some * new work. */ @Test public void testSimpleAwaitAll() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future = generator.async(() -> 3); CompletableFuture<Integer> awaitingFuture = generator.awaitAll(future).thenApply(result -> result * 3); Integer finalResult = awaitingFuture.get(); assertEquals(Integer.valueOf(9), finalResult); } /** * This tests that futures generated via {@link AsyncFuturesGenerator#awaitAll(CompletableFuture)} are registered with * {@link AsyncFuturesHolder} so that we can block on them when completing Controller methods. */ @Test public void testSimpleAwaitAllRegistersNewAwaitingFuture() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future = generator.async(() -> 3); CompletableFuture<Integer> awaitingFuture = generator.awaitAll(future).thenApply(result -> result * 3); List<RegisteredAsyncFutureDetails> registeredFutures = new ArrayList<>(AsyncFuturesHolder.getFuturesOrInitialise()); assertEquals(2, registeredFutures.size()); assertEquals(future, registeredFutures.get(0).getFuture()); assertEquals(awaitingFuture, registeredFutures.get(1).getFuture()); } /** * This test is for {@link AsyncFuturesGenerator#awaitAll(CompletableFuture, CompletableFuture)} to show that 2 * futures can be awaited on and that their subsequent results will be provided as a tuple-2 to the new Future * to perform some new work on the multiple results of the dependent Futures. */ @Test public void testTuple2AwaitAllFuture() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future1 = generator.async(() -> 3); CompletableFuture<Integer> future2 = generator.async(() -> 4); CompletableFuture<Integer> awaitingFuture = generator.awaitAll(future1, future2).thenApply((r1, r2) -> r1 + r2); Integer finalResult = awaitingFuture.get(); assertEquals(Integer.valueOf(7), finalResult); List<RegisteredAsyncFutureDetails> registeredFutures = new ArrayList<>(AsyncFuturesHolder.getFuturesOrInitialise()); assertEquals(3, registeredFutures.size()); assertEquals(future1, registeredFutures.get(0).getFuture()); assertEquals(future2, registeredFutures.get(1).getFuture()); assertEquals(awaitingFuture, registeredFutures.get(2).getFuture()); } /** * This test is for {@link AsyncFuturesGenerator#awaitAll(CompletableFuture, CompletableFuture, CompletableFuture)} * to show that 3 futures can be awaited on and that their subsequent results will be provided as a tuple-3 to the * new Future to perform some new work on the multiple results of the dependent Futures. */ @Test public void testTuple3AwaitAllFuture() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future1 = generator.async(() -> 3); CompletableFuture<Integer> future2 = generator.async(() -> 4); CompletableFuture<Integer> future3 = generator.async(() -> 5); CompletableFuture<Integer> awaitingFuture = generator.awaitAll(future1, future2, future3).thenApply((r1, r2, r3) -> r1 + r2 + r3); Integer finalResult = awaitingFuture.get(); assertEquals(Integer.valueOf(12), finalResult); List<RegisteredAsyncFutureDetails> registeredFutures = new ArrayList<>(AsyncFuturesHolder.getFuturesOrInitialise()); assertEquals(4, registeredFutures.size()); assertEquals(future1, registeredFutures.get(0).getFuture()); assertEquals(future2, registeredFutures.get(1).getFuture()); assertEquals(future3, registeredFutures.get(2).getFuture()); assertEquals(awaitingFuture, registeredFutures.get(3).getFuture()); } /** * This test is for {@link AsyncFuturesGenerator#awaitAll(CompletableFuture, CompletableFuture, CompletableFuture, CompletableFuture[])} * to show that more than 3 futures can be awaited on. */ @Test public void testTupleNAwaitAllFuture() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future1 = generator.async(() -> 3); CompletableFuture<Integer> future2 = generator.async(() -> 4); CompletableFuture<Integer> future3 = generator.async(() -> 5); CompletableFuture<Integer> future4 = generator.async(() -> 6); CompletableFuture<Integer> future5 = generator.async(() -> 7); List<Integer> results = new ArrayList<>(); CompletableFuture<Void> awaitingFuture = generator.awaitAll(future1, future2, future3, future4, future5).thenApply(() -> { results.addAll(asList(future1.get())); results.addAll(asList(future2.get())); results.addAll(asList(future3.get())); results.addAll(asList(future4.get())); results.addAll(asList(future5.get())); return null; }); awaitingFuture.get(); assertEquals(asList(3, 4, 5, 6, 7), results); List<RegisteredAsyncFutureDetails> registeredFutures = new ArrayList<>(AsyncFuturesHolder.getFuturesOrInitialise()); assertEquals(6, registeredFutures.size()); assertEquals(future1, registeredFutures.get(0).getFuture()); assertEquals(future2, registeredFutures.get(1).getFuture()); assertEquals(future3, registeredFutures.get(2).getFuture()); assertEquals(future4, registeredFutures.get(3).getFuture()); assertEquals(future5, registeredFutures.get(4).getFuture()); assertEquals(awaitingFuture, registeredFutures.get(5).getFuture()); } }
ifs-web-service/ifs-web-core/src/test/java/org/innovateuk/ifs/async/generation/AsyncFuturesGeneratorAwaitAllIntegrationTest.java
package org.innovateuk.ifs.async.generation; import org.innovateuk.ifs.commons.BaseIntegrationTest; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; /** * Tests for the {@link AsyncFuturesGenerator#awaitAll} methods. These methods allow us to await the completion of other * Futures before performing another Future piece of work. Above and beyond {@link CompletableFuture#allOf(CompletableFuture[])}, * these methods also register the newly generated Future with {@link AsyncFuturesHolder} so that we can await its completion * during the execution of Controller methods (to prevent Thymeleaf form attempting to render pages before all Futures * have completed writing data to the model. */ public class AsyncFuturesGeneratorAwaitAllIntegrationTest extends BaseIntegrationTest { @Autowired private AsyncFuturesGenerator generator; @Autowired private ThreadPoolTaskExecutor taskExecutor; @Before public void clearRegisteredFutures() { AsyncFuturesHolder.clearFutures(); } /** * This is a simple test for the {@link AsyncFuturesGenerator#awaitAll(CompletableFuture)} method that checks that * the awaiting Future successfully waits for the first Future to complete and then uses its value to perform some * new work. */ @Test public void testSimpleAwaitAll() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future = generator.async(() -> 3); CompletableFuture<Integer> awaitingFuture = generator.awaitAll(future).thenApply(result -> result * 3); Integer finalResult = awaitingFuture.get(); assertEquals(Integer.valueOf(9), finalResult); } /** * This tests that futures generated via {@link AsyncFuturesGenerator#awaitAll(CompletableFuture)} are registered with * {@link AsyncFuturesHolder} so that we can block on them when completing Controller methods. */ @Test public void testSimpleAwaitAllRegistersNewAwaitingFuture() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future = generator.async(() -> 3); CompletableFuture<Integer> awaitingFuture = generator.awaitAll(future).thenApply(result -> result * 3); List<RegisteredAsyncFutureDetails> registeredFutures = new ArrayList<>(AsyncFuturesHolder.getFuturesOrInitialise()); assertEquals(2, registeredFutures.size()); assertEquals(future, registeredFutures.get(0).getFuture()); assertEquals(awaitingFuture, registeredFutures.get(1).getFuture()); } /** * This test is for {@link AsyncFuturesGenerator#awaitAll(CompletableFuture, CompletableFuture)} to show that 2 * futures can be awaited on and that their subsequent results will be provided as a tuple-2 to the new Future * to perform some new work on the multiple results of the dependent Futures. */ @Test public void testTuple2AwaitAllFuture() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future1 = generator.async(() -> 3); CompletableFuture<Integer> future2 = generator.async(() -> 4); CompletableFuture<Integer> awaitingFuture = generator.awaitAll(future1, future2).thenApply((r1, r2) -> r1 + r2); Integer finalResult = awaitingFuture.get(); assertEquals(Integer.valueOf(7), finalResult); List<RegisteredAsyncFutureDetails> registeredFutures = new ArrayList<>(AsyncFuturesHolder.getFuturesOrInitialise()); assertEquals(3, registeredFutures.size()); assertEquals(future1, registeredFutures.get(0).getFuture()); assertEquals(future2, registeredFutures.get(1).getFuture()); assertEquals(awaitingFuture, registeredFutures.get(2).getFuture()); } /** * This test is for {@link AsyncFuturesGenerator#awaitAll(CompletableFuture, CompletableFuture, CompletableFuture)} * to show that 3 futures can be awaited on and that their subsequent results will be provided as a tuple-3 to the * new Future to perform some new work on the multiple results of the dependent Futures. */ @Test public void testTuple3AwaitAllFuture() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future1 = generator.async(() -> 3); CompletableFuture<Integer> future2 = generator.async(() -> 4); CompletableFuture<Integer> future3 = generator.async(() -> 5); CompletableFuture<Integer> awaitingFuture = generator.awaitAll(future1, future2, future3).thenApply((r1, r2, r3) -> r1 + r2 + r3); Integer finalResult = awaitingFuture.get(); assertEquals(Integer.valueOf(12), finalResult); List<RegisteredAsyncFutureDetails> registeredFutures = new ArrayList<>(AsyncFuturesHolder.getFuturesOrInitialise()); assertEquals(4, registeredFutures.size()); assertEquals(future1, registeredFutures.get(0).getFuture()); assertEquals(future2, registeredFutures.get(1).getFuture()); assertEquals(future3, registeredFutures.get(2).getFuture()); assertEquals(awaitingFuture, registeredFutures.get(3).getFuture()); } /** * This test is for {@link AsyncFuturesGenerator#awaitAll(CompletableFuture, CompletableFuture, CompletableFuture, CompletableFuture[])} * to show that more than 3 futures can be awaited on. */ @Test public void testTupleNAwaitAllFuture() throws ExecutionException, InterruptedException { CompletableFuture<Integer> future1 = generator.async(() -> 3); CompletableFuture<Integer> future2 = generator.async(() -> 4); CompletableFuture<Integer> future3 = generator.async(() -> 5); CompletableFuture<Integer> future4 = generator.async(() -> 6); CompletableFuture<Integer> future5 = generator.async(() -> 7); List<Integer> results = new ArrayList<>(); CompletableFuture<Void> awaitingFuture = generator.awaitAll(future1, future2, future3, future4, future5).thenApply(() -> { results.addAll(asList(future1.get())); results.addAll(asList(future2.get())); results.addAll(asList(future3.get())); results.addAll(asList(future4.get())); results.addAll(asList(future5.get())); return null; }); awaitingFuture.get(); assertEquals(asList(3, 4, 5, 6, 7), results); List<RegisteredAsyncFutureDetails> registeredFutures = new ArrayList<>(AsyncFuturesHolder.getFuturesOrInitialise()); assertEquals(6, registeredFutures.size()); assertEquals(future1, registeredFutures.get(0).getFuture()); assertEquals(future2, registeredFutures.get(1).getFuture()); assertEquals(future3, registeredFutures.get(2).getFuture()); assertEquals(future4, registeredFutures.get(3).getFuture()); assertEquals(future5, registeredFutures.get(4).getFuture()); assertEquals(awaitingFuture, registeredFutures.get(5).getFuture()); } }
Added simple tests for all of the awaitAll methods in AsyncFuturesGenerator
ifs-web-service/ifs-web-core/src/test/java/org/innovateuk/ifs/async/generation/AsyncFuturesGeneratorAwaitAllIntegrationTest.java
Added simple tests for all of the awaitAll methods in AsyncFuturesGenerator
<ide><path>fs-web-service/ifs-web-core/src/test/java/org/innovateuk/ifs/async/generation/AsyncFuturesGeneratorAwaitAllIntegrationTest.java <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.springframework.beans.factory.annotation.Autowired; <del>import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; <ide> <ide> import java.util.ArrayList; <ide> import java.util.List; <ide> <ide> @Autowired <ide> private AsyncFuturesGenerator generator; <del> <del> @Autowired <del> private ThreadPoolTaskExecutor taskExecutor; <ide> <ide> @Before <ide> public void clearRegisteredFutures() { <ide> CompletableFuture<Integer> awaitingFuture = generator.awaitAll(future).thenApply(result -> result * 3); <ide> <ide> List<RegisteredAsyncFutureDetails> registeredFutures = new ArrayList<>(AsyncFuturesHolder.getFuturesOrInitialise()); <del> assertEquals(2, registeredFutures.size()); <add> assertEquals(2, registeredFutures.size()); <ide> assertEquals(future, registeredFutures.get(0).getFuture()); <ide> assertEquals(awaitingFuture, registeredFutures.get(1).getFuture()); <ide> }
Java
apache-2.0
6cbd076b0f3dc7b8cf3cc2978c676d8374d25d9a
0
wwjiang007/alluxio,yuluo-ding/alluxio,wwjiang007/alluxio,apc999/alluxio,EvilMcJerkface/alluxio,Reidddddd/alluxio,riversand963/alluxio,maobaolong/alluxio,madanadit/alluxio,apc999/alluxio,madanadit/alluxio,calvinjia/tachyon,riversand963/alluxio,ShailShah/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,wwjiang007/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,bf8086/alluxio,ShailShah/alluxio,WilliamZapata/alluxio,yuluo-ding/alluxio,ShailShah/alluxio,maboelhassan/alluxio,riversand963/alluxio,Reidddddd/alluxio,maobaolong/alluxio,calvinjia/tachyon,ChangerYoung/alluxio,WilliamZapata/alluxio,Reidddddd/mo-alluxio,wwjiang007/alluxio,PasaLab/tachyon,aaudiber/alluxio,wwjiang007/alluxio,uronce-cc/alluxio,yuluo-ding/alluxio,apc999/alluxio,bf8086/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,yuluo-ding/alluxio,EvilMcJerkface/alluxio,ShailShah/alluxio,Alluxio/alluxio,yuluo-ding/alluxio,bf8086/alluxio,uronce-cc/alluxio,ShailShah/alluxio,aaudiber/alluxio,calvinjia/tachyon,jswudi/alluxio,jswudi/alluxio,wwjiang007/alluxio,Reidddddd/mo-alluxio,wwjiang007/alluxio,aaudiber/alluxio,apc999/alluxio,jsimsa/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,maobaolong/alluxio,riversand963/alluxio,riversand963/alluxio,PasaLab/tachyon,wwjiang007/alluxio,madanadit/alluxio,Reidddddd/alluxio,aaudiber/alluxio,wwjiang007/alluxio,Alluxio/alluxio,maboelhassan/alluxio,madanadit/alluxio,ChangerYoung/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,yuluo-ding/alluxio,Alluxio/alluxio,PasaLab/tachyon,PasaLab/tachyon,maobaolong/alluxio,aaudiber/alluxio,ChangerYoung/alluxio,jsimsa/alluxio,madanadit/alluxio,EvilMcJerkface/alluxio,bf8086/alluxio,Reidddddd/alluxio,PasaLab/tachyon,bf8086/alluxio,jswudi/alluxio,calvinjia/tachyon,ShailShah/alluxio,jsimsa/alluxio,apc999/alluxio,uronce-cc/alluxio,apc999/alluxio,madanadit/alluxio,PasaLab/tachyon,jsimsa/alluxio,ChangerYoung/alluxio,maobaolong/alluxio,jswudi/alluxio,Alluxio/alluxio,maobaolong/alluxio,aaudiber/alluxio,Reidddddd/alluxio,riversand963/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,maobaolong/alluxio,calvinjia/tachyon,maboelhassan/alluxio,WilliamZapata/alluxio,uronce-cc/alluxio,WilliamZapata/alluxio,Reidddddd/alluxio,jsimsa/alluxio,EvilMcJerkface/alluxio,maboelhassan/alluxio,Reidddddd/mo-alluxio,PasaLab/tachyon,maboelhassan/alluxio,maboelhassan/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,jswudi/alluxio,Alluxio/alluxio,uronce-cc/alluxio,WilliamZapata/alluxio,maobaolong/alluxio,uronce-cc/alluxio,madanadit/alluxio,Alluxio/alluxio,apc999/alluxio,aaudiber/alluxio,calvinjia/tachyon,EvilMcJerkface/alluxio,ChangerYoung/alluxio,Alluxio/alluxio,jswudi/alluxio,bf8086/alluxio,jsimsa/alluxio,Reidddddd/mo-alluxio,madanadit/alluxio,calvinjia/tachyon,Reidddddd/alluxio,calvinjia/tachyon,maboelhassan/alluxio
/* * Licensed to the University of California, Berkeley 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 tachyon.master; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import tachyon.Constants; import tachyon.TachyonURI; import tachyon.conf.TachyonConf; import tachyon.thrift.BlockInfoException; import tachyon.thrift.ClientFileInfo; import tachyon.thrift.FileAlreadyExistException; import tachyon.thrift.FileDoesNotExistException; import tachyon.thrift.InvalidPathException; import tachyon.thrift.SuspectedFileSizeException; import tachyon.thrift.TableColumnException; import tachyon.thrift.TachyonException; /** * Unit tests for tachyon.MasterInfo */ public class MasterInfoIntegrationTest { class ConcurrentCreator implements Callable<Void> { private int mDepth; private int mConcurrencyDepth; private TachyonURI mInitPath; ConcurrentCreator(int depth, int concurrencyDepth, TachyonURI initPath) { this.mDepth = depth; this.mConcurrencyDepth = concurrencyDepth; this.mInitPath = initPath; } @Override public Void call() throws Exception { exec(this.mDepth, this.mConcurrencyDepth, this.mInitPath); return null; } public void exec(int depth, int concurrencyDepth, TachyonURI path) throws Exception { if (depth < 1) { return; } else if (depth == 1) { int fileId = mMasterInfo.createFile(true, path, false, Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(fileId, mMasterInfo.getFileId(path)); } else { int fileId = mMasterInfo.createFile(true, path, true, 0); Assert.assertEquals(fileId, mMasterInfo.getFileId(path)); } if (concurrencyDepth > 0) { ExecutorService executor = Executors.newCachedThreadPool(); ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE); for (int i = 0; i < FILES_PER_NODE; i ++) { Callable<Void> call = (new ConcurrentCreator(depth - 1, concurrencyDepth - 1, path.join(Integer.toString(i)))); futures.add(executor.submit(call)); } for (Future<Void> f : futures) { f.get(); } executor.shutdown(); } else { for (int i = 0; i < FILES_PER_NODE; i ++) { exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i))); } } } } class ConcurrentDeleter implements Callable<Void> { private int mDepth; private int mConcurrencyDepth; private TachyonURI mInitPath; ConcurrentDeleter(int depth, int concurrencyDepth, TachyonURI initPath) { this.mDepth = depth; this.mConcurrencyDepth = concurrencyDepth; this.mInitPath = initPath; } @Override public Void call() throws Exception { exec(this.mDepth, this.mConcurrencyDepth, this.mInitPath); return null; } private void doDelete(TachyonURI path) throws Exception { mMasterInfo.delete(path, true); Assert.assertEquals(-1, mMasterInfo.getFileId(path)); } public void exec(int depth, int concurrencyDepth, TachyonURI path) throws Exception { if (depth < 1) { return; } else if (depth == 1 || (path.hashCode() % 10 == 0)) { // Sometimes we want to try deleting a path when we're not all the way down, which is what // the second condition is for doDelete(path); } else { if (concurrencyDepth > 0) { ExecutorService executor = Executors.newCachedThreadPool(); ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE); for (int i = 0; i < FILES_PER_NODE; i ++) { Callable<Void> call = (new ConcurrentDeleter(depth - 1, concurrencyDepth - 1, path.join(Integer .toString(i)))); futures.add(executor.submit(call)); } for (Future<Void> f : futures) { f.get(); } executor.shutdown(); } else { for (int i = 0; i < FILES_PER_NODE; i ++) { exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i))); } } doDelete(path); } } } class ConcurrentRenamer implements Callable<Void> { private int mDepth; private int mConcurrencyDepth; private TachyonURI mRootPath; private TachyonURI mRootPath2; private TachyonURI mInitPath; ConcurrentRenamer(int depth, int concurrencyDepth, TachyonURI rootPath, TachyonURI rootPath2, TachyonURI initPath) { this.mDepth = depth; this.mConcurrencyDepth = concurrencyDepth; this.mRootPath = rootPath; this.mRootPath2 = rootPath2; this.mInitPath = initPath; } @Override public Void call() throws Exception { exec(this.mDepth, this.mConcurrencyDepth, this.mInitPath); return null; } public void exec(int depth, int concurrencyDepth, TachyonURI path) throws Exception { if (depth < 1) { return; } else if (depth == 1 || (depth < this.mDepth && path.hashCode() % 10 < 3)) { // Sometimes we want to try renaming a path when we're not all the way down, which is what // the second condition is for. We have to create the path in the destination up till what // we're renaming. This might already exist, so createFile could throw a // FileAlreadyExistException, which we silently handle. TachyonURI srcPath = this.mRootPath.join(path); TachyonURI dstPath = this.mRootPath2.join(path); int fileId = mMasterInfo.getFileId(srcPath); try { mMasterInfo.mkdirs(dstPath.getParent(), true); } catch (FileAlreadyExistException e) { // This is an acceptable exception to get, since we don't know if the parent has been // created yet by another thread. } catch (InvalidPathException e) { // This could happen if we are renaming something that's a child of the root. } mMasterInfo.rename(srcPath, dstPath); Assert.assertEquals(fileId, mMasterInfo.getFileId(dstPath)); } else if (concurrencyDepth > 0) { ExecutorService executor = Executors.newCachedThreadPool(); ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE); for (int i = 0; i < FILES_PER_NODE; i ++) { Callable<Void> call = (new ConcurrentRenamer(depth - 1, concurrencyDepth - 1, this.mRootPath, this.mRootPath2, path.join(Integer.toString(i)))); futures.add(executor.submit(call)); } for (Future<Void> f : futures) { f.get(); } executor.shutdown(); } else { for (int i = 0; i < FILES_PER_NODE; i ++) { exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i))); } } } } private LocalTachyonCluster mLocalTachyonCluster = null; private MasterInfo mMasterInfo = null; private static final int DEPTH = 6; private static final int FILES_PER_NODE = 4; private static final int CONCURRENCY_DEPTH = 3; private static final TachyonURI ROOT_PATH = new TachyonURI("/root"); private static final TachyonURI ROOT_PATH2 = new TachyonURI("/root2"); private ExecutorService mExecutorService = null; private TachyonConf mMasterTachyonConf; @Test public void addCheckpointTest() throws FileDoesNotExistException, SuspectedFileSizeException, FileAlreadyExistException, InvalidPathException, BlockInfoException, FileNotFoundException, TachyonException { int fileId = mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals("", fileInfo.getUfsPath()); mMasterInfo.addCheckpoint(-1, fileId, 1, new TachyonURI("/testPath")); fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals("/testPath", fileInfo.getUfsPath()); mMasterInfo.addCheckpoint(-1, fileId, 1, new TachyonURI("/testPath")); fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals("/testPath", fileInfo.getUfsPath()); } @After public final void after() throws Exception { mLocalTachyonCluster.stop(); mExecutorService.shutdown(); } @Before public final void before() throws IOException { mLocalTachyonCluster = new LocalTachyonCluster(1000, 1000, Constants.GB); mLocalTachyonCluster.start(); mExecutorService = Executors.newFixedThreadPool(2); mMasterInfo = mLocalTachyonCluster.getMasterInfo(); mMasterTachyonConf = mLocalTachyonCluster.getMasterTachyonConf(); } @Test public void clientFileInfoDirectoryTest() throws InvalidPathException, FileDoesNotExistException, FileAlreadyExistException, TachyonException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFolder")); Assert.assertEquals("testFolder", fileInfo.getName()); Assert.assertEquals(2, fileInfo.getId()); Assert.assertEquals(0, fileInfo.getLength()); Assert.assertEquals("", fileInfo.getUfsPath()); Assert.assertTrue(fileInfo.isFolder); Assert.assertFalse(fileInfo.isPinned); Assert.assertFalse(fileInfo.isCache); Assert.assertTrue(fileInfo.isComplete); } @Test public void clientFileInfoEmptyFileTest() throws InvalidPathException, FileDoesNotExistException, FileAlreadyExistException, BlockInfoException, TachyonException { int fileId = mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals("testFile", fileInfo.getName()); Assert.assertEquals(fileId, fileInfo.getId()); Assert.assertEquals(0, fileInfo.getLength()); Assert.assertEquals("", fileInfo.getUfsPath()); Assert.assertFalse(fileInfo.isFolder); Assert.assertFalse(fileInfo.isPinned); Assert.assertTrue(fileInfo.isCache); Assert.assertFalse(fileInfo.isComplete); } // TODO: This test currently relies on the fact the HDFS client is a cached instance to avoid // TODO: invalid lease exception. This should be fixed. @Test public void concurrentCreateJournalTest() throws Exception { // Makes sure the file id's are the same between a master info and the journal it creates for (int i = 0; i < 5; i ++) { ConcurrentCreator concurrentCreator = new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH); concurrentCreator.call(); String masterJournal = mMasterTachyonConf.get(Constants.MASTER_JOURNAL_FOLDER, Constants.DEFAULT_JOURNAL_FOLDER); Journal journal = new Journal(masterJournal, "image.data", "log.data", mMasterTachyonConf); MasterInfo info = new MasterInfo( new InetSocketAddress(9999), journal, mExecutorService, mMasterTachyonConf); info.init(); for (TachyonURI path : mMasterInfo.ls(new TachyonURI("/"), true)) { Assert.assertEquals(mMasterInfo.getFileId(path), info.getFileId(path)); } after(); before(); } } @Test public void concurrentCreateTest() throws Exception { ConcurrentCreator concurrentCreator = new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH); concurrentCreator.call(); } @Test public void concurrentDeleteTest() throws Exception { ConcurrentCreator concurrentCreator = new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH); concurrentCreator.call(); ConcurrentDeleter concurrentDeleter = new ConcurrentDeleter(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH); concurrentDeleter.call(); Assert.assertEquals(1, mMasterInfo.ls(new TachyonURI("/"), true).size()); } @Test public void concurrentRenameTest() throws Exception { ConcurrentCreator concurrentCreator = new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH); concurrentCreator.call(); int numFiles = mMasterInfo.ls(ROOT_PATH, true).size(); ConcurrentRenamer concurrentRenamer = new ConcurrentRenamer( DEPTH, CONCURRENCY_DEPTH, ROOT_PATH, ROOT_PATH2, TachyonURI.EMPTY_URI); concurrentRenamer.call(); Assert.assertEquals(numFiles, mMasterInfo.ls(ROOT_PATH2, true).size()); } @Test(expected = FileAlreadyExistException.class) public void createAlreadyExistFileTest() throws InvalidPathException, FileAlreadyExistException, BlockInfoException, TachyonException { mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); mMasterInfo.mkdirs(new TachyonURI("/testFile"), true); } @Test public void createDirectoryTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException { mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFolder")); Assert.assertTrue(fileInfo.isFolder); } @Test(expected = InvalidPathException.class) public void createFileInvalidPathTest() throws InvalidPathException, FileAlreadyExistException, BlockInfoException, TachyonException { mMasterInfo.createFile(new TachyonURI("testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); } @Test(expected = FileAlreadyExistException.class) public void createFileInvalidPathTest2() throws InvalidPathException, FileAlreadyExistException, BlockInfoException, TachyonException { mMasterInfo.createFile(new TachyonURI("/"), Constants.DEFAULT_BLOCK_SIZE_BYTE); } @Test(expected = InvalidPathException.class) public void createFileInvalidPathTest3() throws InvalidPathException, FileAlreadyExistException, BlockInfoException, TachyonException { mMasterInfo.createFile(new TachyonURI("/testFile1"), Constants.DEFAULT_BLOCK_SIZE_BYTE); mMasterInfo.createFile(new TachyonURI("/testFile1/testFile2"), Constants.DEFAULT_BLOCK_SIZE_BYTE); } @Test public void createFilePerfTest() throws FileAlreadyExistException, InvalidPathException, FileDoesNotExistException, TachyonException { // long sMs = System.currentTimeMillis(); for (int k = 0; k < 200; k ++) { mMasterInfo.mkdirs(new TachyonURI("/testFile").join(Constants.MASTER_COLUMN_FILE_PREFIX + k) .join("0"), true); } // System.out.println(System.currentTimeMillis() - sMs); // sMs = System.currentTimeMillis(); for (int k = 0; k < 200; k ++) { mMasterInfo.getClientFileInfo(new TachyonURI("/testFile").join( Constants.MASTER_COLUMN_FILE_PREFIX + k).join("0")); } // System.out.println(System.currentTimeMillis() - sMs); } @Test public void createFileTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, BlockInfoException, TachyonException { mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertFalse(mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")).isFolder); } @Test public void createRawTableTest() throws InvalidPathException, FileAlreadyExistException, TableColumnException, FileDoesNotExistException, TachyonException { mMasterInfo.createRawTable(new TachyonURI("/testTable"), 1, (ByteBuffer) null); Assert.assertTrue(mMasterInfo.getClientFileInfo(new TachyonURI("/testTable")).isFolder); } @Test public void deleteDirectoryWithDirectoriesTest() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder/testFolder2"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); int fileId2 = mMasterInfo.createFile(new TachyonURI("/testFolder/testFolder2/testFile2"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(3, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertEquals(fileId2, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2/testFile2"))); Assert.assertTrue(mMasterInfo.delete(2, true)); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2"))); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2/testFile2"))); } @Test public void deleteDirectoryWithDirectoriesTest2() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder/testFolder2"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); int fileId2 = mMasterInfo.createFile(new TachyonURI("/testFolder/testFolder2/testFile2"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(3, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertEquals(fileId2, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2/testFile2"))); Assert.assertFalse(mMasterInfo.delete(2, false)); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(3, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertEquals(fileId2, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2/testFile2"))); } @Test public void deleteDirectoryWithFilesTest() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertTrue(mMasterInfo.delete(2, true)); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); } @Test public void deleteDirectoryWithFilesTest2() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertFalse(mMasterInfo.delete(2, false)); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); } @Test public void deleteEmptyDirectoryTest() throws InvalidPathException, FileAlreadyExistException, TachyonException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertTrue(mMasterInfo.delete(new TachyonURI("/testFolder"), true)); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); } @Test public void deleteFileTest() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { int fileId = mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFile"))); Assert.assertTrue(mMasterInfo.delete(fileId, true)); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFile"))); } @Test public void deleteRootTest() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { Assert.assertFalse(mMasterInfo.delete(new TachyonURI("/"), true)); Assert.assertFalse(mMasterInfo.delete(new TachyonURI("/"), false)); } @Test public void getCapacityBytesTest() { Assert.assertEquals(1000, mMasterInfo.getCapacityBytes()); } @Test public void lastModificationTimeAddCheckpointTest() throws FileDoesNotExistException, SuspectedFileSizeException, FileAlreadyExistException, InvalidPathException, BlockInfoException, FileNotFoundException, TachyonException { int fileId = mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); long opTimeMs = System.currentTimeMillis(); mMasterInfo.addCheckpointInternal(-1, fileId, 1, new TachyonURI("/testPath"), opTimeMs); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals(opTimeMs, fileInfo.lastModificationTimeMs); } @Test public void lastModificationTimeCompleteFileTest() throws FileDoesNotExistException, SuspectedFileSizeException, FileAlreadyExistException, InvalidPathException, BlockInfoException, FileNotFoundException, TachyonException { int fileId = mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); long opTimeMs = System.currentTimeMillis(); mMasterInfo.completeFileInternal(fileId, opTimeMs); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals(opTimeMs, fileInfo.lastModificationTimeMs); } @Test public void lastModificationTimeCreateFileTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); long opTimeMs = System.currentTimeMillis(); mMasterInfo.createFileInternal(false, new TachyonURI("/testFolder/testFile"), false, Constants.DEFAULT_BLOCK_SIZE_BYTE, opTimeMs); ClientFileInfo folderInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFolder")); Assert.assertEquals(opTimeMs, folderInfo.lastModificationTimeMs); } @Test public void lastModificationTimeDeleteTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); long opTimeMs = System.currentTimeMillis(); Assert.assertTrue(mMasterInfo.deleteInternal(fileId, true, opTimeMs)); ClientFileInfo folderInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFolder")); Assert.assertEquals(opTimeMs, folderInfo.lastModificationTimeMs); } @Test public void lastModificationTimeRenameTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile1"), Constants.DEFAULT_BLOCK_SIZE_BYTE); long opTimeMs = System.currentTimeMillis(); Assert.assertTrue(mMasterInfo.renameInternal(fileId, new TachyonURI("/testFolder/testFile2"), opTimeMs)); ClientFileInfo folderInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFolder")); Assert.assertEquals(opTimeMs, folderInfo.lastModificationTimeMs); } @Test public void listFilesTest() throws InvalidPathException, FileDoesNotExistException, FileAlreadyExistException, BlockInfoException, TachyonException { HashSet<Integer> ids = new HashSet<Integer>(); HashSet<Integer> dirIds = new HashSet<Integer>(); for (int i = 0; i < 10; i ++) { TachyonURI dir = new TachyonURI("/i" + i); mMasterInfo.mkdirs(dir, true); dirIds.add(mMasterInfo.getFileId(dir)); for (int j = 0; j < 10; j ++) { ids.add(mMasterInfo.createFile(dir.join("j" + j), 64)); } } HashSet<Integer> listedIds = new HashSet<Integer>(mMasterInfo.listFiles(new TachyonURI("/"), true)); HashSet<Integer> listedDirIds = new HashSet<Integer>(mMasterInfo.listFiles(new TachyonURI("/"), false)); Assert.assertEquals(ids, listedIds); Assert.assertEquals(dirIds, listedDirIds); } @Test public void lsTest() throws FileAlreadyExistException, InvalidPathException, TachyonException, BlockInfoException, FileDoesNotExistException { for (int i = 0; i < 10; i ++) { mMasterInfo.mkdirs(new TachyonURI("/i" + i), true); for (int j = 0; j < 10; j ++) { mMasterInfo.createFile(new TachyonURI("/i" + i + "/j" + j), 64); } } Assert.assertEquals(1, mMasterInfo.ls(new TachyonURI("/i0/j0"), false).size()); Assert.assertEquals(1, mMasterInfo.ls(new TachyonURI("/i0/j0"), true).size()); for (int i = 0; i < 10; i ++) { Assert.assertEquals(11, mMasterInfo.ls(new TachyonURI("/i" + i), false).size()); Assert.assertEquals(11, mMasterInfo.ls(new TachyonURI("/i" + i), true).size()); } Assert.assertEquals(11, mMasterInfo.ls(new TachyonURI(TachyonURI.SEPARATOR), false).size()); Assert.assertEquals(111, mMasterInfo.ls(new TachyonURI(TachyonURI.SEPARATOR), true).size()); } @Test(expected = TableColumnException.class) public void negativeColumnTest() throws InvalidPathException, FileAlreadyExistException, TableColumnException, TachyonException { mMasterInfo.createRawTable(new TachyonURI("/testTable"), -1, (ByteBuffer) null); } @Test(expected = FileNotFoundException.class) public void notFileCheckpointTest() throws FileNotFoundException, SuspectedFileSizeException, FileAlreadyExistException, InvalidPathException, BlockInfoException, TachyonException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFile"), true)); mMasterInfo.addCheckpoint(-1, mMasterInfo.getFileId(new TachyonURI("/testFile")), 0, new TachyonURI("/testPath")); } @Test public void renameExistingDstTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { mMasterInfo.createFile(new TachyonURI("/testFile1"), Constants.DEFAULT_BLOCK_SIZE_BYTE); mMasterInfo.createFile(new TachyonURI("/testFile2"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertFalse(mMasterInfo.rename(new TachyonURI("/testFile1"), new TachyonURI("/testFile2"))); } @Test(expected = FileDoesNotExistException.class) public void renameNonexistentTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { mMasterInfo.createFile(new TachyonURI("/testFile1"), Constants.DEFAULT_BLOCK_SIZE_BYTE); mMasterInfo.rename(new TachyonURI("/testFile2"), new TachyonURI("/testFile3")); } @Test(expected = InvalidPathException.class) public void renameToDeeper() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { mMasterInfo.mkdirs(new TachyonURI("/testDir1/testDir2"), true); mMasterInfo.createFile(new TachyonURI("/testDir1/testDir2/testDir3/testFile3"), Constants.DEFAULT_BLOCK_SIZE_BYTE); mMasterInfo.rename(new TachyonURI("/testDir1/testDir2"), new TachyonURI( "/testDir1/testDir2/testDir3/testDir4")); } @Test(expected = TableColumnException.class) public void tooManyColumnsTest() throws InvalidPathException, FileAlreadyExistException, TableColumnException, TachyonException { int maxColumns = new TachyonConf().getInt(Constants.MAX_COLUMNS, 1000); mMasterInfo.createRawTable(new TachyonURI("/testTable"), maxColumns + 1, (ByteBuffer) null); } @Test public void writeImageTest() throws IOException { // initialize the MasterInfo Journal journal = new Journal(mLocalTachyonCluster.getTachyonHome() + "journal/", "image.data", "log.data", mMasterTachyonConf); MasterInfo info = new MasterInfo(new InetSocketAddress(9999), journal, mExecutorService, mMasterTachyonConf); // create the output streams ByteArrayOutputStream os = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(os); ObjectMapper mapper = JsonObject.createObjectMapper(); ObjectWriter writer = mapper.writer(); ImageElement version = null; ImageElement checkpoint = null; // write the image info.writeImage(writer, dos); // parse the written bytes and look for the Checkpoint and Version ImageElements String[] splits = new String(os.toByteArray()).split("\n"); for (String split : splits) { byte[] bytes = split.getBytes(); JsonParser parser = mapper.getFactory().createParser(bytes); ImageElement ele = parser.readValueAs(ImageElement.class); if (ele.mType.equals(ImageElementType.Checkpoint)) { checkpoint = ele; } if (ele.mType.equals(ImageElementType.Version)) { version = ele; } } // test the elements Assert.assertNotNull(checkpoint); Assert.assertEquals(checkpoint.mType, ImageElementType.Checkpoint); Assert.assertEquals(Constants.JOURNAL_VERSION, version.getInt("version").intValue()); Assert.assertEquals(1, checkpoint.getInt("inodeCounter").intValue()); Assert.assertEquals(0, checkpoint.getInt("editTransactionCounter").intValue()); Assert.assertEquals(0, checkpoint.getInt("dependencyCounter").intValue()); } }
integration-tests/src/test/java/tachyon/master/MasterInfoIntegrationTest.java
/* * Licensed to the University of California, Berkeley 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 tachyon.master; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashSet; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import tachyon.Constants; import tachyon.TachyonURI; import tachyon.conf.TachyonConf; import tachyon.thrift.BlockInfoException; import tachyon.thrift.ClientFileInfo; import tachyon.thrift.FileAlreadyExistException; import tachyon.thrift.FileDoesNotExistException; import tachyon.thrift.InvalidPathException; import tachyon.thrift.SuspectedFileSizeException; import tachyon.thrift.TableColumnException; import tachyon.thrift.TachyonException; /** * Unit tests for tachyon.MasterInfo */ public class MasterInfoIntegrationTest { class ConcurrentCreator implements Callable<Void> { private int mDepth; private int mConcurrencyDepth; private TachyonURI mInitPath; ConcurrentCreator(int depth, int concurrencyDepth, TachyonURI initPath) { this.mDepth = depth; this.mConcurrencyDepth = concurrencyDepth; this.mInitPath = initPath; } @Override public Void call() throws Exception { exec(this.mDepth, this.mConcurrencyDepth, this.mInitPath); return null; } public void exec(int depth, int concurrencyDepth, TachyonURI path) throws Exception { if (depth < 1) { return; } else if (depth == 1) { int fileId = mMasterInfo.createFile(true, path, false, Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(fileId, mMasterInfo.getFileId(path)); } else { int fileId = mMasterInfo.createFile(true, path, true, 0); Assert.assertEquals(fileId, mMasterInfo.getFileId(path)); } if (concurrencyDepth > 0) { ExecutorService executor = Executors.newCachedThreadPool(); ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE); for (int i = 0; i < FILES_PER_NODE; i ++) { Callable<Void> call = (new ConcurrentCreator(depth - 1, concurrencyDepth - 1, path.join(Integer.toString(i)))); futures.add(executor.submit(call)); } for (Future<Void> f : futures) { f.get(); } executor.shutdown(); } else { for (int i = 0; i < FILES_PER_NODE; i ++) { exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i))); } } } } class ConcurrentDeleter implements Callable<Void> { private int mDepth; private int mConcurrencyDepth; private TachyonURI mInitPath; ConcurrentDeleter(int depth, int concurrencyDepth, TachyonURI initPath) { this.mDepth = depth; this.mConcurrencyDepth = concurrencyDepth; this.mInitPath = initPath; } @Override public Void call() throws Exception { exec(this.mDepth, this.mConcurrencyDepth, this.mInitPath); return null; } private void doDelete(TachyonURI path) throws Exception { mMasterInfo.delete(path, true); Assert.assertEquals(-1, mMasterInfo.getFileId(path)); } public void exec(int depth, int concurrencyDepth, TachyonURI path) throws Exception { if (depth < 1) { return; } else if (depth == 1 || (path.hashCode() % 10 == 0)) { // Sometimes we want to try deleting a path when we're not all the way down, which is what // the second condition is for doDelete(path); } else { if (concurrencyDepth > 0) { ExecutorService executor = Executors.newCachedThreadPool(); ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE); for (int i = 0; i < FILES_PER_NODE; i ++) { Callable<Void> call = (new ConcurrentDeleter(depth - 1, concurrencyDepth - 1, path.join(Integer .toString(i)))); futures.add(executor.submit(call)); } for (Future<Void> f : futures) { f.get(); } executor.shutdown(); } else { for (int i = 0; i < FILES_PER_NODE; i ++) { exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i))); } } doDelete(path); } } } class ConcurrentRenamer implements Callable<Void> { private int mDepth; private int mConcurrencyDepth; private TachyonURI mRootPath; private TachyonURI mRootPath2; private TachyonURI mInitPath; ConcurrentRenamer(int depth, int concurrencyDepth, TachyonURI rootPath, TachyonURI rootPath2, TachyonURI initPath) { this.mDepth = depth; this.mConcurrencyDepth = concurrencyDepth; this.mRootPath = rootPath; this.mRootPath2 = rootPath2; this.mInitPath = initPath; } @Override public Void call() throws Exception { exec(this.mDepth, this.mConcurrencyDepth, this.mInitPath); return null; } public void exec(int depth, int concurrencyDepth, TachyonURI path) throws Exception { if (depth < 1) { return; } else if (depth == 1 || (depth < this.mDepth && path.hashCode() % 10 < 3)) { // Sometimes we want to try renaming a path when we're not all the way down, which is what // the second condition is for. We have to create the path in the destination up till what // we're renaming. This might already exist, so createFile could throw a // FileAlreadyExistException, which we silently handle. TachyonURI srcPath = this.mRootPath.join(path); TachyonURI dstPath = this.mRootPath2.join(path); int fileId = mMasterInfo.getFileId(srcPath); try { mMasterInfo.mkdirs(dstPath.getParent(), true); } catch (FileAlreadyExistException e) { // This is an acceptable exception to get, since we don't know if the parent has been // created yet by another thread. } catch (InvalidPathException e) { // This could happen if we are renaming something that's a child of the root. } mMasterInfo.rename(srcPath, dstPath); Assert.assertEquals(fileId, mMasterInfo.getFileId(dstPath)); } else if (concurrencyDepth > 0) { ExecutorService executor = Executors.newCachedThreadPool(); ArrayList<Future<Void>> futures = new ArrayList<Future<Void>>(FILES_PER_NODE); for (int i = 0; i < FILES_PER_NODE; i ++) { Callable<Void> call = (new ConcurrentRenamer(depth - 1, concurrencyDepth - 1, this.mRootPath, this.mRootPath2, path.join(Integer.toString(i)))); futures.add(executor.submit(call)); } for (Future<Void> f : futures) { f.get(); } executor.shutdown(); } else { for (int i = 0; i < FILES_PER_NODE; i ++) { exec(depth - 1, concurrencyDepth, path.join(Integer.toString(i))); } } } } private LocalTachyonCluster mLocalTachyonCluster = null; private MasterInfo mMasterInfo = null; private static final int DEPTH = 6; private static final int FILES_PER_NODE = 4; private static final int CONCURRENCY_DEPTH = 3; private static final TachyonURI ROOT_PATH = new TachyonURI("/root"); private static final TachyonURI ROOT_PATH2 = new TachyonURI("/root2"); private ExecutorService mExecutorService = null; private TachyonConf mMasterTachyonConf; @Test public void addCheckpointTest() throws FileDoesNotExistException, SuspectedFileSizeException, FileAlreadyExistException, InvalidPathException, BlockInfoException, FileNotFoundException, TachyonException { int fileId = mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals("", fileInfo.getUfsPath()); mMasterInfo.addCheckpoint(-1, fileId, 1, new TachyonURI("/testPath")); fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals("/testPath", fileInfo.getUfsPath()); mMasterInfo.addCheckpoint(-1, fileId, 1, new TachyonURI("/testPath")); fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals("/testPath", fileInfo.getUfsPath()); } @After public final void after() throws Exception { mLocalTachyonCluster.stop(); mExecutorService.shutdown(); } @Before public final void before() throws IOException { mLocalTachyonCluster = new LocalTachyonCluster(1000, 1000, Constants.GB); mLocalTachyonCluster.start(); mExecutorService = Executors.newFixedThreadPool(2); mMasterInfo = mLocalTachyonCluster.getMasterInfo(); mMasterTachyonConf = mLocalTachyonCluster.getMasterTachyonConf(); } @Test public void clientFileInfoDirectoryTest() throws InvalidPathException, FileDoesNotExistException, FileAlreadyExistException, TachyonException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFolder")); Assert.assertEquals("testFolder", fileInfo.getName()); Assert.assertEquals(2, fileInfo.getId()); Assert.assertEquals(0, fileInfo.getLength()); Assert.assertEquals("", fileInfo.getUfsPath()); Assert.assertTrue(fileInfo.isFolder); Assert.assertFalse(fileInfo.isPinned); Assert.assertFalse(fileInfo.isCache); Assert.assertTrue(fileInfo.isComplete); } @Test public void clientFileInfoEmptyFileTest() throws InvalidPathException, FileDoesNotExistException, FileAlreadyExistException, BlockInfoException, TachyonException { int fileId = mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals("testFile", fileInfo.getName()); Assert.assertEquals(fileId, fileInfo.getId()); Assert.assertEquals(0, fileInfo.getLength()); Assert.assertEquals("", fileInfo.getUfsPath()); Assert.assertFalse(fileInfo.isFolder); Assert.assertFalse(fileInfo.isPinned); Assert.assertTrue(fileInfo.isCache); Assert.assertFalse(fileInfo.isComplete); } @Test public void concurrentCreateJournalTest() throws Exception { // Makes sure the file id's are the same between a master info and the journal it creates for (int i = 0; i < 5; i ++) { ConcurrentCreator concurrentCreator = new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH); concurrentCreator.call(); String masterJournal = mMasterTachyonConf.get(Constants.MASTER_JOURNAL_FOLDER, Constants.DEFAULT_JOURNAL_FOLDER); Journal journal = new Journal(masterJournal, "image.data", "log.data", mMasterTachyonConf); MasterInfo info = new MasterInfo( new InetSocketAddress(9999), journal, mExecutorService, mMasterTachyonConf); info.init(); for (TachyonURI path : mMasterInfo.ls(new TachyonURI("/"), true)) { Assert.assertEquals(mMasterInfo.getFileId(path), info.getFileId(path)); } after(); before(); } } @Test public void concurrentCreateTest() throws Exception { ConcurrentCreator concurrentCreator = new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH); concurrentCreator.call(); } @Test public void concurrentDeleteTest() throws Exception { ConcurrentCreator concurrentCreator = new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH); concurrentCreator.call(); ConcurrentDeleter concurrentDeleter = new ConcurrentDeleter(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH); concurrentDeleter.call(); Assert.assertEquals(1, mMasterInfo.ls(new TachyonURI("/"), true).size()); } @Test public void concurrentRenameTest() throws Exception { ConcurrentCreator concurrentCreator = new ConcurrentCreator(DEPTH, CONCURRENCY_DEPTH, ROOT_PATH); concurrentCreator.call(); int numFiles = mMasterInfo.ls(ROOT_PATH, true).size(); ConcurrentRenamer concurrentRenamer = new ConcurrentRenamer( DEPTH, CONCURRENCY_DEPTH, ROOT_PATH, ROOT_PATH2, TachyonURI.EMPTY_URI); concurrentRenamer.call(); Assert.assertEquals(numFiles, mMasterInfo.ls(ROOT_PATH2, true).size()); } @Test(expected = FileAlreadyExistException.class) public void createAlreadyExistFileTest() throws InvalidPathException, FileAlreadyExistException, BlockInfoException, TachyonException { mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); mMasterInfo.mkdirs(new TachyonURI("/testFile"), true); } @Test public void createDirectoryTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException { mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFolder")); Assert.assertTrue(fileInfo.isFolder); } @Test(expected = InvalidPathException.class) public void createFileInvalidPathTest() throws InvalidPathException, FileAlreadyExistException, BlockInfoException, TachyonException { mMasterInfo.createFile(new TachyonURI("testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); } @Test(expected = FileAlreadyExistException.class) public void createFileInvalidPathTest2() throws InvalidPathException, FileAlreadyExistException, BlockInfoException, TachyonException { mMasterInfo.createFile(new TachyonURI("/"), Constants.DEFAULT_BLOCK_SIZE_BYTE); } @Test(expected = InvalidPathException.class) public void createFileInvalidPathTest3() throws InvalidPathException, FileAlreadyExistException, BlockInfoException, TachyonException { mMasterInfo.createFile(new TachyonURI("/testFile1"), Constants.DEFAULT_BLOCK_SIZE_BYTE); mMasterInfo.createFile(new TachyonURI("/testFile1/testFile2"), Constants.DEFAULT_BLOCK_SIZE_BYTE); } @Test public void createFilePerfTest() throws FileAlreadyExistException, InvalidPathException, FileDoesNotExistException, TachyonException { // long sMs = System.currentTimeMillis(); for (int k = 0; k < 200; k ++) { mMasterInfo.mkdirs(new TachyonURI("/testFile").join(Constants.MASTER_COLUMN_FILE_PREFIX + k) .join("0"), true); } // System.out.println(System.currentTimeMillis() - sMs); // sMs = System.currentTimeMillis(); for (int k = 0; k < 200; k ++) { mMasterInfo.getClientFileInfo(new TachyonURI("/testFile").join( Constants.MASTER_COLUMN_FILE_PREFIX + k).join("0")); } // System.out.println(System.currentTimeMillis() - sMs); } @Test public void createFileTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, BlockInfoException, TachyonException { mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertFalse(mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")).isFolder); } @Test public void createRawTableTest() throws InvalidPathException, FileAlreadyExistException, TableColumnException, FileDoesNotExistException, TachyonException { mMasterInfo.createRawTable(new TachyonURI("/testTable"), 1, (ByteBuffer) null); Assert.assertTrue(mMasterInfo.getClientFileInfo(new TachyonURI("/testTable")).isFolder); } @Test public void deleteDirectoryWithDirectoriesTest() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder/testFolder2"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); int fileId2 = mMasterInfo.createFile(new TachyonURI("/testFolder/testFolder2/testFile2"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(3, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertEquals(fileId2, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2/testFile2"))); Assert.assertTrue(mMasterInfo.delete(2, true)); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2"))); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2/testFile2"))); } @Test public void deleteDirectoryWithDirectoriesTest2() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder/testFolder2"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); int fileId2 = mMasterInfo.createFile(new TachyonURI("/testFolder/testFolder2/testFile2"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(3, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertEquals(fileId2, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2/testFile2"))); Assert.assertFalse(mMasterInfo.delete(2, false)); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(3, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertEquals(fileId2, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFolder2/testFile2"))); } @Test public void deleteDirectoryWithFilesTest() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertTrue(mMasterInfo.delete(2, true)); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); } @Test public void deleteDirectoryWithFilesTest2() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); Assert.assertFalse(mMasterInfo.delete(2, false)); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); } @Test public void deleteEmptyDirectoryTest() throws InvalidPathException, FileAlreadyExistException, TachyonException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertTrue(mMasterInfo.delete(new TachyonURI("/testFolder"), true)); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); } @Test public void deleteFileTest() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { int fileId = mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFile"))); Assert.assertTrue(mMasterInfo.delete(fileId, true)); Assert.assertEquals(-1, mMasterInfo.getFileId(new TachyonURI("/testFile"))); } @Test public void deleteRootTest() throws InvalidPathException, FileAlreadyExistException, TachyonException, BlockInfoException { Assert.assertFalse(mMasterInfo.delete(new TachyonURI("/"), true)); Assert.assertFalse(mMasterInfo.delete(new TachyonURI("/"), false)); } @Test public void getCapacityBytesTest() { Assert.assertEquals(1000, mMasterInfo.getCapacityBytes()); } @Test public void lastModificationTimeAddCheckpointTest() throws FileDoesNotExistException, SuspectedFileSizeException, FileAlreadyExistException, InvalidPathException, BlockInfoException, FileNotFoundException, TachyonException { int fileId = mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); long opTimeMs = System.currentTimeMillis(); mMasterInfo.addCheckpointInternal(-1, fileId, 1, new TachyonURI("/testPath"), opTimeMs); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals(opTimeMs, fileInfo.lastModificationTimeMs); } @Test public void lastModificationTimeCompleteFileTest() throws FileDoesNotExistException, SuspectedFileSizeException, FileAlreadyExistException, InvalidPathException, BlockInfoException, FileNotFoundException, TachyonException { int fileId = mMasterInfo.createFile(new TachyonURI("/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); long opTimeMs = System.currentTimeMillis(); mMasterInfo.completeFileInternal(fileId, opTimeMs); ClientFileInfo fileInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFile")); Assert.assertEquals(opTimeMs, fileInfo.lastModificationTimeMs); } @Test public void lastModificationTimeCreateFileTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); long opTimeMs = System.currentTimeMillis(); mMasterInfo.createFileInternal(false, new TachyonURI("/testFolder/testFile"), false, Constants.DEFAULT_BLOCK_SIZE_BYTE, opTimeMs); ClientFileInfo folderInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFolder")); Assert.assertEquals(opTimeMs, folderInfo.lastModificationTimeMs); } @Test public void lastModificationTimeDeleteTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertEquals(2, mMasterInfo.getFileId(new TachyonURI("/testFolder"))); Assert.assertEquals(fileId, mMasterInfo.getFileId(new TachyonURI("/testFolder/testFile"))); long opTimeMs = System.currentTimeMillis(); Assert.assertTrue(mMasterInfo.deleteInternal(fileId, true, opTimeMs)); ClientFileInfo folderInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFolder")); Assert.assertEquals(opTimeMs, folderInfo.lastModificationTimeMs); } @Test public void lastModificationTimeRenameTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFolder"), true)); int fileId = mMasterInfo.createFile(new TachyonURI("/testFolder/testFile1"), Constants.DEFAULT_BLOCK_SIZE_BYTE); long opTimeMs = System.currentTimeMillis(); Assert.assertTrue(mMasterInfo.renameInternal(fileId, new TachyonURI("/testFolder/testFile2"), opTimeMs)); ClientFileInfo folderInfo = mMasterInfo.getClientFileInfo(new TachyonURI("/testFolder")); Assert.assertEquals(opTimeMs, folderInfo.lastModificationTimeMs); } @Test public void listFilesTest() throws InvalidPathException, FileDoesNotExistException, FileAlreadyExistException, BlockInfoException, TachyonException { HashSet<Integer> ids = new HashSet<Integer>(); HashSet<Integer> dirIds = new HashSet<Integer>(); for (int i = 0; i < 10; i ++) { TachyonURI dir = new TachyonURI("/i" + i); mMasterInfo.mkdirs(dir, true); dirIds.add(mMasterInfo.getFileId(dir)); for (int j = 0; j < 10; j ++) { ids.add(mMasterInfo.createFile(dir.join("j" + j), 64)); } } HashSet<Integer> listedIds = new HashSet<Integer>(mMasterInfo.listFiles(new TachyonURI("/"), true)); HashSet<Integer> listedDirIds = new HashSet<Integer>(mMasterInfo.listFiles(new TachyonURI("/"), false)); Assert.assertEquals(ids, listedIds); Assert.assertEquals(dirIds, listedDirIds); } @Test public void lsTest() throws FileAlreadyExistException, InvalidPathException, TachyonException, BlockInfoException, FileDoesNotExistException { for (int i = 0; i < 10; i ++) { mMasterInfo.mkdirs(new TachyonURI("/i" + i), true); for (int j = 0; j < 10; j ++) { mMasterInfo.createFile(new TachyonURI("/i" + i + "/j" + j), 64); } } Assert.assertEquals(1, mMasterInfo.ls(new TachyonURI("/i0/j0"), false).size()); Assert.assertEquals(1, mMasterInfo.ls(new TachyonURI("/i0/j0"), true).size()); for (int i = 0; i < 10; i ++) { Assert.assertEquals(11, mMasterInfo.ls(new TachyonURI("/i" + i), false).size()); Assert.assertEquals(11, mMasterInfo.ls(new TachyonURI("/i" + i), true).size()); } Assert.assertEquals(11, mMasterInfo.ls(new TachyonURI(TachyonURI.SEPARATOR), false).size()); Assert.assertEquals(111, mMasterInfo.ls(new TachyonURI(TachyonURI.SEPARATOR), true).size()); } @Test(expected = TableColumnException.class) public void negativeColumnTest() throws InvalidPathException, FileAlreadyExistException, TableColumnException, TachyonException { mMasterInfo.createRawTable(new TachyonURI("/testTable"), -1, (ByteBuffer) null); } @Test(expected = FileNotFoundException.class) public void notFileCheckpointTest() throws FileNotFoundException, SuspectedFileSizeException, FileAlreadyExistException, InvalidPathException, BlockInfoException, TachyonException { Assert.assertTrue(mMasterInfo.mkdirs(new TachyonURI("/testFile"), true)); mMasterInfo.addCheckpoint(-1, mMasterInfo.getFileId(new TachyonURI("/testFile")), 0, new TachyonURI("/testPath")); } @Test public void renameExistingDstTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { mMasterInfo.createFile(new TachyonURI("/testFile1"), Constants.DEFAULT_BLOCK_SIZE_BYTE); mMasterInfo.createFile(new TachyonURI("/testFile2"), Constants.DEFAULT_BLOCK_SIZE_BYTE); Assert.assertFalse(mMasterInfo.rename(new TachyonURI("/testFile1"), new TachyonURI("/testFile2"))); } @Test(expected = FileDoesNotExistException.class) public void renameNonexistentTest() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { mMasterInfo.createFile(new TachyonURI("/testFile1"), Constants.DEFAULT_BLOCK_SIZE_BYTE); mMasterInfo.rename(new TachyonURI("/testFile2"), new TachyonURI("/testFile3")); } @Test(expected = InvalidPathException.class) public void renameToDeeper() throws InvalidPathException, FileAlreadyExistException, FileDoesNotExistException, TachyonException, BlockInfoException { mMasterInfo.mkdirs(new TachyonURI("/testDir1/testDir2"), true); mMasterInfo.createFile(new TachyonURI("/testDir1/testDir2/testDir3/testFile3"), Constants.DEFAULT_BLOCK_SIZE_BYTE); mMasterInfo.rename(new TachyonURI("/testDir1/testDir2"), new TachyonURI( "/testDir1/testDir2/testDir3/testDir4")); } @Test(expected = TableColumnException.class) public void tooManyColumnsTest() throws InvalidPathException, FileAlreadyExistException, TableColumnException, TachyonException { int maxColumns = new TachyonConf().getInt(Constants.MAX_COLUMNS, 1000); mMasterInfo.createRawTable(new TachyonURI("/testTable"), maxColumns + 1, (ByteBuffer) null); } @Test public void writeImageTest() throws IOException { // initialize the MasterInfo Journal journal = new Journal(mLocalTachyonCluster.getTachyonHome() + "journal/", "image.data", "log.data", mMasterTachyonConf); MasterInfo info = new MasterInfo(new InetSocketAddress(9999), journal, mExecutorService, mMasterTachyonConf); // create the output streams ByteArrayOutputStream os = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(os); ObjectMapper mapper = JsonObject.createObjectMapper(); ObjectWriter writer = mapper.writer(); ImageElement version = null; ImageElement checkpoint = null; // write the image info.writeImage(writer, dos); // parse the written bytes and look for the Checkpoint and Version ImageElements String[] splits = new String(os.toByteArray()).split("\n"); for (String split : splits) { byte[] bytes = split.getBytes(); JsonParser parser = mapper.getFactory().createParser(bytes); ImageElement ele = parser.readValueAs(ImageElement.class); if (ele.mType.equals(ImageElementType.Checkpoint)) { checkpoint = ele; } if (ele.mType.equals(ImageElementType.Version)) { version = ele; } } // test the elements Assert.assertNotNull(checkpoint); Assert.assertEquals(checkpoint.mType, ImageElementType.Checkpoint); Assert.assertEquals(Constants.JOURNAL_VERSION, version.getInt("version").intValue()); Assert.assertEquals(1, checkpoint.getInt("inodeCounter").intValue()); Assert.assertEquals(0, checkpoint.getInt("editTransactionCounter").intValue()); Assert.assertEquals(0, checkpoint.getInt("dependencyCounter").intValue()); } }
Add TODO statement for master info test.
integration-tests/src/test/java/tachyon/master/MasterInfoIntegrationTest.java
Add TODO statement for master info test.
<ide><path>ntegration-tests/src/test/java/tachyon/master/MasterInfoIntegrationTest.java <ide> Assert.assertFalse(fileInfo.isComplete); <ide> } <ide> <add> // TODO: This test currently relies on the fact the HDFS client is a cached instance to avoid <add> // TODO: invalid lease exception. This should be fixed. <ide> @Test <ide> public void concurrentCreateJournalTest() throws Exception { <ide> // Makes sure the file id's are the same between a master info and the journal it creates
Java
mit
e14c8b2a38086af5d0a486c16d5662c78c1860cf
0
objectify/objectify,RudiaMoon/objectify-appengine,gvaish/attic-objectify-appengine,naveen514/objectify-appengine,google-code-export/objectify-appengine,qickrooms/objectify-appengine,asolfre/objectify-appengine,gvaish/objectify-appengine,zenmeso/objectify-appengine
/* * $Id: BeanMixin.java 1075 2009-05-07 06:41:19Z lhoriman $ * $URL: https://subetha.googlecode.com/svn/branches/resin/rtest/src/org/subethamail/rtest/util/BeanMixin.java $ */ package com.googlecode.objectify.test; import java.util.logging.Logger; import javax.persistence.Entity; import javax.persistence.Id; import org.testng.annotations.Test; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.annotation.Subclass; /** * Just the registration part of polymorphic classes. The 'A' just to alphabetize it before * the other polymorphic tests. * * @author Jeff Schnitzer <[email protected]> */ public class PolymorphicAAATests extends TestBase { /** */ @SuppressWarnings("unused") private static Logger log = Logger.getLogger(PolymorphicAAATests.class.getName()); /** */ @Entity public static class Animal { @Id Long id; String name; } /** */ @Subclass public static class Mammal extends Animal { boolean longHair; } /** */ @Subclass public static class Cat extends Mammal { boolean hypoallergenic; } /** */ @Subclass(unindexed=true) public static class Dog extends Mammal { int loudness; } /** */ @Test public void testRegistrationForwards() throws Exception { this.fact.register(Animal.class); this.fact.register(Mammal.class); this.fact.register(Cat.class); this.fact.register(Dog.class); } /** */ @Test public void testRegistrationBackwards() throws Exception { this.fact.register(Dog.class); this.fact.register(Cat.class); this.fact.register(Mammal.class); this.fact.register(Animal.class); } /** */ @Test public void testBasicFetch() throws Exception { this.testRegistrationForwards(); Animal a = new Animal(); a.name = "Bob"; Animal a2 = this.putAndGet(a); assert a.name.equals(a2.name); Mammal m = new Mammal(); m.name = "Bob"; m.longHair = true; Mammal m2 = this.putAndGet(m); assert m.name.equals(m2.name); assert m.longHair == m2.longHair; Cat c = new Cat(); c.name = "Bob"; c.longHair = true; c.hypoallergenic = true; Cat c2 = this.putAndGet(c); assert c.name.equals(c2.name); assert c.longHair == c2.longHair; assert c.hypoallergenic == c2.hypoallergenic; } /** * Issue #80: http://code.google.com/p/objectify-appengine/issues/detail?id=80 */ @Test public void testNullFind() throws Exception { this.testRegistrationForwards(); Objectify ofy = this.fact.begin(); // This should produce null Cat cat = ofy.find(Cat.class, 123); assert cat == null; } }
src/com/googlecode/objectify/test/PolymorphicAAATests.java
/* * $Id: BeanMixin.java 1075 2009-05-07 06:41:19Z lhoriman $ * $URL: https://subetha.googlecode.com/svn/branches/resin/rtest/src/org/subethamail/rtest/util/BeanMixin.java $ */ package com.googlecode.objectify.test; import java.util.logging.Logger; import javax.persistence.Entity; import javax.persistence.Id; import org.testng.annotations.Test; import com.googlecode.objectify.annotation.Subclass; /** * Just the registration part of polymorphic classes. The 'A' just to alphabetize it before * the other polymorphic tests. * * @author Jeff Schnitzer <[email protected]> */ public class PolymorphicAAATests extends TestBase { /** */ @SuppressWarnings("unused") private static Logger log = Logger.getLogger(PolymorphicAAATests.class.getName()); /** */ @Entity public static class Animal { @Id Long id; String name; } /** */ @Subclass public static class Mammal extends Animal { boolean longHair; } /** */ @Subclass public static class Cat extends Mammal { boolean hypoallergenic; } /** */ @Subclass(unindexed=true) public static class Dog extends Mammal { int loudness; } /** */ @Test public void testRegistrationForwards() throws Exception { this.fact.register(Animal.class); this.fact.register(Mammal.class); this.fact.register(Cat.class); this.fact.register(Dog.class); } /** */ @Test public void testRegistrationBackwards() throws Exception { this.fact.register(Dog.class); this.fact.register(Cat.class); this.fact.register(Mammal.class); this.fact.register(Animal.class); } /** */ @Test public void testBasicFetch() throws Exception { this.testRegistrationForwards(); Animal a = new Animal(); a.name = "Bob"; Animal a2 = this.putAndGet(a); assert a.name.equals(a2.name); Mammal m = new Mammal(); m.name = "Bob"; m.longHair = true; Mammal m2 = this.putAndGet(m); assert m.name.equals(m2.name); assert m.longHair == m2.longHair; Cat c = new Cat(); c.name = "Bob"; c.longHair = true; c.hypoallergenic = true; Cat c2 = this.putAndGet(c); assert c.name.equals(c2.name); assert c.longHair == c2.longHair; assert c.hypoallergenic == c2.hypoallergenic; } }
Added a test case for issue #80, NPE when find()ing for a polymorphic entity that is not in the db. git-svn-id: 1ab7df0ed85a7513fd7b1f64d2838346d91c60ce@691 79e2b5ea-dad9-11de-b64b-7d26b27941e2
src/com/googlecode/objectify/test/PolymorphicAAATests.java
Added a test case for issue #80, NPE when find()ing for a polymorphic entity that is not in the db.
<ide><path>rc/com/googlecode/objectify/test/PolymorphicAAATests.java <ide> <ide> import org.testng.annotations.Test; <ide> <add>import com.googlecode.objectify.Objectify; <ide> import com.googlecode.objectify.annotation.Subclass; <ide> <ide> /** <ide> assert c.hypoallergenic == c2.hypoallergenic; <ide> } <ide> <add> /** <add> * Issue #80: http://code.google.com/p/objectify-appengine/issues/detail?id=80 <add> */ <add> @Test <add> public void testNullFind() throws Exception <add> { <add> this.testRegistrationForwards(); <add> <add> Objectify ofy = this.fact.begin(); <add> <add> // This should produce null <add> Cat cat = ofy.find(Cat.class, 123); <add> <add> assert cat == null; <add> } <add> <ide> }
Java
apache-2.0
dbbcabe2857fedb6bad942c4be0990f14195a706
0
ibauersachs/jitsi,ibauersachs/jitsi,damencho/jitsi,ringdna/jitsi,damencho/jitsi,jitsi/jitsi,HelioGuilherme66/jitsi,HelioGuilherme66/jitsi,jibaro/jitsi,dkcreinoso/jitsi,459below/jitsi,jibaro/jitsi,cobratbq/jitsi,procandi/jitsi,cobratbq/jitsi,bhatvv/jitsi,dkcreinoso/jitsi,dkcreinoso/jitsi,tuijldert/jitsi,pplatek/jitsi,martin7890/jitsi,ringdna/jitsi,459below/jitsi,damencho/jitsi,martin7890/jitsi,mckayclarey/jitsi,Metaswitch/jitsi,marclaporte/jitsi,bhatvv/jitsi,marclaporte/jitsi,martin7890/jitsi,tuijldert/jitsi,ibauersachs/jitsi,bhatvv/jitsi,gpolitis/jitsi,dkcreinoso/jitsi,procandi/jitsi,gpolitis/jitsi,damencho/jitsi,cobratbq/jitsi,marclaporte/jitsi,459below/jitsi,bebo/jitsi,laborautonomo/jitsi,Metaswitch/jitsi,tuijldert/jitsi,gpolitis/jitsi,ibauersachs/jitsi,laborautonomo/jitsi,iant-gmbh/jitsi,HelioGuilherme66/jitsi,martin7890/jitsi,bhatvv/jitsi,iant-gmbh/jitsi,ringdna/jitsi,laborautonomo/jitsi,tuijldert/jitsi,gpolitis/jitsi,marclaporte/jitsi,pplatek/jitsi,martin7890/jitsi,procandi/jitsi,iant-gmbh/jitsi,mckayclarey/jitsi,459below/jitsi,iant-gmbh/jitsi,HelioGuilherme66/jitsi,iant-gmbh/jitsi,bebo/jitsi,jitsi/jitsi,HelioGuilherme66/jitsi,ringdna/jitsi,level7systems/jitsi,marclaporte/jitsi,level7systems/jitsi,bebo/jitsi,Metaswitch/jitsi,level7systems/jitsi,jibaro/jitsi,damencho/jitsi,ibauersachs/jitsi,cobratbq/jitsi,gpolitis/jitsi,jitsi/jitsi,laborautonomo/jitsi,procandi/jitsi,cobratbq/jitsi,bhatvv/jitsi,laborautonomo/jitsi,dkcreinoso/jitsi,jibaro/jitsi,level7systems/jitsi,level7systems/jitsi,procandi/jitsi,jitsi/jitsi,jitsi/jitsi,pplatek/jitsi,bebo/jitsi,tuijldert/jitsi,mckayclarey/jitsi,bebo/jitsi,jibaro/jitsi,459below/jitsi,mckayclarey/jitsi,mckayclarey/jitsi,Metaswitch/jitsi,ringdna/jitsi,pplatek/jitsi,pplatek/jitsi
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.main; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.beans.PropertyChangeEvent; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.KeyStroke; import net.java.sip.communicator.impl.gui.main.configforms.ConfigurationFrame; import net.java.sip.communicator.impl.gui.main.contactlist.CListKeySearchListener; import net.java.sip.communicator.impl.gui.main.contactlist.ContactList; import net.java.sip.communicator.impl.gui.main.contactlist.ContactListModel; import net.java.sip.communicator.impl.gui.main.contactlist.ContactListPanel; import net.java.sip.communicator.impl.gui.main.contactlist.ContactNode; import net.java.sip.communicator.impl.gui.main.contactlist.MetaContactNode; import net.java.sip.communicator.impl.gui.main.i18n.Messages; import net.java.sip.communicator.impl.gui.main.message.ChatWindow; import net.java.sip.communicator.impl.gui.main.utils.Constants; import net.java.sip.communicator.impl.gui.main.utils.ImageLoader; import net.java.sip.communicator.service.contactlist.MetaContact; import net.java.sip.communicator.service.contactlist.MetaContactGroup; import net.java.sip.communicator.service.contactlist.MetaContactListService; import net.java.sip.communicator.service.protocol.Contact; import net.java.sip.communicator.service.protocol.OperationFailedException; import net.java.sip.communicator.service.protocol.OperationSetPersistentPresence; import net.java.sip.communicator.service.protocol.OperationSetPresence; import net.java.sip.communicator.service.protocol.PresenceStatus; import net.java.sip.communicator.service.protocol.ProtocolProviderService; import net.java.sip.communicator.service.protocol.event.ContactPresenceStatusChangeEvent; import net.java.sip.communicator.service.protocol.event.ContactPresenceStatusListener; import net.java.sip.communicator.service.protocol.event.ProviderPresenceStatusChangeEvent; import net.java.sip.communicator.service.protocol.event.ProviderPresenceStatusListener; import net.java.sip.communicator.service.protocol.icqconstants.IcqStatusEnum; /** * The main application frame. * * @author Yana Stamcheva */ public class MainFrame extends JFrame { private JPanel contactListPanel = new JPanel(new BorderLayout()); private JPanel menusPanel = new JPanel(new BorderLayout()); private Menu menu = new Menu(); private ConfigurationFrame configFrame = new ConfigurationFrame(); private CallPanel callPanel; private StatusPanel statusPanel; private MainTabbedPane tabbedPane; private QuickMenu quickMenu; private Hashtable protocolSupportedOperationSets = new Hashtable(); private Hashtable protocolPresenceSets = new Hashtable(); private Dimension minimumFrameSize = new Dimension( Constants.MAINFRAME_MIN_WIDTH, Constants.MAINFRAME_MIN_HEIGHT); private Hashtable protocolProviders = new Hashtable(); private MetaContactListService contactList; private ArrayList accounts = new ArrayList(); public MainFrame() { callPanel = new CallPanel(this); tabbedPane = new MainTabbedPane(this); quickMenu = new QuickMenu(this); statusPanel = new StatusPanel(this); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setInitialBounds(); this.setTitle(Messages.getString("sipCommunicator")); this.setIconImage(ImageLoader.getImage(ImageLoader.SIP_LOGO)); this.init(); } private void init() { this.menusPanel.add(menu, BorderLayout.NORTH); this.menusPanel.add(quickMenu, BorderLayout.CENTER); this.contactListPanel.add(tabbedPane, BorderLayout.CENTER); this.contactListPanel.add(callPanel, BorderLayout.SOUTH); this.getContentPane().add(menusPanel, BorderLayout.NORTH); this.getContentPane().add(contactListPanel, BorderLayout.CENTER); this.getContentPane().add(statusPanel, BorderLayout.SOUTH); } private void setInitialBounds() { this.setSize(155, 400); this.contactListPanel.setPreferredSize(new Dimension(140, 350)); this.contactListPanel.setMinimumSize(new Dimension(80, 200)); this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width - this.getWidth(), 50); } public CallPanel getCallPanel() { return callPanel; } public MetaContactListService getContactList() { return this.contactList; } public void setContactList(MetaContactListService contactList) { this.contactList = contactList; ContactListPanel clistPanel = this.tabbedPane.getContactListPanel(); clistPanel.initTree(contactList); //add a key listener to the tabbed pane, when the contactlist is //initialized this.tabbedPane.addKeyListener(new CListKeySearchListener (clistPanel.getContactList())); } public ConfigurationFrame getConfigFrame() { return configFrame; } public void setConfigFrame(ConfigurationFrame configFrame) { this.configFrame = configFrame; } public Map getSupportedOperationSets (ProtocolProviderService protocolProvider) { return (Map)this.protocolSupportedOperationSets.get(protocolProvider); } public void addProtocolSupportedOperationSets (ProtocolProviderService protocolProvider, Map supportedOperationSets) { this.protocolSupportedOperationSets.put(protocolProvider, supportedOperationSets); Iterator entrySetIter = supportedOperationSets.entrySet().iterator(); for (int i = 0; i < supportedOperationSets.size(); i++) { Map.Entry entry = (Map.Entry) entrySetIter.next(); Object key = entry.getKey(); Object value = entry.getValue(); if(key.equals(OperationSetPersistentPresence.class.getName()) || key.equals(OperationSetPresence.class.getName())){ OperationSetPresence presence = (OperationSetPresence)value; this.protocolPresenceSets.put( protocolProvider, presence); presence .addProviderPresenceStatusListener (new ProviderPresenceStatusAdapter()); presence .addContactPresenceStatusListener (new ContactPresenceStatusAdapter()); try { presence .publishPresenceStatus(IcqStatusEnum.ONLINE, ""); this.getStatusPanel().stopConnecting( protocolProvider.getProtocolName()); this.statusPanel.setSelectedStatus (protocolProvider.getProtocolName(), Constants.ONLINE_STATUS); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OperationFailedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private class ProviderPresenceStatusAdapter implements ProviderPresenceStatusListener { public void providerStatusChanged (ProviderPresenceStatusChangeEvent evt) { } public void providerStatusMessageChanged (PropertyChangeEvent evt) { } } private class ContactPresenceStatusAdapter implements ContactPresenceStatusListener { public void contactPresenceStatusChanged (ContactPresenceStatusChangeEvent evt) { Contact sourceContact = evt.getSourceContact(); PresenceStatus newStatus = evt.getNewStatus(); MetaContact metaContact = contactList.findMetaContactByContact(sourceContact); if (metaContact != null){ ContactListModel model = (ContactListModel)tabbedPane.getContactListPanel() .getContactList().getModel(); MetaContactNode node = model.getContactNodeByContact(metaContact); if(node != null){ node.setStatusIcon (new ImageIcon(Constants.getStatusIcon (newStatus))); node.changeProtocolContactStatus( sourceContact.getProtocolProvider() .getProtocolName(), newStatus); //Refresh the node status icon. model.contactStatusChanged(model.indexOf(node)); } } } } public StatusPanel getStatusPanel() { return statusPanel; } public Map getProtocolProviders() { return this.protocolProviders; } public void addProtocolProvider( ProtocolProviderService protocolProvider) { this.protocolProviders.put( protocolProvider.getProtocolName(), protocolProvider); } public void addAccount(Account account){ this.accounts.add(account); } public Account getAccount(){ return (Account)this.accounts.get(0); } public OperationSetPresence getProtocolPresence (ProtocolProviderService protocolProvider) { return (OperationSetPresence) this.protocolPresenceSets.get(protocolProvider); } }
src/net/java/sip/communicator/impl/gui/main/MainFrame.java
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.gui.main; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.beans.PropertyChangeEvent; import java.util.ArrayList; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.KeyStroke; import net.java.sip.communicator.impl.gui.main.configforms.ConfigurationFrame; import net.java.sip.communicator.impl.gui.main.contactlist.CListKeySearchListener; import net.java.sip.communicator.impl.gui.main.contactlist.ContactList; import net.java.sip.communicator.impl.gui.main.contactlist.ContactListModel; import net.java.sip.communicator.impl.gui.main.contactlist.ContactListPanel; import net.java.sip.communicator.impl.gui.main.contactlist.ContactNode; import net.java.sip.communicator.impl.gui.main.contactlist.MetaContactNode; import net.java.sip.communicator.impl.gui.main.i18n.Messages; import net.java.sip.communicator.impl.gui.main.message.ChatWindow; import net.java.sip.communicator.impl.gui.main.utils.Constants; import net.java.sip.communicator.impl.gui.main.utils.ImageLoader; import net.java.sip.communicator.service.contactlist.MetaContact; import net.java.sip.communicator.service.contactlist.MetaContactGroup; import net.java.sip.communicator.service.contactlist.MetaContactListService; import net.java.sip.communicator.service.protocol.OperationFailedException; import net.java.sip.communicator.service.protocol.OperationSetPersistentPresence; import net.java.sip.communicator.service.protocol.OperationSetPresence; import net.java.sip.communicator.service.protocol.ProtocolProviderService; import net.java.sip.communicator.service.protocol.event.ContactPresenceStatusChangeEvent; import net.java.sip.communicator.service.protocol.event.ContactPresenceStatusListener; import net.java.sip.communicator.service.protocol.event.ProviderPresenceStatusChangeEvent; import net.java.sip.communicator.service.protocol.event.ProviderPresenceStatusListener; import net.java.sip.communicator.service.protocol.icqconstants.IcqStatusEnum; /** * The main application frame. * * @author Yana Stamcheva */ public class MainFrame extends JFrame { private JPanel contactListPanel = new JPanel(new BorderLayout()); private JPanel menusPanel = new JPanel(new BorderLayout()); private Menu menu = new Menu(); private ConfigurationFrame configFrame = new ConfigurationFrame(); private CallPanel callPanel; private StatusPanel statusPanel; private MainTabbedPane tabbedPane; private QuickMenu quickMenu; private Hashtable protocolSupportedOperationSets = new Hashtable(); private Hashtable protocolPresenceSets = new Hashtable(); private Dimension minimumFrameSize = new Dimension( Constants.MAINFRAME_MIN_WIDTH, Constants.MAINFRAME_MIN_HEIGHT); private Hashtable protocolProviders = new Hashtable(); private MetaContactListService contactList; private ArrayList accounts = new ArrayList(); public MainFrame() { callPanel = new CallPanel(this); tabbedPane = new MainTabbedPane(this); quickMenu = new QuickMenu(this); statusPanel = new StatusPanel(this); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setInitialBounds(); this.setTitle(Messages.getString("sipCommunicator")); this.setIconImage(ImageLoader.getImage(ImageLoader.SIP_LOGO)); this.init(); } private void init() { this.menusPanel.add(menu, BorderLayout.NORTH); this.menusPanel.add(quickMenu, BorderLayout.CENTER); this.contactListPanel.add(tabbedPane, BorderLayout.CENTER); this.contactListPanel.add(callPanel, BorderLayout.SOUTH); this.getContentPane().add(menusPanel, BorderLayout.NORTH); this.getContentPane().add(contactListPanel, BorderLayout.CENTER); this.getContentPane().add(statusPanel, BorderLayout.SOUTH); } private void setInitialBounds() { this.setSize(155, 400); this.contactListPanel.setPreferredSize(new Dimension(140, 350)); this.contactListPanel.setMinimumSize(new Dimension(80, 200)); this.setLocation(Toolkit.getDefaultToolkit().getScreenSize().width - this.getWidth(), 50); } public CallPanel getCallPanel() { return callPanel; } public MetaContactListService getContactList() { return this.contactList; } public void setContactList(MetaContactListService contactList) { this.contactList = contactList; ContactListPanel clistPanel = this.tabbedPane.getContactListPanel(); clistPanel.initTree(contactList); //add a key listener to the tabbed pane, when the contactlist is //initialized this.tabbedPane.addKeyListener(new CListKeySearchListener (clistPanel.getContactList())); } public ConfigurationFrame getConfigFrame() { return configFrame; } public void setConfigFrame(ConfigurationFrame configFrame) { this.configFrame = configFrame; } public Map getSupportedOperationSets (ProtocolProviderService protocolProvider) { return (Map)this.protocolSupportedOperationSets.get(protocolProvider); } public void addProtocolSupportedOperationSets (ProtocolProviderService protocolProvider, Map supportedOperationSets) { this.protocolSupportedOperationSets.put(protocolProvider, supportedOperationSets); Iterator entrySetIter = supportedOperationSets.entrySet().iterator(); for (int i = 0; i < supportedOperationSets.size(); i++) { Map.Entry entry = (Map.Entry) entrySetIter.next(); Object key = entry.getKey(); Object value = entry.getValue(); if(key.equals(OperationSetPersistentPresence.class.getName()) || key.equals(OperationSetPresence.class.getName())){ OperationSetPresence presence = (OperationSetPresence)value; this.protocolPresenceSets.put( protocolProvider, presence); presence .addProviderPresenceStatusListener (new ProviderPresenceStatusAdapter()); presence .addContactPresenceStatusListener (new ContactPresenceStatusAdapter()); try { presence .publishPresenceStatus(IcqStatusEnum.ONLINE, ""); this.getStatusPanel().stopConnecting( protocolProvider.getProtocolName()); this.statusPanel.setSelectedStatus (protocolProvider.getProtocolName(), Constants.ONLINE_STATUS); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (OperationFailedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private class ProviderPresenceStatusAdapter implements ProviderPresenceStatusListener { public void providerStatusChanged (ProviderPresenceStatusChangeEvent evt) { } public void providerStatusMessageChanged (PropertyChangeEvent evt) { } } private class ContactPresenceStatusAdapter implements ContactPresenceStatusListener { public void contactPresenceStatusChanged (ContactPresenceStatusChangeEvent evt) { MetaContact metaContact = contactList.findMetaContactByContact(evt.getSourceContact()); if (metaContact != null){ ContactListModel model = (ContactListModel)tabbedPane.getContactListPanel() .getContactList().getModel(); MetaContactNode node = model.getContactNodeByContact(metaContact); if(node != null){ node.setStatusIcon (new ImageIcon(Constants.getStatusIcon (evt.getNewStatus()))); //Refresh the node status icon. model.contactStatusChanged(model.indexOf(node)); } } } } public StatusPanel getStatusPanel() { return statusPanel; } public Map getProtocolProviders() { return this.protocolProviders; } public void addProtocolProvider( ProtocolProviderService protocolProvider) { this.protocolProviders.put( protocolProvider.getProtocolName(), protocolProvider); } public void addAccount(Account account){ this.accounts.add(account); } public Account getAccount(){ return (Account)this.accounts.get(0); } public OperationSetPresence getProtocolPresence (ProtocolProviderService protocolProvider) { return (OperationSetPresence) this.protocolPresenceSets.get(protocolProvider); } }
Protocol status icons behind users
src/net/java/sip/communicator/impl/gui/main/MainFrame.java
Protocol status icons behind users
<ide><path>rc/net/java/sip/communicator/impl/gui/main/MainFrame.java <ide> import net.java.sip.communicator.service.contactlist.MetaContact; <ide> import net.java.sip.communicator.service.contactlist.MetaContactGroup; <ide> import net.java.sip.communicator.service.contactlist.MetaContactListService; <add>import net.java.sip.communicator.service.protocol.Contact; <ide> import net.java.sip.communicator.service.protocol.OperationFailedException; <ide> import net.java.sip.communicator.service.protocol.OperationSetPersistentPresence; <ide> import net.java.sip.communicator.service.protocol.OperationSetPresence; <add>import net.java.sip.communicator.service.protocol.PresenceStatus; <ide> import net.java.sip.communicator.service.protocol.ProtocolProviderService; <ide> import net.java.sip.communicator.service.protocol.event.ContactPresenceStatusChangeEvent; <ide> import net.java.sip.communicator.service.protocol.event.ContactPresenceStatusListener; <ide> public void contactPresenceStatusChanged <ide> (ContactPresenceStatusChangeEvent evt) { <ide> <add> Contact sourceContact = evt.getSourceContact(); <add> PresenceStatus newStatus = evt.getNewStatus(); <add> <ide> MetaContact metaContact <del> = contactList.findMetaContactByContact(evt.getSourceContact()); <add> = contactList.findMetaContactByContact(sourceContact); <ide> <ide> if (metaContact != null){ <ide> ContactListModel model <ide> <ide> node.setStatusIcon <ide> (new ImageIcon(Constants.getStatusIcon <del> (evt.getNewStatus()))); <add> (newStatus))); <ide> <add> node.changeProtocolContactStatus( <add> sourceContact.getProtocolProvider() <add> .getProtocolName(), <add> newStatus); <add> <ide> //Refresh the node status icon. <ide> model.contactStatusChanged(model.indexOf(node)); <ide> }
JavaScript
mit
da706925393f97ca6b0c32565143d70408dc54af
0
Vestorly/ember-tour,Vestorly/ember-tour
import Ember from 'ember'; export default Ember.Component.extend({ /** The CSS properties for the 'spotlight' element over the current target element @property spotlightCSS @type String */ spotlightCSS: '', /** Set to true if the tour is running @property started @type Boolean @default false */ started: false, /** The point at which the tour will start @property firstTourStep @type Integer @default 0 */ firstTourStep: 0, /** The number of the active stop stop @property currentStopStep @type Integer @default null */ currentStopStep: null, /** Set to true if the tour is between stops @property transitioning @type Integer @default false */ transitioning: false, /** The previous tour stop @property previousStop @type previousStop @default null */ previousStop: null, /** When in transition, the stop to which the tour is transitioning @property transitionStop @type Object @default null */ transitionStop: null, /** The height of the window @property windowHeight @type Integer */ windowHeight: null, /** The width of the window @property windowWidth @type Integer */ windowWidth: null, /** @property tourStops @type Object */ tourStops: Ember.computed.alias('model.tourStops'), /** The Ember currentPath @property currentPath @type String */ currentPath: Ember.computed.alias('parentView.controller.currentPath'), /** Starts the tour when `started` is changed to true @private @method _startTour */ _startTour: (function(){ if(this.get('started')){ this.setProperties({ transitionStop: null, currentStop: null }); var startingStep = this.get('firstTourStep') || 0; this.set('currentStopStep', startingStep); this.notifyPropertyChange('currentStopStep'); } }).observes('started'), /** Set to true if there are stops after the `currentStop` in `tourStops` @property moreForwardSteps @type Boolean */ moreForwardSteps: Ember.computed('currentStopStep', 'sortedTourStops', function(){ return this.get('currentStopStep') + 1 < this.get('sortedTourStops.length'); } ), /** Set to true if there are stops before the `currentStop` in `tourStops` @property moreBackwardStops @type Boolean */ moreBackwardSteps: Ember.computed('currentStopStep', function(){ return this.get('currentStopStep') > 0; } ), /** When the current path changes, call a check to see if the user changed the path @method pathChange */ pathChange: (function(){ if(this.get('currentStop') && this.get('started')) { Ember.run.scheduleOnce('afterRender', this, this._checkForUserInitiatedTransition); } }).observes('currentPath'), /** Exits the tour if the user initiated a route change, instead of the tour. Checks to see if the target element is still in the page after the transition; if not the tour ends. @method checkForUserInitiatedTransition */ checkForUserInitiatedTransition: (function(){ var transitioning = this.get('transitioning'); var element = this.get('currentStop.element'); var elementOnPage = $(element); if (!transitioning && Ember.isBlank(elementOnPage)) { this.exitTour(); } }), /** The tour's stops, sorted by the step number @property sortedTourStops @type Object */ sortedTourStops: Ember.computed('tourStops', function(){ var tourStops = this.get('tourStops'); if(tourStops && tourStops.get('length')){ return tourStops.sortBy('step'); } } ), /** When the `currentStopStep` changes, the transitionStop is set to the object at that position. @private @method _setTransitionStop */ _setTransitionStop: (function(){ var step = this.get('currentStopStep'); var transitionStop = this.get('sortedTourStops').objectAt(step); this.set('transitionStop', transitionStop); } ).observes('currentStopStep'), _startTourStopTransition: (function(){ var transitionStop = this.get('transitionStop'), currentStop = this.get('currentStop'); if(currentStop){ currentStop.set('active', false); } if(transitionStop) { this.set('transitioning', true); var previousStop = this.get('previousStop'), targetRoute = transitionStop.get('targetRoute'), router = this.container.lookup('router:main').router, renderedProperty = 'lastRenderedTemplate', targetElement = transitionStop.get('element'), route; var allRoutes = Ember.keys(router.recognizer.names); var routeExists = allRoutes.indexOf(targetRoute) !== -1; if (routeExists) { route = this.container.lookup('route:' + targetRoute); } var currentRouteDifferent = !previousStop || previousStop.get('targetRoute') !== targetRoute; var routePresent = routeExists && route.get(renderedProperty); if (routeExists && (!routePresent || currentRouteDifferent)) { route.transitionTo(targetRoute); if (targetElement) { this._finishWhenElementInPage(targetElement); } else { this._finishTransition(); } } else { this._finishTransition(); } } }).observes('transitionStop'), _finishWhenElementInPage: function(element, waitTime) { var component = this; if(!(typeof waitTime === "number")){ waitTime = 5000 } if(!Ember.isBlank($(element))){ this._finishTransition(); } else if(waitTime > 0) { Ember.run.later(function () { component._finishWhenElementInPage(element, waitTime - 20); },20); } else { this.incrementProperty('currentStopStep'); } }, _finishTransition: function() { var transitionStop = this.get('transitionStop'), currentStop = this.get('currentStop'); transitionStop.set('active', true); this.setProperties({ currentStop: transitionStop, previousStop: currentStop }); Ember.run.scheduleOnce('afterRender', this, function(){this.set('transitioning', false)}); }, currentProgress: Ember.computed('tourStops', 'currentStep', function(){ return ((this.get('currentStep') + 1) / this.get('tourStops.length')) * 100; }), /** Initializes a listener to track window height and width; @private @method _windowSize */ _windowSize: (function(){ var component = this; component.setProperties({ windowWidth: $(window).width(), windowHeight: $(window).height() }); if(this.get('started')){ Ember.$(window).on('resize.tour', function(){ Ember.run(function() { component.setProperties({ windowWidth: $(window).width(), windowHeight: $(window).height() }); }); }); Ember.$(window).on('scroll.tour', function(){ component.set('scrollTop', $(window).scrollTop()); }); } else { Ember.$(window).off('resize.tour'); Ember.$(window).off('scroll.tour'); } }).observes('started').on('init'), exitTour: function(){ this.set('started', false); this.set('transitionStop.active', false); this.set('currentStop.active', false); this.set('previousStop', null); this.sendAction('endTour'); }, actions: { exitTour: function(){ this.exitTour(); }, advance: function(){ this.incrementProperty('currentStopStep', 1); }, reverse: function(){ this.decrementProperty('currentStopStep', 1); }, goToStep: function(number){ this.set('currentStopStep', number); }, goToStop: function(id){ var sortedTourStops = this.get('sortedTourStops'); var tourStop = sortedTourStops.findBy('id', id); var position = sortedTourStops.indexOf(tourStop); this.set('currentStopStep', position); } } });
app/components/ember-tour.js
import Ember from 'ember'; export default Ember.Component.extend({ spotlightCSS: '', started: false, firstTourStep: 0, currentStopStep: null, transitioning: false, startTour: (function(){ if(this.get('started')){ this.setProperties({ transitionStop: null, currentStop: null }); var startingStep = this.get('firstTourStep') || 0; this.set('currentStopStep', startingStep); this.notifyPropertyChange('currentStopStep'); } }).observes('started'), moreForwardSteps: Ember.computed('currentStopStep', 'sortedTourStops', function(){ return this.get('currentStopStep') + 1 < this.get('sortedTourStops.length'); } ), moreBackwardSteps: Ember.computed('currentStopStep', function(){ return this.get('currentStopStep') > 0; } ), currentStopNumber: Ember.computed('currentStopStep', function(){ return this.get('currentStopNumber') + 1; }), previousStopStep: null, previousStop: null, transitionStop: null, windowWidth: null, windowHeight: null, tourStops: Ember.computed.alias('model.tourStops'), currentPath: Ember.computed.alias('parentView.controller.currentPath'), _routeChange: (function(){ if(this.get('currentStop') && this.get('started')) { Ember.run.scheduleOnce('afterRender', this, this._checkForUserInitiatedTransition); } }).observes('currentPath'), _checkForUserInitiatedTransition: (function(){ var transitioning = this.get('transitioning'); var element = this.get('currentStop.element'); var elementOnPage = $(element); if (!transitioning && Ember.isBlank(elementOnPage)) { this.exitTour(); } }), sortedTourStops: Ember.computed('model', function(){ var model = this.get('model'); if(model && model.get('tourStops')){ return model.get('tourStops').sortBy('step'); } } ), _setTransitionStop: (function(){ var step = this.get('currentStopStep'); var transitionStop = this.get('sortedTourStops').objectAt(step); this.set('transitionStop', transitionStop); } ).observes('currentStopStep'), _startTourStopTransition: (function(){ var transitionStop = this.get('transitionStop'), currentStop = this.get('currentStop'); if(currentStop){ currentStop.set('active', false); } if(transitionStop) { this.set('transitioning', true); var previousStop = this.get('previousStop'), targetRoute = transitionStop.get('targetRoute'), router = this.container.lookup('router:main').router, renderedProperty = 'lastRenderedTemplate', targetElement = transitionStop.get('element'), route; var allRoutes = Ember.keys(router.recognizer.names); var routeExists = allRoutes.indexOf(targetRoute) !== -1; if (routeExists) { route = this.container.lookup('route:' + targetRoute); } var currentRouteDifferent = !previousStop || previousStop.get('targetRoute') !== targetRoute; var routePresent = routeExists && route.get(renderedProperty); if (routeExists && (!routePresent || currentRouteDifferent)) { route.transitionTo(targetRoute); if (targetElement) { this._finishWhenElementInPage(targetElement); } else { this._finishTransition(); } } else { this._finishTransition(); } } }).observes('transitionStop'), _finishWhenElementInPage: function(element, waitTime) { var component = this; if(!(typeof waitTime === "number")){ waitTime = 5000 } if(!Ember.isBlank($(element))){ this._finishTransition(); } else if(waitTime > 0) { Ember.run.later(function () { component._finishWhenElementInPage(element, waitTime - 20); },20); } else { this.incrementProperty('currentStopStep'); } }, _finishTransition: function() { var transitionStop = this.get('transitionStop'), currentStop = this.get('currentStop'); transitionStop.set('active', true); this.setProperties({ currentStop: transitionStop, previousStop: currentStop }); Ember.run.scheduleOnce('afterRender', this, function(){this.set('transitioning', false)}); }, currentProgress: Ember.computed('tourStops', 'currentStep', function(){ return ((this.get('currentStep') + 1) / this.get('tourStops.length')) * 100; }), /** * Initializes a listener to set window height and width; * * @api private * @method _getWinSize */ _windowSize: (function(){ var component = this; component.setProperties({ windowWidth: $(window).width(), windowHeight: $(window).height() }); if(this.get('started')){ Ember.$(window).on('resize.tour', function(){ Ember.run(function() { component.setProperties({ windowWidth: $(window).width(), windowHeight: $(window).height() }); }); }); Ember.$(window).on('scroll.tour', function(){ component.set('scrollTop', $(window).scrollTop()); }); } else { Ember.$(window).off('resize.tour'); Ember.$(window).off('scroll.tour'); } }).observes('started').on('init'), exitTour: function(){ this.set('started', false); this.set('transitionStop.active', false); this.set('currentStop.active', false); this.set('previousStop', null); this.sendAction('endTour'); }, actions: { exitTour: function(){ this.exitTour(); }, advance: function(){ this.incrementProperty('currentStopStep', 1); }, reverse: function(){ this.decrementProperty('currentStopStep', 1); }, goToStep: function(number){ this.set('currentStopStep', number); }, goToStop: function(id){ var sortedTourStops = this.get('sortedTourStops'); var tourStop = sortedTourStops.findBy('id', id); var position = sortedTourStops.indexOf(tourStop); this.set('currentStopStep', position); } } });
some documentation for tour
app/components/ember-tour.js
some documentation for tour
<ide><path>pp/components/ember-tour.js <ide> import Ember from 'ember'; <ide> <ide> export default Ember.Component.extend({ <add> <add> /** <add> The CSS properties for the 'spotlight' element over the current target element <add> <add> @property spotlightCSS <add> @type String <add> */ <add> <ide> spotlightCSS: '', <add> <add> /** <add> Set to true if the tour is running <add> <add> @property started <add> @type Boolean <add> @default false <add> */ <add> <ide> started: false, <add> <add> /** <add> The point at which the tour will start <add> <add> @property firstTourStep <add> @type Integer <add> @default 0 <add> */ <add> <ide> firstTourStep: 0, <add> <add> /** <add> The number of the active stop stop <add> <add> @property currentStopStep <add> @type Integer <add> @default null <add> */ <add> <ide> currentStopStep: null, <add> <add> /** <add> Set to true if the tour is between stops <add> <add> @property transitioning <add> @type Integer <add> @default false <add> */ <add> <ide> transitioning: false, <ide> <del> startTour: (function(){ <add> /** <add> The previous tour stop <add> <add> @property previousStop <add> @type previousStop <add> @default null <add> */ <add> <add> previousStop: null, <add> <add> /** <add> When in transition, the stop to which the tour is transitioning <add> <add> @property transitionStop <add> @type Object <add> @default null <add> */ <add> <add> transitionStop: null, <add> <add> /** <add> The height of the window <add> <add> @property windowHeight <add> @type Integer <add> */ <add> <add> windowHeight: null, <add> <add> /** <add> The width of the window <add> <add> @property windowWidth <add> @type Integer <add> */ <add> <add> windowWidth: null, <add> <add> /** <add> @property tourStops <add> @type Object <add> */ <add> <add> tourStops: Ember.computed.alias('model.tourStops'), <add> <add> /** <add> The Ember currentPath <add> <add> @property currentPath <add> @type String <add> */ <add> <add> currentPath: Ember.computed.alias('parentView.controller.currentPath'), <add> <add> /** <add> Starts the tour when `started` is changed to true <add> @private <add> @method _startTour <add> */ <add> <add> _startTour: (function(){ <ide> if(this.get('started')){ <ide> this.setProperties({ <ide> transitionStop: null, <ide> } <ide> }).observes('started'), <ide> <add> /** <add> Set to true if there are stops after the `currentStop` in `tourStops` <add> <add> @property moreForwardSteps <add> @type Boolean <add> */ <add> <ide> moreForwardSteps: Ember.computed('currentStopStep', 'sortedTourStops', <ide> function(){ <ide> return this.get('currentStopStep') + 1 < this.get('sortedTourStops.length'); <ide> } <ide> ), <ide> <add> /** <add> Set to true if there are stops before the `currentStop` in `tourStops` <add> <add> @property moreBackwardStops <add> @type Boolean <add> */ <add> <ide> moreBackwardSteps: Ember.computed('currentStopStep', <ide> function(){ <ide> return this.get('currentStopStep') > 0; <ide> } <ide> ), <ide> <del> currentStopNumber: Ember.computed('currentStopStep', function(){ <del> return this.get('currentStopNumber') + 1; <del> }), <del> <del> previousStopStep: null, <del> previousStop: null, <del> transitionStop: null, <del> windowWidth: null, <del> windowHeight: null, <del> <del> tourStops: Ember.computed.alias('model.tourStops'), <del> currentPath: Ember.computed.alias('parentView.controller.currentPath'), <del> <del> _routeChange: (function(){ <add> /** <add> When the current path changes, call a check to see if the user changed the path <add> <add> @method pathChange <add> */ <add> <add> pathChange: (function(){ <ide> if(this.get('currentStop') && this.get('started')) { <ide> Ember.run.scheduleOnce('afterRender', this, this._checkForUserInitiatedTransition); <ide> } <ide> }).observes('currentPath'), <ide> <del> _checkForUserInitiatedTransition: (function(){ <add> <add> /** <add> Exits the tour if the user initiated a route change, instead of the tour. Checks to see <add> if the target element is still in the page after the transition; if not the tour ends. <add> <add> @method checkForUserInitiatedTransition <add> */ <add> <add> checkForUserInitiatedTransition: (function(){ <ide> var transitioning = this.get('transitioning'); <ide> var element = this.get('currentStop.element'); <ide> var elementOnPage = $(element); <ide> } <ide> }), <ide> <del> sortedTourStops: Ember.computed('model', <add> /** <add> The tour's stops, sorted by the step number <add> <add> @property sortedTourStops <add> @type Object <add> */ <add> <add> sortedTourStops: Ember.computed('tourStops', <ide> function(){ <del> var model = this.get('model'); <del> if(model && model.get('tourStops')){ <del> return model.get('tourStops').sortBy('step'); <add> var tourStops = this.get('tourStops'); <add> if(tourStops && tourStops.get('length')){ <add> return tourStops.sortBy('step'); <ide> } <ide> } <ide> ), <ide> <add> /** <add> When the `currentStopStep` changes, the transitionStop is set to the object at that position. <add> <add> @private <add> @method _setTransitionStop <add> */ <add> <ide> _setTransitionStop: (function(){ <del> var step = this.get('currentStopStep'); <del> var transitionStop = this.get('sortedTourStops').objectAt(step); <del> this.set('transitionStop', transitionStop); <del> } <add> var step = this.get('currentStopStep'); <add> var transitionStop = this.get('sortedTourStops').objectAt(step); <add> this.set('transitionStop', transitionStop); <add> } <ide> ).observes('currentStopStep'), <ide> <ide> _startTourStopTransition: (function(){ <ide> }), <ide> <ide> /** <del> * Initializes a listener to set window height and width; <del> * <del> * @api private <del> * @method _getWinSize <add> Initializes a listener to track window height and width; <add> <add> @private <add> @method _windowSize <ide> */ <ide> <ide> _windowSize: (function(){
JavaScript
mit
5ea7b3c8719c03a72018e2678aa4be77aee4deb5
0
bixbyjs/bixby-express
exports = module.exports = function(IoC, logger) { return IoC.create('app/service') .catch(function(err) { // TODO: Check that the error is failure to create app/service return IoC.create('./service'); throw err; }) .then(function(service) { return IoC.create('./platform/gateways') .then(function(gateways) { // TODO: Implement a way to return the annotations, so those // can be used to drive service discovery. gateways.forEach(function(gateway, i) { // Dispatch requests to the service, which in this case is an // Express app. gateway.on('request', service); }); }); }); }; exports['@implements'] = 'http://i.bixbyjs.org/main'; exports['@singleton'] = true; exports['@require'] = [ '!container', 'http://i.bixbyjs.org/Logger' ];
app/app.js
exports = module.exports = function(IoC, logger) { return IoC.create('app/service') .catch(function(err) { // TODO: Check that the error is failure to create app/service return IoC.create('./service'); throw err; }) .then(function(service) { return IoC.create('./platform/gateways') .then(function(gateways) { // TODO: Implement a way to return the annotations, so those // can be used to drive service discovery. gateways.forEach(function(gateway, i) { // Dispatch requests to the service, which in this case is an // Express app. gateway.on('request', service); }); }); }); }; exports['@implements'] = 'http://i.bixbyjs.org/Main'; exports['@singleton'] = true; exports['@require'] = [ '!container', 'http://i.bixbyjs.org/Logger' ];
Rename main interface.
app/app.js
Rename main interface.
<ide><path>pp/app.js <ide> }); <ide> }; <ide> <del>exports['@implements'] = 'http://i.bixbyjs.org/Main'; <add>exports['@implements'] = 'http://i.bixbyjs.org/main'; <ide> exports['@singleton'] = true; <ide> exports['@require'] = [ <ide> '!container',
JavaScript
mit
cff0d2929d8fab24f620a74cf10e06e3a3be6aaa
0
atom/github,atom/github,atom/github
import {buildFilePatch, buildMultiFilePatch} from '../../../lib/models/patch'; import {TOO_LARGE, EXPANDED} from '../../../lib/models/patch/patch'; import {assertInPatch, assertInFilePatch} from '../../helpers'; describe('buildFilePatch', function() { it('returns a null patch for an empty diff list', function() { const multiFilePatch = buildFilePatch([]); const [filePatch] = multiFilePatch.getFilePatches(); assert.isFalse(filePatch.getOldFile().isPresent()); assert.isFalse(filePatch.getNewFile().isPresent()); assert.isFalse(filePatch.getPatch().isPresent()); }); describe('with a single diff', function() { it('assembles a patch from non-symlink sides', function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '100644', newPath: 'new/path', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 7, newLineCount: 6, lines: [ ' line-0', '-line-1', '-line-2', '-line-3', ' line-4', '+line-5', '+line-6', ' line-7', ' line-8', ], }, { oldStartLine: 10, newStartLine: 11, oldLineCount: 3, newLineCount: 3, lines: [ '-line-9', ' line-10', ' line-11', '+line-12', ], }, { oldStartLine: 20, newStartLine: 21, oldLineCount: 4, newLineCount: 4, lines: [ ' line-13', '-line-14', '-line-15', '+line-16', '+line-17', ' line-18', ], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.strictEqual(p.getOldPath(), 'old/path'); assert.strictEqual(p.getOldMode(), '100644'); assert.strictEqual(p.getNewPath(), 'new/path'); assert.strictEqual(p.getNewMode(), '100755'); assert.strictEqual(p.getPatch().getStatus(), 'modified'); const bufferText = 'line-0\nline-1\nline-2\nline-3\nline-4\nline-5\nline-6\nline-7\nline-8\nline-9\nline-10\n' + 'line-11\nline-12\nline-13\nline-14\nline-15\nline-16\nline-17\nline-18'; assert.strictEqual(buffer.getText(), bufferText); assertInPatch(p, buffer).hunks( { startRow: 0, endRow: 8, header: '@@ -0,7 +0,6 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'deletion', string: '-line-1\n-line-2\n-line-3\n', range: [[1, 0], [3, 6]]}, {kind: 'unchanged', string: ' line-4\n', range: [[4, 0], [4, 6]]}, {kind: 'addition', string: '+line-5\n+line-6\n', range: [[5, 0], [6, 6]]}, {kind: 'unchanged', string: ' line-7\n line-8\n', range: [[7, 0], [8, 6]]}, ], }, { startRow: 9, endRow: 12, header: '@@ -10,3 +11,3 @@', regions: [ {kind: 'deletion', string: '-line-9\n', range: [[9, 0], [9, 6]]}, {kind: 'unchanged', string: ' line-10\n line-11\n', range: [[10, 0], [11, 7]]}, {kind: 'addition', string: '+line-12\n', range: [[12, 0], [12, 7]]}, ], }, { startRow: 13, endRow: 18, header: '@@ -20,4 +21,4 @@', regions: [ {kind: 'unchanged', string: ' line-13\n', range: [[13, 0], [13, 7]]}, {kind: 'deletion', string: '-line-14\n-line-15\n', range: [[14, 0], [15, 7]]}, {kind: 'addition', string: '+line-16\n+line-17\n', range: [[16, 0], [17, 7]]}, {kind: 'unchanged', string: ' line-18', range: [[18, 0], [18, 7]]}, ], }, ); }); it("sets the old file's symlink destination", function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '120000', newPath: 'new/path', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' old/destination'], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); assert.strictEqual(p.getOldSymlink(), 'old/destination'); assert.isNull(p.getNewSymlink()); }); it("sets the new file's symlink destination", function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '100644', newPath: 'new/path', newMode: '120000', status: 'modified', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' new/destination'], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); assert.isNull(p.getOldSymlink()); assert.strictEqual(p.getNewSymlink(), 'new/destination'); }); it("sets both files' symlink destinations", function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '120000', newPath: 'new/path', newMode: '120000', status: 'modified', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [ ' old/destination', ' --', ' new/destination', ], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); assert.strictEqual(p.getOldSymlink(), 'old/destination'); assert.strictEqual(p.getNewSymlink(), 'new/destination'); }); it('assembles a patch from a file deletion', function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '100644', newPath: null, newMode: null, status: 'deleted', hunks: [ { oldStartLine: 1, oldLineCount: 5, newStartLine: 0, newLineCount: 0, lines: [ '-line-0', '-line-1', '-line-2', '-line-3', '-', ], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.isTrue(p.getOldFile().isPresent()); assert.strictEqual(p.getOldPath(), 'old/path'); assert.strictEqual(p.getOldMode(), '100644'); assert.isFalse(p.getNewFile().isPresent()); assert.strictEqual(p.getPatch().getStatus(), 'deleted'); const bufferText = 'line-0\nline-1\nline-2\nline-3\n'; assert.strictEqual(buffer.getText(), bufferText); assertInPatch(p, buffer).hunks( { startRow: 0, endRow: 4, header: '@@ -1,5 +0,0 @@', regions: [ {kind: 'deletion', string: '-line-0\n-line-1\n-line-2\n-line-3\n-', range: [[0, 0], [4, 0]]}, ], }, ); }); it('assembles a patch from a file addition', function() { const multiFilePatch = buildFilePatch([{ oldPath: null, oldMode: null, newPath: 'new/path', newMode: '100755', status: 'added', hunks: [ { oldStartLine: 0, oldLineCount: 0, newStartLine: 1, newLineCount: 3, lines: [ '+line-0', '+line-1', '+line-2', ], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.isFalse(p.getOldFile().isPresent()); assert.isTrue(p.getNewFile().isPresent()); assert.strictEqual(p.getNewPath(), 'new/path'); assert.strictEqual(p.getNewMode(), '100755'); assert.strictEqual(p.getPatch().getStatus(), 'added'); const bufferText = 'line-0\nline-1\nline-2'; assert.strictEqual(buffer.getText(), bufferText); assertInPatch(p, buffer).hunks( { startRow: 0, endRow: 2, header: '@@ -0,0 +1,3 @@', regions: [ {kind: 'addition', string: '+line-0\n+line-1\n+line-2', range: [[0, 0], [2, 6]]}, ], }, ); }); it('throws an error with an unknown diff status character', function() { assert.throws(() => { buildFilePatch([{ oldPath: 'old/path', oldMode: '100644', newPath: 'new/path', newMode: '100644', status: 'modified', hunks: [{oldStartLine: 0, newStartLine: 0, oldLineCount: 1, newLineCount: 1, lines: ['xline-0']}], }]); }, /diff status character: "x"/); }); it('parses a no-newline marker', function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '100644', newPath: 'new/path', newMode: '100644', status: 'modified', hunks: [{oldStartLine: 0, newStartLine: 0, oldLineCount: 1, newLineCount: 1, lines: [ '+line-0', '-line-1', '\\ No newline at end of file', ]}], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.strictEqual(buffer.getText(), 'line-0\nline-1\n No newline at end of file'); assertInPatch(p, buffer).hunks({ startRow: 0, endRow: 2, header: '@@ -0,1 +0,1 @@', regions: [ {kind: 'addition', string: '+line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'deletion', string: '-line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'nonewline', string: '\\ No newline at end of file', range: [[2, 0], [2, 26]]}, ], }); }); }); describe('with a mode change and a content diff', function() { it('identifies a file that was deleted and replaced by a symlink', function() { const multiFilePatch = buildFilePatch([ { oldPath: 'the-path', oldMode: '000000', newPath: 'the-path', newMode: '120000', status: 'added', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' the-destination'], }, ], }, { oldPath: 'the-path', oldMode: '100644', newPath: 'the-path', newMode: '000000', status: 'deleted', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 2, lines: ['+line-0', '+line-1'], }, ], }, ]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.strictEqual(p.getOldPath(), 'the-path'); assert.strictEqual(p.getOldMode(), '100644'); assert.isNull(p.getOldSymlink()); assert.strictEqual(p.getNewPath(), 'the-path'); assert.strictEqual(p.getNewMode(), '120000'); assert.strictEqual(p.getNewSymlink(), 'the-destination'); assert.strictEqual(p.getStatus(), 'deleted'); assert.strictEqual(buffer.getText(), 'line-0\nline-1'); assertInPatch(p, buffer).hunks({ startRow: 0, endRow: 1, header: '@@ -0,0 +0,2 @@', regions: [ {kind: 'addition', string: '+line-0\n+line-1', range: [[0, 0], [1, 6]]}, ], }); }); it('identifies a symlink that was deleted and replaced by a file', function() { const multiFilePatch = buildFilePatch([ { oldPath: 'the-path', oldMode: '120000', newPath: 'the-path', newMode: '000000', status: 'deleted', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' the-destination'], }, ], }, { oldPath: 'the-path', oldMode: '000000', newPath: 'the-path', newMode: '100644', status: 'added', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 2, newLineCount: 0, lines: ['-line-0', '-line-1'], }, ], }, ]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.strictEqual(p.getOldPath(), 'the-path'); assert.strictEqual(p.getOldMode(), '120000'); assert.strictEqual(p.getOldSymlink(), 'the-destination'); assert.strictEqual(p.getNewPath(), 'the-path'); assert.strictEqual(p.getNewMode(), '100644'); assert.isNull(p.getNewSymlink()); assert.strictEqual(p.getStatus(), 'added'); assert.strictEqual(buffer.getText(), 'line-0\nline-1'); assertInPatch(p, buffer).hunks({ startRow: 0, endRow: 1, header: '@@ -0,2 +0,0 @@', regions: [ {kind: 'deletion', string: '-line-0\n-line-1', range: [[0, 0], [1, 6]]}, ], }); }); it('is indifferent to the order of the diffs', function() { const multiFilePatch = buildFilePatch([ { oldMode: '100644', newPath: 'the-path', newMode: '000000', status: 'deleted', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 2, lines: ['+line-0', '+line-1'], }, ], }, { oldPath: 'the-path', oldMode: '000000', newPath: 'the-path', newMode: '120000', status: 'added', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' the-destination'], }, ], }, ]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.strictEqual(p.getOldPath(), 'the-path'); assert.strictEqual(p.getOldMode(), '100644'); assert.isNull(p.getOldSymlink()); assert.strictEqual(p.getNewPath(), 'the-path'); assert.strictEqual(p.getNewMode(), '120000'); assert.strictEqual(p.getNewSymlink(), 'the-destination'); assert.strictEqual(p.getStatus(), 'deleted'); assert.strictEqual(buffer.getText(), 'line-0\nline-1'); assertInPatch(p, buffer).hunks({ startRow: 0, endRow: 1, header: '@@ -0,0 +0,2 @@', regions: [ {kind: 'addition', string: '+line-0\n+line-1', range: [[0, 0], [1, 6]]}, ], }); }); it('throws an error on an invalid mode diff status', function() { assert.throws(() => { buildFilePatch([ { oldMode: '100644', newPath: 'the-path', newMode: '000000', status: 'deleted', hunks: [ {oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 2, lines: ['+line-0', '+line-1']}, ], }, { oldPath: 'the-path', oldMode: '000000', newMode: '120000', status: 'modified', hunks: [ {oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' the-destination']}, ], }, ]); }, /mode change diff status: modified/); }); }); describe('with multiple diffs', function() { it('creates a MultiFilePatch containing each', function() { const mp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 2, newStartLine: 1, newLineCount: 4, lines: [ ' line-0', '+line-1', '+line-2', ' line-3', ], }, { oldStartLine: 10, oldLineCount: 3, newStartLine: 12, newLineCount: 2, lines: [ ' line-4', '-line-5', ' line-6', ], }, ], }, { oldPath: 'second', oldMode: '100644', newPath: 'second', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 5, oldLineCount: 3, newStartLine: 5, newLineCount: 3, lines: [ ' line-5', '+line-6', '-line-7', ' line-8', ], }, ], }, { oldPath: 'third', oldMode: '100755', newPath: 'third', newMode: '100755', status: 'added', hunks: [ { oldStartLine: 1, oldLineCount: 0, newStartLine: 1, newLineCount: 3, lines: [ '+line-0', '+line-1', '+line-2', ], }, ], }, ]); const buffer = mp.getBuffer(); assert.lengthOf(mp.getFilePatches(), 3); assert.strictEqual( mp.getBuffer().getText(), 'line-0\nline-1\nline-2\nline-3\nline-4\nline-5\nline-6\n' + 'line-5\nline-6\nline-7\nline-8\n' + 'line-0\nline-1\nline-2', ); assert.strictEqual(mp.getFilePatches()[0].getOldPath(), 'first'); assert.deepEqual(mp.getFilePatches()[0].getMarker().getRange().serialize(), [[0, 0], [6, 6]]); assertInFilePatch(mp.getFilePatches()[0], buffer).hunks( { startRow: 0, endRow: 3, header: '@@ -1,2 +1,4 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n+line-2\n', range: [[1, 0], [2, 6]]}, {kind: 'unchanged', string: ' line-3\n', range: [[3, 0], [3, 6]]}, ], }, { startRow: 4, endRow: 6, header: '@@ -10,3 +12,2 @@', regions: [ {kind: 'unchanged', string: ' line-4\n', range: [[4, 0], [4, 6]]}, {kind: 'deletion', string: '-line-5\n', range: [[5, 0], [5, 6]]}, {kind: 'unchanged', string: ' line-6\n', range: [[6, 0], [6, 6]]}, ], }, ); assert.strictEqual(mp.getFilePatches()[1].getOldPath(), 'second'); assert.deepEqual(mp.getFilePatches()[1].getMarker().getRange().serialize(), [[7, 0], [10, 6]]); assertInFilePatch(mp.getFilePatches()[1], buffer).hunks( { startRow: 7, endRow: 10, header: '@@ -5,3 +5,3 @@', regions: [ {kind: 'unchanged', string: ' line-5\n', range: [[7, 0], [7, 6]]}, {kind: 'addition', string: '+line-6\n', range: [[8, 0], [8, 6]]}, {kind: 'deletion', string: '-line-7\n', range: [[9, 0], [9, 6]]}, {kind: 'unchanged', string: ' line-8\n', range: [[10, 0], [10, 6]]}, ], }, ); assert.strictEqual(mp.getFilePatches()[2].getOldPath(), 'third'); assert.deepEqual(mp.getFilePatches()[2].getMarker().getRange().serialize(), [[11, 0], [13, 6]]); assertInFilePatch(mp.getFilePatches()[2], buffer).hunks( { startRow: 11, endRow: 13, header: '@@ -1,0 +1,3 @@', regions: [ {kind: 'addition', string: '+line-0\n+line-1\n+line-2', range: [[11, 0], [13, 6]]}, ], }, ); }); it('identifies mode and content change pairs within the patch list', function() { const mp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 2, newStartLine: 1, newLineCount: 3, lines: [ ' line-0', '+line-1', ' line-2', ], }, ], }, { oldPath: 'was-non-symlink', oldMode: '100644', newPath: 'was-non-symlink', newMode: '000000', status: 'deleted', hunks: [ { oldStartLine: 1, oldLineCount: 2, newStartLine: 1, newLineCount: 0, lines: ['-line-0', '-line-1'], }, ], }, { oldPath: 'was-symlink', oldMode: '000000', newPath: 'was-symlink', newMode: '100755', status: 'added', hunks: [ { oldStartLine: 1, oldLineCount: 0, newStartLine: 1, newLineCount: 2, lines: ['+line-0', '+line-1'], }, ], }, { oldMode: '100644', newPath: 'third', newMode: '100644', status: 'deleted', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 0, lines: ['-line-0', '-line-1', '-line-2'], }, ], }, { oldPath: 'was-symlink', oldMode: '120000', newPath: 'was-non-symlink', newMode: '000000', status: 'deleted', hunks: [ { oldStartLine: 1, oldLineCount: 0, newStartLine: 0, newLineCount: 0, lines: ['-was-symlink-destination'], }, ], }, { oldPath: 'was-non-symlink', oldMode: '000000', newPath: 'was-non-symlink', newMode: '120000', status: 'added', hunks: [ { oldStartLine: 1, oldLineCount: 0, newStartLine: 1, newLineCount: 1, lines: ['+was-non-symlink-destination'], }, ], }, ]); const buffer = mp.getBuffer(); assert.lengthOf(mp.getFilePatches(), 4); const [fp0, fp1, fp2, fp3] = mp.getFilePatches(); assert.strictEqual(fp0.getOldPath(), 'first'); assertInFilePatch(fp0, buffer).hunks({ startRow: 0, endRow: 2, header: '@@ -1,2 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'unchanged', string: ' line-2\n', range: [[2, 0], [2, 6]]}, ], }); assert.strictEqual(fp1.getOldPath(), 'was-non-symlink'); assert.isTrue(fp1.hasTypechange()); assert.strictEqual(fp1.getNewSymlink(), 'was-non-symlink-destination'); assertInFilePatch(fp1, buffer).hunks({ startRow: 3, endRow: 4, header: '@@ -1,2 +1,0 @@', regions: [ {kind: 'deletion', string: '-line-0\n-line-1\n', range: [[3, 0], [4, 6]]}, ], }); assert.strictEqual(fp2.getOldPath(), 'was-symlink'); assert.isTrue(fp2.hasTypechange()); assert.strictEqual(fp2.getOldSymlink(), 'was-symlink-destination'); assertInFilePatch(fp2, buffer).hunks({ startRow: 5, endRow: 6, header: '@@ -1,0 +1,2 @@', regions: [ {kind: 'addition', string: '+line-0\n+line-1\n', range: [[5, 0], [6, 6]]}, ], }); assert.strictEqual(fp3.getNewPath(), 'third'); assertInFilePatch(fp3, buffer).hunks({ startRow: 7, endRow: 9, header: '@@ -1,3 +1,0 @@', regions: [ {kind: 'deletion', string: '-line-0\n-line-1\n-line-2', range: [[7, 0], [9, 6]]}, ], }); }); it('sets the correct marker range for diffs with no hunks', function() { const mp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 2, newStartLine: 1, newLineCount: 4, lines: [ ' line-0', '+line-1', '+line-2', ' line-3', ], }, { oldStartLine: 10, oldLineCount: 3, newStartLine: 12, newLineCount: 2, lines: [ ' line-4', '-line-5', ' line-6', ], }, ], }, { oldPath: 'second', oldMode: '100644', newPath: 'second', newMode: '100755', status: 'modified', hunks: [], }, { oldPath: 'third', oldMode: '100755', newPath: 'third', newMode: '100755', status: 'added', hunks: [ { oldStartLine: 5, oldLineCount: 3, newStartLine: 5, newLineCount: 3, lines: [ ' line-5', '+line-6', '-line-7', ' line-8', ], }, ], }, ]); assert.strictEqual(mp.getFilePatches()[0].getOldPath(), 'first'); assert.deepEqual(mp.getFilePatches()[0].getMarker().getRange().serialize(), [[0, 0], [6, 6]]); assert.strictEqual(mp.getFilePatches()[1].getOldPath(), 'second'); assert.deepEqual(mp.getFilePatches()[1].getHunks(), []); assert.deepEqual(mp.getFilePatches()[1].getMarker().getRange().serialize(), [[6, 6], [6, 6]]); assert.strictEqual(mp.getFilePatches()[2].getOldPath(), 'third'); assert.deepEqual(mp.getFilePatches()[2].getMarker().getRange().serialize(), [[7, 0], [10, 6]]); }); }); describe('with a large diff', function() { it('creates a HiddenPatch when the diff is "too large"', function() { const mfp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, { oldPath: 'second', oldMode: '100644', newPath: 'second', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 1, newStartLine: 1, newLineCount: 2, lines: [' line-4', '+line-5'], }, ], }, ], {largeDiffThreshold: 3}); assert.lengthOf(mfp.getFilePatches(), 2); const [fp0, fp1] = mfp.getFilePatches(); assert.strictEqual(fp0.getRenderStatus(), TOO_LARGE); assert.strictEqual(fp0.getOldPath(), 'first'); assert.strictEqual(fp0.getNewPath(), 'first'); assert.deepEqual(fp0.getStartRange().serialize(), [[0, 0], [0, 0]]); assertInFilePatch(fp0).hunks(); assert.strictEqual(fp1.getRenderStatus(), EXPANDED); assert.strictEqual(fp1.getOldPath(), 'second'); assert.strictEqual(fp1.getNewPath(), 'second'); assert.deepEqual(fp1.getMarker().getRange().serialize(), [[0, 0], [1, 6]]); assertInFilePatch(fp1, mfp.getBuffer()).hunks( { startRow: 0, endRow: 1, header: '@@ -1,1 +1,2 @@', regions: [ {kind: 'unchanged', string: ' line-4\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-5', range: [[1, 0], [1, 6]]}, ], }, ); }); it('re-parse a HiddenPatch as a Patch', function() { const mfp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, ], {largeDiffThreshold: 3}); assert.lengthOf(mfp.getFilePatches(), 1); const [fp] = mfp.getFilePatches(); assert.strictEqual(fp.getRenderStatus(), TOO_LARGE); assert.strictEqual(fp.getOldPath(), 'first'); assert.strictEqual(fp.getNewPath(), 'first'); assert.deepEqual(fp.getStartRange().serialize(), [[0, 0], [0, 0]]); assertInFilePatch(fp).hunks(); mfp.expandFilePatch(fp); assert.strictEqual(fp.getRenderStatus(), EXPANDED); assert.deepEqual(fp.getMarker().getRange().serialize(), [[0, 0], [3, 6]]); assertInFilePatch(fp, mfp.getBuffer()).hunks( { startRow: 0, endRow: 3, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[2, 0], [2, 6]]}, {kind: 'unchanged', string: ' line-3', range: [[3, 0], [3, 6]]}, ], }, ); }); it('does not interfere with markers from surrounding visible patches when expanded', function() { const mfp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, { oldPath: 'big', oldMode: '100644', newPath: 'big', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 4, lines: [' line-0', '+line-1', '+line-2', '-line-3', ' line-4'], }, ], }, { oldPath: 'last', oldMode: '100644', newPath: 'last', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, ], {largeDiffThreshold: 4}); assert.lengthOf(mfp.getFilePatches(), 3); const [fp0, fp1, fp2] = mfp.getFilePatches(); assert.strictEqual(fp0.getRenderStatus(), EXPANDED); assertInFilePatch(fp0, mfp.getBuffer()).hunks( { startRow: 0, endRow: 3, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[2, 0], [2, 6]]}, {kind: 'unchanged', string: ' line-3\n', range: [[3, 0], [3, 6]]}, ], }, ); assert.strictEqual(fp1.getRenderStatus(), TOO_LARGE); assertInFilePatch(fp1, mfp.getBuffer()).hunks(); assert.strictEqual(fp2.getRenderStatus(), EXPANDED); assertInFilePatch(fp2, mfp.getBuffer()).hunks( { startRow: 4, endRow: 7, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[4, 0], [4, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[5, 0], [5, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[6, 0], [6, 6]]}, {kind: 'unchanged', string: ' line-3', range: [[7, 0], [7, 6]]}, ], }, ); mfp.expandFilePatch(fp1); assert.strictEqual(fp0.getRenderStatus(), EXPANDED); assertInFilePatch(fp0, mfp.getBuffer()).hunks( { startRow: 0, endRow: 3, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[2, 0], [2, 6]]}, {kind: 'unchanged', string: ' line-3\n', range: [[3, 0], [3, 6]]}, ], }, ); assert.strictEqual(fp1.getRenderStatus(), EXPANDED); assertInFilePatch(fp1, mfp.getBuffer()).hunks( { startRow: 4, endRow: 8, header: '@@ -1,3 +1,4 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[4, 0], [4, 6]]}, {kind: 'addition', string: '+line-1\n+line-2\n', range: [[5, 0], [6, 6]]}, {kind: 'deletion', string: '-line-3\n', range: [[7, 0], [7, 6]]}, {kind: 'unchanged', string: ' line-4\n', range: [[8, 0], [8, 6]]}, ], }, ); assert.strictEqual(fp2.getRenderStatus(), EXPANDED); assertInFilePatch(fp2, mfp.getBuffer()).hunks( { startRow: 9, endRow: 12, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[9, 0], [9, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[10, 0], [10, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[11, 0], [11, 6]]}, {kind: 'unchanged', string: ' line-3', range: [[12, 0], [12, 6]]}, ], }, ); }); it('does not interfere with markers from surrounding non-visible patches when expanded', function() { const mfp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, { oldPath: 'second', oldMode: '100644', newPath: 'second', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, { oldPath: 'third', oldMode: '100644', newPath: 'third', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, ], {largeDiffThreshold: 3}); assert.lengthOf(mfp.getFilePatches(), 3); const [fp0, fp1, fp2] = mfp.getFilePatches(); assert.deepEqual(fp0.getMarker().getRange().serialize(), [[0, 0], [0, 0]]); assert.deepEqual(fp1.getMarker().getRange().serialize(), [[0, 0], [0, 0]]); assert.deepEqual(fp2.getMarker().getRange().serialize(), [[0, 0], [0, 0]]); mfp.expandFilePatch(fp1); assert.deepEqual(fp0.getMarker().getRange().serialize(), [[0, 0], [0, 0]]); assert.deepEqual(fp1.getMarker().getRange().serialize(), [[0, 0], [3, 6]]); assert.deepEqual(fp2.getMarker().getRange().serialize(), [[3, 6], [3, 6]]); }); it('does not create a HiddenPatch when the patch has been explicitly expanded', function() { const mfp = buildMultiFilePatch([ { oldPath: 'big/file.txt', oldMode: '100644', newPath: 'big/file.txt', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, ], {largeDiffThreshold: 3, renderStatusOverrides: {'big/file.txt': EXPANDED}}); assert.lengthOf(mfp.getFilePatches(), 1); const [fp] = mfp.getFilePatches(); assert.strictEqual(fp.getRenderStatus(), EXPANDED); assert.strictEqual(fp.getOldPath(), 'big/file.txt'); assert.strictEqual(fp.getNewPath(), 'big/file.txt'); assert.deepEqual(fp.getMarker().getRange().serialize(), [[0, 0], [3, 6]]); assertInFilePatch(fp, mfp.getBuffer()).hunks( { startRow: 0, endRow: 3, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[2, 0], [2, 6]]}, {kind: 'unchanged', string: ' line-3', range: [[3, 0], [3, 6]]}, ], }, ); }); }); it('throws an error with an unexpected number of diffs', function() { assert.throws(() => buildFilePatch([1, 2, 3]), /Unexpected number of diffs: 3/); }); });
test/models/patch/builder.test.js
import {buildFilePatch, buildMultiFilePatch} from '../../../lib/models/patch'; import {TOO_LARGE, EXPANDED} from '../../../lib/models/patch/patch'; import {assertInPatch, assertInFilePatch} from '../../helpers'; describe('buildFilePatch', function() { it('returns a null patch for an empty diff list', function() { const multiFilePatch = buildFilePatch([]); const [filePatch] = multiFilePatch.getFilePatches(); assert.isFalse(filePatch.getOldFile().isPresent()); assert.isFalse(filePatch.getNewFile().isPresent()); assert.isFalse(filePatch.getPatch().isPresent()); }); describe('with a single diff', function() { it('assembles a patch from non-symlink sides', function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '100644', newPath: 'new/path', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 7, newLineCount: 6, lines: [ ' line-0', '-line-1', '-line-2', '-line-3', ' line-4', '+line-5', '+line-6', ' line-7', ' line-8', ], }, { oldStartLine: 10, newStartLine: 11, oldLineCount: 3, newLineCount: 3, lines: [ '-line-9', ' line-10', ' line-11', '+line-12', ], }, { oldStartLine: 20, newStartLine: 21, oldLineCount: 4, newLineCount: 4, lines: [ ' line-13', '-line-14', '-line-15', '+line-16', '+line-17', ' line-18', ], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.strictEqual(p.getOldPath(), 'old/path'); assert.strictEqual(p.getOldMode(), '100644'); assert.strictEqual(p.getNewPath(), 'new/path'); assert.strictEqual(p.getNewMode(), '100755'); assert.strictEqual(p.getPatch().getStatus(), 'modified'); const bufferText = 'line-0\nline-1\nline-2\nline-3\nline-4\nline-5\nline-6\nline-7\nline-8\nline-9\nline-10\n' + 'line-11\nline-12\nline-13\nline-14\nline-15\nline-16\nline-17\nline-18'; assert.strictEqual(buffer.getText(), bufferText); assertInPatch(p, buffer).hunks( { startRow: 0, endRow: 8, header: '@@ -0,7 +0,6 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'deletion', string: '-line-1\n-line-2\n-line-3\n', range: [[1, 0], [3, 6]]}, {kind: 'unchanged', string: ' line-4\n', range: [[4, 0], [4, 6]]}, {kind: 'addition', string: '+line-5\n+line-6\n', range: [[5, 0], [6, 6]]}, {kind: 'unchanged', string: ' line-7\n line-8\n', range: [[7, 0], [8, 6]]}, ], }, { startRow: 9, endRow: 12, header: '@@ -10,3 +11,3 @@', regions: [ {kind: 'deletion', string: '-line-9\n', range: [[9, 0], [9, 6]]}, {kind: 'unchanged', string: ' line-10\n line-11\n', range: [[10, 0], [11, 7]]}, {kind: 'addition', string: '+line-12\n', range: [[12, 0], [12, 7]]}, ], }, { startRow: 13, endRow: 18, header: '@@ -20,4 +21,4 @@', regions: [ {kind: 'unchanged', string: ' line-13\n', range: [[13, 0], [13, 7]]}, {kind: 'deletion', string: '-line-14\n-line-15\n', range: [[14, 0], [15, 7]]}, {kind: 'addition', string: '+line-16\n+line-17\n', range: [[16, 0], [17, 7]]}, {kind: 'unchanged', string: ' line-18', range: [[18, 0], [18, 7]]}, ], }, ); }); it("sets the old file's symlink destination", function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '120000', newPath: 'new/path', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' old/destination'], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); assert.strictEqual(p.getOldSymlink(), 'old/destination'); assert.isNull(p.getNewSymlink()); }); it("sets the new file's symlink destination", function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '100644', newPath: 'new/path', newMode: '120000', status: 'modified', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' new/destination'], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); assert.isNull(p.getOldSymlink()); assert.strictEqual(p.getNewSymlink(), 'new/destination'); }); it("sets both files' symlink destinations", function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '120000', newPath: 'new/path', newMode: '120000', status: 'modified', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [ ' old/destination', ' --', ' new/destination', ], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); assert.strictEqual(p.getOldSymlink(), 'old/destination'); assert.strictEqual(p.getNewSymlink(), 'new/destination'); }); it('assembles a patch from a file deletion', function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '100644', newPath: null, newMode: null, status: 'deleted', hunks: [ { oldStartLine: 1, oldLineCount: 5, newStartLine: 0, newLineCount: 0, lines: [ '-line-0', '-line-1', '-line-2', '-line-3', '-', ], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.isTrue(p.getOldFile().isPresent()); assert.strictEqual(p.getOldPath(), 'old/path'); assert.strictEqual(p.getOldMode(), '100644'); assert.isFalse(p.getNewFile().isPresent()); assert.strictEqual(p.getPatch().getStatus(), 'deleted'); const bufferText = 'line-0\nline-1\nline-2\nline-3\n'; assert.strictEqual(buffer.getText(), bufferText); assertInPatch(p, buffer).hunks( { startRow: 0, endRow: 4, header: '@@ -1,5 +0,0 @@', regions: [ {kind: 'deletion', string: '-line-0\n-line-1\n-line-2\n-line-3\n-', range: [[0, 0], [4, 0]]}, ], }, ); }); it('assembles a patch from a file addition', function() { const multiFilePatch = buildFilePatch([{ oldPath: null, oldMode: null, newPath: 'new/path', newMode: '100755', status: 'added', hunks: [ { oldStartLine: 0, oldLineCount: 0, newStartLine: 1, newLineCount: 3, lines: [ '+line-0', '+line-1', '+line-2', ], }, ], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.isFalse(p.getOldFile().isPresent()); assert.isTrue(p.getNewFile().isPresent()); assert.strictEqual(p.getNewPath(), 'new/path'); assert.strictEqual(p.getNewMode(), '100755'); assert.strictEqual(p.getPatch().getStatus(), 'added'); const bufferText = 'line-0\nline-1\nline-2'; assert.strictEqual(buffer.getText(), bufferText); assertInPatch(p, buffer).hunks( { startRow: 0, endRow: 2, header: '@@ -0,0 +1,3 @@', regions: [ {kind: 'addition', string: '+line-0\n+line-1\n+line-2', range: [[0, 0], [2, 6]]}, ], }, ); }); it('throws an error with an unknown diff status character', function() { assert.throws(() => { buildFilePatch([{ oldPath: 'old/path', oldMode: '100644', newPath: 'new/path', newMode: '100644', status: 'modified', hunks: [{oldStartLine: 0, newStartLine: 0, oldLineCount: 1, newLineCount: 1, lines: ['xline-0']}], }]); }, /diff status character: "x"/); }); it('parses a no-newline marker', function() { const multiFilePatch = buildFilePatch([{ oldPath: 'old/path', oldMode: '100644', newPath: 'new/path', newMode: '100644', status: 'modified', hunks: [{oldStartLine: 0, newStartLine: 0, oldLineCount: 1, newLineCount: 1, lines: [ '+line-0', '-line-1', '\\ No newline at end of file', ]}], }]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.strictEqual(buffer.getText(), 'line-0\nline-1\n No newline at end of file'); assertInPatch(p, buffer).hunks({ startRow: 0, endRow: 2, header: '@@ -0,1 +0,1 @@', regions: [ {kind: 'addition', string: '+line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'deletion', string: '-line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'nonewline', string: '\\ No newline at end of file', range: [[2, 0], [2, 26]]}, ], }); }); }); describe('with a mode change and a content diff', function() { it('identifies a file that was deleted and replaced by a symlink', function() { const multiFilePatch = buildFilePatch([ { oldPath: 'the-path', oldMode: '000000', newPath: 'the-path', newMode: '120000', status: 'added', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' the-destination'], }, ], }, { oldPath: 'the-path', oldMode: '100644', newPath: 'the-path', newMode: '000000', status: 'deleted', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 2, lines: ['+line-0', '+line-1'], }, ], }, ]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.strictEqual(p.getOldPath(), 'the-path'); assert.strictEqual(p.getOldMode(), '100644'); assert.isNull(p.getOldSymlink()); assert.strictEqual(p.getNewPath(), 'the-path'); assert.strictEqual(p.getNewMode(), '120000'); assert.strictEqual(p.getNewSymlink(), 'the-destination'); assert.strictEqual(p.getStatus(), 'deleted'); assert.strictEqual(buffer.getText(), 'line-0\nline-1'); assertInPatch(p, buffer).hunks({ startRow: 0, endRow: 1, header: '@@ -0,0 +0,2 @@', regions: [ {kind: 'addition', string: '+line-0\n+line-1', range: [[0, 0], [1, 6]]}, ], }); }); it('identifies a symlink that was deleted and replaced by a file', function() { const multiFilePatch = buildFilePatch([ { oldPath: 'the-path', oldMode: '120000', newPath: 'the-path', newMode: '000000', status: 'deleted', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' the-destination'], }, ], }, { oldPath: 'the-path', oldMode: '000000', newPath: 'the-path', newMode: '100644', status: 'added', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 2, newLineCount: 0, lines: ['-line-0', '-line-1'], }, ], }, ]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.strictEqual(p.getOldPath(), 'the-path'); assert.strictEqual(p.getOldMode(), '120000'); assert.strictEqual(p.getOldSymlink(), 'the-destination'); assert.strictEqual(p.getNewPath(), 'the-path'); assert.strictEqual(p.getNewMode(), '100644'); assert.isNull(p.getNewSymlink()); assert.strictEqual(p.getStatus(), 'added'); assert.strictEqual(buffer.getText(), 'line-0\nline-1'); assertInPatch(p, buffer).hunks({ startRow: 0, endRow: 1, header: '@@ -0,2 +0,0 @@', regions: [ {kind: 'deletion', string: '-line-0\n-line-1', range: [[0, 0], [1, 6]]}, ], }); }); it('is indifferent to the order of the diffs', function() { const multiFilePatch = buildFilePatch([ { oldMode: '100644', newPath: 'the-path', newMode: '000000', status: 'deleted', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 2, lines: ['+line-0', '+line-1'], }, ], }, { oldPath: 'the-path', oldMode: '000000', newPath: 'the-path', newMode: '120000', status: 'added', hunks: [ { oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' the-destination'], }, ], }, ]); assert.lengthOf(multiFilePatch.getFilePatches(), 1); const [p] = multiFilePatch.getFilePatches(); const buffer = multiFilePatch.getBuffer(); assert.strictEqual(p.getOldPath(), 'the-path'); assert.strictEqual(p.getOldMode(), '100644'); assert.isNull(p.getOldSymlink()); assert.strictEqual(p.getNewPath(), 'the-path'); assert.strictEqual(p.getNewMode(), '120000'); assert.strictEqual(p.getNewSymlink(), 'the-destination'); assert.strictEqual(p.getStatus(), 'deleted'); assert.strictEqual(buffer.getText(), 'line-0\nline-1'); assertInPatch(p, buffer).hunks({ startRow: 0, endRow: 1, header: '@@ -0,0 +0,2 @@', regions: [ {kind: 'addition', string: '+line-0\n+line-1', range: [[0, 0], [1, 6]]}, ], }); }); it('throws an error on an invalid mode diff status', function() { assert.throws(() => { buildFilePatch([ { oldMode: '100644', newPath: 'the-path', newMode: '000000', status: 'deleted', hunks: [ {oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 2, lines: ['+line-0', '+line-1']}, ], }, { oldPath: 'the-path', oldMode: '000000', newMode: '120000', status: 'modified', hunks: [ {oldStartLine: 0, newStartLine: 0, oldLineCount: 0, newLineCount: 0, lines: [' the-destination']}, ], }, ]); }, /mode change diff status: modified/); }); }); describe('with multiple diffs', function() { it('creates a MultiFilePatch containing each', function() { const mp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 2, newStartLine: 1, newLineCount: 4, lines: [ ' line-0', '+line-1', '+line-2', ' line-3', ], }, { oldStartLine: 10, oldLineCount: 3, newStartLine: 12, newLineCount: 2, lines: [ ' line-4', '-line-5', ' line-6', ], }, ], }, { oldPath: 'second', oldMode: '100644', newPath: 'second', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 5, oldLineCount: 3, newStartLine: 5, newLineCount: 3, lines: [ ' line-5', '+line-6', '-line-7', ' line-8', ], }, ], }, { oldPath: 'third', oldMode: '100755', newPath: 'third', newMode: '100755', status: 'added', hunks: [ { oldStartLine: 1, oldLineCount: 0, newStartLine: 1, newLineCount: 3, lines: [ '+line-0', '+line-1', '+line-2', ], }, ], }, ]); const buffer = mp.getBuffer(); assert.lengthOf(mp.getFilePatches(), 3); assert.strictEqual( mp.getBuffer().getText(), 'line-0\nline-1\nline-2\nline-3\nline-4\nline-5\nline-6\n' + 'line-5\nline-6\nline-7\nline-8\n' + 'line-0\nline-1\nline-2', ); assert.strictEqual(mp.getFilePatches()[0].getOldPath(), 'first'); assert.deepEqual(mp.getFilePatches()[0].getMarker().getRange().serialize(), [[0, 0], [6, 6]]); assertInFilePatch(mp.getFilePatches()[0], buffer).hunks( { startRow: 0, endRow: 3, header: '@@ -1,2 +1,4 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n+line-2\n', range: [[1, 0], [2, 6]]}, {kind: 'unchanged', string: ' line-3\n', range: [[3, 0], [3, 6]]}, ], }, { startRow: 4, endRow: 6, header: '@@ -10,3 +12,2 @@', regions: [ {kind: 'unchanged', string: ' line-4\n', range: [[4, 0], [4, 6]]}, {kind: 'deletion', string: '-line-5\n', range: [[5, 0], [5, 6]]}, {kind: 'unchanged', string: ' line-6\n', range: [[6, 0], [6, 6]]}, ], }, ); assert.strictEqual(mp.getFilePatches()[1].getOldPath(), 'second'); assert.deepEqual(mp.getFilePatches()[1].getMarker().getRange().serialize(), [[7, 0], [10, 6]]); assertInFilePatch(mp.getFilePatches()[1], buffer).hunks( { startRow: 7, endRow: 10, header: '@@ -5,3 +5,3 @@', regions: [ {kind: 'unchanged', string: ' line-5\n', range: [[7, 0], [7, 6]]}, {kind: 'addition', string: '+line-6\n', range: [[8, 0], [8, 6]]}, {kind: 'deletion', string: '-line-7\n', range: [[9, 0], [9, 6]]}, {kind: 'unchanged', string: ' line-8\n', range: [[10, 0], [10, 6]]}, ], }, ); assert.strictEqual(mp.getFilePatches()[2].getOldPath(), 'third'); assert.deepEqual(mp.getFilePatches()[2].getMarker().getRange().serialize(), [[11, 0], [13, 6]]); assertInFilePatch(mp.getFilePatches()[2], buffer).hunks( { startRow: 11, endRow: 13, header: '@@ -1,0 +1,3 @@', regions: [ {kind: 'addition', string: '+line-0\n+line-1\n+line-2', range: [[11, 0], [13, 6]]}, ], }, ); }); it('identifies mode and content change pairs within the patch list', function() { const mp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 2, newStartLine: 1, newLineCount: 3, lines: [ ' line-0', '+line-1', ' line-2', ], }, ], }, { oldPath: 'was-non-symlink', oldMode: '100644', newPath: 'was-non-symlink', newMode: '000000', status: 'deleted', hunks: [ { oldStartLine: 1, oldLineCount: 2, newStartLine: 1, newLineCount: 0, lines: ['-line-0', '-line-1'], }, ], }, { oldPath: 'was-symlink', oldMode: '000000', newPath: 'was-symlink', newMode: '100755', status: 'added', hunks: [ { oldStartLine: 1, oldLineCount: 0, newStartLine: 1, newLineCount: 2, lines: ['+line-0', '+line-1'], }, ], }, { oldMode: '100644', newPath: 'third', newMode: '100644', status: 'deleted', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 0, lines: ['-line-0', '-line-1', '-line-2'], }, ], }, { oldPath: 'was-symlink', oldMode: '120000', newPath: 'was-non-symlink', newMode: '000000', status: 'deleted', hunks: [ { oldStartLine: 1, oldLineCount: 0, newStartLine: 0, newLineCount: 0, lines: ['-was-symlink-destination'], }, ], }, { oldPath: 'was-non-symlink', oldMode: '000000', newPath: 'was-non-symlink', newMode: '120000', status: 'added', hunks: [ { oldStartLine: 1, oldLineCount: 0, newStartLine: 1, newLineCount: 1, lines: ['+was-non-symlink-destination'], }, ], }, ]); const buffer = mp.getBuffer(); assert.lengthOf(mp.getFilePatches(), 4); const [fp0, fp1, fp2, fp3] = mp.getFilePatches(); assert.strictEqual(fp0.getOldPath(), 'first'); assertInFilePatch(fp0, buffer).hunks({ startRow: 0, endRow: 2, header: '@@ -1,2 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'unchanged', string: ' line-2\n', range: [[2, 0], [2, 6]]}, ], }); assert.strictEqual(fp1.getOldPath(), 'was-non-symlink'); assert.isTrue(fp1.hasTypechange()); assert.strictEqual(fp1.getNewSymlink(), 'was-non-symlink-destination'); assertInFilePatch(fp1, buffer).hunks({ startRow: 3, endRow: 4, header: '@@ -1,2 +1,0 @@', regions: [ {kind: 'deletion', string: '-line-0\n-line-1\n', range: [[3, 0], [4, 6]]}, ], }); assert.strictEqual(fp2.getOldPath(), 'was-symlink'); assert.isTrue(fp2.hasTypechange()); assert.strictEqual(fp2.getOldSymlink(), 'was-symlink-destination'); assertInFilePatch(fp2, buffer).hunks({ startRow: 5, endRow: 6, header: '@@ -1,0 +1,2 @@', regions: [ {kind: 'addition', string: '+line-0\n+line-1\n', range: [[5, 0], [6, 6]]}, ], }); assert.strictEqual(fp3.getNewPath(), 'third'); assertInFilePatch(fp3, buffer).hunks({ startRow: 7, endRow: 9, header: '@@ -1,3 +1,0 @@', regions: [ {kind: 'deletion', string: '-line-0\n-line-1\n-line-2', range: [[7, 0], [9, 6]]}, ], }); }); it('sets the correct marker range for diffs with no hunks', function() { const mp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 2, newStartLine: 1, newLineCount: 4, lines: [ ' line-0', '+line-1', '+line-2', ' line-3', ], }, { oldStartLine: 10, oldLineCount: 3, newStartLine: 12, newLineCount: 2, lines: [ ' line-4', '-line-5', ' line-6', ], }, ], }, { oldPath: 'second', oldMode: '100644', newPath: 'second', newMode: '100755', status: 'modified', hunks: [], }, { oldPath: 'third', oldMode: '100755', newPath: 'third', newMode: '100755', status: 'added', hunks: [ { oldStartLine: 5, oldLineCount: 3, newStartLine: 5, newLineCount: 3, lines: [ ' line-5', '+line-6', '-line-7', ' line-8', ], }, ], }, ]); assert.strictEqual(mp.getFilePatches()[0].getOldPath(), 'first'); assert.deepEqual(mp.getFilePatches()[0].getMarker().getRange().serialize(), [[0, 0], [6, 6]]); assert.strictEqual(mp.getFilePatches()[1].getOldPath(), 'second'); assert.deepEqual(mp.getFilePatches()[1].getHunks(), []); assert.deepEqual(mp.getFilePatches()[1].getMarker().getRange().serialize(), [[6, 6], [6, 6]]); assert.strictEqual(mp.getFilePatches()[2].getOldPath(), 'third'); assert.deepEqual(mp.getFilePatches()[2].getMarker().getRange().serialize(), [[7, 0], [10, 6]]); }); }); describe('with a large diff', function() { it('creates a HiddenPatch when the diff is "too large"', function() { const mfp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, { oldPath: 'second', oldMode: '100644', newPath: 'second', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 1, newStartLine: 1, newLineCount: 2, lines: [' line-4', '+line-5'], }, ], }, ], {largeDiffThreshold: 3}); assert.lengthOf(mfp.getFilePatches(), 2); const [fp0, fp1] = mfp.getFilePatches(); assert.strictEqual(fp0.getRenderStatus(), TOO_LARGE); assert.strictEqual(fp0.getOldPath(), 'first'); assert.strictEqual(fp0.getNewPath(), 'first'); assert.deepEqual(fp0.getStartRange().serialize(), [[0, 0], [0, 0]]); assertInFilePatch(fp0).hunks(); assert.strictEqual(fp1.getRenderStatus(), EXPANDED); assert.strictEqual(fp1.getOldPath(), 'second'); assert.strictEqual(fp1.getNewPath(), 'second'); assert.deepEqual(fp1.getMarker().getRange().serialize(), [[0, 0], [1, 6]]); assertInFilePatch(fp1, mfp.getBuffer()).hunks( { startRow: 0, endRow: 1, header: '@@ -1,1 +1,2 @@', regions: [ {kind: 'unchanged', string: ' line-4\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-5', range: [[1, 0], [1, 6]]}, ], }, ); }); it('re-parse a HiddenPatch as a Patch', function() { const mfp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, ], {largeDiffThreshold: 3}); assert.lengthOf(mfp.getFilePatches(), 1); const [fp] = mfp.getFilePatches(); assert.strictEqual(fp.getRenderStatus(), TOO_LARGE); assert.strictEqual(fp.getOldPath(), 'first'); assert.strictEqual(fp.getNewPath(), 'first'); assert.deepEqual(fp.getStartRange().serialize(), [[0, 0], [0, 0]]); assertInFilePatch(fp).hunks(); mfp.expandFilePatch(fp); assert.strictEqual(fp.getRenderStatus(), EXPANDED); assert.deepEqual(fp.getMarker().getRange().serialize(), [[0, 0], [3, 6]]); assertInFilePatch(fp, mfp.getBuffer()).hunks( { startRow: 0, endRow: 3, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[2, 0], [2, 6]]}, {kind: 'unchanged', string: ' line-3', range: [[3, 0], [3, 6]]}, ], }, ); }); it('does not interfere with markers from surrounding visible patches when expanded', function() { const mfp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, { oldPath: 'big', oldMode: '100644', newPath: 'big', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 4, lines: [' line-0', '+line-1', '+line-2', '-line-3', ' line-4'], }, ], }, { oldPath: 'last', oldMode: '100644', newPath: 'last', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, ], {largeDiffThreshold: 4}); assert.lengthOf(mfp.getFilePatches(), 3); const [fp0, fp1, fp2] = mfp.getFilePatches(); assert.strictEqual(fp0.getRenderStatus(), EXPANDED); assertInFilePatch(fp0, mfp.getBuffer()).hunks( { startRow: 0, endRow: 3, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[2, 0], [2, 6]]}, {kind: 'unchanged', string: ' line-3\n', range: [[3, 0], [3, 6]]}, ], }, ); assert.strictEqual(fp1.getRenderStatus(), TOO_LARGE); assertInFilePatch(fp1, mfp.getBuffer()).hunks(); assert.strictEqual(fp2.getRenderStatus(), EXPANDED); assertInFilePatch(fp2, mfp.getBuffer()).hunks( { startRow: 4, endRow: 7, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[4, 0], [4, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[5, 0], [5, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[6, 0], [6, 6]]}, {kind: 'unchanged', string: ' line-3', range: [[7, 0], [7, 6]]}, ], }, ); mfp.expandFilePatch(fp1); assert.strictEqual(fp0.getRenderStatus(), EXPANDED); assertInFilePatch(fp0, mfp.getBuffer()).hunks( { startRow: 0, endRow: 3, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[2, 0], [2, 6]]}, {kind: 'unchanged', string: ' line-3\n', range: [[3, 0], [3, 6]]}, ], }, ); assert.strictEqual(fp1.getRenderStatus(), EXPANDED); assertInFilePatch(fp1, mfp.getBuffer()).hunks( { startRow: 4, endRow: 8, header: '@@ -1,3 +1,4 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[4, 0], [4, 6]]}, {kind: 'addition', string: '+line-1\n+line-2\n', range: [[5, 0], [6, 6]]}, {kind: 'deletion', string: '-line-3\n', range: [[7, 0], [7, 6]]}, {kind: 'unchanged', string: ' line-4\n', range: [[8, 0], [8, 6]]}, ], }, ); assert.strictEqual(fp2.getRenderStatus(), EXPANDED); assertInFilePatch(fp2, mfp.getBuffer()).hunks( { startRow: 9, endRow: 12, header: '@@ -1,3 +1,3 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[9, 0], [9, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[10, 0], [10, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[11, 0], [11, 6]]}, {kind: 'unchanged', string: ' line-3', range: [[12, 0], [12, 6]]}, ], }, ); }); it('does not interfere with markers from surrounding non-visible patches when expanded', function() { const mfp = buildMultiFilePatch([ { oldPath: 'first', oldMode: '100644', newPath: 'first', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, { oldPath: 'second', oldMode: '100644', newPath: 'second', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, { oldPath: 'third', oldMode: '100644', newPath: 'third', newMode: '100644', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, ], {largeDiffThreshold: 3}); assert.lengthOf(mfp.getFilePatches(), 3); const [fp0, fp1, fp2] = mfp.getFilePatches(); assert.deepEqual(fp0.getMarker().getRange().serialize(), [[0, 0], [0, 0]]); assert.deepEqual(fp1.getMarker().getRange().serialize(), [[0, 0], [0, 0]]); assert.deepEqual(fp2.getMarker().getRange().serialize(), [[0, 0], [0, 0]]); mfp.expandFilePatch(fp1); assert.deepEqual(fp0.getMarker().getRange().serialize(), [[0, 0], [0, 0]]); assert.deepEqual(fp1.getMarker().getRange().serialize(), [[0, 0], [3, 6]]); assert.deepEqual(fp2.getMarker().getRange().serialize(), [[3, 6], [3, 6]]); }); it('does not create a HiddenPatch when the patch has been explicitly expanded', function() { const mfp = buildMultiFilePatch([ { oldPath: 'big/file.txt', oldMode: '100644', newPath: 'big/file.txt', newMode: '100755', status: 'modified', hunks: [ { oldStartLine: 1, oldLineCount: 3, newStartLine: 1, newLineCount: 3, lines: [' line-0', '+line-1', '-line-2', ' line-3'], }, ], }, ], {largeDiffThreshold: 3, renderStatusOverrides: {'big/file.txt': EXPANDED}}); assert.lengthOf(mfp.getFilePatches(), 1); const [fp] = mfp.getFilePatches(); assert.strictEqual(fp.getRenderStatus(), EXPANDED); assert.strictEqual(fp.getOldPath(), 'big/file.txt'); assert.strictEqual(fp.getNewPath(), 'big/file.txt'); assert.deepEqual(fp.getMarker().getRange().serialize(), [[0, 0], [3, 6]]); assertInFilePatch(fp, mfp.getBuffer()).hunks( { startRow: 0, endRow: 3, header: '@@ -1,1 +1,2 @@', regions: [ {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, {kind: 'deletion', string: '-line-2\n', range: [[2, 0], [2, 6]]}, {kind: 'unchanged', string: ' line-3', range: [[3, 0], [3, 6]]}, ], }, ); }); }); it('throws an error with an unexpected number of diffs', function() { assert.throws(() => buildFilePatch([1, 2, 3]), /Unexpected number of diffs: 3/); }); });
Correct expected Hunk header
test/models/patch/builder.test.js
Correct expected Hunk header
<ide><path>est/models/patch/builder.test.js <ide> assert.deepEqual(fp.getMarker().getRange().serialize(), [[0, 0], [3, 6]]); <ide> assertInFilePatch(fp, mfp.getBuffer()).hunks( <ide> { <del> startRow: 0, endRow: 3, header: '', regions: [ <add> startRow: 0, endRow: 3, header: '', regions: [ <ide> {kind: 'unchanged', string: ' line-0\n', range: [[0, 0], [0, 6]]}, <ide> {kind: 'addition', string: '+line-1\n', range: [[1, 0], [1, 6]]}, <ide> {kind: 'deletion', string: '-line-2\n', range: [[2, 0], [2, 6]]},
JavaScript
mit
6b2a41db322d413366c4dcafd23019e7e36511c2
0
nmmascia/webet,nmmascia/webet
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound' }); Router.map(function(){ this.route('home', { path: '/' }); this.route('betsList', { path: '/bets' }); this.route('dashboard', { path: 'dashboard' }); this.route('createBetForm',{ path: 'bet' }); this.route('/bets/:_id', { name: 'singleBet', data: function() {return Bets.findOne(this.params._id)} }); });
lib/router.js
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading' }); Router.map(function(){ this.route('home', { path: '/' }); this.route('betsList', { path: '/bets' }); this.route('dashboard', { path: 'dashboard' }); this.route('createBetForm',{ path: 'bet' }); this.route('/bets/:_id', { name: 'singleBet', data: function() {return Bets.findOne(this.params._id)} }); });
Insert not found template into router.
lib/router.js
Insert not found template into router.
<ide><path>ib/router.js <ide> Router.configure({ <ide> layoutTemplate: 'layout', <del> loadingTemplate: 'loading' <add> loadingTemplate: 'loading', <add> notFoundTemplate: 'notFound' <ide> }); <ide> <ide> Router.map(function(){
Java
apache-2.0
0f9dc491b41b74be7f43ef82ac4b33045d459cc2
0
Mikuz/Boarder
package fi.mikuz.boarder.gui; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.ListIterator; import java.util.Timer; import java.util.TimerTask; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Vibrator; import android.provider.MediaStore; import android.util.Log; import android.util.TypedValue; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.thoughtworks.xstream.XStream; import fi.mikuz.boarder.R; import fi.mikuz.boarder.app.BoarderActivity; import fi.mikuz.boarder.component.Slot; import fi.mikuz.boarder.component.soundboard.BoardHistory; import fi.mikuz.boarder.component.soundboard.GraphicalSound; import fi.mikuz.boarder.component.soundboard.GraphicalSoundboard; import fi.mikuz.boarder.component.soundboard.GraphicalSoundboardHolder; import fi.mikuz.boarder.util.AutoArrange; import fi.mikuz.boarder.util.FileProcessor; import fi.mikuz.boarder.util.Handlers.ToastHandler; import fi.mikuz.boarder.util.IconUtils; import fi.mikuz.boarder.util.OrientationUtil; import fi.mikuz.boarder.util.SoundPlayerControl; import fi.mikuz.boarder.util.XStreamUtil; import fi.mikuz.boarder.util.dbadapter.MenuDbAdapter; import fi.mikuz.boarder.util.editor.BoardHistoryProvider; import fi.mikuz.boarder.util.editor.GraphicalSoundboardProvider; import fi.mikuz.boarder.util.editor.ImageDrawing; import fi.mikuz.boarder.util.editor.Joystick; import fi.mikuz.boarder.util.editor.PageDrawer; import fi.mikuz.boarder.util.editor.Pagination; import fi.mikuz.boarder.util.editor.SoundNameDrawing; /** * * @author Jan Mikael Lindlf */ public class BoardEditor extends BoarderActivity { //TODO destroy god object private static final String TAG = BoardEditor.class.getSimpleName(); Vibrator vibrator; private int mCurrentOrientation; public GraphicalSoundboard mGsb; private GraphicalSoundboardProvider mGsbp; private BoardHistory mBoardHistory; private BoardHistoryProvider mBoardHistoryProvider; private Pagination mPagination; private PageDrawer mPageDrawer; private Joystick mJoystick = null; private static final int LISTEN_BOARD = 0; private static final int EDIT_BOARD = 1; private int mMode = LISTEN_BOARD; private static final int DRAG_TEXT = 0; private static final int DRAG_IMAGE = 1; private int mDragTarget = DRAG_TEXT; private static final int EXPLORE_SOUND = 0; private static final int EXPLORE_BACKGROUD = 1; private static final int EXPLORE_SOUND_IMAGE = 2; private static final int CHANGE_NAME_COLOR = 3; private static final int CHANGE_INNER_PAINT_COLOR = 4; private static final int CHANGE_BORDER_PAINT_COLOR = 5; private static final int CHANGE_BACKGROUND_COLOR = 6; private static final int CHANGE_SOUND_PATH = 7; private static final int EXPLORE_SOUND_ACTIVE_IMAGE = 8; private int mCopyColor = 0; /** * PRESS_BLANK: initial state before swipe gestures * PRESS_BOARD: initial state before tap, drag and swipe gestures * DRAG: sound is being dragged * SWIPE: swiping to other page */ private enum TouchGesture {PRESS_BLANK, PRESS_BOARD, DRAG, SWIPE, TAP}; private TouchGesture mCurrentGesture = null; private final int DRAG_SWIPE_TIME = 300; private GraphicalSound mPressedSound = null; private float mInitialNameFrameX = 0; private float mInitialNameFrameY = 0; private float mInitialImageX = 0; private float mInitialImageY = 0; private float mNameFrameDragDistanceX = -1; private float mNameFrameDragDistanceY = -1; private float mImageDragDistanceX = -1; private float mImageDragDistanceY = -1; private long mLastTrackballEvent = 0; private DrawingThread mThread; private Menu mMenu; private DrawingPanel mPanel; boolean mCanvasInvalidated = false; boolean mPanelInitialized = false; AlertDialog mResolutionAlert; private boolean mMoveBackground = false; private float mBackgroundLeftDistance = 0; private float mBackgroundTopDistance = 0; private GraphicalSound mFineTuningSound = null; private ToastHandler mToastHandler; final Handler mHandler = new Handler(); ProgressDialog mWaitDialog; boolean mClearBoardDir = false; private File mSbDir = SoundboardMenu.mSbDir; private String mBoardName = null; private AlertDialog mSoundImageDialog; private TextView mSoundImageWidthText; private TextView mSoundImageHeightText; private EditText mSoundImageWidthInput; private EditText mSoundImageHeightInput; private AlertDialog mBackgroundDialog; private TextView mBackgroundWidthText; private TextView mBackgroundHeightText; private EditText mBackgroundWidthInput; private EditText mBackgroundHeightInput; private float mWidthHeightScale; int mNullCanvasCount = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); mBoardHistoryProvider = new BoardHistoryProvider(); Bundle extras = getIntent().getExtras(); if (extras != null) { mBoardName = extras.getString(MenuDbAdapter.KEY_TITLE); setTitle(mBoardName); mGsbp = new GraphicalSoundboardProvider(mBoardName); mPagination = new Pagination(mGsbp); initEditorBoard(); if (mGsb.getSoundList().isEmpty()) { mMode = EDIT_BOARD; } } else { mMode = EDIT_BOARD; mGsb = new GraphicalSoundboard(); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Set board name"); final EditText input = new EditText(this); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String inputText = input.getText().toString(); if (inputText.contains("\n")) { mBoardName = inputText.substring(0, inputText.indexOf("\n")); } else { mBoardName = inputText; } if (mBoardName.equals("")) { mBoardName = null; finish(); } else { mGsbp = new GraphicalSoundboardProvider(mBoardName); mPagination = new Pagination(mGsbp); initEditorBoard(); setTitle(mBoardName); save(); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { finish(); } }); alert.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); alert.show(); } File icon = new File(mSbDir, mBoardName + "/icon.png"); if (icon.exists()) { Bitmap bitmap = ImageDrawing.decodeFile(mToastHandler, icon); Drawable drawable = new BitmapDrawable(getResources(), IconUtils.resizeIcon(this, bitmap, (40/6))); this.getActionBar().setLogo(drawable); } mPanel = new DrawingPanel(this); ViewTreeObserver vto = mPanel.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!mPanelInitialized) { mPanelInitialized = true; issueResolutionConversion(); } } }); } public void initEditorBoard() { Configuration config = getResources().getConfiguration(); int orientation = OrientationUtil.getBoarderOrientation(config); if (mGsbp.getOrientationMode() == GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_PORTRAIT) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); orientation = GraphicalSoundboard.SCREEN_ORIENTATION_PORTRAIT; } else if (mGsbp.getOrientationMode() == GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_LANDSCAPE) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); orientation = GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE; } this.mCurrentOrientation = orientation; GraphicalSoundboard newGsb = mPagination.getBoard(orientation); mPageDrawer = new PageDrawer(this.getApplicationContext(), mJoystick); changeBoard(newGsb, false); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.clear(); mMenu = menu; MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.board_editor_bottom, menu); if (mMode == EDIT_BOARD) { menu.setGroupVisible(R.id.listen_mode, false); } else { menu.setGroupVisible(R.id.edit_mode, false); } if (!mPagination.isMovePageMode()) { menu.setGroupVisible(R.id.move_page_mode, false); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_listen_mode: mMode = LISTEN_BOARD; this.onCreateOptionsMenu(mMenu); return true; case R.id.menu_edit_mode: mMode = EDIT_BOARD; this.onCreateOptionsMenu(mMenu); return true; case R.id.menu_undo: mBoardHistory.undo(this); mFineTuningSound = null; return true; case R.id.menu_redo: mBoardHistory.redo(this); mFineTuningSound = null; return true; case R.id.menu_add_sound: Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_ADD_GRAPHICAL_SOUND); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_SOUND); return true; case R.id.menu_paste_sound: GraphicalSound pasteSound = SoundboardMenu.mCopiedSound; if (pasteSound == null) { Toast.makeText(this.getApplicationContext(), "Nothing copied", Toast.LENGTH_LONG).show(); } else { if (mGsb.getAutoArrange()) { if (placeToFreeSlot(pasteSound)) { mGsb.getSoundList().add(pasteSound); } } else { placeToFreeSpace(pasteSound); mGsb.getSoundList().add(pasteSound); } mBoardHistory.createHistoryCheckpoint(mGsb); } return true; case R.id.menu_save_board: save(); return true; case R.id.menu_page_options: CharSequence[] pageItems = {"Add page", "Delete this page", "Move this page"}; Configuration config = getResources().getConfiguration(); final int currentOrientation = OrientationUtil.getBoarderOrientation(config); AlertDialog.Builder pageBuilder = new AlertDialog.Builder(BoardEditor.this); pageBuilder.setTitle("Page options"); pageBuilder.setItems(pageItems, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { GraphicalSoundboard swapGsb = mGsbp.addBoardPage(currentOrientation); changeBoard(swapGsb, true); } else if (item == 1) { GraphicalSoundboard deleteGsb = mGsb; mGsbp.deletePage(deleteGsb); GraphicalSoundboard gsb = mGsbp.getPage(deleteGsb.getScreenOrientation(), deleteGsb.getPageNumber()); if (gsb == null) gsb = mPagination.getBoard(deleteGsb.getScreenOrientation()); changeBoard(gsb, false); } else if (item == 2) { mPagination.initMove(mGsb); BoardEditor.this.onCreateOptionsMenu(mMenu); } } }); AlertDialog pageAlert = pageBuilder.create(); pageAlert.show(); return true; case R.id.menu_move_page_here: GraphicalSoundboard currentGsb = mGsb; int toPageNumber = currentGsb.getPageNumber(); mGsbp.overrideBoard(currentGsb); mPagination.movePage(mToastHandler, mGsb); GraphicalSoundboard gsb = mGsbp.getPage(currentGsb.getScreenOrientation(), toPageNumber); changeBoard(gsb, false); BoardEditor.this.onCreateOptionsMenu(mMenu); return true; case R.id.menu_convert_board: AlertDialog.Builder convertBuilder = new AlertDialog.Builder(this); convertBuilder.setTitle("Convert"); convertBuilder.setMessage("Clear board directory?"); convertBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mClearBoardDir = true; initializeConvert(); } }); convertBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mClearBoardDir = false; initializeConvert(); } }); convertBuilder.setCancelable(false); convertBuilder.show(); return true; case R.id.menu_play_pause: SoundPlayerControl.togglePlayPause(this.getApplicationContext()); return true; case R.id.menu_notification: SoundboardMenu.updateNotification(this, mBoardName, mBoardName); return true; case R.id.menu_take_screenshot: Bitmap bitmap = Bitmap.createBitmap(mPanel.getWidth(), mPanel.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); mPanel.onDraw(canvas); Toast.makeText(getApplicationContext(), FileProcessor.saveScreenshot(bitmap, mBoardName), Toast.LENGTH_LONG).show(); return true; case R.id.menu_board_settings: final CharSequence[] items = {"Sound", "Background", "Icon", "Screen orientation", "Auto-arrange", "Reset position"}; AlertDialog.Builder setAsBuilder = new AlertDialog.Builder(BoardEditor.this); setAsBuilder.setTitle("Board settings"); setAsBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.graphical_soundboard_editor_alert_board_sound_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkPlaySimultaneously = (CheckBox) layout.findViewById(R.id.playSimultaneouslyCheckBox); checkPlaySimultaneously.setChecked(mGsb.getPlaySimultaneously()); final EditText boardVolumeInput = (EditText) layout.findViewById(R.id.boardVolumeInput); boardVolumeInput.setText(mGsb.getBoardVolume()*100 + "%"); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Board settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; mGsb.setPlaySimultaneously(checkPlaySimultaneously.isChecked()); Float boardVolumeValue = null; try { String boardVolumeString = boardVolumeInput.getText().toString(); if (boardVolumeString.contains("%")) { boardVolumeValue = Float.valueOf(boardVolumeString.substring(0, boardVolumeString.indexOf("%"))).floatValue()/100; } else { boardVolumeValue = Float.valueOf(boardVolumeString).floatValue()/100; } if (boardVolumeValue >= 0 && boardVolumeValue <= 1 && boardVolumeValue != null) { mGsb.setBoardVolume(boardVolumeValue); } else { notifyIncorrectValue = true; } } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 1) { LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout. graphical_soundboard_editor_alert_board_background_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkUseBackgroundImage = (CheckBox) layout.findViewById(R.id.useBackgroundFileCheckBox); checkUseBackgroundImage.setChecked(mGsb.getUseBackgroundImage()); final Button backgroundColorButton = (Button) layout.findViewById(R.id.backgroundColorButton); backgroundColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(BoardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeBackgroundColor"); i.putExtras(XStreamUtil.getSoundboardBundle(mGsb)); startActivityForResult(i, CHANGE_BACKGROUND_COLOR); } }); final Button toggleMoveBackgroundFileButton = (Button) layout.findViewById(R.id.toggleMoveBackgroundFileButton); if (mMoveBackground) { toggleMoveBackgroundFileButton.setText("Move Background (file) : Yes"); } else { toggleMoveBackgroundFileButton.setText("Move Background (file) : No"); } toggleMoveBackgroundFileButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mMoveBackground = mMoveBackground ? false : true; if (mMoveBackground) { toggleMoveBackgroundFileButton.setText("Move Background (file) : Yes"); } else { toggleMoveBackgroundFileButton.setText("Move Background (file) : No"); } } }); final Button backgroundFileButton = (Button) layout.findViewById(R.id.backgroundFileButton); backgroundFileButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { selectBackgroundFile(); } }); mBackgroundWidthText = (TextView) layout.findViewById(R.id.backgroundWidthText); mBackgroundHeightText = (TextView) layout.findViewById(R.id.backgroundHeightText); if (mGsb.getBackgroundImage() != null) { mBackgroundWidthText.setText("Width (" + mGsb.getBackgroundImage().getWidth() + ")"); mBackgroundHeightText.setText("Height (" + mGsb.getBackgroundImage().getHeight() + ")"); } mBackgroundWidthInput = (EditText) layout.findViewById(R.id.backgroundWidthInput); mBackgroundWidthInput.setText(Float.toString(mGsb.getBackgroundWidth())); mBackgroundHeightInput = (EditText) layout.findViewById(R.id.backgroundHeightInput); mBackgroundHeightInput.setText(Float.toString(mGsb.getBackgroundHeight())); final CheckBox scaleWidthHeight = (CheckBox) layout.findViewById(R.id.scaleWidthHeightCheckBox); scaleWidthHeight.setChecked(true); scaleWidthHeight.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { // Calculate a new scale mWidthHeightScale = Float.valueOf(mBackgroundWidthInput.getText().toString()).floatValue() / Float.valueOf(mBackgroundHeightInput.getText().toString()).floatValue(); } catch(NumberFormatException nfe) {Log.e(TAG, "Unable to calculate width and height scale", nfe);} } }); mWidthHeightScale = mGsb.getBackgroundWidth() / mGsb.getBackgroundHeight(); mBackgroundWidthInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf( mBackgroundWidthInput.getText().toString()).floatValue(); mBackgroundHeightInput.setText( Float.valueOf(value/mWidthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); mBackgroundHeightInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf( mBackgroundHeightInput.getText().toString()).floatValue(); mBackgroundWidthInput.setText( Float.valueOf(value*mWidthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Board settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; mGsb.setUseBackgroundImage(checkUseBackgroundImage.isChecked()); try { mGsb.setBackgroundWidth(Float.valueOf(mBackgroundWidthInput.getText().toString()).floatValue()); mGsb.setBackgroundHeight(Float.valueOf(mBackgroundHeightInput.getText().toString()).floatValue()); } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mBoardHistory.createHistoryCheckpoint(mGsb); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mBackgroundDialog = null; } }); mBackgroundDialog = builder.create(); mBackgroundDialog.show(); } else if (item == 2) { AlertDialog.Builder resetBuilder = new AlertDialog.Builder( BoardEditor.this); resetBuilder.setTitle("Change board icon"); resetBuilder.setMessage("You can change icon for this board.\n\n" + "You need a png image:\n " + mSbDir + "/" + mBoardName + "/" + "icon.png\n\n" + "Recommended size is about 80x80 pixels."); AlertDialog resetAlert = resetBuilder.create(); resetAlert.show(); } else if (item == 3) { final CharSequence[] items = {"Portrait", "Landscape", "Hybrid (beta)"}; AlertDialog.Builder orientationBuilder = new AlertDialog.Builder(BoardEditor.this); orientationBuilder.setTitle("Select orientation"); orientationBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0 && mGsbp.getOrientationMode() != GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_PORTRAIT) { if (mGsbp.getOrientationMode() == GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_HYBRID) { useOrientationAndAskToRemoveUnusedAlert(GraphicalSoundboard.SCREEN_ORIENTATION_PORTRAIT); } else { if (mGsbp.boardWithOrientationExists(GraphicalSoundboard.SCREEN_ORIENTATION_PORTRAIT)) { orientationTurningConflictActionAlert(GraphicalSoundboard.SCREEN_ORIENTATION_PORTRAIT); } else { orientationTurningAlert(GraphicalSoundboard.SCREEN_ORIENTATION_PORTRAIT); } } } else if (item == 1 && mGsbp.getOrientationMode() != GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_LANDSCAPE) { if (mGsbp.getOrientationMode() == GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_HYBRID) { useOrientationAndAskToRemoveUnusedAlert(GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE); } else { if (mGsbp.boardWithOrientationExists(GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE)) { orientationTurningConflictActionAlert(GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE); } else { orientationTurningAlert(GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE); } } } else if (item == 2 && mGsbp.getOrientationMode() != GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_HYBRID) { hybridAlert(); } } }); AlertDialog orientationAlert = orientationBuilder.create(); orientationAlert.show(); } else if (item == 4) { //Auto-arrange LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout. graphical_soundboard_editor_alert_auto_arrange, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkEnableAutoArrange = (CheckBox) layout.findViewById(R.id.enableAutoArrange); checkEnableAutoArrange.setChecked(mGsb.getAutoArrange()); final EditText columnsInput = (EditText) layout.findViewById(R.id.columnsInput); columnsInput.setText(Integer.toString(mGsb.getAutoArrangeColumns())); final EditText rowsInput = (EditText) layout.findViewById(R.id.rowsInput); rowsInput.setText(Integer.toString(mGsb.getAutoArrangeRows())); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Board settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { int columns = Integer.valueOf( columnsInput.getText().toString()).intValue(); int rows = Integer.valueOf( rowsInput.getText().toString()).intValue(); if (mGsb.getSoundList().size() <= columns*rows || !checkEnableAutoArrange.isChecked()) { if (mGsb.getAutoArrange() != checkEnableAutoArrange.isChecked() || mGsb.getAutoArrangeColumns() != columns || mGsb.getAutoArrangeRows() != rows) { mGsb.setAutoArrange(checkEnableAutoArrange.isChecked()); mGsb.setAutoArrangeColumns(columns); mGsb.setAutoArrangeRows(rows); } } else { Toast.makeText(getApplicationContext(), "Not enought slots", Toast.LENGTH_SHORT).show(); } mBoardHistory.createHistoryCheckpoint(mGsb); } catch(NumberFormatException nfe) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 5) { ArrayList<String> itemArray = new ArrayList<String>(); final int extraItemCount = 1; itemArray.add("> Background image"); for (GraphicalSound sound : mGsb.getSoundList()) { itemArray.add(sound.getName()); } CharSequence[] items = itemArray.toArray(new CharSequence[itemArray.size()]); AlertDialog.Builder resetBuilder = new AlertDialog.Builder( BoardEditor.this); resetBuilder.setTitle("Reset position"); resetBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { // Background mGsb.setBackgroundX(0); mGsb.setBackgroundY(0); mBoardHistory.createHistoryCheckpoint(mGsb); } else { // Sound GraphicalSound sound = mGsb.getSoundList().get(item - extraItemCount); sound.setNameFrameX(50); sound.setNameFrameY(50); sound.generateImageXYFromNameFrameLocation(); mBoardHistory.createHistoryCheckpoint(mGsb); } } }); AlertDialog resetAlert = resetBuilder.create(); resetAlert.show(); } } }); AlertDialog setAsAlert = setAsBuilder.create(); setAsAlert.show(); return true; default: return super.onOptionsItemSelected(item); } } public void changeBoard(GraphicalSoundboard gsb, boolean overrideCurrentBoard) { GraphicalSoundboard lastGsb = mGsb; boolean samePage = lastGsb != null && (gsb.getPageNumber() == lastGsb.getPageNumber() && gsb.getScreenOrientation() == lastGsb.getScreenOrientation()); if (!samePage) { loadBoard(gsb); mPageDrawer.switchPage(gsb); if (overrideCurrentBoard) { GraphicalSoundboard.unloadImages(lastGsb); mGsbp.overrideBoard(lastGsb); } refreshPageTitle(); int boardId = gsb.getId(); BoardHistory boardHistory = mBoardHistoryProvider.getBoardHistory(boardId); if (boardHistory == null) { boardHistory = mBoardHistoryProvider.createBoardHistory(boardId, gsb); } this.mBoardHistory = boardHistory; } else { Log.v(TAG, "Won't change page to same page."); } } public void refreshPageTitle() { setTitle(mBoardName + " - " + (mGsb.getPageNumber()+1)); } public void loadBoard(GraphicalSoundboard gsb) { GraphicalSoundboard.loadImages(this.getApplicationContext(), mToastHandler, gsb); mGsb = gsb; } private void orientationTurningConflictActionAlert(final int screenOrientation) { String orientationName = GraphicalSoundboard.getOrientationName(screenOrientation); String oppositeOrientationName = GraphicalSoundboard.getOppositeOrientationName(screenOrientation); AlertDialog.Builder orientationWarningBuilder = new AlertDialog.Builder(BoardEditor.this); orientationWarningBuilder.setTitle("Conflicting board"); orientationWarningBuilder.setMessage( "A board for " + orientationName + " orientation already exists. You can either use it or remove it.\n\n" + "By removing it you can turn " + oppositeOrientationName + " board to " + orientationName + " orientation.\n\n"); orientationWarningBuilder.setPositiveButton("Remove board", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsbp.deleteBoardWithOrientation(screenOrientation); orientationTurningAlert(screenOrientation); } }); orientationWarningBuilder.setNegativeButton("Use board", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsbp.setOrientationMode(screenOrientation); useOrientationAndAskToRemoveUnusedAlert(screenOrientation); } }); AlertDialog orientationWarningAlert = orientationWarningBuilder.create(); orientationWarningAlert.show(); } private void orientationTurningAlert(final int screenOrientation) { AlertDialog.Builder orientationWarningBuilder = new AlertDialog.Builder( BoardEditor.this); orientationWarningBuilder.setTitle("Changing orientation"); orientationWarningBuilder.setMessage( "Changing screen orientation will delete all position data if you don't " + "select deny.\n\n" + "Proceed?"); orientationWarningBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsb.setBackgroundX(0); mGsb.setBackgroundY(0); for(GraphicalSound sound : mGsb.getSoundList()) { sound.setNameFrameX(50); sound.setNameFrameY(50); sound.generateImageXYFromNameFrameLocation(); } mGsbp.setOrientationMode(screenOrientation); mGsb.setScreenOrientation(screenOrientation); finishBoard(); } }); orientationWarningBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); orientationWarningBuilder.setNeutralButton("Deny", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsbp.setOrientationMode(screenOrientation); mGsb.setScreenOrientation(screenOrientation); finishBoard(); } }); AlertDialog orientationWarningAlert = orientationWarningBuilder.create(); orientationWarningAlert.show(); } private void hybridAlert() { AlertDialog.Builder orientationWarningBuilder = new AlertDialog.Builder( BoardEditor.this); orientationWarningBuilder.setTitle("Hybrid mode"); orientationWarningBuilder.setMessage( "Hybrid mode allows you to switch between portrait and landscape by turning the screen.\n\n" + "However both orientations must be created and maintained separately.\n\n" + "Proceed?"); orientationWarningBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsbp.setOrientationMode(GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_HYBRID); finishBoard(); } }); orientationWarningBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog orientationWarningAlert = orientationWarningBuilder.create(); orientationWarningAlert.show(); } private void useOrientationAndAskToRemoveUnusedAlert(final int screenOrientation) { final int oppositeOrientation = GraphicalSoundboard.getOppositeOrientation(screenOrientation); AlertDialog.Builder orientationWarningBuilder = new AlertDialog.Builder( BoardEditor.this); orientationWarningBuilder.setTitle("Unused board"); orientationWarningBuilder.setMessage( "Do you want to delete unused board in " + GraphicalSoundboard.getOrientationName(oppositeOrientation) + " orientation?\n\n"); orientationWarningBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //mThread.setRunning(false); // TODO handle board deleting better mGsb = mPagination.getBoard(screenOrientation); mGsbp.deleteBoardWithOrientation(oppositeOrientation); mGsbp.setOrientationMode(screenOrientation); finishBoard(); } }); orientationWarningBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsbp.setOrientationMode(screenOrientation); finishBoard(); } }); AlertDialog orientationWarningAlert = orientationWarningBuilder.create(); orientationWarningAlert.show(); } private void finishBoard() { try { BoardEditor.this.finish(); } catch (Throwable e) { Log.e(TAG, "Error closing board", e); } } private void selectBackgroundFile() { Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_SELECT_BACKGROUND_FILE); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_BACKGROUD); } private void selectImageFile() { Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_SELECT_SOUND_IMAGE_FILE); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_SOUND_IMAGE); } private void selectActiveImageFile() { Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_SELECT_SOUND_ACTIVE_IMAGE_FILE); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_SOUND_ACTIVE_IMAGE); } @Override protected void onActivityResult(int requestCode, int resultCode, final Intent intent) { super.onActivityResult(requestCode, resultCode, intent); switch(requestCode) { case EXPLORE_SOUND: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); XStream xstream = XStreamUtil.graphicalBoardXStream(); GraphicalSound sound = (GraphicalSound) xstream.fromXML(extras.getString(FileExplorer.ACTION_ADD_GRAPHICAL_SOUND)); sound.setImage(BitmapFactory.decodeResource(getResources(), R.drawable.sound)); sound.setAutoArrangeColumn(0); sound.setAutoArrangeRow(0); if (mGsb.getAutoArrange()) { if (placeToFreeSlot(sound)) { mGsb.getSoundList().add(sound); } } else { placeToFreeSpace(sound); mGsb.getSoundList().add(sound); } mBoardHistory.createHistoryCheckpoint(mGsb); } break; case EXPLORE_BACKGROUD: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); File background = new File(extras.getString(FileExplorer.ACTION_SELECT_BACKGROUND_FILE)); mGsb.setBackgroundImagePath(background); mGsb.setBackgroundImage(ImageDrawing.decodeFile(mToastHandler, mGsb.getBackgroundImagePath())); mGsb.setBackgroundWidth(mGsb.getBackgroundImage().getWidth()); mGsb.setBackgroundHeight(mGsb.getBackgroundImage().getHeight()); mGsb.setBackgroundX(0); mGsb.setBackgroundY(0); mBoardHistory.createHistoryCheckpoint(mGsb); } if (mBackgroundDialog != null && mGsb.getBackgroundImage() != null) { mBackgroundWidthText.setText("Width (" + mGsb.getBackgroundImage().getWidth() + ")"); mBackgroundHeightText.setText("Height (" + mGsb.getBackgroundImage().getHeight() + ")"); mBackgroundWidthInput.setText(Float.toString(mGsb.getBackgroundWidth())); mBackgroundHeightInput.setText(Float.toString(mGsb.getBackgroundHeight())); } break; case EXPLORE_SOUND_IMAGE: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); File image = new File(extras.getString(FileExplorer.ACTION_SELECT_SOUND_IMAGE_FILE)); mPressedSound.setImagePath(image); mPressedSound.setImage(ImageDrawing.decodeFile(mToastHandler, mPressedSound.getImagePath())); } if (mSoundImageDialog != null) { mSoundImageWidthText.setText("Width (" + mPressedSound.getImage().getWidth() + ")"); mSoundImageHeightText.setText("Height (" + mPressedSound.getImage().getHeight() + ")"); mSoundImageWidthInput.setText(Float.toString(mPressedSound.getImage().getWidth())); mSoundImageHeightInput.setText(Float.toString(mPressedSound.getImage().getHeight())); } break; case EXPLORE_SOUND_ACTIVE_IMAGE: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); File image = new File(extras.getString(FileExplorer.ACTION_SELECT_SOUND_ACTIVE_IMAGE_FILE)); mPressedSound.setActiveImagePath(image); mPressedSound.setActiveImage(ImageDrawing.decodeFile(mToastHandler, mPressedSound.getActiveImagePath())); } break; case CHANGE_NAME_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); if (extras.getBoolean("copyKey")) { mCopyColor = CHANGE_NAME_COLOR; } else { mPressedSound.setNameTextColorInt(extras.getInt("colorKey")); } } break; case CHANGE_INNER_PAINT_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); if (extras.getBoolean("copyKey")) { mCopyColor = CHANGE_INNER_PAINT_COLOR; } else { mPressedSound.setNameFrameInnerColorInt(extras.getInt("colorKey")); } } break; case CHANGE_BORDER_PAINT_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); if (extras.getBoolean("copyKey")) { mCopyColor = CHANGE_BORDER_PAINT_COLOR; } else { mPressedSound.setNameFrameBorderColorInt(extras.getInt("colorKey")); } } break; case CHANGE_BACKGROUND_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); mGsb.setBackgroundColor(extras.getInt("colorKey")); mBoardHistory.createHistoryCheckpoint(mGsb); } break; case CHANGE_SOUND_PATH: if (resultCode == RESULT_OK) { LayoutInflater removeInflater = (LayoutInflater) BoardEditor.this.getSystemService(LAYOUT_INFLATER_SERVICE); View removeLayout = removeInflater.inflate( R.layout.graphical_soundboard_editor_alert_remove_sound, (ViewGroup) findViewById(R.id.alert_remove_sound_root)); final CheckBox removeFileCheckBox = (CheckBox) removeLayout.findViewById(R.id.removeFile); removeFileCheckBox.setText(" DELETE " + mPressedSound.getPath().getAbsolutePath()); AlertDialog.Builder removeBuilder = new AlertDialog.Builder( BoardEditor.this); removeBuilder.setView(removeLayout); removeBuilder.setTitle("Changing sound"); removeBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (removeFileCheckBox.isChecked() == true) { mPressedSound.getPath().delete(); } Bundle extras = intent.getExtras(); mPressedSound.setPath(new File(extras.getString(FileExplorer.ACTION_CHANGE_SOUND_PATH))); } }); removeBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); removeBuilder.setCancelable(false); removeBuilder.show(); } break; default: break; } } private void initializeConvert() { mWaitDialog = ProgressDialog.show(BoardEditor.this, "", "Please wait", true); Thread t = new Thread() { public void run() { Looper.prepare(); try { if (mClearBoardDir) { cleanDirectory(new File(mSbDir, mBoardName).listFiles()); } FileProcessor.convertGraphicalBoard(BoardEditor.this, mBoardName, mGsb); save(); } catch (IOException e) { Log.e(TAG, "Error converting board", e); } mHandler.post(mUpdateResults); } }; t.start(); } private void cleanDirectory(File[] files) { for (File file : files) { if (file.isDirectory()) { cleanDirectory(file.listFiles()); if (file.listFiles().length == 0) { Log.d(TAG, "Deleting empty directory " + file.getAbsolutePath()); file.delete(); } } else { boolean boardUsesFile = false; if (file.getName().equals("graphicalBoard") == true || file.getName().equals("icon.png") == true) { boardUsesFile = true; } try { if (file.getName().equals(mGsb.getBackgroundImagePath().getName())) boardUsesFile = true; } catch (NullPointerException e) {} for (GraphicalSound sound : mGsb.getSoundList()) { if (boardUsesFile) break; try { if (sound.getPath().getAbsolutePath().equals(file.getAbsolutePath())) boardUsesFile = true; } catch (NullPointerException e) {} try { if (sound.getImagePath().getAbsolutePath().equals(file.getAbsolutePath())) boardUsesFile = true; } catch (NullPointerException e) {} try { if (sound.getActiveImagePath().getAbsolutePath().equals(file.getAbsolutePath())) boardUsesFile = true; } catch (NullPointerException e) {} } if (boardUsesFile == false) { Log.d(TAG, "Deleting unused file " + file.getAbsolutePath()); file.delete(); } } } } final Runnable mUpdateResults = new Runnable() { public void run() { mWaitDialog.dismiss(); } }; @Override public void onConfigurationChanged(Configuration newConfig) { int newOrientation = OrientationUtil.getBoarderOrientation(newConfig); if (newOrientation != this.mCurrentOrientation) { this.mCurrentOrientation = newOrientation; GraphicalSoundboard newOrientationGsb = mPagination.getBoard(newOrientation); changeBoard(newOrientationGsb, true); // Set resolution handling stuff for the new orientation if (mResolutionAlert != null) { mResolutionAlert.dismiss(); } mPanelInitialized = false; } super.onConfigurationChanged(newConfig); } @Override protected void onResume() { super.onResume(); mToastHandler = new ToastHandler(getApplicationContext()); setContentView(mPanel); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override protected void onPause() { save(); super.onPause(); } @Override protected void onDestroy() { GraphicalSoundboard.unloadImages(mGsb); super.onDestroy(); } private void save() { if (mBoardName != null) { try { GraphicalSoundboard gsb = GraphicalSoundboard.copy(mGsb); if (mPressedSound != null && mCurrentGesture == TouchGesture.DRAG) gsb.getSoundList().add(mPressedSound); // Sound is being dragged mGsbp.overrideBoard(gsb); mGsbp.saveBoard(mBoardName); Log.v(TAG, "Board " + mBoardName + " saved"); } catch (IOException e) { Log.e(TAG, "Unable to save " + mBoardName, e); } } } private void playTouchedSound(GraphicalSound sound) { if (sound.getPath().getAbsolutePath().equals(SoundboardMenu.mPauseSoundFilePath)) { SoundPlayerControl.togglePlayPause(this.getApplicationContext()); } else { if (sound.getSecondClickAction() == GraphicalSound.SECOND_CLICK_PLAY_NEW) { SoundPlayerControl.playSound(mGsb.getPlaySimultaneously(), sound.getPath(), sound.getVolumeLeft(), sound.getVolumeRight(), mGsb.getBoardVolume()); } else if (sound.getSecondClickAction() == GraphicalSound.SECOND_CLICK_PAUSE) { SoundPlayerControl.pauseSound(mGsb.getPlaySimultaneously(), sound.getPath(), sound.getVolumeLeft(), sound.getVolumeRight(), mGsb.getBoardVolume()); } else if (sound.getSecondClickAction() == GraphicalSound.SECOND_CLICK_STOP) { SoundPlayerControl.stopSound(mGsb.getPlaySimultaneously(), sound.getPath(), sound.getVolumeLeft(), sound.getVolumeRight(), mGsb.getBoardVolume()); } mCanvasInvalidated = true; } } private void initializeDrag(float initTouchEventX, float initTouchEventY, GraphicalSound sound) { mPressedSound = sound; mCurrentGesture = TouchGesture.DRAG; mInitialNameFrameX = sound.getNameFrameX(); mInitialNameFrameY = sound.getNameFrameY(); mInitialImageX = sound.getImageX(); mInitialImageY = sound.getImageY(); mGsb.getSoundList().remove(sound); mNameFrameDragDistanceX = initTouchEventX - sound.getNameFrameX(); mNameFrameDragDistanceY = initTouchEventY - sound.getNameFrameY(); mImageDragDistanceX = initTouchEventX - sound.getImageX(); mImageDragDistanceY = initTouchEventY - sound.getImageY(); } private void copyColor(GraphicalSound sound) { switch(mCopyColor) { case CHANGE_NAME_COLOR: mPressedSound.setNameTextColorInt(sound.getNameTextColor()); break; case CHANGE_INNER_PAINT_COLOR: mPressedSound.setNameFrameInnerColorInt(sound.getNameFrameInnerColor()); break; case CHANGE_BORDER_PAINT_COLOR: mPressedSound.setNameFrameBorderColorInt(sound.getNameFrameBorderColor()); break; } mCopyColor = 0; mBoardHistory.createHistoryCheckpoint(mGsb); } void moveSound(float X, float Y) { if (mPressedSound.getLinkNameAndImage() || mDragTarget == DRAG_TEXT) { mPressedSound.setNameFrameX(X-mNameFrameDragDistanceX); mPressedSound.setNameFrameY(Y-mNameFrameDragDistanceY); } if (mPressedSound.getLinkNameAndImage() || mDragTarget == DRAG_IMAGE) { mPressedSound.setImageX(X-mImageDragDistanceX); mPressedSound.setImageY(Y-mImageDragDistanceY); } } public void moveSoundToSlot(GraphicalSound sound, int column, int row, float imageX, float imageY, float nameX, float nameY) { int width = mPanel.getWidth(); int height = mPanel.getHeight(); float middlePointX = width/mGsb.getAutoArrangeColumns()/2; float middlePointY = height/mGsb.getAutoArrangeRows()/2; float lowPointX; float highPointX; float lowPointY; float highPointY; boolean moveName = false; boolean moveImage = false; SoundNameDrawing soundNameDrawing = new SoundNameDrawing(sound); float nameFrameWidth = soundNameDrawing.getNameFrameRect().width(); float nameFrameHeight = soundNameDrawing.getNameFrameRect().height(); if (sound.getHideImageOrText() == GraphicalSound.HIDE_TEXT) { lowPointX = imageX; highPointX = imageX+sound.getImageWidth(); lowPointY = imageY; highPointY = imageY+sound.getImageHeight(); moveImage = true; } else if (sound.getHideImageOrText() == GraphicalSound.HIDE_IMAGE) { lowPointX = nameX; highPointX = nameX+nameFrameWidth; lowPointY = nameY; highPointY = nameY+nameFrameHeight; moveName = true; } else { lowPointX = imageX < nameX ? imageX : nameX; highPointX = imageX+sound.getImageWidth() > nameX+nameFrameWidth ? imageX+sound.getImageWidth() : nameX+nameFrameWidth; lowPointY = imageY < nameY ? imageY : nameY; highPointY = imageY+sound.getImageHeight() > nameY+nameFrameHeight ? imageY+sound.getImageHeight() : nameY+nameFrameHeight; moveImage = true; moveName = true; } float xPoint = (highPointX-lowPointX)/2; float imageDistanceX = imageX-(lowPointX+xPoint); float nameDistanceX = nameX-(lowPointX+xPoint); float yPoint = (highPointY-lowPointY)/2; float imageDistanceY = imageY-(lowPointY+yPoint); float nameDistanceY = nameY-(lowPointY+yPoint); float slotX = column*(width/mGsb.getAutoArrangeColumns()); float slotY = row*(height/mGsb.getAutoArrangeRows()); if (moveImage) { sound.setImageX(slotX+middlePointX+imageDistanceX); sound.setImageY(slotY+middlePointY+imageDistanceY); } if (moveName) { sound.setNameFrameX(slotX+middlePointX+nameDistanceX); sound.setNameFrameY(slotY+middlePointY+nameDistanceY); } sound.setAutoArrangeColumn(column); sound.setAutoArrangeRow(row); mBoardHistory.createHistoryCheckpoint(mGsb); } public boolean placeToFreeSlot(GraphicalSound sound) { try { Slot slot = AutoArrange.getFreeSlot(mGsb.getSoundList(), mGsb.getAutoArrangeColumns(), mGsb.getAutoArrangeRows()); moveSoundToSlot(sound, slot.getColumn(), slot.getRow(), sound.getImageX(), sound.getImageY(), sound.getNameFrameX(), sound.getNameFrameY()); return true; } catch (NullPointerException e) { Toast.makeText(getApplicationContext(), "No slot available", Toast.LENGTH_SHORT).show(); return false; } } public void placeToFreeSpace(GraphicalSound sound) { boolean spaceAvailable = true; float freeSpaceX = 0; float freeSpaceY = 0; int width = mPanel.getWidth(); int height = mPanel.getHeight(); while (freeSpaceY + sound.getImageHeight() < height) { spaceAvailable = true; for (GraphicalSound spaceEater : mGsb.getSoundList()) { if (((freeSpaceX >= spaceEater.getImageX() && freeSpaceX <= spaceEater.getImageX()+spaceEater.getImageWidth()) || freeSpaceX+sound.getImageWidth() >= spaceEater.getImageX() && freeSpaceX+sound.getImageWidth() <= spaceEater.getImageX()+spaceEater.getImageWidth()) && (freeSpaceY >= spaceEater.getImageY() && freeSpaceY <= spaceEater.getImageY()+spaceEater.getImageHeight() || freeSpaceY+sound.getImageHeight() >= spaceEater.getImageY() && freeSpaceY+sound.getImageHeight() <= spaceEater.getImageY()+spaceEater.getImageHeight())) { spaceAvailable = false; break; } } if (spaceAvailable) { sound.setImageX(freeSpaceX); sound.setImageY(freeSpaceY); sound.generateNameFrameXYFromImageLocation(); break; } freeSpaceX = freeSpaceX + 5; if (freeSpaceX + sound.getImageWidth() >= width) { freeSpaceX = 0; freeSpaceY = freeSpaceY + 5; } } if (!spaceAvailable) { sound.setNameFrameX(10); sound.setNameFrameY(sound.getImageHeight()+10); sound.generateImageXYFromNameFrameLocation(); } } public boolean onTrackballEvent (MotionEvent event) { if (mMode == EDIT_BOARD && event.getAction() == MotionEvent.ACTION_MOVE && mPressedSound != null && (mLastTrackballEvent == 0 || System.currentTimeMillis() - mLastTrackballEvent > 500)) { mLastTrackballEvent = System.currentTimeMillis(); int movementX = 0; int movementY = 0; if (event.getX() > 0) { movementX = 1; } else if (event.getX() < 0) { movementX = -1; }else if (event.getY() > 0) { movementY = 1; } else if (event.getY() < 0) { movementY = -1; } if (mPressedSound.getLinkNameAndImage() || mDragTarget == DRAG_TEXT) { mPressedSound.setNameFrameX(mPressedSound.getNameFrameX() + movementX); mPressedSound.setNameFrameY(mPressedSound.getNameFrameY() + movementY); } if (mPressedSound.getLinkNameAndImage() || mDragTarget == DRAG_IMAGE) { mPressedSound.setImageX(mPressedSound.getImageX() + movementX); mPressedSound.setImageY(mPressedSound.getImageY() + movementY); } mBoardHistory.setHistoryCheckpoint(mGsb); return true; } else { return false; } } public void issueResolutionConversion() { Thread t = new Thread() { public void run() { Looper.prepare(); final int windowWidth = mPanel.getWidth(); final int windowHeight = mPanel.getHeight(); if (mGsb.getScreenHeight() == 0 || mGsb.getScreenWidth() == 0) { mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } else if (mGsb.getScreenWidth() != windowWidth || mGsb.getScreenHeight() != windowHeight) { Log.v(TAG, "Soundoard resolution has changed. X: " + mGsb.getScreenWidth() + " -> " + windowWidth + " - Y: " + mGsb.getScreenHeight() + " -> " + windowHeight); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setTitle("Display size"); builder.setMessage("Display size used to make this board differs from your display size.\n\n" + "You can resize this board to fill your display or " + "fit this board to your display. Fit looks accurately like the original one.\n\n" + "(Ps. In 'Edit board' mode you can undo this.)"); builder.setPositiveButton("Resize", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.v(TAG, "Resizing board"); clearBlackBars(); float xScale = (float) windowWidth/(float) (mGsb.getScreenWidth()); float yScale = (float) windowHeight/(float) (mGsb.getScreenHeight()); float avarageScale = xScale+(yScale-xScale)/2; Log.v(TAG, "X scale: \"" + xScale + "\"" + ", old width: \""+mGsb.getScreenWidth() + "\", new width: \"" + windowWidth + "\""); Log.v(TAG, "Y scale: \"" + yScale + "\"" + ", old height: \""+mGsb.getScreenHeight() + "\", new height: \"" + windowHeight + "\""); Log.v(TAG, "Avarage scale: \"" + avarageScale + "\""); mGsb.setBackgroundX(mGsb.getBackgroundX()*xScale); mGsb.setBackgroundY(mGsb.getBackgroundY()*yScale); mGsb.setBackgroundWidth(mGsb.getBackgroundWidth()*xScale); mGsb.setBackgroundHeight(mGsb.getBackgroundHeight()*yScale); for (GraphicalSound sound : mGsb.getSoundList()) { sound = SoundNameDrawing.getScaledTextSize(sound, avarageScale); sound.setNameFrameX(sound.getNameFrameX()*xScale); sound.setNameFrameY(sound.getNameFrameY()*yScale); sound.setImageX(sound.getImageX()*xScale); sound.setImageY(sound.getImageY()*yScale); sound.setImageWidth(sound.getImageWidth()*avarageScale); sound.setImageHeight(sound.getImageHeight()*avarageScale); if (sound.getLinkNameAndImage()) sound.generateNameFrameXYFromImageLocation(); } mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } }); builder.setNeutralButton("Fit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.v(TAG, "Fitting board"); clearBlackBars(); float xScale = (float) (windowWidth)/(float) (mGsb.getScreenWidth()); float yScale = (float) (windowHeight)/(float) (mGsb.getScreenHeight()); boolean xFillsDisplay = xScale < yScale; float applicableScale = (xScale < yScale) ? xScale : yScale; float hiddenAreaSize; if (xFillsDisplay) { hiddenAreaSize = ((float) windowHeight-(float) mGsb.getScreenHeight()*applicableScale)/2; } else { hiddenAreaSize = ((float) windowWidth-(float) mGsb.getScreenWidth()*applicableScale)/2; } Log.v(TAG, "X scale: \"" + xScale + "\"" + ", old width: \""+mGsb.getScreenWidth() + "\", new width: \"" + windowWidth + "\""); Log.v(TAG, "Y scale: \"" + yScale + "\"" + ", old height: \""+mGsb.getScreenHeight() + "\", new height: \"" + windowHeight + "\""); Log.v(TAG, "Applicable scale: \"" + applicableScale + "\""); Log.v(TAG, "Hidden area size: \"" + hiddenAreaSize + "\""); mGsb.setBackgroundWidth(mGsb.getBackgroundWidth()*applicableScale); mGsb.setBackgroundHeight(mGsb.getBackgroundHeight()*applicableScale); if (xFillsDisplay) { mGsb.setBackgroundX(mGsb.getBackgroundX()*applicableScale); mGsb.setBackgroundY(hiddenAreaSize+mGsb.getBackgroundY()*applicableScale); } else { mGsb.setBackgroundX(hiddenAreaSize+mGsb.getBackgroundX()*applicableScale); mGsb.setBackgroundY(mGsb.getBackgroundY()*applicableScale); } for (GraphicalSound sound : mGsb.getSoundList()) { sound = SoundNameDrawing.getScaledTextSize(sound, applicableScale); if (xFillsDisplay) { sound.setNameFrameX(sound.getNameFrameX()*applicableScale); sound.setNameFrameY(hiddenAreaSize+sound.getNameFrameY()*applicableScale); sound.setImageX(sound.getImageX()*applicableScale); sound.setImageY(hiddenAreaSize+sound.getImageY()*applicableScale); } else { Log.w(TAG, "sound: " + sound.getName()); Log.w(TAG, "hiddenAreaSize: " + hiddenAreaSize + " sound.getNameFrameX(): " + sound.getNameFrameX() + " applicableScale: " + applicableScale); Log.w(TAG, "hiddenAreaSize+sound.getNameFrameX()*applicableScale: " + (hiddenAreaSize+sound.getNameFrameX()*applicableScale)); sound.setNameFrameX(hiddenAreaSize+sound.getNameFrameX()*applicableScale); sound.setNameFrameY(sound.getNameFrameY()*applicableScale); sound.setImageX(hiddenAreaSize+sound.getImageX()*applicableScale); sound.setImageY(sound.getImageY()*applicableScale); } sound.setImageWidth(sound.getImageWidth()*applicableScale); sound.setImageHeight(sound.getImageHeight()*applicableScale); if (sound.getLinkNameAndImage()) sound.generateNameFrameXYFromImageLocation(); } GraphicalSound blackBar1 = new GraphicalSound(); blackBar1.setNameFrameInnerColor(255, 0, 0, 0); GraphicalSound blackBar2 = new GraphicalSound(); blackBar2.setNameFrameInnerColor(255, 0, 0, 0); if (xFillsDisplay) { blackBar1.setName("I hide top of the board."); blackBar2.setName("I hide bottom of the board."); blackBar1.setPath(new File(SoundboardMenu.mTopBlackBarSoundFilePath)); blackBar2.setPath(new File(SoundboardMenu.mBottomBlackBarSoundFilePath)); blackBar1.setNameFrameY(hiddenAreaSize); blackBar2.setNameFrameY((float) windowHeight-hiddenAreaSize); } else { blackBar1.setName("I hide left side of the board."); blackBar2.setName("I hide right side of the board."); blackBar1.setPath(new File(SoundboardMenu.mLeftBlackBarSoundFilePath)); blackBar2.setPath(new File(SoundboardMenu.mRightBlackBarSoundFilePath)); blackBar1.setNameFrameX(hiddenAreaSize); blackBar2.setNameFrameX((float) windowWidth-hiddenAreaSize); } mGsb.addSound(blackBar1); mGsb.addSound(blackBar2); mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } }); builder.setNegativeButton("Keep", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } }); mResolutionAlert = builder.create(); mResolutionAlert.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { mResolutionAlert = null; mBoardHistory.createHistoryCheckpoint(mGsb); } }); mResolutionAlert.show(); } Looper.loop(); Looper.myLooper().quit(); } }; t.start(); } private void clearBlackBars() { ListIterator<GraphicalSound> iterator = mGsb.getSoundList().listIterator(); while (iterator.hasNext()) { GraphicalSound sound = iterator.next(); if (sound.getPath().getAbsolutePath().equals(SoundboardMenu.mTopBlackBarSoundFilePath) || sound.getPath().getAbsolutePath().equals(SoundboardMenu.mBottomBlackBarSoundFilePath)) { mGsb.setScreenHeight(mGsb.getScreenHeight() - Float.valueOf(sound.getImageHeight()).intValue()); iterator.remove(); } else if (sound.getPath().getAbsolutePath().equals(SoundboardMenu.mLeftBlackBarSoundFilePath) || sound.getPath().getAbsolutePath().equals(SoundboardMenu.mRightBlackBarSoundFilePath)) { mGsb.setScreenWidth(mGsb.getScreenWidth() - Float.valueOf(sound.getImageWidth()).intValue()); iterator.remove(); } } } class DrawingPanel extends SurfaceView implements SurfaceHolder.Callback { private float mInitTouchEventX = 0; private float mInitTouchEventY = 0; private long mClickTime = 0; private float mLatestEventX = 0; private float mLatestEventY = 0; Timer mJoystickTimer = null; Object mGestureLock = new Object(); public DrawingPanel(Context context) { super(context); getHolder().addCallback(this); mThread = new DrawingThread(getHolder(), this); mJoystick = new Joystick(context); } private GraphicalSound findPressedSound(MotionEvent pressInitEvent) { GraphicalSound pressedSound = null; ListIterator<GraphicalSound> iterator = mGsb.getSoundList().listIterator(); while (iterator.hasNext()) {iterator.next();} while (iterator.hasPrevious()) { GraphicalSound sound = iterator.previous(); String soundPath = sound.getPath().getAbsolutePath(); SoundNameDrawing soundNameDrawing = new SoundNameDrawing(sound); float nameFrameX = sound.getNameFrameX(); float nameFrameY = sound.getNameFrameY(); float nameFrameWidth = soundNameDrawing.getNameFrameRect().width(); float nameFrameHeight = soundNameDrawing.getNameFrameRect().height(); if (pressInitEvent.getX() >= sound.getImageX() && pressInitEvent.getX() <= sound.getImageWidth() + sound.getImageX() && pressInitEvent.getY() >= sound.getImageY() && pressInitEvent.getY() <= sound.getImageHeight() + sound.getImageY()) { mDragTarget = DRAG_IMAGE; return sound; } else if ((pressInitEvent.getX() >= sound.getNameFrameX() && pressInitEvent.getX() <= nameFrameWidth + sound.getNameFrameX() && pressInitEvent.getY() >= sound.getNameFrameY() && pressInitEvent.getY() <= nameFrameHeight + sound.getNameFrameY()) || soundPath.equals(SoundboardMenu.mTopBlackBarSoundFilePath) && pressInitEvent.getY() <= nameFrameY || soundPath.equals(SoundboardMenu.mBottomBlackBarSoundFilePath) && pressInitEvent.getY() >= nameFrameY || soundPath.equals(SoundboardMenu.mLeftBlackBarSoundFilePath) && pressInitEvent.getX() <= nameFrameX || soundPath.equals(SoundboardMenu.mRightBlackBarSoundFilePath) && pressInitEvent.getX() >= nameFrameX) { mDragTarget = DRAG_TEXT; return sound; } } return pressedSound; } private long holdTime() { return Calendar.getInstance().getTimeInMillis()-mClickTime; } private void updateClickTime() { mClickTime = Calendar.getInstance().getTimeInMillis(); } private void dragEvent(float eventX, float eventY) { if (mFineTuningSound != null) { eventX = mJoystick.dragDistanceX(eventX); eventY = mJoystick.dragDistanceY(eventY); } moveSound(eventX, eventY); } class DragInitializeTimer extends TimerTask { public void run() { synchronized (mGestureLock) { if (mCurrentGesture == TouchGesture.PRESS_BOARD && mMode == EDIT_BOARD) { initializeDrag(mInitTouchEventX, mInitTouchEventY, mPressedSound); vibrator.vibrate(60); } } } } class JoystickTimer extends TimerTask { public void run() { dragEvent(mLatestEventX, mLatestEventY); } } @Override public boolean onTouchEvent(MotionEvent event) { mLatestEventX = event.getX(); mLatestEventY = event.getY(); if (mThread == null) return false; synchronized (mThread.getSurfaceHolder()) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (mMoveBackground) { mBackgroundLeftDistance = event.getX() - mGsb.getBackgroundX(); mBackgroundTopDistance = event.getY() - mGsb.getBackgroundY(); } else if (mFineTuningSound != null) { mInitTouchEventX = event.getX(); mInitTouchEventY = event.getY(); mPressedSound = mFineTuningSound; updateClickTime(); mCurrentGesture = TouchGesture.PRESS_BOARD; new Timer().schedule(new DragInitializeTimer(), 200); mJoystick.init(event); mJoystickTimer = new Timer(); mJoystickTimer.schedule(new JoystickTimer(), 210, 50); } else { mInitTouchEventX = event.getX(); mInitTouchEventY = event.getY(); mPressedSound = findPressedSound(event); updateClickTime(); if (mPressedSound == null) { mCurrentGesture = TouchGesture.PRESS_BLANK; } else { mCurrentGesture = TouchGesture.PRESS_BOARD; vibrator.vibrate(15); new Timer().schedule(new DragInitializeTimer(), DRAG_SWIPE_TIME); } if (mCopyColor != 0) { copyColor(mPressedSound); mPressedSound = null; } } } else if (event.getAction() == MotionEvent.ACTION_MOVE) { if (mMoveBackground) { mGsb.setBackgroundX(event.getX() - mBackgroundLeftDistance); mGsb.setBackgroundY(event.getY() - mBackgroundTopDistance); } else if ((mCurrentGesture == TouchGesture.PRESS_BOARD || // PRESS_BOARD has timed gesture changing (mCurrentGesture == TouchGesture.PRESS_BLANK && holdTime() < DRAG_SWIPE_TIME)) && mFineTuningSound == null) { float swipeTriggerDistance = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, getResources().getDisplayMetrics()); double distanceFromInit = Math.sqrt( Math.pow((mInitTouchEventX - event.getX()), 2) + Math.pow((mInitTouchEventY - event.getY()), 2)); // hypotenuse synchronized (mGestureLock) { if (distanceFromInit > swipeTriggerDistance) { mCurrentGesture = TouchGesture.SWIPE; GraphicalSoundboard swapGsb = null; if (event.getX() < mInitTouchEventX) { swapGsb = mPagination.getNextBoardPage(mGsb); } else { swapGsb = mPagination.getPreviousPage(mGsb); } if (swapGsb == null) { Toast.makeText(getApplicationContext(), "No page there", Toast.LENGTH_SHORT).show(); } else { changeBoard(swapGsb, true); } } } } else if (mCurrentGesture == TouchGesture.DRAG) { if (mFineTuningSound == null) dragEvent(event.getX(), event.getY()); } } else if (event.getAction() == MotionEvent.ACTION_UP) { synchronized (mGestureLock) { if (mMoveBackground) { mGsb.setBackgroundX(event.getX() - mBackgroundLeftDistance); mGsb.setBackgroundY(event.getY() - mBackgroundTopDistance); mBoardHistory.createHistoryCheckpoint(mGsb); } else if ((mCurrentGesture == TouchGesture.PRESS_BOARD || mFineTuningSound != null) && mMode == EDIT_BOARD && holdTime() < 200) { mCurrentGesture = TouchGesture.TAP; mClickTime = 0; invalidate(); String fineTuningText = (mFineTuningSound == null) ? "on" : "off"; final CharSequence[] items = {"Fine tuning "+fineTuningText, "Info", "Name settings", "Image settings", "Sound settings", "Copy sound", "Remove sound", "Set as..."}; AlertDialog.Builder optionsBuilder = new AlertDialog.Builder(BoardEditor.this); optionsBuilder.setTitle("Options"); optionsBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { if (mFineTuningSound == null) { mFineTuningSound = mPressedSound; } else { mFineTuningSound = null; } } else if (item == 1) { SoundNameDrawing soundNameDrawing = new SoundNameDrawing(mPressedSound); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setTitle("Sound info"); builder.setMessage("Name:\n"+mPressedSound.getName()+ "\n\nSound path:\n"+mPressedSound.getPath()+ "\n\nImage path:\n"+mPressedSound.getImagePath()+ "\n\nActive image path:\n"+mPressedSound.getActiveImagePath()+ "\n\nName and image linked:\n"+mPressedSound.getLinkNameAndImage()+ "\n\nHide image or text:\n"+mPressedSound.getHideImageOrText()+ "\n\nImage X:\n"+mPressedSound.getImageX()+ "\n\nImage Y:\n"+mPressedSound.getImageY()+ "\n\nImage width:\n"+mPressedSound.getImageWidth()+ "\n\nImage height:\n"+mPressedSound.getImageHeight()+ "\n\nName frame X:\n"+mPressedSound.getNameFrameX()+ "\n\nName frame Y:\n"+mPressedSound.getNameFrameY()+ "\n\nName frame width:\n"+soundNameDrawing.getNameFrameRect().width()+ "\n\nName frame height:\n"+soundNameDrawing.getNameFrameRect().height()+ "\n\nAuto arrange column:\n"+mPressedSound.getAutoArrangeColumn()+ "\n\nAuto arrange row:\n"+mPressedSound.getAutoArrangeRow()+ "\n\nSecond click action:\n"+mPressedSound.getSecondClickAction()+ "\n\nLeft volume:\n"+mPressedSound.getVolumeLeft()+ "\n\nRight volume:\n"+mPressedSound.getVolumeRight()+ "\n\nName frame border color:\n"+mPressedSound.getNameFrameBorderColor()+ "\n\nName frame inner color:\n"+mPressedSound.getNameFrameInnerColor()+ "\n\nName text color:\n"+mPressedSound.getNameTextColor()+ "\n\nName text size:\n"+mPressedSound.getNameSize()+ "\n\nShow name frame border paint:\n"+mPressedSound.getShowNameFrameBorderPaint()+ "\n\nShow name frame inner paint:\n"+mPressedSound.getShowNameFrameBorderPaint()); builder.show(); } else if (item == 2) { LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate( R.layout.graphical_soundboard_editor_alert_sound_name_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final EditText soundNameInput = (EditText) layout.findViewById(R.id.soundNameInput); soundNameInput.setText(mPressedSound.getName()); final EditText soundNameSizeInput = (EditText) layout.findViewById(R.id.soundNameSizeInput); soundNameSizeInput.setText(Float.toString(mPressedSound.getNameSize())); final CheckBox checkShowSoundName = (CheckBox) layout.findViewById(R.id.showSoundNameCheckBox); checkShowSoundName.setChecked(mPressedSound.getHideImageOrText() != GraphicalSound.HIDE_TEXT); final CheckBox checkShowInnerPaint = (CheckBox) layout.findViewById(R.id.showInnerPaintCheckBox); checkShowInnerPaint.setChecked(mPressedSound.getShowNameFrameInnerPaint()); final CheckBox checkShowBorderPaint = (CheckBox) layout.findViewById(R.id.showBorderPaintCheckBox); checkShowBorderPaint.setChecked(mPressedSound.getShowNameFrameBorderPaint()); final Button nameColorButton = (Button) layout.findViewById(R.id.nameColorButton); nameColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPressedSound.setName(soundNameInput.getText().toString()); mPressedSound.generateImageXYFromNameFrameLocation(); Intent i = new Intent(BoardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeNameColor"); i.putExtras(XStreamUtil.getSoundBundle(mPressedSound, mGsb)); startActivityForResult(i, CHANGE_NAME_COLOR); } }); final Button innerPaintColorButton = (Button) layout.findViewById(R.id.innerPaintColorButton); innerPaintColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPressedSound.setName(soundNameInput.getText().toString()); mPressedSound.generateImageXYFromNameFrameLocation(); Intent i = new Intent(BoardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeinnerPaintColor"); i.putExtras(XStreamUtil.getSoundBundle(mPressedSound, mGsb)); startActivityForResult(i, CHANGE_INNER_PAINT_COLOR); } }); final Button borderPaintColorButton = (Button) layout.findViewById(R.id.borderPaintColorButton); borderPaintColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPressedSound.setName(soundNameInput.getText().toString()); mPressedSound.generateImageXYFromNameFrameLocation(); Intent i = new Intent(BoardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeBorderPaintColor"); i.putExtras(XStreamUtil.getSoundBundle(mPressedSound, mGsb)); startActivityForResult(i, CHANGE_BORDER_PAINT_COLOR); } }); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Name settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; if (checkShowSoundName.isChecked() == false) { mPressedSound.setHideImageOrText(GraphicalSound.HIDE_TEXT); } else if (checkShowSoundName.isChecked() && mPressedSound.getHideImageOrText() == GraphicalSound.HIDE_TEXT) { mPressedSound.setHideImageOrText(GraphicalSound.SHOW_ALL); mPressedSound.generateImageXYFromNameFrameLocation(); } mPressedSound.setShowNameFrameInnerPaint(checkShowInnerPaint.isChecked()); mPressedSound.setShowNameFrameBorderPaint(checkShowBorderPaint.isChecked()); mPressedSound.setName(soundNameInput.getText().toString()); try { mPressedSound.setNameSize(Float.valueOf( soundNameSizeInput.getText().toString()).floatValue()); } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (mPressedSound.getLinkNameAndImage()) { mPressedSound.generateImageXYFromNameFrameLocation(); } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mBoardHistory.createHistoryCheckpoint(mGsb); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 3) { LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate( R.layout.graphical_soundboard_editor_alert_sound_image_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkShowSoundImage = (CheckBox) layout.findViewById(R.id.showSoundImageCheckBox); checkShowSoundImage.setChecked(mPressedSound.getHideImageOrText() != GraphicalSound.HIDE_IMAGE); mSoundImageWidthText = (TextView) layout.findViewById(R.id.soundImageWidthText); mSoundImageWidthText.setText("Width (" + mPressedSound.getImage().getWidth() + ")"); mSoundImageHeightText = (TextView) layout.findViewById(R.id.soundImageHeightText); mSoundImageHeightText.setText("Height (" + mPressedSound.getImage().getHeight() + ")"); mSoundImageWidthInput = (EditText) layout.findViewById(R.id.soundImageWidthInput); mSoundImageWidthInput.setText(Float.toString(mPressedSound.getImageWidth())); mSoundImageHeightInput = (EditText) layout.findViewById(R.id.soundImageHeightInput); mSoundImageHeightInput.setText(Float.toString(mPressedSound.getImageHeight())); final CheckBox scaleWidthHeight = (CheckBox) layout.findViewById(R.id.scaleWidthHeightCheckBox); scaleWidthHeight.setChecked(true); scaleWidthHeight.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { // Calculate a new scale mWidthHeightScale = Float.valueOf(mSoundImageWidthInput.getText().toString()).floatValue() / Float.valueOf(mSoundImageHeightInput.getText().toString()).floatValue(); } catch(NumberFormatException nfe) {Log.e(TAG, "Unable to calculate width and height scale", nfe);} } }); mWidthHeightScale = mPressedSound.getImageWidth() / mPressedSound.getImageHeight(); mSoundImageWidthInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf(mSoundImageWidthInput.getText().toString()).floatValue(); mSoundImageHeightInput.setText(Float.valueOf(value/mWidthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); mSoundImageHeightInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf(mSoundImageHeightInput.getText().toString()).floatValue(); mSoundImageWidthInput.setText(Float.valueOf(value*mWidthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); final Button revertSizeButton = (Button) layout.findViewById(R.id.revertImageSizeButton); revertSizeButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mSoundImageWidthInput.setText(Float.valueOf(mPressedSound.getImageWidth()).toString()); mSoundImageHeightInput.setText(Float.valueOf(mPressedSound.getImageHeight()).toString()); mWidthHeightScale = mPressedSound.getImageWidth() / mPressedSound.getImageHeight(); } }); final Button setSoundImageButton = (Button) layout.findViewById(R.id.setSoundImageButton); setSoundImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { selectImageFile(); } }); final Button resetSoundImageButton = (Button) layout.findViewById(R.id.resetSoundImageButton); resetSoundImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Bitmap defaultSound = BitmapFactory.decodeResource(getResources(), R.drawable.sound); String soundWidth = Integer.toString(defaultSound.getWidth()); String soundHeight = Integer.toString(defaultSound.getHeight()); mPressedSound.setImage(defaultSound); mPressedSound.setImagePath(null); mSoundImageWidthInput.setText(soundWidth); mSoundImageHeightInput.setText(soundHeight); mSoundImageWidthText.setText("Width (" + soundWidth + ")"); mSoundImageHeightText.setText("Height (" + soundHeight + ")"); } }); final Button setSoundActiveImageButton = (Button) layout.findViewById(R.id.setSoundActiveImageButton); setSoundActiveImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { selectActiveImageFile(); } }); final Button resetSoundActiveImageButton = (Button) layout.findViewById(R.id.resetSoundActiveImageButton); resetSoundActiveImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPressedSound.setActiveImage(null); mPressedSound.setActiveImagePath(null); } }); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Image settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; if (checkShowSoundImage.isChecked() == false) { mPressedSound.setHideImageOrText(GraphicalSound.HIDE_IMAGE); } else if (checkShowSoundImage.isChecked() && mPressedSound.getHideImageOrText() == GraphicalSound.HIDE_IMAGE) { mPressedSound.setHideImageOrText(GraphicalSound.SHOW_ALL); } try { mPressedSound.setImageWidth(Float.valueOf( mSoundImageWidthInput.getText().toString()).floatValue()); mPressedSound.setImageHeight(Float.valueOf( mSoundImageHeightInput.getText().toString()).floatValue()); } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } mPressedSound.generateImageXYFromNameFrameLocation(); if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mBoardHistory.createHistoryCheckpoint(mGsb); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mSoundImageDialog = null; } }); mSoundImageDialog = builder.create(); mSoundImageDialog.show(); } else if (item == 4) { LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate( R.layout.graphical_soundboard_editor_alert_sound_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox linkNameAndImageCheckBox = (CheckBox) layout.findViewById(R.id.linkNameAndImageCheckBox); linkNameAndImageCheckBox.setChecked(mPressedSound.getLinkNameAndImage()); final Button changeSoundPathButton = (Button) layout.findViewById(R.id.changeSoundPathButton); changeSoundPathButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(BoardEditor.this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_CHANGE_SOUND_PATH); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, CHANGE_SOUND_PATH); } }); final Button secondClickActionButton = (Button) layout.findViewById(R.id.secondClickActionButton); secondClickActionButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { final CharSequence[] items = {"Play new", "Pause", "Stop"}; AlertDialog.Builder secondClickBuilder = new AlertDialog.Builder( BoardEditor.this); secondClickBuilder.setTitle("Action"); secondClickBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { mPressedSound.setSecondClickAction(GraphicalSound.SECOND_CLICK_PLAY_NEW); } else if (item == 1) { mPressedSound.setSecondClickAction(GraphicalSound.SECOND_CLICK_PAUSE); } else if (item == 2) { mPressedSound.setSecondClickAction(GraphicalSound.SECOND_CLICK_STOP); } } }); AlertDialog secondClickAlert = secondClickBuilder.create(); secondClickAlert.show(); } }); final EditText leftVolumeInput = (EditText) layout.findViewById(R.id.leftVolumeInput); leftVolumeInput.setText(Float.toString(mPressedSound.getVolumeLeft()*100) + "%"); final EditText rightVolumeInput = (EditText) layout.findViewById(R.id.rightVolumeInput); rightVolumeInput.setText(Float.toString(mPressedSound.getVolumeRight()*100) + "%"); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Sound settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mPressedSound.setLinkNameAndImage(linkNameAndImageCheckBox.isChecked()); if (mPressedSound.getLinkNameAndImage()) { mPressedSound.generateImageXYFromNameFrameLocation(); } boolean notifyIncorrectValue = false; Float leftVolumeValue = null; try { String leftVolumeString = leftVolumeInput.getText().toString(); if (leftVolumeString.contains("%")) { leftVolumeValue = Float.valueOf(leftVolumeString.substring(0, leftVolumeString.indexOf("%"))).floatValue()/100; } else { leftVolumeValue = Float.valueOf(leftVolumeString).floatValue()/100; } if (leftVolumeValue >= 0 && leftVolumeValue <= 1 && leftVolumeValue != null) { mPressedSound.setVolumeLeft(leftVolumeValue); } else { notifyIncorrectValue = true; } } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } Float rightVolumeValue = null; try { String rightVolumeString = rightVolumeInput.getText().toString(); if (rightVolumeString.contains("%")) { rightVolumeValue = Float.valueOf(rightVolumeString.substring(0, rightVolumeString.indexOf("%"))).floatValue()/100; } else { rightVolumeValue = Float.valueOf(rightVolumeString).floatValue()/100; } if (rightVolumeValue >= 0 && rightVolumeValue <= 1 && rightVolumeValue != null) { mPressedSound.setVolumeRight(rightVolumeValue); } else { notifyIncorrectValue = true; } } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mBoardHistory.createHistoryCheckpoint(mGsb); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item ==5) { SoundboardMenu.mCopiedSound = (GraphicalSound) mPressedSound.clone(); } else if (item == 6) { LayoutInflater removeInflater = (LayoutInflater) BoardEditor.this.getSystemService(LAYOUT_INFLATER_SERVICE); View removeLayout = removeInflater.inflate( R.layout.graphical_soundboard_editor_alert_remove_sound, (ViewGroup) findViewById(R.id.alert_remove_sound_root)); final CheckBox removeFileCheckBox = (CheckBox) removeLayout.findViewById(R.id.removeFile); removeFileCheckBox.setText(" DELETE " + mPressedSound.getPath().getAbsolutePath()); AlertDialog.Builder removeBuilder = new AlertDialog.Builder( BoardEditor.this); removeBuilder.setView(removeLayout); removeBuilder.setTitle("Removing " + mPressedSound.getName()); removeBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (removeFileCheckBox.isChecked() == true) { mPressedSound.getPath().delete(); } mGsb.getSoundList().remove(mPressedSound); mBoardHistory.createHistoryCheckpoint(mGsb); } }); removeBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); removeBuilder.show(); } else if (item == 7) { final CharSequence[] items = {"Ringtone", "Notification", "Alerts"}; AlertDialog.Builder setAsBuilder = new AlertDialog.Builder( BoardEditor.this); setAsBuilder.setTitle("Set as..."); setAsBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { String filePath = mPressedSound.getPath().getAbsolutePath(); ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, filePath); values.put(MediaStore.MediaColumns.TITLE, mPressedSound.getName()); values.put(MediaStore.MediaColumns.MIME_TYPE, MimeTypeMap.getSingleton().getMimeTypeFromExtension( filePath.substring(filePath.lastIndexOf('.'+1)))); values.put(MediaStore.Audio.Media.ARTIST, "Artist"); int selectedAction = 0; if (item == 0) { selectedAction = RingtoneManager.TYPE_RINGTONE; values.put(MediaStore.Audio.Media.IS_RINGTONE, true); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); values.put(MediaStore.Audio.Media.IS_ALARM, false); values.put(MediaStore.Audio.Media.IS_MUSIC, false); } else if (item == 1) { selectedAction = RingtoneManager.TYPE_NOTIFICATION; values.put(MediaStore.Audio.Media.IS_RINGTONE, false); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); values.put(MediaStore.Audio.Media.IS_ALARM, false); values.put(MediaStore.Audio.Media.IS_MUSIC, false); } else if (item == 2) { selectedAction = RingtoneManager.TYPE_ALARM; values.put(MediaStore.Audio.Media.IS_RINGTONE, false); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); values.put(MediaStore.Audio.Media.IS_ALARM, true); values.put(MediaStore.Audio.Media.IS_MUSIC, false); } Uri uri = MediaStore.Audio.Media.getContentUriForPath(filePath); getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + filePath + "\"", null); Uri newUri = BoardEditor.this.getContentResolver().insert(uri, values); RingtoneManager.setActualDefaultRingtoneUri(BoardEditor.this, selectedAction, newUri); } }); AlertDialog setAsAlert = setAsBuilder.create(); setAsAlert.show(); } } }); AlertDialog optionsAlert = optionsBuilder.create(); optionsAlert.show(); invalidate(); } else if (mCurrentGesture == TouchGesture.DRAG) { if (mGsb.getAutoArrange()) { int width = mPanel.getWidth(); int height = mPanel.getHeight(); int column = -1, i = 0; while (column == -1) { if (event.getX() >= i*(width/mGsb.getAutoArrangeColumns()) && event.getX() <= (i+1)*(width/(mGsb.getAutoArrangeColumns()))) { column = i; } if (i > 1000) { Log.e(TAG, "column fail"); mPressedSound.getAutoArrangeColumn(); break; } i++; } i = 0; int row = -1; while (row == -1) { if (event.getY() >= i*(height/mGsb.getAutoArrangeRows()) && event.getY() <= (i+1)*(height/(mGsb.getAutoArrangeRows()))) { row = i; } if (i > 1000) { Log.e(TAG, "row fail"); mPressedSound.getAutoArrangeRow(); break; } i++; } GraphicalSound swapSound = null; for (GraphicalSound sound : mGsb.getSoundList()) { if (sound.getAutoArrangeColumn() == column && sound.getAutoArrangeRow() == row) { swapSound = sound; } } if (column == mPressedSound.getAutoArrangeColumn() && row == mPressedSound.getAutoArrangeRow()) { moveSound(event.getX(), event.getY()); } else { try { moveSoundToSlot(swapSound, mPressedSound.getAutoArrangeColumn(), mPressedSound.getAutoArrangeRow(), swapSound.getImageX(), swapSound.getImageY(), swapSound.getNameFrameX(), swapSound.getNameFrameY()); } catch (NullPointerException e) {} moveSoundToSlot(mPressedSound, column, row, mInitialImageX, mInitialImageY, mInitialNameFrameX, mInitialNameFrameY); mGsb.addSound(mPressedSound); } } else { mGsb.getSoundList().add(mPressedSound); } mBoardHistory.createHistoryCheckpoint(mGsb); } else if (mCurrentGesture == TouchGesture.PRESS_BOARD && mMode == LISTEN_BOARD) { playTouchedSound(mPressedSound); } mCurrentGesture = null; if (mJoystickTimer != null) { mJoystickTimer.cancel(); mJoystickTimer = null; } } } return true; } } @Override public void onDraw(Canvas canvas) { if (canvas == null) { Log.w(TAG, "Got null canvas"); mNullCanvasCount++; // Drawing thread is still running while the activity is destroyed (surfaceCreated was probably called after surfaceDestroyed). // Reproduce by killing the editor immediately after it is created. // It's difficult to kill the thread properly while supporting different orientations and closing of screen. if (mNullCanvasCount > 5) { Log.e(TAG, "Drawing thread was not destroyed properly"); mThread.setRunning(false); mThread = null; } } else { mNullCanvasCount = 0; super.dispatchDraw(canvas); GraphicalSound pressedSound = null; GraphicalSound fineTuningSound = null; if (mCurrentGesture == TouchGesture.DRAG) pressedSound = mPressedSound; if (mFineTuningSound != null && mCurrentGesture == TouchGesture.DRAG) fineTuningSound = mFineTuningSound; mPageDrawer.drawSurface(canvas, pressedSound, fineTuningSound); } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } public void surfaceCreated(SurfaceHolder holder) { try { mThread.setRunning(true); mThread.start(); } catch (NullPointerException e) { mThread = new DrawingThread(getHolder(), this); mThread.setRunning(true); mThread.start(); } Log.d(TAG, "Surface created"); } public void surfaceDestroyed(SurfaceHolder holder) { mThread.setRunning(false); mThread = null; Log.d(TAG, "Surface destroyed"); } } class DrawingThread extends Thread { private SurfaceHolder mSurfaceHolder; private boolean mRun = false; public DrawingThread(SurfaceHolder surfaceHolder, DrawingPanel panel) { mSurfaceHolder = surfaceHolder; mPanel = panel; } public void setRunning(boolean run) { mRun = run; } public SurfaceHolder getSurfaceHolder() { return mSurfaceHolder; } @Override public void run() { while (mRun) { Canvas c; c = null; try { c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { mPanel.onDraw(c); } } finally { if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } try { if (mPageDrawer.needAnimationRefreshSpeed()) { Thread.sleep(1); } else if (mMode == EDIT_BOARD && (mCurrentGesture == TouchGesture.DRAG || mMoveBackground )) { Thread.sleep(10); } else if (mMode == EDIT_BOARD && mCurrentGesture != TouchGesture.DRAG && mMoveBackground == false) { for (int i = 0; i <= 5; i++) { Thread.sleep(100); if (mCurrentGesture == TouchGesture.DRAG || mMoveBackground) { break; } } } else if (mMode == LISTEN_BOARD) { for (int i = 0; i <= 30; i++) { Thread.sleep(20); if (mMode == EDIT_BOARD || mCanvasInvalidated == true) { mCanvasInvalidated = false; break; } } } else { Log.e(TAG, "Undefined redraw rate state"); Thread.sleep(1000); } } catch (InterruptedException e) {} } } } }
src/fi/mikuz/boarder/gui/BoardEditor.java
package fi.mikuz.boarder.gui; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.ListIterator; import java.util.Timer; import java.util.TimerTask; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Vibrator; import android.provider.MediaStore; import android.util.Log; import android.util.TypedValue; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.thoughtworks.xstream.XStream; import fi.mikuz.boarder.R; import fi.mikuz.boarder.app.BoarderActivity; import fi.mikuz.boarder.component.Slot; import fi.mikuz.boarder.component.soundboard.BoardHistory; import fi.mikuz.boarder.component.soundboard.GraphicalSound; import fi.mikuz.boarder.component.soundboard.GraphicalSoundboard; import fi.mikuz.boarder.component.soundboard.GraphicalSoundboardHolder; import fi.mikuz.boarder.util.AutoArrange; import fi.mikuz.boarder.util.FileProcessor; import fi.mikuz.boarder.util.Handlers.ToastHandler; import fi.mikuz.boarder.util.IconUtils; import fi.mikuz.boarder.util.OrientationUtil; import fi.mikuz.boarder.util.SoundPlayerControl; import fi.mikuz.boarder.util.XStreamUtil; import fi.mikuz.boarder.util.dbadapter.MenuDbAdapter; import fi.mikuz.boarder.util.editor.BoardHistoryProvider; import fi.mikuz.boarder.util.editor.GraphicalSoundboardProvider; import fi.mikuz.boarder.util.editor.ImageDrawing; import fi.mikuz.boarder.util.editor.Joystick; import fi.mikuz.boarder.util.editor.PageDrawer; import fi.mikuz.boarder.util.editor.Pagination; import fi.mikuz.boarder.util.editor.SoundNameDrawing; /** * * @author Jan Mikael Lindlf */ public class BoardEditor extends BoarderActivity { //TODO destroy god object private static final String TAG = BoardEditor.class.getSimpleName(); Vibrator vibrator; private int mCurrentOrientation; public GraphicalSoundboard mGsb; private GraphicalSoundboardProvider mGsbp; private BoardHistory mBoardHistory; private BoardHistoryProvider mBoardHistoryProvider; private Pagination mPagination; private PageDrawer mPageDrawer; private Joystick mJoystick = null; private static final int LISTEN_BOARD = 0; private static final int EDIT_BOARD = 1; private int mMode = LISTEN_BOARD; private static final int DRAG_TEXT = 0; private static final int DRAG_IMAGE = 1; private int mDragTarget = DRAG_TEXT; private static final int EXPLORE_SOUND = 0; private static final int EXPLORE_BACKGROUD = 1; private static final int EXPLORE_SOUND_IMAGE = 2; private static final int CHANGE_NAME_COLOR = 3; private static final int CHANGE_INNER_PAINT_COLOR = 4; private static final int CHANGE_BORDER_PAINT_COLOR = 5; private static final int CHANGE_BACKGROUND_COLOR = 6; private static final int CHANGE_SOUND_PATH = 7; private static final int EXPLORE_SOUND_ACTIVE_IMAGE = 8; private int mCopyColor = 0; /** * PRESS_BLANK: initial state before swipe gestures * PRESS_BOARD: initial state before tap, drag and swipe gestures * DRAG: sound is being dragged * SWIPE: swiping to other page */ private enum TouchGesture {PRESS_BLANK, PRESS_BOARD, DRAG, SWIPE, TAP}; private TouchGesture mCurrentGesture = null; private final int DRAG_SWIPE_TIME = 300; private GraphicalSound mPressedSound = null; private float mInitialNameFrameX = 0; private float mInitialNameFrameY = 0; private float mInitialImageX = 0; private float mInitialImageY = 0; private float mNameFrameDragDistanceX = -1; private float mNameFrameDragDistanceY = -1; private float mImageDragDistanceX = -1; private float mImageDragDistanceY = -1; private long mLastTrackballEvent = 0; private DrawingThread mThread; private Menu mMenu; private DrawingPanel mPanel; boolean mCanvasInvalidated = false; boolean mPanelInitialized = false; AlertDialog mResolutionAlert; private boolean mMoveBackground = false; private float mBackgroundLeftDistance = 0; private float mBackgroundTopDistance = 0; private GraphicalSound mFineTuningSound = null; private ToastHandler mToastHandler; final Handler mHandler = new Handler(); ProgressDialog mWaitDialog; boolean mClearBoardDir = false; private File mSbDir = SoundboardMenu.mSbDir; private String mBoardName = null; private AlertDialog mSoundImageDialog; private TextView mSoundImageWidthText; private TextView mSoundImageHeightText; private EditText mSoundImageWidthInput; private EditText mSoundImageHeightInput; private AlertDialog mBackgroundDialog; private TextView mBackgroundWidthText; private TextView mBackgroundHeightText; private EditText mBackgroundWidthInput; private EditText mBackgroundHeightInput; private float mWidthHeightScale; int mNullCanvasCount = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); mBoardHistoryProvider = new BoardHistoryProvider(); Bundle extras = getIntent().getExtras(); if (extras != null) { mBoardName = extras.getString(MenuDbAdapter.KEY_TITLE); setTitle(mBoardName); mGsbp = new GraphicalSoundboardProvider(mBoardName); mPagination = new Pagination(mGsbp); initEditorBoard(); if (mGsb.getSoundList().isEmpty()) { mMode = EDIT_BOARD; } } else { mMode = EDIT_BOARD; mGsb = new GraphicalSoundboard(); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Set board name"); final EditText input = new EditText(this); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String inputText = input.getText().toString(); if (inputText.contains("\n")) { mBoardName = inputText.substring(0, inputText.indexOf("\n")); } else { mBoardName = inputText; } if (mBoardName.equals("")) { mBoardName = null; finish(); } else { mGsbp = new GraphicalSoundboardProvider(mBoardName); mPagination = new Pagination(mGsbp); initEditorBoard(); setTitle(mBoardName); save(); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { finish(); } }); alert.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); alert.show(); } File icon = new File(mSbDir, mBoardName + "/icon.png"); if (icon.exists()) { Bitmap bitmap = ImageDrawing.decodeFile(mToastHandler, icon); Drawable drawable = new BitmapDrawable(getResources(), IconUtils.resizeIcon(this, bitmap, (40/6))); this.getActionBar().setLogo(drawable); } mPanel = new DrawingPanel(this); ViewTreeObserver vto = mPanel.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!mPanelInitialized) { mPanelInitialized = true; issueResolutionConversion(); } } }); } public void initEditorBoard() { if (mGsbp.getOrientationMode() == GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_PORTRAIT) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else if (mGsbp.getOrientationMode() == GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_LANDSCAPE) { this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } Configuration config = getResources().getConfiguration(); int orientation = OrientationUtil.getBoarderOrientation(config); this.mCurrentOrientation = orientation; GraphicalSoundboard newGsb = mPagination.getBoard(orientation); mPageDrawer = new PageDrawer(this.getApplicationContext(), mJoystick); changeBoard(newGsb, false); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.clear(); mMenu = menu; MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.board_editor_bottom, menu); if (mMode == EDIT_BOARD) { menu.setGroupVisible(R.id.listen_mode, false); } else { menu.setGroupVisible(R.id.edit_mode, false); } if (!mPagination.isMovePageMode()) { menu.setGroupVisible(R.id.move_page_mode, false); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_listen_mode: mMode = LISTEN_BOARD; this.onCreateOptionsMenu(mMenu); return true; case R.id.menu_edit_mode: mMode = EDIT_BOARD; this.onCreateOptionsMenu(mMenu); return true; case R.id.menu_undo: mBoardHistory.undo(this); mFineTuningSound = null; return true; case R.id.menu_redo: mBoardHistory.redo(this); mFineTuningSound = null; return true; case R.id.menu_add_sound: Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_ADD_GRAPHICAL_SOUND); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_SOUND); return true; case R.id.menu_paste_sound: GraphicalSound pasteSound = SoundboardMenu.mCopiedSound; if (pasteSound == null) { Toast.makeText(this.getApplicationContext(), "Nothing copied", Toast.LENGTH_LONG).show(); } else { if (mGsb.getAutoArrange()) { if (placeToFreeSlot(pasteSound)) { mGsb.getSoundList().add(pasteSound); } } else { placeToFreeSpace(pasteSound); mGsb.getSoundList().add(pasteSound); } mBoardHistory.createHistoryCheckpoint(mGsb); } return true; case R.id.menu_save_board: save(); return true; case R.id.menu_page_options: CharSequence[] pageItems = {"Add page", "Delete this page", "Move this page"}; Configuration config = getResources().getConfiguration(); final int currentOrientation = OrientationUtil.getBoarderOrientation(config); AlertDialog.Builder pageBuilder = new AlertDialog.Builder(BoardEditor.this); pageBuilder.setTitle("Page options"); pageBuilder.setItems(pageItems, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { GraphicalSoundboard swapGsb = mGsbp.addBoardPage(currentOrientation); changeBoard(swapGsb, true); } else if (item == 1) { GraphicalSoundboard deleteGsb = mGsb; mGsbp.deletePage(deleteGsb); GraphicalSoundboard gsb = mGsbp.getPage(deleteGsb.getScreenOrientation(), deleteGsb.getPageNumber()); if (gsb == null) gsb = mPagination.getBoard(deleteGsb.getScreenOrientation()); changeBoard(gsb, false); } else if (item == 2) { mPagination.initMove(mGsb); BoardEditor.this.onCreateOptionsMenu(mMenu); } } }); AlertDialog pageAlert = pageBuilder.create(); pageAlert.show(); return true; case R.id.menu_move_page_here: GraphicalSoundboard currentGsb = mGsb; int toPageNumber = currentGsb.getPageNumber(); mGsbp.overrideBoard(currentGsb); mPagination.movePage(mToastHandler, mGsb); GraphicalSoundboard gsb = mGsbp.getPage(currentGsb.getScreenOrientation(), toPageNumber); changeBoard(gsb, false); BoardEditor.this.onCreateOptionsMenu(mMenu); return true; case R.id.menu_convert_board: AlertDialog.Builder convertBuilder = new AlertDialog.Builder(this); convertBuilder.setTitle("Convert"); convertBuilder.setMessage("Clear board directory?"); convertBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mClearBoardDir = true; initializeConvert(); } }); convertBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mClearBoardDir = false; initializeConvert(); } }); convertBuilder.setCancelable(false); convertBuilder.show(); return true; case R.id.menu_play_pause: SoundPlayerControl.togglePlayPause(this.getApplicationContext()); return true; case R.id.menu_notification: SoundboardMenu.updateNotification(this, mBoardName, mBoardName); return true; case R.id.menu_take_screenshot: Bitmap bitmap = Bitmap.createBitmap(mPanel.getWidth(), mPanel.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); mPanel.onDraw(canvas); Toast.makeText(getApplicationContext(), FileProcessor.saveScreenshot(bitmap, mBoardName), Toast.LENGTH_LONG).show(); return true; case R.id.menu_board_settings: final CharSequence[] items = {"Sound", "Background", "Icon", "Screen orientation", "Auto-arrange", "Reset position"}; AlertDialog.Builder setAsBuilder = new AlertDialog.Builder(BoardEditor.this); setAsBuilder.setTitle("Board settings"); setAsBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.graphical_soundboard_editor_alert_board_sound_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkPlaySimultaneously = (CheckBox) layout.findViewById(R.id.playSimultaneouslyCheckBox); checkPlaySimultaneously.setChecked(mGsb.getPlaySimultaneously()); final EditText boardVolumeInput = (EditText) layout.findViewById(R.id.boardVolumeInput); boardVolumeInput.setText(mGsb.getBoardVolume()*100 + "%"); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Board settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; mGsb.setPlaySimultaneously(checkPlaySimultaneously.isChecked()); Float boardVolumeValue = null; try { String boardVolumeString = boardVolumeInput.getText().toString(); if (boardVolumeString.contains("%")) { boardVolumeValue = Float.valueOf(boardVolumeString.substring(0, boardVolumeString.indexOf("%"))).floatValue()/100; } else { boardVolumeValue = Float.valueOf(boardVolumeString).floatValue()/100; } if (boardVolumeValue >= 0 && boardVolumeValue <= 1 && boardVolumeValue != null) { mGsb.setBoardVolume(boardVolumeValue); } else { notifyIncorrectValue = true; } } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 1) { LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout. graphical_soundboard_editor_alert_board_background_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkUseBackgroundImage = (CheckBox) layout.findViewById(R.id.useBackgroundFileCheckBox); checkUseBackgroundImage.setChecked(mGsb.getUseBackgroundImage()); final Button backgroundColorButton = (Button) layout.findViewById(R.id.backgroundColorButton); backgroundColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(BoardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeBackgroundColor"); i.putExtras(XStreamUtil.getSoundboardBundle(mGsb)); startActivityForResult(i, CHANGE_BACKGROUND_COLOR); } }); final Button toggleMoveBackgroundFileButton = (Button) layout.findViewById(R.id.toggleMoveBackgroundFileButton); if (mMoveBackground) { toggleMoveBackgroundFileButton.setText("Move Background (file) : Yes"); } else { toggleMoveBackgroundFileButton.setText("Move Background (file) : No"); } toggleMoveBackgroundFileButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mMoveBackground = mMoveBackground ? false : true; if (mMoveBackground) { toggleMoveBackgroundFileButton.setText("Move Background (file) : Yes"); } else { toggleMoveBackgroundFileButton.setText("Move Background (file) : No"); } } }); final Button backgroundFileButton = (Button) layout.findViewById(R.id.backgroundFileButton); backgroundFileButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { selectBackgroundFile(); } }); mBackgroundWidthText = (TextView) layout.findViewById(R.id.backgroundWidthText); mBackgroundHeightText = (TextView) layout.findViewById(R.id.backgroundHeightText); if (mGsb.getBackgroundImage() != null) { mBackgroundWidthText.setText("Width (" + mGsb.getBackgroundImage().getWidth() + ")"); mBackgroundHeightText.setText("Height (" + mGsb.getBackgroundImage().getHeight() + ")"); } mBackgroundWidthInput = (EditText) layout.findViewById(R.id.backgroundWidthInput); mBackgroundWidthInput.setText(Float.toString(mGsb.getBackgroundWidth())); mBackgroundHeightInput = (EditText) layout.findViewById(R.id.backgroundHeightInput); mBackgroundHeightInput.setText(Float.toString(mGsb.getBackgroundHeight())); final CheckBox scaleWidthHeight = (CheckBox) layout.findViewById(R.id.scaleWidthHeightCheckBox); scaleWidthHeight.setChecked(true); scaleWidthHeight.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { // Calculate a new scale mWidthHeightScale = Float.valueOf(mBackgroundWidthInput.getText().toString()).floatValue() / Float.valueOf(mBackgroundHeightInput.getText().toString()).floatValue(); } catch(NumberFormatException nfe) {Log.e(TAG, "Unable to calculate width and height scale", nfe);} } }); mWidthHeightScale = mGsb.getBackgroundWidth() / mGsb.getBackgroundHeight(); mBackgroundWidthInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf( mBackgroundWidthInput.getText().toString()).floatValue(); mBackgroundHeightInput.setText( Float.valueOf(value/mWidthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); mBackgroundHeightInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf( mBackgroundHeightInput.getText().toString()).floatValue(); mBackgroundWidthInput.setText( Float.valueOf(value*mWidthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Board settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; mGsb.setUseBackgroundImage(checkUseBackgroundImage.isChecked()); try { mGsb.setBackgroundWidth(Float.valueOf(mBackgroundWidthInput.getText().toString()).floatValue()); mGsb.setBackgroundHeight(Float.valueOf(mBackgroundHeightInput.getText().toString()).floatValue()); } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mBoardHistory.createHistoryCheckpoint(mGsb); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { mBackgroundDialog = null; } }); mBackgroundDialog = builder.create(); mBackgroundDialog.show(); } else if (item == 2) { AlertDialog.Builder resetBuilder = new AlertDialog.Builder( BoardEditor.this); resetBuilder.setTitle("Change board icon"); resetBuilder.setMessage("You can change icon for this board.\n\n" + "You need a png image:\n " + mSbDir + "/" + mBoardName + "/" + "icon.png\n\n" + "Recommended size is about 80x80 pixels."); AlertDialog resetAlert = resetBuilder.create(); resetAlert.show(); } else if (item == 3) { final CharSequence[] items = {"Portrait", "Landscape", "Hybrid (beta)"}; AlertDialog.Builder orientationBuilder = new AlertDialog.Builder(BoardEditor.this); orientationBuilder.setTitle("Select orientation"); orientationBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0 && mGsbp.getOrientationMode() != GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_PORTRAIT) { if (mGsbp.getOrientationMode() == GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_HYBRID) { useOrientationAndAskToRemoveUnusedAlert(GraphicalSoundboard.SCREEN_ORIENTATION_PORTRAIT); } else { if (mGsbp.boardWithOrientationExists(GraphicalSoundboard.SCREEN_ORIENTATION_PORTRAIT)) { orientationTurningConflictActionAlert(GraphicalSoundboard.SCREEN_ORIENTATION_PORTRAIT); } else { orientationTurningAlert(GraphicalSoundboard.SCREEN_ORIENTATION_PORTRAIT); } } } else if (item == 1 && mGsbp.getOrientationMode() != GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_LANDSCAPE) { if (mGsbp.getOrientationMode() == GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_HYBRID) { useOrientationAndAskToRemoveUnusedAlert(GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE); } else { if (mGsbp.boardWithOrientationExists(GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE)) { orientationTurningConflictActionAlert(GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE); } else { orientationTurningAlert(GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE); } } } else if (item == 2 && mGsbp.getOrientationMode() != GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_HYBRID) { hybridAlert(); } } }); AlertDialog orientationAlert = orientationBuilder.create(); orientationAlert.show(); } else if (item == 4) { //Auto-arrange LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout. graphical_soundboard_editor_alert_auto_arrange, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkEnableAutoArrange = (CheckBox) layout.findViewById(R.id.enableAutoArrange); checkEnableAutoArrange.setChecked(mGsb.getAutoArrange()); final EditText columnsInput = (EditText) layout.findViewById(R.id.columnsInput); columnsInput.setText(Integer.toString(mGsb.getAutoArrangeColumns())); final EditText rowsInput = (EditText) layout.findViewById(R.id.rowsInput); rowsInput.setText(Integer.toString(mGsb.getAutoArrangeRows())); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Board settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { int columns = Integer.valueOf( columnsInput.getText().toString()).intValue(); int rows = Integer.valueOf( rowsInput.getText().toString()).intValue(); if (mGsb.getSoundList().size() <= columns*rows || !checkEnableAutoArrange.isChecked()) { if (mGsb.getAutoArrange() != checkEnableAutoArrange.isChecked() || mGsb.getAutoArrangeColumns() != columns || mGsb.getAutoArrangeRows() != rows) { mGsb.setAutoArrange(checkEnableAutoArrange.isChecked()); mGsb.setAutoArrangeColumns(columns); mGsb.setAutoArrangeRows(rows); } } else { Toast.makeText(getApplicationContext(), "Not enought slots", Toast.LENGTH_SHORT).show(); } mBoardHistory.createHistoryCheckpoint(mGsb); } catch(NumberFormatException nfe) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 5) { ArrayList<String> itemArray = new ArrayList<String>(); final int extraItemCount = 1; itemArray.add("> Background image"); for (GraphicalSound sound : mGsb.getSoundList()) { itemArray.add(sound.getName()); } CharSequence[] items = itemArray.toArray(new CharSequence[itemArray.size()]); AlertDialog.Builder resetBuilder = new AlertDialog.Builder( BoardEditor.this); resetBuilder.setTitle("Reset position"); resetBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { // Background mGsb.setBackgroundX(0); mGsb.setBackgroundY(0); mBoardHistory.createHistoryCheckpoint(mGsb); } else { // Sound GraphicalSound sound = mGsb.getSoundList().get(item - extraItemCount); sound.setNameFrameX(50); sound.setNameFrameY(50); sound.generateImageXYFromNameFrameLocation(); mBoardHistory.createHistoryCheckpoint(mGsb); } } }); AlertDialog resetAlert = resetBuilder.create(); resetAlert.show(); } } }); AlertDialog setAsAlert = setAsBuilder.create(); setAsAlert.show(); return true; default: return super.onOptionsItemSelected(item); } } public void changeBoard(GraphicalSoundboard gsb, boolean overrideCurrentBoard) { GraphicalSoundboard lastGsb = mGsb; boolean samePage = lastGsb != null && (gsb.getPageNumber() == lastGsb.getPageNumber() && gsb.getScreenOrientation() == lastGsb.getScreenOrientation()); if (!samePage) { loadBoard(gsb); mPageDrawer.switchPage(gsb); if (overrideCurrentBoard) { GraphicalSoundboard.unloadImages(lastGsb); mGsbp.overrideBoard(lastGsb); } refreshPageTitle(); int boardId = gsb.getId(); BoardHistory boardHistory = mBoardHistoryProvider.getBoardHistory(boardId); if (boardHistory == null) { boardHistory = mBoardHistoryProvider.createBoardHistory(boardId, gsb); } this.mBoardHistory = boardHistory; } else { Log.v(TAG, "Won't change page to same page."); } } public void refreshPageTitle() { setTitle(mBoardName + " - " + (mGsb.getPageNumber()+1)); } public void loadBoard(GraphicalSoundboard gsb) { GraphicalSoundboard.loadImages(this.getApplicationContext(), mToastHandler, gsb); mGsb = gsb; } private void orientationTurningConflictActionAlert(final int screenOrientation) { String orientationName = GraphicalSoundboard.getOrientationName(screenOrientation); String oppositeOrientationName = GraphicalSoundboard.getOppositeOrientationName(screenOrientation); AlertDialog.Builder orientationWarningBuilder = new AlertDialog.Builder(BoardEditor.this); orientationWarningBuilder.setTitle("Conflicting board"); orientationWarningBuilder.setMessage( "A board for " + orientationName + " orientation already exists. You can either use it or remove it.\n\n" + "By removing it you can turn " + oppositeOrientationName + " board to " + orientationName + " orientation.\n\n"); orientationWarningBuilder.setPositiveButton("Remove board", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsbp.deleteBoardWithOrientation(screenOrientation); orientationTurningAlert(screenOrientation); } }); orientationWarningBuilder.setNegativeButton("Use board", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsbp.setOrientationMode(screenOrientation); useOrientationAndAskToRemoveUnusedAlert(screenOrientation); } }); AlertDialog orientationWarningAlert = orientationWarningBuilder.create(); orientationWarningAlert.show(); } private void orientationTurningAlert(final int screenOrientation) { AlertDialog.Builder orientationWarningBuilder = new AlertDialog.Builder( BoardEditor.this); orientationWarningBuilder.setTitle("Changing orientation"); orientationWarningBuilder.setMessage( "Changing screen orientation will delete all position data if you don't " + "select deny.\n\n" + "Proceed?"); orientationWarningBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsb.setBackgroundX(0); mGsb.setBackgroundY(0); for(GraphicalSound sound : mGsb.getSoundList()) { sound.setNameFrameX(50); sound.setNameFrameY(50); sound.generateImageXYFromNameFrameLocation(); } mGsbp.setOrientationMode(screenOrientation); mGsb.setScreenOrientation(screenOrientation); finishBoard(); } }); orientationWarningBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); orientationWarningBuilder.setNeutralButton("Deny", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsbp.setOrientationMode(screenOrientation); mGsb.setScreenOrientation(screenOrientation); finishBoard(); } }); AlertDialog orientationWarningAlert = orientationWarningBuilder.create(); orientationWarningAlert.show(); } private void hybridAlert() { AlertDialog.Builder orientationWarningBuilder = new AlertDialog.Builder( BoardEditor.this); orientationWarningBuilder.setTitle("Hybrid mode"); orientationWarningBuilder.setMessage( "Hybrid mode allows you to switch between portrait and landscape by turning the screen.\n\n" + "However both orientations must be created and maintained separately.\n\n" + "Proceed?"); orientationWarningBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsbp.setOrientationMode(GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_HYBRID); finishBoard(); } }); orientationWarningBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog orientationWarningAlert = orientationWarningBuilder.create(); orientationWarningAlert.show(); } private void useOrientationAndAskToRemoveUnusedAlert(final int screenOrientation) { final int oppositeOrientation = GraphicalSoundboard.getOppositeOrientation(screenOrientation); AlertDialog.Builder orientationWarningBuilder = new AlertDialog.Builder( BoardEditor.this); orientationWarningBuilder.setTitle("Unused board"); orientationWarningBuilder.setMessage( "Do you want to delete unused board in " + GraphicalSoundboard.getOrientationName(oppositeOrientation) + " orientation?\n\n"); orientationWarningBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //mThread.setRunning(false); // TODO handle board deleting better mGsb = mPagination.getBoard(screenOrientation); mGsbp.deleteBoardWithOrientation(oppositeOrientation); mGsbp.setOrientationMode(screenOrientation); finishBoard(); } }); orientationWarningBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsbp.setOrientationMode(screenOrientation); finishBoard(); } }); AlertDialog orientationWarningAlert = orientationWarningBuilder.create(); orientationWarningAlert.show(); } private void finishBoard() { try { BoardEditor.this.finish(); } catch (Throwable e) { Log.e(TAG, "Error closing board", e); } } private void selectBackgroundFile() { Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_SELECT_BACKGROUND_FILE); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_BACKGROUD); } private void selectImageFile() { Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_SELECT_SOUND_IMAGE_FILE); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_SOUND_IMAGE); } private void selectActiveImageFile() { Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_SELECT_SOUND_ACTIVE_IMAGE_FILE); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_SOUND_ACTIVE_IMAGE); } @Override protected void onActivityResult(int requestCode, int resultCode, final Intent intent) { super.onActivityResult(requestCode, resultCode, intent); switch(requestCode) { case EXPLORE_SOUND: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); XStream xstream = XStreamUtil.graphicalBoardXStream(); GraphicalSound sound = (GraphicalSound) xstream.fromXML(extras.getString(FileExplorer.ACTION_ADD_GRAPHICAL_SOUND)); sound.setImage(BitmapFactory.decodeResource(getResources(), R.drawable.sound)); sound.setAutoArrangeColumn(0); sound.setAutoArrangeRow(0); if (mGsb.getAutoArrange()) { if (placeToFreeSlot(sound)) { mGsb.getSoundList().add(sound); } } else { placeToFreeSpace(sound); mGsb.getSoundList().add(sound); } mBoardHistory.createHistoryCheckpoint(mGsb); } break; case EXPLORE_BACKGROUD: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); File background = new File(extras.getString(FileExplorer.ACTION_SELECT_BACKGROUND_FILE)); mGsb.setBackgroundImagePath(background); mGsb.setBackgroundImage(ImageDrawing.decodeFile(mToastHandler, mGsb.getBackgroundImagePath())); mGsb.setBackgroundWidth(mGsb.getBackgroundImage().getWidth()); mGsb.setBackgroundHeight(mGsb.getBackgroundImage().getHeight()); mGsb.setBackgroundX(0); mGsb.setBackgroundY(0); mBoardHistory.createHistoryCheckpoint(mGsb); } if (mBackgroundDialog != null && mGsb.getBackgroundImage() != null) { mBackgroundWidthText.setText("Width (" + mGsb.getBackgroundImage().getWidth() + ")"); mBackgroundHeightText.setText("Height (" + mGsb.getBackgroundImage().getHeight() + ")"); mBackgroundWidthInput.setText(Float.toString(mGsb.getBackgroundWidth())); mBackgroundHeightInput.setText(Float.toString(mGsb.getBackgroundHeight())); } break; case EXPLORE_SOUND_IMAGE: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); File image = new File(extras.getString(FileExplorer.ACTION_SELECT_SOUND_IMAGE_FILE)); mPressedSound.setImagePath(image); mPressedSound.setImage(ImageDrawing.decodeFile(mToastHandler, mPressedSound.getImagePath())); } if (mSoundImageDialog != null) { mSoundImageWidthText.setText("Width (" + mPressedSound.getImage().getWidth() + ")"); mSoundImageHeightText.setText("Height (" + mPressedSound.getImage().getHeight() + ")"); mSoundImageWidthInput.setText(Float.toString(mPressedSound.getImage().getWidth())); mSoundImageHeightInput.setText(Float.toString(mPressedSound.getImage().getHeight())); } break; case EXPLORE_SOUND_ACTIVE_IMAGE: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); File image = new File(extras.getString(FileExplorer.ACTION_SELECT_SOUND_ACTIVE_IMAGE_FILE)); mPressedSound.setActiveImagePath(image); mPressedSound.setActiveImage(ImageDrawing.decodeFile(mToastHandler, mPressedSound.getActiveImagePath())); } break; case CHANGE_NAME_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); if (extras.getBoolean("copyKey")) { mCopyColor = CHANGE_NAME_COLOR; } else { mPressedSound.setNameTextColorInt(extras.getInt("colorKey")); } } break; case CHANGE_INNER_PAINT_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); if (extras.getBoolean("copyKey")) { mCopyColor = CHANGE_INNER_PAINT_COLOR; } else { mPressedSound.setNameFrameInnerColorInt(extras.getInt("colorKey")); } } break; case CHANGE_BORDER_PAINT_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); if (extras.getBoolean("copyKey")) { mCopyColor = CHANGE_BORDER_PAINT_COLOR; } else { mPressedSound.setNameFrameBorderColorInt(extras.getInt("colorKey")); } } break; case CHANGE_BACKGROUND_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); mGsb.setBackgroundColor(extras.getInt("colorKey")); mBoardHistory.createHistoryCheckpoint(mGsb); } break; case CHANGE_SOUND_PATH: if (resultCode == RESULT_OK) { LayoutInflater removeInflater = (LayoutInflater) BoardEditor.this.getSystemService(LAYOUT_INFLATER_SERVICE); View removeLayout = removeInflater.inflate( R.layout.graphical_soundboard_editor_alert_remove_sound, (ViewGroup) findViewById(R.id.alert_remove_sound_root)); final CheckBox removeFileCheckBox = (CheckBox) removeLayout.findViewById(R.id.removeFile); removeFileCheckBox.setText(" DELETE " + mPressedSound.getPath().getAbsolutePath()); AlertDialog.Builder removeBuilder = new AlertDialog.Builder( BoardEditor.this); removeBuilder.setView(removeLayout); removeBuilder.setTitle("Changing sound"); removeBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (removeFileCheckBox.isChecked() == true) { mPressedSound.getPath().delete(); } Bundle extras = intent.getExtras(); mPressedSound.setPath(new File(extras.getString(FileExplorer.ACTION_CHANGE_SOUND_PATH))); } }); removeBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); removeBuilder.setCancelable(false); removeBuilder.show(); } break; default: break; } } private void initializeConvert() { mWaitDialog = ProgressDialog.show(BoardEditor.this, "", "Please wait", true); Thread t = new Thread() { public void run() { Looper.prepare(); try { if (mClearBoardDir) { cleanDirectory(new File(mSbDir, mBoardName).listFiles()); } FileProcessor.convertGraphicalBoard(BoardEditor.this, mBoardName, mGsb); save(); } catch (IOException e) { Log.e(TAG, "Error converting board", e); } mHandler.post(mUpdateResults); } }; t.start(); } private void cleanDirectory(File[] files) { for (File file : files) { if (file.isDirectory()) { cleanDirectory(file.listFiles()); if (file.listFiles().length == 0) { Log.d(TAG, "Deleting empty directory " + file.getAbsolutePath()); file.delete(); } } else { boolean boardUsesFile = false; if (file.getName().equals("graphicalBoard") == true || file.getName().equals("icon.png") == true) { boardUsesFile = true; } try { if (file.getName().equals(mGsb.getBackgroundImagePath().getName())) boardUsesFile = true; } catch (NullPointerException e) {} for (GraphicalSound sound : mGsb.getSoundList()) { if (boardUsesFile) break; try { if (sound.getPath().getAbsolutePath().equals(file.getAbsolutePath())) boardUsesFile = true; } catch (NullPointerException e) {} try { if (sound.getImagePath().getAbsolutePath().equals(file.getAbsolutePath())) boardUsesFile = true; } catch (NullPointerException e) {} try { if (sound.getActiveImagePath().getAbsolutePath().equals(file.getAbsolutePath())) boardUsesFile = true; } catch (NullPointerException e) {} } if (boardUsesFile == false) { Log.d(TAG, "Deleting unused file " + file.getAbsolutePath()); file.delete(); } } } } final Runnable mUpdateResults = new Runnable() { public void run() { mWaitDialog.dismiss(); } }; @Override public void onConfigurationChanged(Configuration newConfig) { int newOrientation = OrientationUtil.getBoarderOrientation(newConfig); if (newOrientation != this.mCurrentOrientation) { this.mCurrentOrientation = newOrientation; GraphicalSoundboard newOrientationGsb = mPagination.getBoard(newOrientation); changeBoard(newOrientationGsb, true); // Set resolution handling stuff for the new orientation if (mResolutionAlert != null) { mResolutionAlert.dismiss(); } mPanelInitialized = false; } super.onConfigurationChanged(newConfig); } @Override protected void onResume() { super.onResume(); mToastHandler = new ToastHandler(getApplicationContext()); setContentView(mPanel); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override protected void onPause() { save(); super.onPause(); } @Override protected void onDestroy() { GraphicalSoundboard.unloadImages(mGsb); super.onDestroy(); } private void save() { if (mBoardName != null) { try { GraphicalSoundboard gsb = GraphicalSoundboard.copy(mGsb); if (mPressedSound != null && mCurrentGesture == TouchGesture.DRAG) gsb.getSoundList().add(mPressedSound); // Sound is being dragged mGsbp.overrideBoard(gsb); mGsbp.saveBoard(mBoardName); Log.v(TAG, "Board " + mBoardName + " saved"); } catch (IOException e) { Log.e(TAG, "Unable to save " + mBoardName, e); } } } private void playTouchedSound(GraphicalSound sound) { if (sound.getPath().getAbsolutePath().equals(SoundboardMenu.mPauseSoundFilePath)) { SoundPlayerControl.togglePlayPause(this.getApplicationContext()); } else { if (sound.getSecondClickAction() == GraphicalSound.SECOND_CLICK_PLAY_NEW) { SoundPlayerControl.playSound(mGsb.getPlaySimultaneously(), sound.getPath(), sound.getVolumeLeft(), sound.getVolumeRight(), mGsb.getBoardVolume()); } else if (sound.getSecondClickAction() == GraphicalSound.SECOND_CLICK_PAUSE) { SoundPlayerControl.pauseSound(mGsb.getPlaySimultaneously(), sound.getPath(), sound.getVolumeLeft(), sound.getVolumeRight(), mGsb.getBoardVolume()); } else if (sound.getSecondClickAction() == GraphicalSound.SECOND_CLICK_STOP) { SoundPlayerControl.stopSound(mGsb.getPlaySimultaneously(), sound.getPath(), sound.getVolumeLeft(), sound.getVolumeRight(), mGsb.getBoardVolume()); } mCanvasInvalidated = true; } } private void initializeDrag(float initTouchEventX, float initTouchEventY, GraphicalSound sound) { mPressedSound = sound; mCurrentGesture = TouchGesture.DRAG; mInitialNameFrameX = sound.getNameFrameX(); mInitialNameFrameY = sound.getNameFrameY(); mInitialImageX = sound.getImageX(); mInitialImageY = sound.getImageY(); mGsb.getSoundList().remove(sound); mNameFrameDragDistanceX = initTouchEventX - sound.getNameFrameX(); mNameFrameDragDistanceY = initTouchEventY - sound.getNameFrameY(); mImageDragDistanceX = initTouchEventX - sound.getImageX(); mImageDragDistanceY = initTouchEventY - sound.getImageY(); } private void copyColor(GraphicalSound sound) { switch(mCopyColor) { case CHANGE_NAME_COLOR: mPressedSound.setNameTextColorInt(sound.getNameTextColor()); break; case CHANGE_INNER_PAINT_COLOR: mPressedSound.setNameFrameInnerColorInt(sound.getNameFrameInnerColor()); break; case CHANGE_BORDER_PAINT_COLOR: mPressedSound.setNameFrameBorderColorInt(sound.getNameFrameBorderColor()); break; } mCopyColor = 0; mBoardHistory.createHistoryCheckpoint(mGsb); } void moveSound(float X, float Y) { if (mPressedSound.getLinkNameAndImage() || mDragTarget == DRAG_TEXT) { mPressedSound.setNameFrameX(X-mNameFrameDragDistanceX); mPressedSound.setNameFrameY(Y-mNameFrameDragDistanceY); } if (mPressedSound.getLinkNameAndImage() || mDragTarget == DRAG_IMAGE) { mPressedSound.setImageX(X-mImageDragDistanceX); mPressedSound.setImageY(Y-mImageDragDistanceY); } } public void moveSoundToSlot(GraphicalSound sound, int column, int row, float imageX, float imageY, float nameX, float nameY) { int width = mPanel.getWidth(); int height = mPanel.getHeight(); float middlePointX = width/mGsb.getAutoArrangeColumns()/2; float middlePointY = height/mGsb.getAutoArrangeRows()/2; float lowPointX; float highPointX; float lowPointY; float highPointY; boolean moveName = false; boolean moveImage = false; SoundNameDrawing soundNameDrawing = new SoundNameDrawing(sound); float nameFrameWidth = soundNameDrawing.getNameFrameRect().width(); float nameFrameHeight = soundNameDrawing.getNameFrameRect().height(); if (sound.getHideImageOrText() == GraphicalSound.HIDE_TEXT) { lowPointX = imageX; highPointX = imageX+sound.getImageWidth(); lowPointY = imageY; highPointY = imageY+sound.getImageHeight(); moveImage = true; } else if (sound.getHideImageOrText() == GraphicalSound.HIDE_IMAGE) { lowPointX = nameX; highPointX = nameX+nameFrameWidth; lowPointY = nameY; highPointY = nameY+nameFrameHeight; moveName = true; } else { lowPointX = imageX < nameX ? imageX : nameX; highPointX = imageX+sound.getImageWidth() > nameX+nameFrameWidth ? imageX+sound.getImageWidth() : nameX+nameFrameWidth; lowPointY = imageY < nameY ? imageY : nameY; highPointY = imageY+sound.getImageHeight() > nameY+nameFrameHeight ? imageY+sound.getImageHeight() : nameY+nameFrameHeight; moveImage = true; moveName = true; } float xPoint = (highPointX-lowPointX)/2; float imageDistanceX = imageX-(lowPointX+xPoint); float nameDistanceX = nameX-(lowPointX+xPoint); float yPoint = (highPointY-lowPointY)/2; float imageDistanceY = imageY-(lowPointY+yPoint); float nameDistanceY = nameY-(lowPointY+yPoint); float slotX = column*(width/mGsb.getAutoArrangeColumns()); float slotY = row*(height/mGsb.getAutoArrangeRows()); if (moveImage) { sound.setImageX(slotX+middlePointX+imageDistanceX); sound.setImageY(slotY+middlePointY+imageDistanceY); } if (moveName) { sound.setNameFrameX(slotX+middlePointX+nameDistanceX); sound.setNameFrameY(slotY+middlePointY+nameDistanceY); } sound.setAutoArrangeColumn(column); sound.setAutoArrangeRow(row); mBoardHistory.createHistoryCheckpoint(mGsb); } public boolean placeToFreeSlot(GraphicalSound sound) { try { Slot slot = AutoArrange.getFreeSlot(mGsb.getSoundList(), mGsb.getAutoArrangeColumns(), mGsb.getAutoArrangeRows()); moveSoundToSlot(sound, slot.getColumn(), slot.getRow(), sound.getImageX(), sound.getImageY(), sound.getNameFrameX(), sound.getNameFrameY()); return true; } catch (NullPointerException e) { Toast.makeText(getApplicationContext(), "No slot available", Toast.LENGTH_SHORT).show(); return false; } } public void placeToFreeSpace(GraphicalSound sound) { boolean spaceAvailable = true; float freeSpaceX = 0; float freeSpaceY = 0; int width = mPanel.getWidth(); int height = mPanel.getHeight(); while (freeSpaceY + sound.getImageHeight() < height) { spaceAvailable = true; for (GraphicalSound spaceEater : mGsb.getSoundList()) { if (((freeSpaceX >= spaceEater.getImageX() && freeSpaceX <= spaceEater.getImageX()+spaceEater.getImageWidth()) || freeSpaceX+sound.getImageWidth() >= spaceEater.getImageX() && freeSpaceX+sound.getImageWidth() <= spaceEater.getImageX()+spaceEater.getImageWidth()) && (freeSpaceY >= spaceEater.getImageY() && freeSpaceY <= spaceEater.getImageY()+spaceEater.getImageHeight() || freeSpaceY+sound.getImageHeight() >= spaceEater.getImageY() && freeSpaceY+sound.getImageHeight() <= spaceEater.getImageY()+spaceEater.getImageHeight())) { spaceAvailable = false; break; } } if (spaceAvailable) { sound.setImageX(freeSpaceX); sound.setImageY(freeSpaceY); sound.generateNameFrameXYFromImageLocation(); break; } freeSpaceX = freeSpaceX + 5; if (freeSpaceX + sound.getImageWidth() >= width) { freeSpaceX = 0; freeSpaceY = freeSpaceY + 5; } } if (!spaceAvailable) { sound.setNameFrameX(10); sound.setNameFrameY(sound.getImageHeight()+10); sound.generateImageXYFromNameFrameLocation(); } } public boolean onTrackballEvent (MotionEvent event) { if (mMode == EDIT_BOARD && event.getAction() == MotionEvent.ACTION_MOVE && mPressedSound != null && (mLastTrackballEvent == 0 || System.currentTimeMillis() - mLastTrackballEvent > 500)) { mLastTrackballEvent = System.currentTimeMillis(); int movementX = 0; int movementY = 0; if (event.getX() > 0) { movementX = 1; } else if (event.getX() < 0) { movementX = -1; }else if (event.getY() > 0) { movementY = 1; } else if (event.getY() < 0) { movementY = -1; } if (mPressedSound.getLinkNameAndImage() || mDragTarget == DRAG_TEXT) { mPressedSound.setNameFrameX(mPressedSound.getNameFrameX() + movementX); mPressedSound.setNameFrameY(mPressedSound.getNameFrameY() + movementY); } if (mPressedSound.getLinkNameAndImage() || mDragTarget == DRAG_IMAGE) { mPressedSound.setImageX(mPressedSound.getImageX() + movementX); mPressedSound.setImageY(mPressedSound.getImageY() + movementY); } mBoardHistory.setHistoryCheckpoint(mGsb); return true; } else { return false; } } public void issueResolutionConversion() { Thread t = new Thread() { public void run() { Looper.prepare(); final int windowWidth = mPanel.getWidth(); final int windowHeight = mPanel.getHeight(); if (mGsb.getScreenHeight() == 0 || mGsb.getScreenWidth() == 0) { mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } else if (mGsb.getScreenWidth() != windowWidth || mGsb.getScreenHeight() != windowHeight) { Log.v(TAG, "Soundoard resolution has changed. X: " + mGsb.getScreenWidth() + " -> " + windowWidth + " - Y: " + mGsb.getScreenHeight() + " -> " + windowHeight); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setTitle("Display size"); builder.setMessage("Display size used to make this board differs from your display size.\n\n" + "You can resize this board to fill your display or " + "fit this board to your display. Fit looks accurately like the original one.\n\n" + "(Ps. In 'Edit board' mode you can undo this.)"); builder.setPositiveButton("Resize", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.v(TAG, "Resizing board"); clearBlackBars(); float xScale = (float) windowWidth/(float) (mGsb.getScreenWidth()); float yScale = (float) windowHeight/(float) (mGsb.getScreenHeight()); float avarageScale = xScale+(yScale-xScale)/2; Log.v(TAG, "X scale: \"" + xScale + "\"" + ", old width: \""+mGsb.getScreenWidth() + "\", new width: \"" + windowWidth + "\""); Log.v(TAG, "Y scale: \"" + yScale + "\"" + ", old height: \""+mGsb.getScreenHeight() + "\", new height: \"" + windowHeight + "\""); Log.v(TAG, "Avarage scale: \"" + avarageScale + "\""); mGsb.setBackgroundX(mGsb.getBackgroundX()*xScale); mGsb.setBackgroundY(mGsb.getBackgroundY()*yScale); mGsb.setBackgroundWidth(mGsb.getBackgroundWidth()*xScale); mGsb.setBackgroundHeight(mGsb.getBackgroundHeight()*yScale); for (GraphicalSound sound : mGsb.getSoundList()) { sound = SoundNameDrawing.getScaledTextSize(sound, avarageScale); sound.setNameFrameX(sound.getNameFrameX()*xScale); sound.setNameFrameY(sound.getNameFrameY()*yScale); sound.setImageX(sound.getImageX()*xScale); sound.setImageY(sound.getImageY()*yScale); sound.setImageWidth(sound.getImageWidth()*avarageScale); sound.setImageHeight(sound.getImageHeight()*avarageScale); if (sound.getLinkNameAndImage()) sound.generateNameFrameXYFromImageLocation(); } mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } }); builder.setNeutralButton("Fit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.v(TAG, "Fitting board"); clearBlackBars(); float xScale = (float) (windowWidth)/(float) (mGsb.getScreenWidth()); float yScale = (float) (windowHeight)/(float) (mGsb.getScreenHeight()); boolean xFillsDisplay = xScale < yScale; float applicableScale = (xScale < yScale) ? xScale : yScale; float hiddenAreaSize; if (xFillsDisplay) { hiddenAreaSize = ((float) windowHeight-(float) mGsb.getScreenHeight()*applicableScale)/2; } else { hiddenAreaSize = ((float) windowWidth-(float) mGsb.getScreenWidth()*applicableScale)/2; } Log.v(TAG, "X scale: \"" + xScale + "\"" + ", old width: \""+mGsb.getScreenWidth() + "\", new width: \"" + windowWidth + "\""); Log.v(TAG, "Y scale: \"" + yScale + "\"" + ", old height: \""+mGsb.getScreenHeight() + "\", new height: \"" + windowHeight + "\""); Log.v(TAG, "Applicable scale: \"" + applicableScale + "\""); Log.v(TAG, "Hidden area size: \"" + hiddenAreaSize + "\""); mGsb.setBackgroundWidth(mGsb.getBackgroundWidth()*applicableScale); mGsb.setBackgroundHeight(mGsb.getBackgroundHeight()*applicableScale); if (xFillsDisplay) { mGsb.setBackgroundX(mGsb.getBackgroundX()*applicableScale); mGsb.setBackgroundY(hiddenAreaSize+mGsb.getBackgroundY()*applicableScale); } else { mGsb.setBackgroundX(hiddenAreaSize+mGsb.getBackgroundX()*applicableScale); mGsb.setBackgroundY(mGsb.getBackgroundY()*applicableScale); } for (GraphicalSound sound : mGsb.getSoundList()) { sound = SoundNameDrawing.getScaledTextSize(sound, applicableScale); if (xFillsDisplay) { sound.setNameFrameX(sound.getNameFrameX()*applicableScale); sound.setNameFrameY(hiddenAreaSize+sound.getNameFrameY()*applicableScale); sound.setImageX(sound.getImageX()*applicableScale); sound.setImageY(hiddenAreaSize+sound.getImageY()*applicableScale); } else { Log.w(TAG, "sound: " + sound.getName()); Log.w(TAG, "hiddenAreaSize: " + hiddenAreaSize + " sound.getNameFrameX(): " + sound.getNameFrameX() + " applicableScale: " + applicableScale); Log.w(TAG, "hiddenAreaSize+sound.getNameFrameX()*applicableScale: " + (hiddenAreaSize+sound.getNameFrameX()*applicableScale)); sound.setNameFrameX(hiddenAreaSize+sound.getNameFrameX()*applicableScale); sound.setNameFrameY(sound.getNameFrameY()*applicableScale); sound.setImageX(hiddenAreaSize+sound.getImageX()*applicableScale); sound.setImageY(sound.getImageY()*applicableScale); } sound.setImageWidth(sound.getImageWidth()*applicableScale); sound.setImageHeight(sound.getImageHeight()*applicableScale); if (sound.getLinkNameAndImage()) sound.generateNameFrameXYFromImageLocation(); } GraphicalSound blackBar1 = new GraphicalSound(); blackBar1.setNameFrameInnerColor(255, 0, 0, 0); GraphicalSound blackBar2 = new GraphicalSound(); blackBar2.setNameFrameInnerColor(255, 0, 0, 0); if (xFillsDisplay) { blackBar1.setName("I hide top of the board."); blackBar2.setName("I hide bottom of the board."); blackBar1.setPath(new File(SoundboardMenu.mTopBlackBarSoundFilePath)); blackBar2.setPath(new File(SoundboardMenu.mBottomBlackBarSoundFilePath)); blackBar1.setNameFrameY(hiddenAreaSize); blackBar2.setNameFrameY((float) windowHeight-hiddenAreaSize); } else { blackBar1.setName("I hide left side of the board."); blackBar2.setName("I hide right side of the board."); blackBar1.setPath(new File(SoundboardMenu.mLeftBlackBarSoundFilePath)); blackBar2.setPath(new File(SoundboardMenu.mRightBlackBarSoundFilePath)); blackBar1.setNameFrameX(hiddenAreaSize); blackBar2.setNameFrameX((float) windowWidth-hiddenAreaSize); } mGsb.addSound(blackBar1); mGsb.addSound(blackBar2); mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } }); builder.setNegativeButton("Keep", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } }); mResolutionAlert = builder.create(); mResolutionAlert.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { mResolutionAlert = null; mBoardHistory.createHistoryCheckpoint(mGsb); } }); mResolutionAlert.show(); } Looper.loop(); Looper.myLooper().quit(); } }; t.start(); } private void clearBlackBars() { ListIterator<GraphicalSound> iterator = mGsb.getSoundList().listIterator(); while (iterator.hasNext()) { GraphicalSound sound = iterator.next(); if (sound.getPath().getAbsolutePath().equals(SoundboardMenu.mTopBlackBarSoundFilePath) || sound.getPath().getAbsolutePath().equals(SoundboardMenu.mBottomBlackBarSoundFilePath)) { mGsb.setScreenHeight(mGsb.getScreenHeight() - Float.valueOf(sound.getImageHeight()).intValue()); iterator.remove(); } else if (sound.getPath().getAbsolutePath().equals(SoundboardMenu.mLeftBlackBarSoundFilePath) || sound.getPath().getAbsolutePath().equals(SoundboardMenu.mRightBlackBarSoundFilePath)) { mGsb.setScreenWidth(mGsb.getScreenWidth() - Float.valueOf(sound.getImageWidth()).intValue()); iterator.remove(); } } } class DrawingPanel extends SurfaceView implements SurfaceHolder.Callback { private float mInitTouchEventX = 0; private float mInitTouchEventY = 0; private long mClickTime = 0; private float mLatestEventX = 0; private float mLatestEventY = 0; Timer mJoystickTimer = null; Object mGestureLock = new Object(); public DrawingPanel(Context context) { super(context); getHolder().addCallback(this); mThread = new DrawingThread(getHolder(), this); mJoystick = new Joystick(context); } private GraphicalSound findPressedSound(MotionEvent pressInitEvent) { GraphicalSound pressedSound = null; ListIterator<GraphicalSound> iterator = mGsb.getSoundList().listIterator(); while (iterator.hasNext()) {iterator.next();} while (iterator.hasPrevious()) { GraphicalSound sound = iterator.previous(); String soundPath = sound.getPath().getAbsolutePath(); SoundNameDrawing soundNameDrawing = new SoundNameDrawing(sound); float nameFrameX = sound.getNameFrameX(); float nameFrameY = sound.getNameFrameY(); float nameFrameWidth = soundNameDrawing.getNameFrameRect().width(); float nameFrameHeight = soundNameDrawing.getNameFrameRect().height(); if (pressInitEvent.getX() >= sound.getImageX() && pressInitEvent.getX() <= sound.getImageWidth() + sound.getImageX() && pressInitEvent.getY() >= sound.getImageY() && pressInitEvent.getY() <= sound.getImageHeight() + sound.getImageY()) { mDragTarget = DRAG_IMAGE; return sound; } else if ((pressInitEvent.getX() >= sound.getNameFrameX() && pressInitEvent.getX() <= nameFrameWidth + sound.getNameFrameX() && pressInitEvent.getY() >= sound.getNameFrameY() && pressInitEvent.getY() <= nameFrameHeight + sound.getNameFrameY()) || soundPath.equals(SoundboardMenu.mTopBlackBarSoundFilePath) && pressInitEvent.getY() <= nameFrameY || soundPath.equals(SoundboardMenu.mBottomBlackBarSoundFilePath) && pressInitEvent.getY() >= nameFrameY || soundPath.equals(SoundboardMenu.mLeftBlackBarSoundFilePath) && pressInitEvent.getX() <= nameFrameX || soundPath.equals(SoundboardMenu.mRightBlackBarSoundFilePath) && pressInitEvent.getX() >= nameFrameX) { mDragTarget = DRAG_TEXT; return sound; } } return pressedSound; } private long holdTime() { return Calendar.getInstance().getTimeInMillis()-mClickTime; } private void updateClickTime() { mClickTime = Calendar.getInstance().getTimeInMillis(); } private void dragEvent(float eventX, float eventY) { if (mFineTuningSound != null) { eventX = mJoystick.dragDistanceX(eventX); eventY = mJoystick.dragDistanceY(eventY); } moveSound(eventX, eventY); } class DragInitializeTimer extends TimerTask { public void run() { synchronized (mGestureLock) { if (mCurrentGesture == TouchGesture.PRESS_BOARD && mMode == EDIT_BOARD) { initializeDrag(mInitTouchEventX, mInitTouchEventY, mPressedSound); vibrator.vibrate(60); } } } } class JoystickTimer extends TimerTask { public void run() { dragEvent(mLatestEventX, mLatestEventY); } } @Override public boolean onTouchEvent(MotionEvent event) { mLatestEventX = event.getX(); mLatestEventY = event.getY(); if (mThread == null) return false; synchronized (mThread.getSurfaceHolder()) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (mMoveBackground) { mBackgroundLeftDistance = event.getX() - mGsb.getBackgroundX(); mBackgroundTopDistance = event.getY() - mGsb.getBackgroundY(); } else if (mFineTuningSound != null) { mInitTouchEventX = event.getX(); mInitTouchEventY = event.getY(); mPressedSound = mFineTuningSound; updateClickTime(); mCurrentGesture = TouchGesture.PRESS_BOARD; new Timer().schedule(new DragInitializeTimer(), 200); mJoystick.init(event); mJoystickTimer = new Timer(); mJoystickTimer.schedule(new JoystickTimer(), 210, 50); } else { mInitTouchEventX = event.getX(); mInitTouchEventY = event.getY(); mPressedSound = findPressedSound(event); updateClickTime(); if (mPressedSound == null) { mCurrentGesture = TouchGesture.PRESS_BLANK; } else { mCurrentGesture = TouchGesture.PRESS_BOARD; vibrator.vibrate(15); new Timer().schedule(new DragInitializeTimer(), DRAG_SWIPE_TIME); } if (mCopyColor != 0) { copyColor(mPressedSound); mPressedSound = null; } } } else if (event.getAction() == MotionEvent.ACTION_MOVE) { if (mMoveBackground) { mGsb.setBackgroundX(event.getX() - mBackgroundLeftDistance); mGsb.setBackgroundY(event.getY() - mBackgroundTopDistance); } else if ((mCurrentGesture == TouchGesture.PRESS_BOARD || // PRESS_BOARD has timed gesture changing (mCurrentGesture == TouchGesture.PRESS_BLANK && holdTime() < DRAG_SWIPE_TIME)) && mFineTuningSound == null) { float swipeTriggerDistance = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30, getResources().getDisplayMetrics()); double distanceFromInit = Math.sqrt( Math.pow((mInitTouchEventX - event.getX()), 2) + Math.pow((mInitTouchEventY - event.getY()), 2)); // hypotenuse synchronized (mGestureLock) { if (distanceFromInit > swipeTriggerDistance) { mCurrentGesture = TouchGesture.SWIPE; GraphicalSoundboard swapGsb = null; if (event.getX() < mInitTouchEventX) { swapGsb = mPagination.getNextBoardPage(mGsb); } else { swapGsb = mPagination.getPreviousPage(mGsb); } if (swapGsb == null) { Toast.makeText(getApplicationContext(), "No page there", Toast.LENGTH_SHORT).show(); } else { changeBoard(swapGsb, true); } } } } else if (mCurrentGesture == TouchGesture.DRAG) { if (mFineTuningSound == null) dragEvent(event.getX(), event.getY()); } } else if (event.getAction() == MotionEvent.ACTION_UP) { synchronized (mGestureLock) { if (mMoveBackground) { mGsb.setBackgroundX(event.getX() - mBackgroundLeftDistance); mGsb.setBackgroundY(event.getY() - mBackgroundTopDistance); mBoardHistory.createHistoryCheckpoint(mGsb); } else if ((mCurrentGesture == TouchGesture.PRESS_BOARD || mFineTuningSound != null) && mMode == EDIT_BOARD && holdTime() < 200) { mCurrentGesture = TouchGesture.TAP; mClickTime = 0; invalidate(); String fineTuningText = (mFineTuningSound == null) ? "on" : "off"; final CharSequence[] items = {"Fine tuning "+fineTuningText, "Info", "Name settings", "Image settings", "Sound settings", "Copy sound", "Remove sound", "Set as..."}; AlertDialog.Builder optionsBuilder = new AlertDialog.Builder(BoardEditor.this); optionsBuilder.setTitle("Options"); optionsBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { if (mFineTuningSound == null) { mFineTuningSound = mPressedSound; } else { mFineTuningSound = null; } } else if (item == 1) { SoundNameDrawing soundNameDrawing = new SoundNameDrawing(mPressedSound); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setTitle("Sound info"); builder.setMessage("Name:\n"+mPressedSound.getName()+ "\n\nSound path:\n"+mPressedSound.getPath()+ "\n\nImage path:\n"+mPressedSound.getImagePath()+ "\n\nActive image path:\n"+mPressedSound.getActiveImagePath()+ "\n\nName and image linked:\n"+mPressedSound.getLinkNameAndImage()+ "\n\nHide image or text:\n"+mPressedSound.getHideImageOrText()+ "\n\nImage X:\n"+mPressedSound.getImageX()+ "\n\nImage Y:\n"+mPressedSound.getImageY()+ "\n\nImage width:\n"+mPressedSound.getImageWidth()+ "\n\nImage height:\n"+mPressedSound.getImageHeight()+ "\n\nName frame X:\n"+mPressedSound.getNameFrameX()+ "\n\nName frame Y:\n"+mPressedSound.getNameFrameY()+ "\n\nName frame width:\n"+soundNameDrawing.getNameFrameRect().width()+ "\n\nName frame height:\n"+soundNameDrawing.getNameFrameRect().height()+ "\n\nAuto arrange column:\n"+mPressedSound.getAutoArrangeColumn()+ "\n\nAuto arrange row:\n"+mPressedSound.getAutoArrangeRow()+ "\n\nSecond click action:\n"+mPressedSound.getSecondClickAction()+ "\n\nLeft volume:\n"+mPressedSound.getVolumeLeft()+ "\n\nRight volume:\n"+mPressedSound.getVolumeRight()+ "\n\nName frame border color:\n"+mPressedSound.getNameFrameBorderColor()+ "\n\nName frame inner color:\n"+mPressedSound.getNameFrameInnerColor()+ "\n\nName text color:\n"+mPressedSound.getNameTextColor()+ "\n\nName text size:\n"+mPressedSound.getNameSize()+ "\n\nShow name frame border paint:\n"+mPressedSound.getShowNameFrameBorderPaint()+ "\n\nShow name frame inner paint:\n"+mPressedSound.getShowNameFrameBorderPaint()); builder.show(); } else if (item == 2) { LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate( R.layout.graphical_soundboard_editor_alert_sound_name_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final EditText soundNameInput = (EditText) layout.findViewById(R.id.soundNameInput); soundNameInput.setText(mPressedSound.getName()); final EditText soundNameSizeInput = (EditText) layout.findViewById(R.id.soundNameSizeInput); soundNameSizeInput.setText(Float.toString(mPressedSound.getNameSize())); final CheckBox checkShowSoundName = (CheckBox) layout.findViewById(R.id.showSoundNameCheckBox); checkShowSoundName.setChecked(mPressedSound.getHideImageOrText() != GraphicalSound.HIDE_TEXT); final CheckBox checkShowInnerPaint = (CheckBox) layout.findViewById(R.id.showInnerPaintCheckBox); checkShowInnerPaint.setChecked(mPressedSound.getShowNameFrameInnerPaint()); final CheckBox checkShowBorderPaint = (CheckBox) layout.findViewById(R.id.showBorderPaintCheckBox); checkShowBorderPaint.setChecked(mPressedSound.getShowNameFrameBorderPaint()); final Button nameColorButton = (Button) layout.findViewById(R.id.nameColorButton); nameColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPressedSound.setName(soundNameInput.getText().toString()); mPressedSound.generateImageXYFromNameFrameLocation(); Intent i = new Intent(BoardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeNameColor"); i.putExtras(XStreamUtil.getSoundBundle(mPressedSound, mGsb)); startActivityForResult(i, CHANGE_NAME_COLOR); } }); final Button innerPaintColorButton = (Button) layout.findViewById(R.id.innerPaintColorButton); innerPaintColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPressedSound.setName(soundNameInput.getText().toString()); mPressedSound.generateImageXYFromNameFrameLocation(); Intent i = new Intent(BoardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeinnerPaintColor"); i.putExtras(XStreamUtil.getSoundBundle(mPressedSound, mGsb)); startActivityForResult(i, CHANGE_INNER_PAINT_COLOR); } }); final Button borderPaintColorButton = (Button) layout.findViewById(R.id.borderPaintColorButton); borderPaintColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPressedSound.setName(soundNameInput.getText().toString()); mPressedSound.generateImageXYFromNameFrameLocation(); Intent i = new Intent(BoardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeBorderPaintColor"); i.putExtras(XStreamUtil.getSoundBundle(mPressedSound, mGsb)); startActivityForResult(i, CHANGE_BORDER_PAINT_COLOR); } }); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Name settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; if (checkShowSoundName.isChecked() == false) { mPressedSound.setHideImageOrText(GraphicalSound.HIDE_TEXT); } else if (checkShowSoundName.isChecked() && mPressedSound.getHideImageOrText() == GraphicalSound.HIDE_TEXT) { mPressedSound.setHideImageOrText(GraphicalSound.SHOW_ALL); mPressedSound.generateImageXYFromNameFrameLocation(); } mPressedSound.setShowNameFrameInnerPaint(checkShowInnerPaint.isChecked()); mPressedSound.setShowNameFrameBorderPaint(checkShowBorderPaint.isChecked()); mPressedSound.setName(soundNameInput.getText().toString()); try { mPressedSound.setNameSize(Float.valueOf( soundNameSizeInput.getText().toString()).floatValue()); } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (mPressedSound.getLinkNameAndImage()) { mPressedSound.generateImageXYFromNameFrameLocation(); } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mBoardHistory.createHistoryCheckpoint(mGsb); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 3) { LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate( R.layout.graphical_soundboard_editor_alert_sound_image_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkShowSoundImage = (CheckBox) layout.findViewById(R.id.showSoundImageCheckBox); checkShowSoundImage.setChecked(mPressedSound.getHideImageOrText() != GraphicalSound.HIDE_IMAGE); mSoundImageWidthText = (TextView) layout.findViewById(R.id.soundImageWidthText); mSoundImageWidthText.setText("Width (" + mPressedSound.getImage().getWidth() + ")"); mSoundImageHeightText = (TextView) layout.findViewById(R.id.soundImageHeightText); mSoundImageHeightText.setText("Height (" + mPressedSound.getImage().getHeight() + ")"); mSoundImageWidthInput = (EditText) layout.findViewById(R.id.soundImageWidthInput); mSoundImageWidthInput.setText(Float.toString(mPressedSound.getImageWidth())); mSoundImageHeightInput = (EditText) layout.findViewById(R.id.soundImageHeightInput); mSoundImageHeightInput.setText(Float.toString(mPressedSound.getImageHeight())); final CheckBox scaleWidthHeight = (CheckBox) layout.findViewById(R.id.scaleWidthHeightCheckBox); scaleWidthHeight.setChecked(true); scaleWidthHeight.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { // Calculate a new scale mWidthHeightScale = Float.valueOf(mSoundImageWidthInput.getText().toString()).floatValue() / Float.valueOf(mSoundImageHeightInput.getText().toString()).floatValue(); } catch(NumberFormatException nfe) {Log.e(TAG, "Unable to calculate width and height scale", nfe);} } }); mWidthHeightScale = mPressedSound.getImageWidth() / mPressedSound.getImageHeight(); mSoundImageWidthInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf(mSoundImageWidthInput.getText().toString()).floatValue(); mSoundImageHeightInput.setText(Float.valueOf(value/mWidthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); mSoundImageHeightInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf(mSoundImageHeightInput.getText().toString()).floatValue(); mSoundImageWidthInput.setText(Float.valueOf(value*mWidthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); final Button revertSizeButton = (Button) layout.findViewById(R.id.revertImageSizeButton); revertSizeButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mSoundImageWidthInput.setText(Float.valueOf(mPressedSound.getImageWidth()).toString()); mSoundImageHeightInput.setText(Float.valueOf(mPressedSound.getImageHeight()).toString()); mWidthHeightScale = mPressedSound.getImageWidth() / mPressedSound.getImageHeight(); } }); final Button setSoundImageButton = (Button) layout.findViewById(R.id.setSoundImageButton); setSoundImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { selectImageFile(); } }); final Button resetSoundImageButton = (Button) layout.findViewById(R.id.resetSoundImageButton); resetSoundImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Bitmap defaultSound = BitmapFactory.decodeResource(getResources(), R.drawable.sound); String soundWidth = Integer.toString(defaultSound.getWidth()); String soundHeight = Integer.toString(defaultSound.getHeight()); mPressedSound.setImage(defaultSound); mPressedSound.setImagePath(null); mSoundImageWidthInput.setText(soundWidth); mSoundImageHeightInput.setText(soundHeight); mSoundImageWidthText.setText("Width (" + soundWidth + ")"); mSoundImageHeightText.setText("Height (" + soundHeight + ")"); } }); final Button setSoundActiveImageButton = (Button) layout.findViewById(R.id.setSoundActiveImageButton); setSoundActiveImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { selectActiveImageFile(); } }); final Button resetSoundActiveImageButton = (Button) layout.findViewById(R.id.resetSoundActiveImageButton); resetSoundActiveImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mPressedSound.setActiveImage(null); mPressedSound.setActiveImagePath(null); } }); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Image settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; if (checkShowSoundImage.isChecked() == false) { mPressedSound.setHideImageOrText(GraphicalSound.HIDE_IMAGE); } else if (checkShowSoundImage.isChecked() && mPressedSound.getHideImageOrText() == GraphicalSound.HIDE_IMAGE) { mPressedSound.setHideImageOrText(GraphicalSound.SHOW_ALL); } try { mPressedSound.setImageWidth(Float.valueOf( mSoundImageWidthInput.getText().toString()).floatValue()); mPressedSound.setImageHeight(Float.valueOf( mSoundImageHeightInput.getText().toString()).floatValue()); } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } mPressedSound.generateImageXYFromNameFrameLocation(); if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mBoardHistory.createHistoryCheckpoint(mGsb); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mSoundImageDialog = null; } }); mSoundImageDialog = builder.create(); mSoundImageDialog.show(); } else if (item == 4) { LayoutInflater inflater = (LayoutInflater) BoardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate( R.layout.graphical_soundboard_editor_alert_sound_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox linkNameAndImageCheckBox = (CheckBox) layout.findViewById(R.id.linkNameAndImageCheckBox); linkNameAndImageCheckBox.setChecked(mPressedSound.getLinkNameAndImage()); final Button changeSoundPathButton = (Button) layout.findViewById(R.id.changeSoundPathButton); changeSoundPathButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(BoardEditor.this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_CHANGE_SOUND_PATH); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, CHANGE_SOUND_PATH); } }); final Button secondClickActionButton = (Button) layout.findViewById(R.id.secondClickActionButton); secondClickActionButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { final CharSequence[] items = {"Play new", "Pause", "Stop"}; AlertDialog.Builder secondClickBuilder = new AlertDialog.Builder( BoardEditor.this); secondClickBuilder.setTitle("Action"); secondClickBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { mPressedSound.setSecondClickAction(GraphicalSound.SECOND_CLICK_PLAY_NEW); } else if (item == 1) { mPressedSound.setSecondClickAction(GraphicalSound.SECOND_CLICK_PAUSE); } else if (item == 2) { mPressedSound.setSecondClickAction(GraphicalSound.SECOND_CLICK_STOP); } } }); AlertDialog secondClickAlert = secondClickBuilder.create(); secondClickAlert.show(); } }); final EditText leftVolumeInput = (EditText) layout.findViewById(R.id.leftVolumeInput); leftVolumeInput.setText(Float.toString(mPressedSound.getVolumeLeft()*100) + "%"); final EditText rightVolumeInput = (EditText) layout.findViewById(R.id.rightVolumeInput); rightVolumeInput.setText(Float.toString(mPressedSound.getVolumeRight()*100) + "%"); AlertDialog.Builder builder = new AlertDialog.Builder(BoardEditor.this); builder.setView(layout); builder.setTitle("Sound settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mPressedSound.setLinkNameAndImage(linkNameAndImageCheckBox.isChecked()); if (mPressedSound.getLinkNameAndImage()) { mPressedSound.generateImageXYFromNameFrameLocation(); } boolean notifyIncorrectValue = false; Float leftVolumeValue = null; try { String leftVolumeString = leftVolumeInput.getText().toString(); if (leftVolumeString.contains("%")) { leftVolumeValue = Float.valueOf(leftVolumeString.substring(0, leftVolumeString.indexOf("%"))).floatValue()/100; } else { leftVolumeValue = Float.valueOf(leftVolumeString).floatValue()/100; } if (leftVolumeValue >= 0 && leftVolumeValue <= 1 && leftVolumeValue != null) { mPressedSound.setVolumeLeft(leftVolumeValue); } else { notifyIncorrectValue = true; } } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } Float rightVolumeValue = null; try { String rightVolumeString = rightVolumeInput.getText().toString(); if (rightVolumeString.contains("%")) { rightVolumeValue = Float.valueOf(rightVolumeString.substring(0, rightVolumeString.indexOf("%"))).floatValue()/100; } else { rightVolumeValue = Float.valueOf(rightVolumeString).floatValue()/100; } if (rightVolumeValue >= 0 && rightVolumeValue <= 1 && rightVolumeValue != null) { mPressedSound.setVolumeRight(rightVolumeValue); } else { notifyIncorrectValue = true; } } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mBoardHistory.createHistoryCheckpoint(mGsb); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item ==5) { SoundboardMenu.mCopiedSound = (GraphicalSound) mPressedSound.clone(); } else if (item == 6) { LayoutInflater removeInflater = (LayoutInflater) BoardEditor.this.getSystemService(LAYOUT_INFLATER_SERVICE); View removeLayout = removeInflater.inflate( R.layout.graphical_soundboard_editor_alert_remove_sound, (ViewGroup) findViewById(R.id.alert_remove_sound_root)); final CheckBox removeFileCheckBox = (CheckBox) removeLayout.findViewById(R.id.removeFile); removeFileCheckBox.setText(" DELETE " + mPressedSound.getPath().getAbsolutePath()); AlertDialog.Builder removeBuilder = new AlertDialog.Builder( BoardEditor.this); removeBuilder.setView(removeLayout); removeBuilder.setTitle("Removing " + mPressedSound.getName()); removeBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (removeFileCheckBox.isChecked() == true) { mPressedSound.getPath().delete(); } mGsb.getSoundList().remove(mPressedSound); mBoardHistory.createHistoryCheckpoint(mGsb); } }); removeBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); removeBuilder.show(); } else if (item == 7) { final CharSequence[] items = {"Ringtone", "Notification", "Alerts"}; AlertDialog.Builder setAsBuilder = new AlertDialog.Builder( BoardEditor.this); setAsBuilder.setTitle("Set as..."); setAsBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { String filePath = mPressedSound.getPath().getAbsolutePath(); ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, filePath); values.put(MediaStore.MediaColumns.TITLE, mPressedSound.getName()); values.put(MediaStore.MediaColumns.MIME_TYPE, MimeTypeMap.getSingleton().getMimeTypeFromExtension( filePath.substring(filePath.lastIndexOf('.'+1)))); values.put(MediaStore.Audio.Media.ARTIST, "Artist"); int selectedAction = 0; if (item == 0) { selectedAction = RingtoneManager.TYPE_RINGTONE; values.put(MediaStore.Audio.Media.IS_RINGTONE, true); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); values.put(MediaStore.Audio.Media.IS_ALARM, false); values.put(MediaStore.Audio.Media.IS_MUSIC, false); } else if (item == 1) { selectedAction = RingtoneManager.TYPE_NOTIFICATION; values.put(MediaStore.Audio.Media.IS_RINGTONE, false); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); values.put(MediaStore.Audio.Media.IS_ALARM, false); values.put(MediaStore.Audio.Media.IS_MUSIC, false); } else if (item == 2) { selectedAction = RingtoneManager.TYPE_ALARM; values.put(MediaStore.Audio.Media.IS_RINGTONE, false); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); values.put(MediaStore.Audio.Media.IS_ALARM, true); values.put(MediaStore.Audio.Media.IS_MUSIC, false); } Uri uri = MediaStore.Audio.Media.getContentUriForPath(filePath); getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + filePath + "\"", null); Uri newUri = BoardEditor.this.getContentResolver().insert(uri, values); RingtoneManager.setActualDefaultRingtoneUri(BoardEditor.this, selectedAction, newUri); } }); AlertDialog setAsAlert = setAsBuilder.create(); setAsAlert.show(); } } }); AlertDialog optionsAlert = optionsBuilder.create(); optionsAlert.show(); invalidate(); } else if (mCurrentGesture == TouchGesture.DRAG) { if (mGsb.getAutoArrange()) { int width = mPanel.getWidth(); int height = mPanel.getHeight(); int column = -1, i = 0; while (column == -1) { if (event.getX() >= i*(width/mGsb.getAutoArrangeColumns()) && event.getX() <= (i+1)*(width/(mGsb.getAutoArrangeColumns()))) { column = i; } if (i > 1000) { Log.e(TAG, "column fail"); mPressedSound.getAutoArrangeColumn(); break; } i++; } i = 0; int row = -1; while (row == -1) { if (event.getY() >= i*(height/mGsb.getAutoArrangeRows()) && event.getY() <= (i+1)*(height/(mGsb.getAutoArrangeRows()))) { row = i; } if (i > 1000) { Log.e(TAG, "row fail"); mPressedSound.getAutoArrangeRow(); break; } i++; } GraphicalSound swapSound = null; for (GraphicalSound sound : mGsb.getSoundList()) { if (sound.getAutoArrangeColumn() == column && sound.getAutoArrangeRow() == row) { swapSound = sound; } } if (column == mPressedSound.getAutoArrangeColumn() && row == mPressedSound.getAutoArrangeRow()) { moveSound(event.getX(), event.getY()); } else { try { moveSoundToSlot(swapSound, mPressedSound.getAutoArrangeColumn(), mPressedSound.getAutoArrangeRow(), swapSound.getImageX(), swapSound.getImageY(), swapSound.getNameFrameX(), swapSound.getNameFrameY()); } catch (NullPointerException e) {} moveSoundToSlot(mPressedSound, column, row, mInitialImageX, mInitialImageY, mInitialNameFrameX, mInitialNameFrameY); mGsb.addSound(mPressedSound); } } else { mGsb.getSoundList().add(mPressedSound); } mBoardHistory.createHistoryCheckpoint(mGsb); } else if (mCurrentGesture == TouchGesture.PRESS_BOARD && mMode == LISTEN_BOARD) { playTouchedSound(mPressedSound); } mCurrentGesture = null; if (mJoystickTimer != null) { mJoystickTimer.cancel(); mJoystickTimer = null; } } } return true; } } @Override public void onDraw(Canvas canvas) { if (canvas == null) { Log.w(TAG, "Got null canvas"); mNullCanvasCount++; // Drawing thread is still running while the activity is destroyed (surfaceCreated was probably called after surfaceDestroyed). // Reproduce by killing the editor immediately after it is created. // It's difficult to kill the thread properly while supporting different orientations and closing of screen. if (mNullCanvasCount > 5) { Log.e(TAG, "Drawing thread was not destroyed properly"); mThread.setRunning(false); mThread = null; } } else { mNullCanvasCount = 0; super.dispatchDraw(canvas); GraphicalSound pressedSound = null; GraphicalSound fineTuningSound = null; if (mCurrentGesture == TouchGesture.DRAG) pressedSound = mPressedSound; if (mFineTuningSound != null && mCurrentGesture == TouchGesture.DRAG) fineTuningSound = mFineTuningSound; mPageDrawer.drawSurface(canvas, pressedSound, fineTuningSound); } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } public void surfaceCreated(SurfaceHolder holder) { try { mThread.setRunning(true); mThread.start(); } catch (NullPointerException e) { mThread = new DrawingThread(getHolder(), this); mThread.setRunning(true); mThread.start(); } Log.d(TAG, "Surface created"); } public void surfaceDestroyed(SurfaceHolder holder) { mThread.setRunning(false); mThread = null; Log.d(TAG, "Surface destroyed"); } } class DrawingThread extends Thread { private SurfaceHolder mSurfaceHolder; private boolean mRun = false; public DrawingThread(SurfaceHolder surfaceHolder, DrawingPanel panel) { mSurfaceHolder = surfaceHolder; mPanel = panel; } public void setRunning(boolean run) { mRun = run; } public SurfaceHolder getSurfaceHolder() { return mSurfaceHolder; } @Override public void run() { while (mRun) { Canvas c; c = null; try { c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { mPanel.onDraw(c); } } finally { if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } try { if (mPageDrawer.needAnimationRefreshSpeed()) { Thread.sleep(1); } else if (mMode == EDIT_BOARD && (mCurrentGesture == TouchGesture.DRAG || mMoveBackground )) { Thread.sleep(10); } else if (mMode == EDIT_BOARD && mCurrentGesture != TouchGesture.DRAG && mMoveBackground == false) { for (int i = 0; i <= 5; i++) { Thread.sleep(100); if (mCurrentGesture == TouchGesture.DRAG || mMoveBackground) { break; } } } else if (mMode == LISTEN_BOARD) { for (int i = 0; i <= 30; i++) { Thread.sleep(20); if (mMode == EDIT_BOARD || mCanvasInvalidated == true) { mCanvasInvalidated = false; break; } } } else { Log.e(TAG, "Undefined redraw rate state"); Thread.sleep(1000); } } catch (InterruptedException e) {} } } } }
Board is not created to the initial orientation if board only uses the other orientation.
src/fi/mikuz/boarder/gui/BoardEditor.java
Board is not created to the initial orientation if board only uses the other orientation.
<ide><path>rc/fi/mikuz/boarder/gui/BoardEditor.java <ide> <ide> public void initEditorBoard() { <ide> <add> Configuration config = getResources().getConfiguration(); <add> int orientation = OrientationUtil.getBoarderOrientation(config); <add> <ide> if (mGsbp.getOrientationMode() == GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_PORTRAIT) { <ide> this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); <add> orientation = GraphicalSoundboard.SCREEN_ORIENTATION_PORTRAIT; <ide> } else if (mGsbp.getOrientationMode() == GraphicalSoundboardHolder.OrientationMode.ORIENTATION_MODE_LANDSCAPE) { <ide> this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); <del> } <del> <del> Configuration config = getResources().getConfiguration(); <del> int orientation = OrientationUtil.getBoarderOrientation(config); <add> orientation = GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE; <add> } <add> <add> <ide> this.mCurrentOrientation = orientation; <del> <ide> GraphicalSoundboard newGsb = mPagination.getBoard(orientation); <ide> <ide> mPageDrawer = new PageDrawer(this.getApplicationContext(), mJoystick);
Java
apache-2.0
cd3f31cf2f33f933934a5cfbf45d40cacb8a9c32
0
sylvanmist/Web-Karma,usc-isi-i2/Web-Karma,rpiotti/Web-Karma,sylvanmist/Web-Karma,usc-isi-i2/Web-Karma,usc-isi-i2/Web-Karma,rpiotti/Web-Karma,sylvanmist/Web-Karma,usc-isi-i2/Web-Karma,sylvanmist/Web-Karma,sylvanmist/Web-Karma,rpiotti/Web-Karma,rpiotti/Web-Karma,rpiotti/Web-Karma,usc-isi-i2/Web-Karma
karma-offline/src/test/java/edu/isi/karma/rdf/TestJSONRDFGeneratorWithAugmentData.java
/******************************************************************************* * Copyright 2012 University of Southern California * * 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. * * This code was developed by the Information Integration Group as part * of the Karma project at the Information Sciences Institute of the * University of Southern California. For more information, publications, * and related projects, please see: http://www.isi.edu/integration ******************************************************************************/ package edu.isi.karma.rdf; import static org.junit.Assert.fail; import java.net.URL; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.isi.karma.er.helper.TripleStoreUtil; import edu.isi.karma.kr2rml.mapping.R2RMLMappingIdentifier; /** * @author dipsy * */ public class TestJSONRDFGeneratorWithAugmentData extends TestJSONRDFGenerator{ private static Logger logger = LoggerFactory.getLogger(TestJSONRDFGeneratorWithAugmentData.class); /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { } /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { rdfGen = new GenericRDFGenerator(); // Add the models in R2RMLMappingIdentifier modelIdentifier = new R2RMLMappingIdentifier( "augmentdata-model", getTestResource( "augmentdata/augmentdata-model.ttl")); rdfGen.addModel(modelIdentifier); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } @Test public void testAugmentData() { TripleStoreUtil util = new TripleStoreUtil(); try { util.testTripleStoreConnection("http://localhost:8080" + TripleStoreUtil.defaultDataRepoUrl.substring(1)); }catch(Exception e) { return; } try { executeBasicJSONTest("augmentdata/schedule.json", "augmentdata-model", false, 376); } catch (Exception e) { logger.error("testAugmentData failed:", e); fail("Execption: " + e.getMessage()); } } @Override protected URL getTestResource(String name) { return getClass().getClassLoader().getResource(name); } }
delete test with augment data
karma-offline/src/test/java/edu/isi/karma/rdf/TestJSONRDFGeneratorWithAugmentData.java
delete test with augment data
<ide><path>arma-offline/src/test/java/edu/isi/karma/rdf/TestJSONRDFGeneratorWithAugmentData.java <del>/******************************************************************************* <del> * Copyright 2012 University of Southern California <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> * <del> * This code was developed by the Information Integration Group as part <del> * of the Karma project at the Information Sciences Institute of the <del> * University of Southern California. For more information, publications, <del> * and related projects, please see: http://www.isi.edu/integration <del> ******************************************************************************/ <del> <del>package edu.isi.karma.rdf; <del> <del>import static org.junit.Assert.fail; <del> <del>import java.net.URL; <del> <del>import org.junit.After; <del>import org.junit.AfterClass; <del>import org.junit.Before; <del>import org.junit.Test; <del>import org.slf4j.Logger; <del>import org.slf4j.LoggerFactory; <del> <del>import edu.isi.karma.er.helper.TripleStoreUtil; <del>import edu.isi.karma.kr2rml.mapping.R2RMLMappingIdentifier; <del> <del> <del>/** <del> * @author dipsy <del> * <del> */ <del>public class TestJSONRDFGeneratorWithAugmentData extends TestJSONRDFGenerator{ <del> <del> private static Logger logger = LoggerFactory.getLogger(TestJSONRDFGeneratorWithAugmentData.class); <del> <del> <del> /** <del> * @throws java.lang.Exception <del> */ <del> @AfterClass <del> public static void tearDownAfterClass() throws Exception { <del> } <del> <del> /** <del> * @throws java.lang.Exception <del> */ <del> @Before <del> public void setUp() throws Exception { <del> rdfGen = new GenericRDFGenerator(); <del> <del> // Add the models in <del> R2RMLMappingIdentifier modelIdentifier = new R2RMLMappingIdentifier( <del> "augmentdata-model", getTestResource( <del> "augmentdata/augmentdata-model.ttl")); <del> rdfGen.addModel(modelIdentifier); <del> <del> } <del> <del> /** <del> * @throws java.lang.Exception <del> */ <del> @After <del> public void tearDown() throws Exception { <del> } <del> <del> @Test <del> public void testAugmentData() { <del> TripleStoreUtil util = new TripleStoreUtil(); <del> try { <del> util.testTripleStoreConnection("http://localhost:8080" + TripleStoreUtil.defaultDataRepoUrl.substring(1)); <del> }catch(Exception e) { <del> return; <del> } <del> try { <del> <del> executeBasicJSONTest("augmentdata/schedule.json", "augmentdata-model", false, 376); <del> <del> } catch (Exception e) { <del> logger.error("testAugmentData failed:", e); <del> fail("Execption: " + e.getMessage()); <del> } <del> } <del> <del> @Override <del> protected URL getTestResource(String name) <del> { <del> return getClass().getClassLoader().getResource(name); <del> } <del>}
Java
apache-2.0
602fc15816b5dd3717976c3f3784962a3a911361
0
efsavage/ajah
/* * Copyright 2011 Eric F. Savage, [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ajah.spring.mvc.form.validation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.ajah.spring.mvc.form.AutoForm; /** * Serves as a wrapper to support the custom validation annotations in this * library. Invokes validate() method from standardValidator first, then * validates against custom annotations. * * @author <a href="http://efsavage.com">Eric F. Savage</a>, <a * href="mailto:[email protected]">[email protected]</a>. * */ public class AutoFormValidator implements Validator { @Autowired private Validator standardValidator; private final Validator[] customValidators = new Validator[] { new MatchValidator(), new StringSizeValidator() }; /** * Returns the "standard" validator, i.e. the one that will handle standard * validation like java.validation annotations. * * @return The standard validator, if set, otherwise null. */ public Validator getStandardValidator() { return this.standardValidator; } /** * Sets the "standard" validator, i.e. the one that will handle standard * validation like java.validation annotations. * * @param standardValidator * The "standard" validator, may be null. */ public void setStandardValidator(Validator standardValidator) { this.standardValidator = standardValidator; } /** * This validator realistically only supports classes with the * {@link AutoForm} attribute, but there's no real reason to enforce this * restriction. * * @return Always returns true */ public boolean supports(Class<?> clazz) { return true; } /** * Invokes validate() method from superclass first, then validates against * custom annotations. * * @see org.springframework.validation.beanvalidation.SpringValidatorAdapter# * validate(java.lang.Object, org.springframework.validation.Errors) */ public void validate(Object object, Errors errors) { if (this.standardValidator != null) { ValidationUtils.invokeValidator(this.standardValidator, object, errors); } for (Validator validator : this.customValidators) { ValidationUtils.invokeValidator(validator, object, errors); } } }
ajah-spring-mvc/src/main/java/com/ajah/spring/mvc/form/validation/AutoFormValidator.java
/* * Copyright 2011 Eric F. Savage, [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ajah.spring.mvc.form.validation; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.ajah.spring.mvc.form.AutoForm; /** * Serves as a wrapper to support the custom validation annotations in this * library. Invokes validate() method from standardValidator first, then * validates against custom annotations. * * @author <a href="http://efsavage.com">Eric F. Savage</a>, <a * href="mailto:[email protected]">[email protected]</a>. * */ public class AutoFormValidator implements Validator { private Validator standardValidator; private Validator[] customValidators = new Validator[] { new MatchValidator(), new StringSizeValidator() }; /** * Returns the "standard" validator, i.e. the one that will handle standard * validation like java.validation annotations. * * @return The standard validator, if set, otherwise null. */ public Validator getStandardValidator() { return this.standardValidator; } /** * Sets the "standard" validator, i.e. the one that will handle standard * validation like java.validation annotations. * * @param standardValidator * The "standard" validator, may be null. */ public void setStandardValidator(Validator standardValidator) { this.standardValidator = standardValidator; } /** * This validator realistically only supports classes with the * {@link AutoForm} attribute, but there's no real reason to enforce this * restriction. * * @return Always returns true */ public boolean supports(Class<?> clazz) { return true; } /** * Invokes validate() method from superclass first, then validates against * custom annotations. * * @see org.springframework.validation.beanvalidation.SpringValidatorAdapter# * validate(java.lang.Object, org.springframework.validation.Errors) */ public void validate(Object object, Errors errors) { if (this.standardValidator != null) { ValidationUtils.invokeValidator(this.standardValidator, object, errors); } for (Validator validator : this.customValidators) { ValidationUtils.invokeValidator(validator, object, errors); } } }
Autowire standardValidator
ajah-spring-mvc/src/main/java/com/ajah/spring/mvc/form/validation/AutoFormValidator.java
Autowire standardValidator
<ide><path>jah-spring-mvc/src/main/java/com/ajah/spring/mvc/form/validation/AutoFormValidator.java <ide> */ <ide> package com.ajah.spring.mvc.form.validation; <ide> <add>import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.validation.Errors; <ide> import org.springframework.validation.ValidationUtils; <ide> import org.springframework.validation.Validator; <ide> */ <ide> public class AutoFormValidator implements Validator { <ide> <add> @Autowired <ide> private Validator standardValidator; <ide> <del> private Validator[] customValidators = new Validator[] { new MatchValidator(), new StringSizeValidator() }; <add> private final Validator[] customValidators = new Validator[] { new MatchValidator(), new StringSizeValidator() }; <ide> <ide> /** <ide> * Returns the "standard" validator, i.e. the one that will handle standard
Java
agpl-3.0
2748c3cc53b9f464c29e484f7370b9435085e5a4
0
jzhu8803/rstudio,jar1karp/rstudio,suribes/rstudio,thklaus/rstudio,githubfun/rstudio,thklaus/rstudio,suribes/rstudio,tbarrongh/rstudio,more1/rstudio,more1/rstudio,john-r-mcpherson/rstudio,piersharding/rstudio,piersharding/rstudio,sfloresm/rstudio,JanMarvin/rstudio,brsimioni/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,jar1karp/rstudio,pssguy/rstudio,more1/rstudio,brsimioni/rstudio,edrogers/rstudio,piersharding/rstudio,sfloresm/rstudio,piersharding/rstudio,edrogers/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,jzhu8803/rstudio,jar1karp/rstudio,suribes/rstudio,more1/rstudio,jar1karp/rstudio,tbarrongh/rstudio,pssguy/rstudio,jzhu8803/rstudio,jrnold/rstudio,edrogers/rstudio,edrogers/rstudio,JanMarvin/rstudio,jar1karp/rstudio,jzhu8803/rstudio,vbelakov/rstudio,pssguy/rstudio,piersharding/rstudio,sfloresm/rstudio,tbarrongh/rstudio,jrnold/rstudio,githubfun/rstudio,tbarrongh/rstudio,edrogers/rstudio,jrnold/rstudio,JanMarvin/rstudio,brsimioni/rstudio,githubfun/rstudio,thklaus/rstudio,john-r-mcpherson/rstudio,jrnold/rstudio,suribes/rstudio,more1/rstudio,jar1karp/rstudio,sfloresm/rstudio,more1/rstudio,githubfun/rstudio,vbelakov/rstudio,jzhu8803/rstudio,edrogers/rstudio,jrnold/rstudio,more1/rstudio,pssguy/rstudio,jar1karp/rstudio,thklaus/rstudio,vbelakov/rstudio,edrogers/rstudio,vbelakov/rstudio,jrnold/rstudio,JanMarvin/rstudio,john-r-mcpherson/rstudio,pssguy/rstudio,piersharding/rstudio,jrnold/rstudio,thklaus/rstudio,piersharding/rstudio,jzhu8803/rstudio,brsimioni/rstudio,JanMarvin/rstudio,sfloresm/rstudio,piersharding/rstudio,sfloresm/rstudio,githubfun/rstudio,githubfun/rstudio,vbelakov/rstudio,githubfun/rstudio,brsimioni/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,sfloresm/rstudio,jar1karp/rstudio,brsimioni/rstudio,john-r-mcpherson/rstudio,edrogers/rstudio,jzhu8803/rstudio,thklaus/rstudio,JanMarvin/rstudio,john-r-mcpherson/rstudio,sfloresm/rstudio,vbelakov/rstudio,githubfun/rstudio,brsimioni/rstudio,vbelakov/rstudio,suribes/rstudio,JanMarvin/rstudio,more1/rstudio,JanMarvin/rstudio,jrnold/rstudio,jzhu8803/rstudio,pssguy/rstudio,brsimioni/rstudio,jar1karp/rstudio,pssguy/rstudio,tbarrongh/rstudio,JanMarvin/rstudio,tbarrongh/rstudio,tbarrongh/rstudio,tbarrongh/rstudio,piersharding/rstudio,pssguy/rstudio,thklaus/rstudio,thklaus/rstudio,jrnold/rstudio,vbelakov/rstudio
/* * CollabEditStartParams.java * * Copyright (C) 2009-15 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source.events; import com.google.gwt.core.client.JavaScriptObject; public class CollabEditStartParams extends JavaScriptObject { protected CollabEditStartParams() { } public final native String getUrl() /*-{ return this.url; }-*/; public final native String getPath() /*-{ return this.path; }-*/; public final native String cursorColor() /*-{ return this.cursor_color; }-*/; public final native boolean isMaster() /*-{ return this.master; }-*/; }
src/gwt/src/org/rstudio/studio/client/workbench/views/source/events/CollabEditStartParams.java
/* * CollabEditStartParams.java * * Copyright (C) 2009-15 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source.events; import com.google.gwt.core.client.JavaScriptObject; public class CollabEditStartParams extends JavaScriptObject { protected CollabEditStartParams() { } public final native String getUrl() /*-{ return this.url; }-*/; public final native String getPath() /*-{ return this.path; }-*/; public final native boolean isMaster() /*-{ return this.master; }-*/; }
include cursor color when initiating collab edit session
src/gwt/src/org/rstudio/studio/client/workbench/views/source/events/CollabEditStartParams.java
include cursor color when initiating collab edit session
<ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/source/events/CollabEditStartParams.java <ide> return this.path; <ide> }-*/; <ide> <add> public final native String cursorColor() /*-{ <add> return this.cursor_color; <add> }-*/; <add> <ide> public final native boolean isMaster() /*-{ <ide> return this.master; <ide> }-*/;
Java
apache-2.0
8c5df073f32886e78ffa2fc8fe42bcf92b368350
0
feer921/BaseProject
package common.base.fragments; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import common.base.R; import common.base.activitys.IProxyCallback; import common.base.activitys.UIHintAgent; import common.base.interfaces.ICommonUiHintActions; import common.base.netAbout.BaseServerResult; import common.base.netAbout.NetRequestLifeMarker; import common.base.utils.CommonLog; import common.base.views.ToastUtil; /** * User: fee([email protected]) * Date: 2016-05-16 * Time: 15:21 * DESC: 碎片的基类 */ public abstract class BaseFragment extends Fragment implements View.OnClickListener, IProxyCallback, DialogInterface.OnClickListener, ICommonUiHintActions{ protected final String TAG = getClass().getSimpleName(); protected LayoutInflater mLayoutInflater; protected Context context; protected Context appContext; /** * 是否开启生命周期打印调试 */ protected boolean LIFE_DEBUG = false; protected String extraInfoInLifeDebug = ""; protected UIHintAgent someUiHintAgent; protected NetRequestLifeMarker netRequestLifeMarker = new NetRequestLifeMarker(); //生命周期方法 @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onActivityCreated() savedInstanceState = " + savedInstanceState); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onAttach(Context context) { super.onAttach(context); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onAttach() "); } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onCreate() savedInstanceState = " + savedInstanceState); } } @Override public void onStart() { super.onStart(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onStart() "); } } @Override public void onResume() { super.onResume(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onResume() "); } if (someUiHintAgent != null) { someUiHintAgent.setOwnerVisibility(true); } if (needUpdateData) { initData(); needUpdateData = false; } } @Override public void onPause() { super.onPause(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onPause() "); } } @Override public void onStop() { super.onStop(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onStop() "); } if (someUiHintAgent != null) { someUiHintAgent.setOwnerVisibility(false); } } @Override public void onDetach() { super.onDetach(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onDetach() "); } } @Override public void onDestroyView() { super.onDestroyView(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onDestroyView() "); } } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onHiddenChanged() hidden = " + hidden); } } @Override public void onDestroy() { super.onDestroy(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onDestroy() "); } } private View rootView; private boolean needReDrawUi = true; protected boolean needUpdateData = false; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onCreateView() container id = " + container.getId() +" savedInstanceState = " + savedInstanceState); CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onCreateView() rootView = " + rootView); } mLayoutInflater = inflater; context = getActivity(); appContext = context.getApplicationContext(); if (rootView == null) { needReDrawUi = true; int curFragmentViewResId = providedFragmentViewResId(); if (curFragmentViewResId > 0) { rootView = inflater.inflate(curFragmentViewResId, null); } else{ rootView = providedFragmentView(); } } else{ needReDrawUi = false; } if (rootView == null) { needReDrawUi = false; return null; } ViewGroup rootViewOldParentView = (ViewGroup) rootView.getParent(); if (rootViewOldParentView != null) { rootViewOldParentView.removeView(rootView); } return rootView; } /** * 一般在这个生命周期方法中初始化视图 * @param view * @param savedInstanceState */ @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (needReDrawUi) { initViews(view); initData(); initEvent(); } } /** * 对所加载的视图进行初始化工作 * @param contentView */ protected abstract void initViews(View contentView); /** * 初始化数据 */ protected abstract void initData(); protected void initEvent() { } protected void fixPageHeaderView(View headerView) { } /** * 提供当前碎片的内容视图布局的资源ID * @return */ protected abstract int providedFragmentViewResId(); /** * 提供当前碎片的内容视图View * @return */ protected abstract View providedFragmentView(); @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onActivityResult() requestCode = " + requestCode + " resultCode = " + resultCode + " data = " + data); } } protected void needSomeUiHintAgent() { if (someUiHintAgent == null) { someUiHintAgent = new UIHintAgent(context); someUiHintAgent.setProxyCallback(this); someUiHintAgent.setHintDialogOnClickListener(this); } } protected void switchActivity(boolean finishSelf) { if (finishSelf) { getActivity().overridePendingTransition(R.anim.common_part_left_in, R.anim.common_whole_right_out); } else { getActivity().overridePendingTransition(R.anim.common_whole_right_in, R.anim.common_part_right_out); } } /** * 被代理者(雇佣代理者)是否处理服务正常响应结果,如果被代理者处理了,则代理者不处理 * * @param requestDataType 处理的当前是何种请求 * @param result * @return true:[被代理者]处理了 false:交由[代理者]处理 */ @Override public boolean ownerDealWithServerResult(int requestDataType, BaseServerResult result) { return false; } /** * 被代理者(雇佣代理者)是否处理连接服务端异常结果,如果被代理者处理了,则代理者不处理 * * @param requestDataType 处理的当前是何种请求 * @param errorInfo * @return true:[被代理者]处理了 false:交由[代理者]处理 */ @Override public boolean ownerDealWithServerError(int requestDataType, String errorInfo) { return false; } /** * 被代理者(宿主)想主动取消(网络)数据的请求,在各自实现中实现各网络请求的取消并标志好该请求已取消 */ @Override public void ownerToCancelLoadingRequest() { } @Override public void ownerToCancelHintDialog() { } /** * Called when a view has been clicked. * * @param v The view that was clicked. */ @Override public void onClick(View v) { } /** * This method will be invoked when a button in the dialog is clicked. * * @param dialog The dialog that received the click. * @param which The button that was clicked (e.g. * {@link DialogInterface#BUTTON1}) or the position */ @Override public void onClick(DialogInterface dialog, int which) { } //一些工具性质的方法 /** * 从xml文件中找到一个Viwe控件的通配方法,将使用方需要的强制转换通用实现 * @param viewId * @param <T> 控件类型 * @return T类型的视图控件 */ protected <T extends View> T findAviewById(int viewId) { return findLocalViewById(viewId);//changed by fee 2017-09-13 一个Fragment在宿主Activity中来查找子视图控件不太合适 } /** * 在宿主Activity中根据view id 查找控件 * @param viewId * @param <T> * @return */ protected <T extends View> T findAviewByIdInHostActivity(int viewId){ if (viewId > 0) { return (T) getActivity().findViewById(viewId); } return null; } /** * 在Fragment所加载的视图里查找视图控件 * @param viewId * @param <T> * @return */ protected <T extends View> T findLocalViewById(int viewId) { if (viewId > 0 && rootView != null) { return (T) rootView.findViewById(viewId); } return null; } /** * 在一个容器视图中依据View ID查找子视图 * @param containerView 容器View * @param childViewId 子View ID * @param <T> * @return */ protected <T extends View> T findAviewInContainer(ViewGroup containerView, int childViewId) { if (containerView == null || childViewId <= 0) { return null; } return (T) containerView.findViewById(childViewId); } protected void jumpToActivity(Intent startIntent, int requestCode,boolean needReturnResult) { if (startIntent != null) { if (!needReturnResult) { startActivity(startIntent); } else{ startActivityForResult(startIntent,requestCode); } } } protected void jumpToActivity(Class<?> targetActivityClass) { Intent startIntent = new Intent(context, targetActivityClass); jumpToActivity(startIntent,0,false); } protected void jumpToActivity(Class<?> targetActiviyClass, int requestCode, boolean needReturnResult) { Intent startIntent = new Intent(context,targetActiviyClass); jumpToActivity(startIntent,requestCode,needReturnResult); } /** * 当前的请求是否取消了 * @param dataType * @return */ protected boolean curRequestCanceled(int dataType) { if(netRequestLifeMarker != null){ return netRequestLifeMarker.curRequestCanceled(dataType); } return false; } /** * 标记当前网络请求的状态 : 正在请求、已完成、已取消等 * @see {@link NetRequestLifeMarker#REQUEST_STATE_ING} * @param requestDataType * @param targetState */ protected void addRequestStateMark(int requestDataType,byte targetState){ if(netRequestLifeMarker != null){ netRequestLifeMarker.addRequestToMark(requestDataType, targetState); } } /** * 开始追踪、标记一个对应的网络请求类型的请求状态 * @param curRequestDataType */ protected void trackARequestState(int curRequestDataType) { if (netRequestLifeMarker != null) { netRequestLifeMarker.addRequestToMark(curRequestDataType, NetRequestLifeMarker.REQUEST_STATE_ING); } } /** * 某个请求类型的网络请求是否已经完成 * @param requestDataType * @return */ protected boolean curRequestFinished(int requestDataType) { if (netRequestLifeMarker != null) { return netRequestLifeMarker.curRequestLifeState(requestDataType) == NetRequestLifeMarker.REQUEST_STATE_FINISHED; } return false; } /*** * 取消网络请求(注:该方法只适合本框架的Retrofit请求模块才会真正取消网络请求, * 如果使用的是本框架的OkGo请求模块,还请各APP的基类再进行处理一下,或本框架再优化来统一处理) * @param curRequestType 要取消的网络请求类型 */ protected void cancelNetRequest(int curRequestType) { if (netRequestLifeMarker != null) { netRequestLifeMarker.cancelCallRequest(curRequestType); } } /** * 判断是否某些网络请求全部完成了 * @param theRequestTypes 对应要加入判断的网络请求类型 * @return true:所有参与判断的网络请求都完成了;false:只要有任何一个请求未完成即未完成。 */ protected boolean isAllRequestFinished(int... theRequestTypes) { if (theRequestTypes == null || theRequestTypes.length == 0) { return false; } for (int oneRequestType : theRequestTypes) { if (!curRequestFinished(oneRequestType)) { return false;//只要有一个请求没有完成,就是未全部完成 } } return true; } /** * 注意:该提示性PopupWindow适用与在一个界面的顶部经由上至下的动画弹出 * * @param anchorView 一般为顶部的一个控件 * @param xOffset X方向的偏移量 * @param yOffset Y方向的偏移量 */ @Override public void initCommonHintPopuWindow(View anchorView, int xOffset, int yOffset) { if (someUiHintAgent != null) { someUiHintAgent.initHintPopuWindow(anchorView,xOffset,yOffset); } } @Override public void showCommonLoading(String hintMsg) { if (someUiHintAgent != null) { someUiHintAgent.showLoading(hintMsg); } } @Override public void showCommonLoading(int hintMsgResID) { showCommonLoading(getString(hintMsgResID)); } @Override public void dialogHint(String dialogTitle, String hintMsg, String cancelBtnName, String sureBtnName, int dialogInCase) { if (someUiHintAgent != null) { someUiHintAgent.dialogHint(dialogTitle, hintMsg, cancelBtnName, sureBtnName, dialogInCase); } } @Override public void dialogHint(int titleResID, int hintMsgResID, int cancelBtnNameResID, int sureBtnNameResID, int dialogInCase) { String dialogTitle = getString(titleResID); String hintMsg = getString(hintMsgResID); String cancelBtnName = getString(cancelBtnNameResID); String sureBtnName = getString(sureBtnNameResID); dialogHint(dialogTitle, hintMsg, cancelBtnName, sureBtnName, dialogInCase); } @Override public void popupHint(String hintMsg) { if(someUiHintAgent != null) someUiHintAgent.popupHint(hintMsg); } @Override public void popupHint(int hintMsgResID) { popupHint(getString(hintMsgResID)); } protected void topToast(String msg) { ToastUtil.topShow(msg); } protected void topToast(int msgResId) { topToast(getString(msgResId)); } protected void i(String tag,Object... logBodys) { if (tag == null) { tag = TAG + "[" + extraInfoInLifeDebug + "]"; } CommonLog.i(tag, logBodys); } protected void e(String tag, Object... logBodys) { if (tag == null) { tag = TAG + "[" + extraInfoInLifeDebug + "]"; } CommonLog.e(tag, logBodys); } }
src/main/java/common/base/fragments/BaseFragment.java
package common.base.fragments; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import common.base.R; import common.base.activitys.IProxyCallback; import common.base.activitys.UIHintAgent; import common.base.interfaces.ICommonUiHintActions; import common.base.netAbout.BaseServerResult; import common.base.netAbout.NetRequestLifeMarker; import common.base.utils.CommonLog; import common.base.views.ToastUtil; /** * User: fee([email protected]) * Date: 2016-05-16 * Time: 15:21 * DESC: 碎片的基类 */ public abstract class BaseFragment extends Fragment implements View.OnClickListener, IProxyCallback, DialogInterface.OnClickListener, ICommonUiHintActions{ protected final String TAG = getClass().getSimpleName(); protected LayoutInflater mLayoutInflater; protected Context context; protected Context appContext; /** * 是否开启生命周期打印调试 */ protected boolean LIFE_DEBUG = false; protected String extraInfoInLifeDebug = ""; protected UIHintAgent someUiHintAgent; protected NetRequestLifeMarker netRequestLifeMarker = new NetRequestLifeMarker(); //生命周期方法 @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onActivityCreated() savedInstanceState = " + savedInstanceState); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onAttach(Context context) { super.onAttach(context); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onAttach() "); } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onCreate() savedInstanceState = " + savedInstanceState); } } @Override public void onStart() { super.onStart(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onStart() "); } } @Override public void onResume() { super.onResume(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onResume() "); } if (someUiHintAgent != null) { someUiHintAgent.setOwnerVisibility(true); } if (needUpdateData) { initData(); needUpdateData = false; } } @Override public void onPause() { super.onPause(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onPause() "); } } @Override public void onStop() { super.onStop(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onStop() "); } if (someUiHintAgent != null) { someUiHintAgent.setOwnerVisibility(false); } } @Override public void onDetach() { super.onDetach(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onDetach() "); } } @Override public void onDestroyView() { super.onDestroyView(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onDestroyView() "); } } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onHiddenChanged() hidden = " + hidden); } } @Override public void onDestroy() { super.onDestroy(); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onDestroy() "); } } private View rootView; private boolean needReDrawUi = true; protected boolean needUpdateData = false; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onCreateView() container id = " + container.getId() +" savedInstanceState = " + savedInstanceState); CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onCreateView() rootView = " + rootView); } mLayoutInflater = inflater; context = getActivity(); appContext = context.getApplicationContext(); if (rootView == null) { needReDrawUi = true; int curFragmentViewResId = providedFragmentViewResId(); if (curFragmentViewResId > 0) { rootView = inflater.inflate(curFragmentViewResId, null); } else{ rootView = providedFragmentView(); } } else{ needReDrawUi = false; } if (rootView == null) { needReDrawUi = false; return null; } ViewGroup rootViewOldParentView = (ViewGroup) rootView.getParent(); if (rootViewOldParentView != null) { rootViewOldParentView.removeView(rootView); } return rootView; } /** * 一般在这个生命周期方法中初始化视图 * @param view * @param savedInstanceState */ @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (needReDrawUi) { initViews(view); initData(); initEvent(); } } /** * 对所加载的视图进行初始化工作 * @param contentView */ protected abstract void initViews(View contentView); /** * 初始化数据 */ protected abstract void initData(); protected void initEvent() { } protected void fixPageHeaderView(View headerView) { } /** * 提供当前碎片的内容视图布局的资源ID * @return */ protected abstract int providedFragmentViewResId(); /** * 提供当前碎片的内容视图View * @return */ protected abstract View providedFragmentView(); @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (LIFE_DEBUG) { CommonLog.i(TAG + "[" + extraInfoInLifeDebug +"]","--> onActivityResult() requestCode = " + requestCode + " resultCode = " + resultCode + " data = " + data); } } protected void needSomeUiHintAgent() { if (someUiHintAgent == null) { someUiHintAgent = new UIHintAgent(context); someUiHintAgent.setProxyCallback(this); someUiHintAgent.setHintDialogOnClickListener(this); } } protected void switchActivity(boolean finishSelf) { if (finishSelf) { getActivity().overridePendingTransition(R.anim.common_part_left_in, R.anim.common_whole_right_out); } else { getActivity().overridePendingTransition(R.anim.common_whole_right_in, R.anim.common_part_right_out); } } /** * 被代理者(雇佣代理者)是否处理服务正常响应结果,如果被代理者处理了,则代理者不处理 * * @param requestDataType 处理的当前是何种请求 * @param result * @return true:[被代理者]处理了 false:交由[代理者]处理 */ @Override public boolean ownerDealWithServerResult(int requestDataType, BaseServerResult result) { return false; } /** * 被代理者(雇佣代理者)是否处理连接服务端异常结果,如果被代理者处理了,则代理者不处理 * * @param requestDataType 处理的当前是何种请求 * @param errorInfo * @return true:[被代理者]处理了 false:交由[代理者]处理 */ @Override public boolean ownerDealWithServerError(int requestDataType, String errorInfo) { return false; } /** * 被代理者(宿主)想主动取消(网络)数据的请求,在各自实现中实现各网络请求的取消并标志好该请求已取消 */ @Override public void ownerToCancelLoadingRequest() { } @Override public void ownerToCancelHintDialog() { } /** * Called when a view has been clicked. * * @param v The view that was clicked. */ @Override public void onClick(View v) { } /** * This method will be invoked when a button in the dialog is clicked. * * @param dialog The dialog that received the click. * @param which The button that was clicked (e.g. * {@link DialogInterface#BUTTON1}) or the position */ @Override public void onClick(DialogInterface dialog, int which) { } //一些工具性质的方法 /** * 从xml文件中找到一个Viwe控件的通配方法,将使用方需要的强制转换通用实现 * @param viewId * @param <T> 控件类型 * @return T类型的视图控件 */ protected <T extends View> T findAviewById(int viewId) { // if (viewId > 0) { // return (T) getActivity().findViewById(viewId); // } // return null; return findLocalViewById(viewId);//changed by fee 2017-09-13 一个Fragment在宿主Activity中来查找子视图控件不太合适 } /** * 在Fragment所加载的视图里查找视图控件 * @param viewId * @param <T> * @return */ protected <T extends View> T findLocalViewById(int viewId) { if (viewId > 0 && rootView != null) { return (T) rootView.findViewById(viewId); } return null; } /** * 在一个容器视图中依据View ID查找子视图 * @param containerView 容器View * @param childViewId 子View ID * @param <T> * @return */ protected <T extends View> T findAviewInContainer(ViewGroup containerView, int childViewId) { if (containerView == null || childViewId <= 0) { return null; } return (T) containerView.findViewById(childViewId); } protected void jumpToActivity(Intent startIntent, int requestCode,boolean needReturnResult) { if (startIntent != null) { if (!needReturnResult) { startActivity(startIntent); } else{ startActivityForResult(startIntent,requestCode); } } } protected void jumpToActivity(Class<?> targetActivityClass) { Intent startIntent = new Intent(context, targetActivityClass); jumpToActivity(startIntent,0,false); } protected void jumpToActivity(Class<?> targetActiviyClass, int requestCode, boolean needReturnResult) { Intent startIntent = new Intent(context,targetActiviyClass); jumpToActivity(startIntent,requestCode,needReturnResult); } /** * 当前的请求是否取消了 * @param dataType * @return */ protected boolean curRequestCanceled(int dataType) { if(netRequestLifeMarker != null){ return netRequestLifeMarker.curRequestCanceled(dataType); } return false; } /** * 标记当前网络请求的状态 : 正在请求、已完成、已取消等 * @see {@link NetRequestLifeMarker#REQUEST_STATE_ING} * @param requestDataType * @param targetState */ protected void addRequestStateMark(int requestDataType,byte targetState){ if(netRequestLifeMarker != null){ netRequestLifeMarker.addRequestToMark(requestDataType, targetState); } } /** * 开始追踪、标记一个对应的网络请求类型的请求状态 * @param curRequestDataType */ protected void trackARequestState(int curRequestDataType) { if (netRequestLifeMarker != null) { netRequestLifeMarker.addRequestToMark(curRequestDataType, NetRequestLifeMarker.REQUEST_STATE_ING); } } /** * 某个请求类型的网络请求是否已经完成 * @param requestDataType * @return */ protected boolean curRequestFinished(int requestDataType) { if (netRequestLifeMarker != null) { return netRequestLifeMarker.curRequestLifeState(requestDataType) == NetRequestLifeMarker.REQUEST_STATE_FINISHED; } return false; } /*** * 取消网络请求(注:该方法只适合本框架的Retrofit请求模块才会真正取消网络请求, * 如果使用的是本框架的OkGo请求模块,还请各APP的基类再进行处理一下,或本框架再优化来统一处理) * @param curRequestType 要取消的网络请求类型 */ protected void cancelNetRequest(int curRequestType) { if (netRequestLifeMarker != null) { netRequestLifeMarker.cancelCallRequest(curRequestType); } } /** * 判断是否某些网络请求全部完成了 * @param theRequestTypes 对应要加入判断的网络请求类型 * @return true:所有参与判断的网络请求都完成了;false:只要有任何一个请求未完成即未完成。 */ protected boolean isAllRequestFinished(int... theRequestTypes) { if (theRequestTypes == null || theRequestTypes.length == 0) { return false; } for (int oneRequestType : theRequestTypes) { if (!curRequestFinished(oneRequestType)) { return false;//只要有一个请求没有完成,就是未全部完成 } } return true; } /** * 注意:该提示性PopupWindow适用与在一个界面的顶部经由上至下的动画弹出 * * @param anchorView 一般为顶部的一个控件 * @param xOffset X方向的偏移量 * @param yOffset Y方向的偏移量 */ @Override public void initCommonHintPopuWindow(View anchorView, int xOffset, int yOffset) { if (someUiHintAgent != null) { someUiHintAgent.initHintPopuWindow(anchorView,xOffset,yOffset); } } @Override public void showCommonLoading(String hintMsg) { if (someUiHintAgent != null) { someUiHintAgent.showLoading(hintMsg); } } @Override public void showCommonLoading(int hintMsgResID) { showCommonLoading(getString(hintMsgResID)); } @Override public void dialogHint(String dialogTitle, String hintMsg, String cancelBtnName, String sureBtnName, int dialogInCase) { if (someUiHintAgent != null) { someUiHintAgent.dialogHint(dialogTitle, hintMsg, cancelBtnName, sureBtnName, dialogInCase); } } @Override public void dialogHint(int titleResID, int hintMsgResID, int cancelBtnNameResID, int sureBtnNameResID, int dialogInCase) { String dialogTitle = getString(titleResID); String hintMsg = getString(hintMsgResID); String cancelBtnName = getString(cancelBtnNameResID); String sureBtnName = getString(sureBtnNameResID); dialogHint(dialogTitle, hintMsg, cancelBtnName, sureBtnName, dialogInCase); } @Override public void popupHint(String hintMsg) { if(someUiHintAgent != null) someUiHintAgent.popupHint(hintMsg); } @Override public void popupHint(int hintMsgResID) { popupHint(getString(hintMsgResID)); } protected void topToast(String msg) { ToastUtil.topShow(msg); } protected void topToast(int msgResId) { topToast(getString(msgResId)); } protected void i(String tag,Object... logBodys) { if (tag == null) { tag = TAG + "[" + extraInfoInLifeDebug + "]"; } CommonLog.i(tag, logBodys); } protected void e(String tag, Object... logBodys) { if (tag == null) { tag = TAG + "[" + extraInfoInLifeDebug + "]"; } CommonLog.e(tag, logBodys); } }
BaseFragment中增加通过id获取宿主Activity中的视图
src/main/java/common/base/fragments/BaseFragment.java
BaseFragment中增加通过id获取宿主Activity中的视图
<ide><path>rc/main/java/common/base/fragments/BaseFragment.java <ide> * @return T类型的视图控件 <ide> */ <ide> protected <T extends View> T findAviewById(int viewId) { <del>// if (viewId > 0) { <del>// return (T) getActivity().findViewById(viewId); <del>// } <del>// return null; <add> <ide> return findLocalViewById(viewId);//changed by fee 2017-09-13 一个Fragment在宿主Activity中来查找子视图控件不太合适 <ide> } <ide> <add> /** <add> * 在宿主Activity中根据view id 查找控件 <add> * @param viewId <add> * @param <T> <add> * @return <add> */ <add> protected <T extends View> T findAviewByIdInHostActivity(int viewId){ <add> if (viewId > 0) { <add> return (T) getActivity().findViewById(viewId); <add> } <add> return null; <add> } <ide> /** <ide> * 在Fragment所加载的视图里查找视图控件 <ide> * @param viewId
JavaScript
mit
cc39b800f4539971e82330c065a493e493f9095b
0
gibbok/keyframes-tool
const css = require('css'); const R = require('ramda'); const fs = require('fs'); fs.readFile(__dirname + '/test.css', function (err, data) { if (err) { throw err; } parse(data); }); let parse = function (data) { debugger // parse data file let obj = css.parse(data.toString(), { silent: false }); // validation if(!R.path(['type'], obj) === 'stylesheet'){ throw 'file is not a stylesheet'; } if(!R.length(R.path(['stylesheet','parsingErrors'], obj)) === 0){ throw 'file has parsing errors'; } var predRulesKeyframes = (rule) => rule.type === 'keyframes'; let hasKeyframes = R.any(predRulesKeyframes, obj.stylesheet.rules); if (!hasKeyframes) { throw 'file does not contain keyframes rules'; } debugger var processKeyframe = (vals, declarations) => [ R.map(R.cond([ [R.equals('from'), R.always(0)], [R.equals('to'), R.always(100)], [R.T, parseFloat] ]), vals), R.reduce(R.merge, {}, R.map(R.converge(R.objOf, [ R.prop('property'), R.prop('value') ]), declarations)) ] var processAnimation = (offsets, transf) => R.map(R.pipe( R.objOf('offset'), R.merge(transf)), offsets) var getContentOfKeyframes = R.map(R.pipe( R.converge(processKeyframe, [ R.prop('values'), R.prop('declarations') ]), R.converge(processAnimation, [ R.nth(0), R.nth(1) ]))) var transformAST = R.pipe( R.path(['stylesheet', 'rules']), R.filter(R.propEq('type', 'keyframes')), R.map((keyframe) => ({ name: keyframe.name, content: getContentOfKeyframes(keyframe.keyframes) })), R.converge(R.zipObj, [ R.map(R.prop('name')), R.map(R.pipe(R.prop('content'), R.flatten)) ])) var result = transformAST(obj) debugger // //-------------------------------------- // var result = {}; // // keyframes // kfs.forEach(function (kf) { // result[kf.name] = []; // kf.keyframes.forEach(function (kfi) { // kfi.values.forEach(function (v) { // var r = {}; // var vNew; // vNew = v; // if (v === 'from') { // vNew = 0; // } else if (v === 'to') { // vNew = 100; // } else { // vNew = parseFloat(v); // } // r.offset = vNew; // kfi.declarations.forEach(function (d) { // r[d.property] = d.value; // }); // result[kf.name].push(r); // }); // }); // }); //let result = css.stringify(obj); //console.log(JSON.stringify(result)); };
index.js
const css = require('css'); const R = require('ramda'); const fs = require('fs'); fs.readFile(__dirname + '/test.css', function (err, data) { if (err) { throw err; } parse(data); }); let parse = function (data) { // parse data file let obj = css.parse(data.toString(), { silent: false }); // validation let isStylesheet = R.equals(obj.type, 'stylesheet'); if (!isStylesheet) { throw 'file is not a stylesheet'; } let hasParsingErrors = R.length(obj.stylesheet.parsingErrors.length) > 0; if (hasParsingErrors) { throw 'file has parsing errors'; } var predRulesKeyframes = (rule) => rule.type === 'keyframes'; let hasKeyframes = R.any(predRulesKeyframes, obj.stylesheet.rules); if (!hasKeyframes) { throw 'file does not contain keyframes rules'; } var kfs = obj.stylesheet.rules.filter(function (rule) { return rule.type === 'keyframes' }); var result = {}; // keyframes kfs.forEach(function (kf) { result[kf.name] = []; kf.keyframes.forEach(function (kfi) { kfi.values.forEach(function (v) { var r = {}; var vNew; vNew = v; if (v === 'from') { vNew = 0; } else if (v === 'to') { vNew = 100; } else { vNew = parseFloat(v); } r.offset = vNew; kfi.declarations.forEach(function (d) { r[d.property] = d.value; }); result[kf.name].push(r); }); }); }); debugger // get all rules with type keyframes // for each rule keyframe take values // for each values // loop in declarations // create an object for result for each property and value debugger console.log(obj); //let result = css.stringify(obj); //console.log(JSON.stringify(result)); };
Add conversion to ramdajs
index.js
<ide><path>ndex.js <ide> }); <ide> <ide> let parse = function (data) { <add> debugger <ide> // parse data file <ide> let obj = css.parse(data.toString(), { silent: false }); <ide> <ide> // validation <del> let isStylesheet = R.equals(obj.type, 'stylesheet'); <del> if (!isStylesheet) { <add> if(!R.path(['type'], obj) === 'stylesheet'){ <ide> throw 'file is not a stylesheet'; <ide> } <del> let hasParsingErrors = R.length(obj.stylesheet.parsingErrors.length) > 0; <del> if (hasParsingErrors) { <add> if(!R.length(R.path(['stylesheet','parsingErrors'], obj)) === 0){ <ide> throw 'file has parsing errors'; <ide> } <add> <ide> var predRulesKeyframes = (rule) => rule.type === 'keyframes'; <ide> let hasKeyframes = R.any(predRulesKeyframes, obj.stylesheet.rules); <ide> if (!hasKeyframes) { <ide> throw 'file does not contain keyframes rules'; <ide> } <del> var kfs = obj.stylesheet.rules.filter(function (rule) { <del> return rule.type === 'keyframes' <del> }); <del> var result = {}; <del> // keyframes <del> kfs.forEach(function (kf) { <del> result[kf.name] = []; <del> kf.keyframes.forEach(function (kfi) { <del> kfi.values.forEach(function (v) { <del> var r = {}; <del> var vNew; <del> vNew = v; <del> if (v === 'from') { <del> vNew = 0; <del> } else if (v === 'to') { <del> vNew = 100; <del> } else { <del> vNew = parseFloat(v); <del> } <del> r.offset = vNew; <del> kfi.declarations.forEach(function (d) { <del> r[d.property] = d.value; <del> <del> }); <del> result[kf.name].push(r); <del> }); <del> }); <del> }); <ide> <ide> debugger <del> // get all rules with type keyframes <del> // for each rule keyframe take values <del> // for each values <del> // loop in declarations <del> // create an object for result for each property and value <add> var processKeyframe = (vals, declarations) => [ <add> R.map(R.cond([ <add> [R.equals('from'), R.always(0)], <add> [R.equals('to'), R.always(100)], <add> [R.T, parseFloat] <add> ]), vals), <add> R.reduce(R.merge, {}, <add> R.map(R.converge(R.objOf, [ <add> R.prop('property'), <add> R.prop('value') <add> ]), declarations)) <add> ] <ide> <add> var processAnimation = (offsets, transf) => <add> R.map(R.pipe( <add> R.objOf('offset'), <add> R.merge(transf)), offsets) <add> <add> var getContentOfKeyframes = R.map(R.pipe( <add> R.converge(processKeyframe, [ <add> R.prop('values'), <add> R.prop('declarations') <add> ]), <add> R.converge(processAnimation, [ <add> R.nth(0), <add> R.nth(1) <add> ]))) <add> <add> var transformAST = R.pipe( <add> R.path(['stylesheet', 'rules']), <add> R.filter(R.propEq('type', 'keyframes')), <add> R.map((keyframe) => ({ <add> name: keyframe.name, <add> content: getContentOfKeyframes(keyframe.keyframes) <add> })), <add> R.converge(R.zipObj, [ <add> R.map(R.prop('name')), <add> R.map(R.pipe(R.prop('content'), R.flatten)) <add> ])) <add> <add> var result = transformAST(obj) <ide> debugger <add> // //-------------------------------------- <add> // var result = {}; <add> // // keyframes <add> // kfs.forEach(function (kf) { <add> // result[kf.name] = []; <add> // kf.keyframes.forEach(function (kfi) { <add> // kfi.values.forEach(function (v) { <add> // var r = {}; <add> // var vNew; <add> // vNew = v; <add> // if (v === 'from') { <add> // vNew = 0; <add> // } else if (v === 'to') { <add> // vNew = 100; <add> // } else { <add> // vNew = parseFloat(v); <add> // } <add> // r.offset = vNew; <add> // kfi.declarations.forEach(function (d) { <add> // r[d.property] = d.value; <ide> <add> // }); <add> // result[kf.name].push(r); <add> // }); <add> // }); <add> // }); <ide> <del> <del> <del> console.log(obj); <ide> <ide> //let result = css.stringify(obj); <ide> //console.log(JSON.stringify(result));
Java
mit
36ee6cc798aa87ebd2fc8d437590d98181080df6
0
inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid,inaturalist/iNaturalistAndroid
package org.inaturalist.android; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.tinylog.Logger; import com.crashlytics.android.Crashlytics; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import com.google.maps.GeoApiContext; import com.google.maps.TimeZoneApi; import com.google.maps.model.LatLng; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import android.annotation.SuppressLint; import android.app.IntentService; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.SQLException; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.provider.MediaStore; import androidx.core.app.NotificationCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import android.widget.Toast; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static java.net.HttpURLConnection.HTTP_GONE; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; import static java.net.HttpURLConnection.HTTP_UNAVAILABLE; public class INaturalistService extends IntentService { // How many observations should we initially download for the user private static final int INITIAL_SYNC_OBSERVATION_COUNT = 100; private static final int JWT_TOKEN_EXPIRATION_MINS = 25; // JWT Tokens expire after 30 mins - consider 25 mins as the max time (safe margin) private static final int OLD_PHOTOS_MAX_COUNT = 100; // Number of cached photos to save before removing them and turning them into online photos private static final int MAX_PHOTO_REPLACEMENTS_PER_RUN = 50; // Max number of photo replacements we'll do per run public static final String IS_SHARED_ON_APP = "is_shared_on_app"; private static final Map<String, String> TIMEZONE_ID_TO_INAT_TIMEZONE; private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final long HTTP_CONNECTION_TIMEOUT_SECONDS = 10; private static final long HTTP_READ_WRITE_TIMEOUT_SECONDS = 40; static { TIMEZONE_ID_TO_INAT_TIMEZONE = new HashMap(); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Algiers", "West Central Africa"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Cairo", "Cairo"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Casablanca", "Casablanca"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Harare", "Harare"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Johannesburg", "Pretoria"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Monrovia", "Monrovia"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Nairobi", "Nairobi"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Argentina/Buenos_Aires", "Buenos Aires"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Bogota", "Bogota"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Caracas", "Caracas"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Chicago", "Central Time (US & Canada)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Chihuahua", "Chihuahua"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Denver", "Mountain Time (US & Canada)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Godthab", "Greenland"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Guatemala", "Central America"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Guyana", "Georgetown"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Halifax", "Atlantic Time (Canada)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Indiana/Indianapolis", "Indiana (East)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Juneau", "Alaska"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/La_Paz", "La Paz"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Lima", "Lima"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Los_Angeles", "Pacific Time (US & Canada)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Mazatlan", "Mazatlan"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Mexico_City", "Mexico City"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Monterrey", "Monterrey"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Montevideo", "Montevideo"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/New_York", "Eastern Time (US & Canada)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Phoenix", "Arizona"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Regina", "Saskatchewan"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Santiago", "Santiago"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Sao_Paulo", "Brasilia"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/St_Johns", "Newfoundland"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Tijuana", "Tijuana"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Almaty", "Almaty"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Baghdad", "Baghdad"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Baku", "Baku"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Bangkok", "Bangkok"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Chongqing", "Chongqing"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Colombo", "Sri Jayawardenepura"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Dhaka", "Dhaka"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Hong_Kong", "Hong Kong"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Irkutsk", "Irkutsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Jakarta", "Jakarta"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Jerusalem", "Jerusalem"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kabul", "Kabul"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kamchatka", "Kamchatka"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Karachi", "Karachi"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kathmandu", "Kathmandu"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kolkata", "Kolkata"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Krasnoyarsk", "Krasnoyarsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kuala_Lumpur", "Kuala Lumpur"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kuwait", "Kuwait"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Magadan", "Magadan"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Muscat", "Muscat"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Novosibirsk", "Novosibirsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Rangoon", "Rangoon"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Riyadh", "Riyadh"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Seoul", "Seoul"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Shanghai", "Beijing"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Singapore", "Singapore"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Srednekolymsk", "Srednekolymsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Taipei", "Taipei"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Tashkent", "Tashkent"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Tbilisi", "Tbilisi"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Tehran", "Tehran"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Tokyo", "Tokyo"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Ulaanbaatar", "Ulaanbaatar"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Urumqi", "Urumqi"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Vladivostok", "Vladivostok"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Yakutsk", "Yakutsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Yekaterinburg", "Ekaterinburg"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Yerevan", "Yerevan"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Atlantic/Azores", "Azores"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Atlantic/Cape_Verde", "Cape Verde Is."); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Atlantic/South_Georgia", "Mid-Atlantic"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Adelaide", "Adelaide"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Brisbane", "Brisbane"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Darwin", "Darwin"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Hobart", "Hobart"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Melbourne", "Melbourne"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Perth", "Perth"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Sydney", "Sydney"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Etc/UTC", "UTC"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Amsterdam", "Amsterdam"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Athens", "Athens"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Belgrade", "Belgrade"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Berlin", "Berlin"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Bratislava", "Bratislava"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Brussels", "Brussels"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Bucharest", "Bucharest"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Budapest", "Budapest"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Copenhagen", "Copenhagen"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Dublin", "Dublin"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Helsinki", "Helsinki"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Istanbul", "Istanbul"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Kaliningrad", "Kaliningrad"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Kiev", "Kyiv"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Lisbon", "Lisbon"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Ljubljana", "Ljubljana"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/London", "London"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Madrid", "Madrid"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Minsk", "Minsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Moscow", "Moscow"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Paris", "Paris"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Prague", "Prague"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Riga", "Riga"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Rome", "Rome"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Samara", "Samara"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Sarajevo", "Sarajevo"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Skopje", "Skopje"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Sofia", "Sofia"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Stockholm", "Stockholm"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Tallinn", "Tallinn"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Vienna", "Vienna"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Vilnius", "Vilnius"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Volgograd", "Volgograd"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Warsaw", "Warsaw"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Zagreb", "Zagreb"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Apia", "Samoa"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Auckland", "Auckland"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Chatham", "Chatham Is."); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Fakaofo", "Tokelau Is."); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Fiji", "Fiji"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Guadalcanal", "Solomon Is."); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Guam", "Guam"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Honolulu", "Hawaii"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Majuro", "Marshall Is."); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Midway", "Midway Island"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Noumea", "New Caledonia"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Pago_Pago", "American Samoa"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Port_Moresby", "Port Moresby"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Tongatapu", "Nuku'alofa"); } private static final int MAX_OBSVERATIONS_TO_REDOWNLOAD = 100; // Happens when user switches language and we need the new taxon name in that language public static final String USER = "user"; public static final String AUTHENTICATION_FAILED = "authentication_failed"; public static final String USER_DELETED = "user_deleted"; public static final String IDENTIFICATION_ID = "identification_id"; public static final String OBSERVATION_ID = "observation_id"; public static final String GET_PROJECTS = "get_projects"; public static final String OBSERVATION_ID_INTERNAL = "observation_id_internal"; public static final String METRIC = "metric"; public static final String ATTRIBUTE_ID = "attribute_id"; public static final String VALUE_ID = "value_id"; public static final String FOLLOWING = "following"; public static final String FIELD_ID = "field_id"; public static final String COMMENT_ID = "comment_id"; public static final String OBSERVATION_RESULT = "observation_result"; public static final String HISTOGRAM_RESULT = "histogram_result"; public static final String POPULAR_FIELD_VALUES_RESULT = "popular_field_values_result"; public static final String USER_OBSERVATIONS_RESULT = "user_observations_result"; public static final String USER_SEARCH_OBSERVATIONS_RESULT = "user_search_observations_result"; public static final String OBSERVATION_JSON_RESULT = "observation_json_result"; public static final String SUCCESS = "success"; public static final String FLAGGABLE_TYPE = "flaggable_type"; public static final String FLAGGABLE_ID = "flaggable_id"; public static final String FLAG = "flag"; public static final String FLAG_EXPLANATION = "flag_explanation"; public static final String OBSERVATION_COUNT = "observation_count"; public static final String PROJECTS_RESULT = "projects_result"; public static final String IDENTIFICATIONS_RESULT = "identifications_result"; public static final String EXPLORE_GET_OBSERVATIONS_RESULT = "explore_get_observations_result"; public static final String EXPLORE_GET_SPECIES_RESULT = "explore_get_species_result"; public static final String EXPLORE_GET_IDENTIFIERS_RESULT = "explore_get_identifiers_result"; public static final String EXPLORE_GET_OBSERVERS_RESULT = "explore_get_observers_result"; public static final String GET_ATTRIBUTES_FOR_TAXON_RESULT = "get_attributes_for_taxon_result"; public static final String GET_ALL_ATTRIBUTES_RESULT = "get_all_attributes_result"; public static final String DELETE_ANNOTATION_RESULT = "delete_annotation_result"; public static final String DELETE_ANNOTATION_VOTE_RESULT = "delete_annotation_vote_result"; public static final String DELETE_DATA_QUALITY_VOTE_RESULT = "delete_data_quality_vote_result"; public static final String SET_ANNOTATION_VALUE_RESULT = "set_annotation_value_result"; public static final String DATA_QUALITY_METRICS_RESULT = "data_quality_metrics_result"; public static final String AGREE_ANNOTATION_RESULT = "agree_annotation_result"; public static final String DELETE_ID_CAN_BE_IMPROVED_VOTE_RESULT = "delete_id_can_be_improved_vote_result"; public static final String ID_CAN_BE_IMPROVED_RESULT = "id_can_be_improved_result"; public static final String ID_CANNOT_BE_IMPROVED_RESULT = "id_cannot_be_improved_result"; public static final String AGREE_DATA_QUALITY_RESULT = "agree_data_quality_result"; public static final String DISAGREE_DATA_QUALITY_RESULT = "disagree_data_quality_result"; public static final String DISAGREE_ANNOTATION_RESULT = "disagree_annotation_result"; public static final String UPDATES_RESULT = "updates_results"; public static final String UPDATES_FOLLOWING_RESULT = "updates_following_results"; public static final String LIFE_LIST_RESULT = "life_list_result"; public static final String SPECIES_COUNT_RESULT = "species_count_result"; public static final String RECOMMENDED_MISSIONS_RESULT = "recommended_missions_result"; public static final String MISSIONS_BY_TAXON_RESULT = "missions_by_taxon_result"; public static final String GET_CURRENT_LOCATION_RESULT = "get_current_location_result"; public static final String TAXON_OBSERVATION_BOUNDS_RESULT = "taxon_observation_bounds_result"; public static final String USER_DETAILS_RESULT = "user_details_result"; public static final String PLACE_DETAILS_RESULT = "place_details_result"; public static final String REFRESH_CURRENT_USER_SETTINGS_RESULT = "refresh_current_user_settings_result"; public static final String UPDATE_CURRENT_USER_DETAILS_RESULT = "update_current_user_details_result"; public static final String OBSERVATION_SYNC_PROGRESS = "observation_sync_progress"; public static final String ADD_OBSERVATION_TO_PROJECT_RESULT = "add_observation_to_project_result"; public static final String DELETE_ACCOUNT_RESULT = "delete_account_result"; public static final String TAXON_ID = "taxon_id"; public static final String RESEARCH_GRADE = "research_grade"; public static final String TAXON = "taxon"; public static final String UUID = "uuid"; public static final String NETWORK_SITE_ID = "network_site_id"; public static final String COMMENT_BODY = "comment_body"; public static final String IDENTIFICATION_BODY = "id_body"; public static final String DISAGREEMENT = "disagreement"; public static final String FROM_VISION = "from_vision"; public static final String PROJECT_ID = "project_id"; public static final String CHECK_LIST_ID = "check_list_id"; public static final String ACTION_CHECK_LIST_RESULT = "action_check_list_result"; public static final String ACTION_MESSAGES_RESULT = "action_messages_result"; public static final String ACTION_NOTIFICATION_COUNTS_RESULT = "action_notification_counts_result"; public static final String ACTION_POST_MESSAGE_RESULT = "action_post_message_result"; public static final String ACTION_MUTE_USER_RESULT = "action_mute_user_result"; public static final String ACTION_POST_FLAG_RESULT = "action_post_flag_result"; public static final String ACTION_UNMUTE_USER_RESULT = "action_unmute_user_result"; public static final String CHECK_LIST_RESULT = "check_list_result"; public static final String ACTION_GET_TAXON_RESULT = "action_get_taxon_result"; public static final String SEARCH_TAXA_RESULT = "search_taxa_result"; public static final String SEARCH_USERS_RESULT = "search_users_result"; public static final String SEARCH_PLACES_RESULT = "search_places_result"; public static final String ACTION_GET_TAXON_NEW_RESULT = "action_get_taxon_new_result"; public static final String ACTION_GET_TAXON_SUGGESTIONS_RESULT = "action_get_taxon_suggestions_result"; public static final String TAXON_RESULT = "taxon_result"; public static final String TAXON_SUGGESTIONS = "taxon_suggestions"; public static final String GUIDE_XML_RESULT = "guide_xml_result"; public static final String EMAIL = "email"; public static final String OBS_PHOTO_FILENAME = "obs_photo_filename"; public static final String OBS_PHOTO_URL = "obs_photo_url"; public static final String LONGITUDE = "longitude"; public static final String ACCURACY = "accuracy"; public static final String TITLE = "title"; public static final String GEOPRIVACY = "geoprivacy"; public static final String LATITUDE = "latitude"; public static final String OBSERVED_ON = "observed_on"; public static final String USERNAME = "username"; public static final String PLACE = "place"; public static final String PLACE_ID = "place_id"; public static final String LOCATION = "location"; public static final String FILTERS = "filters"; public static final String PROGRESS = "progress"; public static final String EXPAND_LOCATION_BY_DEGREES = "expand_location_by_degrees"; public static final String QUERY = "query"; public static final String BOX = "box"; public static final String GROUP_BY_THREADS = "group_by_threads"; public static final String MESSAGE_ID = "message_id"; public static final String NOTIFICATIONS = "notifications"; public static final String TO_USER = "to_user"; public static final String THREAD_ID = "thread_id"; public static final String SUBJECT = "subject"; public static final String BODY = "body"; public static final String OBSERVATIONS = "observations"; public static final String IDENTIFICATIONS = "identifications"; public static final String LIFE_LIST_ID = "life_list_id"; public static final String PASSWORD = "password"; public static final String LICENSE = "license"; public static final String RESULTS = "results"; public static final String LIFE_LIST = "life_list"; public static final String REGISTER_USER_ERROR = "error"; public static final String REGISTER_USER_STATUS = "status"; public static final String SYNC_CANCELED = "sync_canceled"; public static final String SYNC_FAILED = "sync_failed"; public static final String FIRST_SYNC = "first_sync"; public static final String PAGE_NUMBER = "page_number"; public static final String PAGE_SIZE = "page_size"; public static final String ID = "id"; public static final String OBS_IDS_TO_SYNC = "obs_ids_to_sync"; public static final String OBS_IDS_TO_DELETE = "obs_ids_to_delete"; public static final int NEAR_BY_OBSERVATIONS_PER_PAGE = 25; public static final int EXPLORE_DEFAULT_RESULTS_PER_PAGE = 30; public static String TAG = "INaturalistService"; public static String HOST = "https://www.inaturalist.org"; public static String API_HOST = "https://api.inaturalist.org/v1"; public static String USER_AGENT = "iNaturalist/%VERSION% (" + "Build %BUILD%; " + "Android " + System.getProperty("os.version") + " " + android.os.Build.VERSION.INCREMENTAL + "; " + "SDK " + android.os.Build.VERSION.SDK_INT + "; " + android.os.Build.DEVICE + " " + android.os.Build.MODEL + " " + android.os.Build.PRODUCT + "; OS Version " + android.os.Build.VERSION.RELEASE + ")"; public static String ACTION_GET_HISTOGRAM = "action_get_histogram"; public static String ACTION_GET_POPULAR_FIELD_VALUES = "action_get_popular_field_values"; public static String ACTION_ADD_MISSING_OBS_UUID = "action_add_missing_obs_uuid"; public static String ACTION_REGISTER_USER = "register_user"; public static String ACTION_PASSIVE_SYNC = "passive_sync"; public static String ACTION_GET_ADDITIONAL_OBS = "get_additional_observations"; public static String ACTION_ADD_IDENTIFICATION = "add_identification"; public static String ACTION_ADD_PROJECT_FIELD = "add_project_field"; public static String ACTION_ADD_FAVORITE = "add_favorite"; public static String ACTION_REMOVE_FAVORITE = "remove_favorite"; public static String ACTION_GET_TAXON = "get_taxon"; public static String ACTION_SEARCH_TAXA = "search_taxa"; public static String ACTION_SEARCH_USERS = "search_users"; public static String ACTION_SEARCH_PLACES = "search_places"; public static String ACTION_GET_TAXON_NEW = "get_taxon_new"; public static String ACTION_GET_TAXON_SUGGESTIONS = "get_taxon_suggestions"; public static String ACTION_FIRST_SYNC = "first_sync"; public static String ACTION_PULL_OBSERVATIONS = "pull_observations"; public static String ACTION_DELETE_OBSERVATIONS = "delete_observations"; public static String ACTION_GET_OBSERVATION = "get_observation"; public static String ACTION_GET_AND_SAVE_OBSERVATION = "get_and_save_observation"; public static String ACTION_FLAG_OBSERVATION_AS_CAPTIVE = "flag_observation_as_captive"; public static String ACTION_GET_CHECK_LIST = "get_check_list"; public static String ACTION_GET_MESSAGES = "get_messages"; public static String ACTION_GET_NOTIFICATION_COUNTS = "get_notification_counts"; public static String ACTION_POST_MESSAGE = "post_message"; public static String ACTION_MUTE_USER = "mute_user"; public static String ACTION_POST_FLAG = "post_flag"; public static String ACTION_UNMUTE_USER = "unmute_user"; public static String ACTION_JOIN_PROJECT = "join_project"; public static String ACTION_LEAVE_PROJECT = "leave_project"; public static String ACTION_GET_JOINED_PROJECTS = "get_joined_projects"; public static String ACTION_GET_JOINED_PROJECTS_ONLINE = "get_joined_projects_online"; public static String ACTION_GET_NEARBY_PROJECTS = "get_nearby_projects"; public static String ACTION_GET_FEATURED_PROJECTS = "get_featured_projects"; public static String ACTION_ADD_OBSERVATION_TO_PROJECT = "add_observation_to_project"; public static String ACTION_REMOVE_OBSERVATION_FROM_PROJECT = "remove_observation_from_project"; public static String ACTION_REDOWNLOAD_OBSERVATIONS_FOR_TAXON = "redownload_observations_for_taxon"; public static String ACTION_SYNC_JOINED_PROJECTS = "sync_joined_projects"; public static String ACTION_DELETE_ACCOUNT = "delete_account"; public static String ACTION_GET_ALL_GUIDES = "get_all_guides"; public static String ACTION_GET_MY_GUIDES = "get_my_guides"; public static String ACTION_GET_NEAR_BY_GUIDES = "get_near_by_guides"; public static String ACTION_TAXA_FOR_GUIDE = "get_taxa_for_guide"; public static String ACTION_GET_USER_DETAILS = "get_user_details"; public static String ACTION_UPDATE_USER_DETAILS = "update_user_details"; public static String ACTION_CLEAR_OLD_PHOTOS_CACHE = "clear_old_photos_cache"; public static String ACTION_GET_ATTRIBUTES_FOR_TAXON = "get_attributes_for_taxon"; public static String ACTION_GET_ALL_ATTRIBUTES = "get_all_attributes"; public static String ACTION_DELETE_ANNOTATION = "delete_annotation"; public static String ACTION_AGREE_ANNOTATION = "agree_annotation"; public static String ACTION_AGREE_DATA_QUALITY = "agree_data_quality"; public static String ACTION_DISAGREE_DATA_QUALITY = "disagree_data_quality"; public static String ACTION_DELETE_ID_CAN_BE_IMPROVED_VOTE = "delete_id_can_be_improved_vote"; public static String ACTION_ID_CAN_BE_IMPROVED_VOTE = "id_can_be_improved_vote"; public static String ACTION_ID_CANNOT_BE_IMPROVED_VOTE = "id_cannot_be_improved_vote"; public static String ACTION_DELETE_ANNOTATION_VOTE = "delete_annotation_vote"; public static String ACTION_DELETE_DATA_QUALITY_VOTE = "delete_data_quality_vote"; public static String ACTION_GET_DATA_QUALITY_METRICS = "get_data_quality_metrics"; public static String ACTION_SET_ANNOTATION_VALUE = "set_annotation_value"; public static String ACTION_DISAGREE_ANNOTATION = "disagree_annotation"; public static String ACTION_GET_PROJECT_NEWS = "get_project_news"; public static String ACTION_GET_NEWS = "get_news"; public static String ACTION_GET_PROJECT_OBSERVATIONS = "get_project_observations"; public static String ACTION_GET_PROJECT_SPECIES = "get_project_species"; public static String ACTION_GET_PROJECT_OBSERVERS = "get_project_observers"; public static String ACTION_GET_PROJECT_IDENTIFIERS = "get_project_identifiers"; public static String ACTION_PROJECT_OBSERVATIONS_RESULT = "get_project_observations_result"; public static String ACTION_PROJECT_NEWS_RESULT = "get_project_news_result"; public static String ACTION_NEWS_RESULT = "get_news_result"; public static String ACTION_PROJECT_SPECIES_RESULT = "get_project_species_result"; public static String ACTION_PROJECT_OBSERVERS_RESULT = "get_project_observers_result"; public static String ACTION_PROJECT_IDENTIFIERS_RESULT = "get_project_identifiers_result"; public static String ACTION_SYNC = "sync"; public static String ACTION_NEARBY = "nearby"; public static String ACTION_AGREE_ID = "agree_id"; public static String ACTION_REMOVE_ID = "remove_id"; public static String ACTION_UPDATE_ID = "update_id"; public static String ACTION_RESTORE_ID = "restore_id"; public static String ACTION_GUIDE_ID = "guide_id"; public static String ACTION_ADD_COMMENT = "add_comment"; public static String ACTION_UPDATE_COMMENT = "update_comment"; public static String ACTION_DELETE_COMMENT = "delete_comment"; public static String ACTION_SYNC_COMPLETE = "sync_complete"; public static String ACTION_GET_AND_SAVE_OBSERVATION_RESULT = "get_and_save_observation_result"; public static String ACTION_GET_ADDITIONAL_OBS_RESULT = "get_additional_obs_result"; public static String ACTION_OBSERVATION_RESULT = "action_observation_result"; public static String ACTION_JOINED_PROJECTS_RESULT = "joined_projects_result"; public static String ACTION_NEARBY_PROJECTS_RESULT = "nearby_projects_result"; public static String ACTION_FEATURED_PROJECTS_RESULT = "featured_projects_result"; public static String ACTION_ALL_GUIDES_RESULT = "all_guides_results"; public static String ACTION_MY_GUIDES_RESULT = "my_guides_results"; public static String ACTION_NEAR_BY_GUIDES_RESULT = "near_by_guides_results"; public static String ACTION_TAXA_FOR_GUIDES_RESULT = "taxa_for_guides_results"; public static String ACTION_GET_USER_DETAILS_RESULT = "get_user_details_result"; public static String ACTION_UPDATE_USER_DETAILS_RESULT = "update_user_details_result"; public static String ACTION_GUIDE_XML_RESULT = "guide_xml_result"; public static String ACTION_GUIDE_XML = "guide_xml"; public static String GUIDES_RESULT = "guides_result"; public static String ACTION_USERNAME = "username"; public static String ACTION_FULL_NAME = "full_name"; public static String ACTION_USER_BIO = "user_bio"; public static String ACTION_USER_PASSWORD = "user_password"; public static String ACTION_USER_EMAIL = "user_email"; public static String ACTION_USER_PIC = "user_pic"; public static String ACTION_USER_DELETE_PIC = "user_delete_pic"; public static String ACTION_REGISTER_USER_RESULT = "register_user_result"; public static String TAXA_GUIDE_RESULT = "taxa_guide_result"; public static String ACTION_GET_SPECIFIC_USER_DETAILS = "get_specific_user_details"; public static String ACTION_GET_PLACE_DETAILS = "get_place_details"; public static String ACTION_PIN_LOCATION = "pin_location"; public static String ACTION_DELETE_PINNED_LOCATION = "delete_pinned_location"; public static String ACTION_REFRESH_CURRENT_USER_SETTINGS = "refresh_current_user_settings"; public static String ACTION_UPDATE_CURRENT_USER_DETAILS = "update_current_user_details"; public static String ACTION_GET_CURRENT_LOCATION = "get_current_location"; public static String ACTION_GET_LIFE_LIST = "get_life_list"; public static String ACTION_GET_USER_SPECIES_COUNT = "get_species_count"; public static String ACTION_GET_USER_IDENTIFICATIONS = "get_user_identifications"; public static String ACTION_GET_USER_UPDATES = "get_user_udpates"; public static String ACTION_EXPLORE_GET_OBSERVATIONS = "explore_get_observations"; public static String ACTION_EXPLORE_GET_SPECIES = "explore_get_species"; public static String ACTION_EXPLORE_GET_IDENTIFIERS = "explore_get_identifiers"; public static String ACTION_EXPLORE_GET_OBSERVERS = "explore_get_observers"; public static String ACTION_VIEWED_UPDATE = "viewed_update"; public static String ACTION_GET_USER_OBSERVATIONS = "get_user_observations"; public static String ACTION_GET_RECOMMENDED_MISSIONS = "get_recommended_missions"; public static String ACTION_GET_MISSIONS_BY_TAXON = "get_missions_by_taxon"; public static String ACTION_SEARCH_USER_OBSERVATIONS = "search_user_observations"; public static String ACTION_GET_TAXON_OBSERVATION_BOUNDS = "get_taxon_observation_bounds"; public static String ACTION_UPDATE_USER_NETWORK = "update_user_network"; public static Integer SYNC_OBSERVATIONS_NOTIFICATION = 1; public static Integer SYNC_PHOTOS_NOTIFICATION = 2; public static Integer AUTH_NOTIFICATION = 3; private String mLogin; private String mCredentials; private SharedPreferences mPreferences; private boolean mPassive; private INaturalistApp mApp; private LoginType mLoginType; private boolean mIsStopped = false; private boolean mIsSyncing; private boolean mIsClearingOldPhotosCache; private long mLastConnectionTest = 0; private Handler mHandler; private GoogleApiClient mLocationClient; private ArrayList<SerializableJSONArray> mProjectObservations; private Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>> mProjectFieldValues; private Headers mResponseHeaders = null; private Date mRetryAfterDate = null; private long mLastServiceUnavailableNotification = 0; private boolean mServiceUnavailable = false; private JSONArray mResponseErrors; private String mNearByObservationsUrl; private int mLastStatusCode = 0; private Object mObservationLock = new Object(); private Object mSyncJsonLock = new Object(); private List<String> mSyncedJSONs = new ArrayList<>(); private Location mLastLocation = null; public enum LoginType { PASSWORD, GOOGLE, FACEBOOK, OAUTH_PASSWORD }; public INaturalistService() { super("INaturalistService"); mHandler = new Handler(); } @Override public void onCreate() { super.onCreate(); Logger.tag(TAG).info("Service onCreate"); startIntentForeground(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Logger.tag(TAG).info("Service onStartCommand"); startIntentForeground(); return super.onStartCommand(intent, flags, startId); } private void startIntentForeground() { String channelId = "inaturalist_service"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Logger.tag(TAG).info("Service startIntentForeground"); // See: https://stackoverflow.com/a/46449975/1233767 NotificationChannel channel = new NotificationChannel(channelId, " ", NotificationManager.IMPORTANCE_LOW); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId) .setOngoing(false) .setPriority(NotificationCompat.PRIORITY_MIN) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.running_in_background_notfication)) .setCategory(Notification.CATEGORY_SERVICE) .setSmallIcon(R.drawable.ic_notification); Notification notification = builder.build(); startForeground(101, notification); } } @Override protected void onHandleIntent(final Intent intent) { new Thread(new Runnable() { @Override public void run() { onHandleIntentWorker(intent); } }).start(); } protected void onHandleIntentWorker(final Intent intent) { boolean cancelSyncRequested = false; boolean syncFailed = false; boolean dontStopSync = false; mPreferences = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); mLogin = mPreferences.getString("username", null); mCredentials = mPreferences.getString("credentials", null); mLoginType = LoginType.valueOf(mPreferences.getString("login_type", LoginType.OAUTH_PASSWORD.toString())); mApp = (INaturalistApp) getApplicationContext(); if (intent == null) return; String action = intent.getAction(); if (action == null) return; mPassive = action.equals(ACTION_PASSIVE_SYNC); Logger.tag(TAG).debug("Service: " + action); try { if (action.equals(ACTION_NEARBY)) { Boolean getLocation = intent.getBooleanExtra("get_location", false); final float locationExpansion = intent.getFloatExtra("location_expansion", 0); if (!getLocation) { getNearbyObservations(intent); } else { // Retrieve current place before getting nearby observations getLocation(new IOnLocation() { @Override public void onLocation(Location location) { final Intent newIntent = new Intent(intent); if (location != null) { if (locationExpansion == 0) { newIntent.putExtra("lat", location.getLatitude()); newIntent.putExtra("lng", location.getLongitude()); } else { // Expand place by requested degrees (to make sure results are returned from this API) newIntent.putExtra("minx", location.getLongitude() - locationExpansion); newIntent.putExtra("miny", location.getLatitude() - locationExpansion); newIntent.putExtra("maxx", location.getLongitude() + locationExpansion); newIntent.putExtra("maxy", location.getLatitude() + locationExpansion); } } try { getNearbyObservations(newIntent); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); } } }); } } else if (action.equals(ACTION_FIRST_SYNC)) { mIsSyncing = true; mApp.setIsSyncing(mIsSyncing); saveJoinedProjects(); boolean success = getUserObservations(INITIAL_SYNC_OBSERVATION_COUNT); // Get total obs count BetterJSONObject user = getUserDetails(); if (user == null) { throw new SyncFailedException(); } int totalObsCount = user.getInt("observations_count"); mPreferences.edit().putInt("observation_count", totalObsCount).commit(); Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "(is_deleted = 0 OR is_deleted is NULL) AND (user_login = '" + mLogin + "')", null, Observation.DEFAULT_SORT_ORDER); c.moveToLast(); if (c.getCount() > 0) { BetterCursor bc = new BetterCursor(c); int lastId = bc.getInteger(Observation.ID); mPreferences.edit().putInt("last_downloaded_id", lastId).commit(); } else { // No observations - probably a new user // Update the user's timezone (in case we registered via FB/G+) getTimezoneByCurrentLocation(new IOnTimezone() { @Override public void onTimezone(String timezoneName) { Logger.tag(TAG).debug("Detected Timezone: " + timezoneName); if (timezoneName != null) { try { updateUserTimezone(timezoneName); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); } } } }); } c.close(); if (success) { long lastSync = System.currentTimeMillis(); mPreferences.edit().putLong("last_sync_time", lastSync).commit(); } if (!success) throw new SyncFailedException(); syncObservationFields(); postProjectObservations(); } else if (action.equals(ACTION_GET_HISTOGRAM)) { int taxonId = intent.getIntExtra(TAXON_ID, 0); boolean researchGrade = intent.getBooleanExtra(RESEARCH_GRADE, false); BetterJSONObject results = getHistogram(taxonId, researchGrade); Intent reply = new Intent(HISTOGRAM_RESULT); reply.putExtra(HISTOGRAM_RESULT, results); reply.putExtra(RESEARCH_GRADE, researchGrade); reply.putExtra(TAXON_ID, taxonId); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_ADD_MISSING_OBS_UUID)) { addObservationUUIDsToPhotosAndSounds(); } else if (action.equals(ACTION_GET_POPULAR_FIELD_VALUES)) { int taxonId = intent.getIntExtra(TAXON_ID, 0); BetterJSONObject results = getPopularFieldValues(taxonId); Intent reply = new Intent(POPULAR_FIELD_VALUES_RESULT); reply.putExtra(POPULAR_FIELD_VALUES_RESULT, results); reply.putExtra(TAXON_ID, taxonId); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_AGREE_ID)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int taxonId = intent.getIntExtra(TAXON_ID, 0); boolean disagreement = intent.getBooleanExtra(DISAGREEMENT, false); addIdentification(observationId, taxonId, null, disagreement, false); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_RESTORE_ID)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int identificationId = intent.getIntExtra(IDENTIFICATION_ID, 0); restoreIdentification(identificationId); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_UPDATE_ID)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int taxonId = intent.getIntExtra(TAXON_ID, 0); int identificationId = intent.getIntExtra(IDENTIFICATION_ID, 0); String body = intent.getStringExtra(IDENTIFICATION_BODY); updateIdentification(observationId, identificationId, taxonId, body); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_REMOVE_ID)) { int id = intent.getIntExtra(IDENTIFICATION_ID, 0); int observationId = intent.getIntExtra(OBSERVATION_ID, 0); JSONObject result = removeIdentification(id); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_ADD_FAVORITE)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); addFavorite(observationId); } else if (action.equals(ACTION_REMOVE_FAVORITE)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); removeFavorite(observationId); } else if (action.equals(ACTION_GET_ADDITIONAL_OBS)) { int obsCount = getAdditionalUserObservations(20); Intent reply = new Intent(ACTION_GET_ADDITIONAL_OBS_RESULT); reply.putExtra(SUCCESS, obsCount > -1); reply.putExtra(OBSERVATION_COUNT, obsCount); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_ADD_IDENTIFICATION)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int taxonId = intent.getIntExtra(TAXON_ID, 0); String body = intent.getStringExtra(IDENTIFICATION_BODY); boolean disagreement = intent.getBooleanExtra(DISAGREEMENT, false); boolean fromVision = intent.getBooleanExtra(FROM_VISION, false); addIdentification(observationId, taxonId, body, disagreement, fromVision); // Wait a little before refreshing the observation details - so we'll let the server update the ID // list (otherwise, it won't return the new ID) try { Thread.sleep(1000); } catch (InterruptedException e) { Logger.tag(TAG).error(e); } // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_ADD_PROJECT_FIELD)) { int fieldId = intent.getIntExtra(FIELD_ID, 0); addProjectField(fieldId); } else if (action.equals(ACTION_REGISTER_USER)) { String email = intent.getStringExtra(EMAIL); String password = intent.getStringExtra(PASSWORD); String username = intent.getStringExtra(USERNAME); String license = intent.getStringExtra(LICENSE); getTimezoneByCurrentLocation(new IOnTimezone() { @Override public void onTimezone(String timezoneName) { Logger.tag(TAG).debug("Detected Timezone: " + timezoneName); String error = null; try { error = registerUser(email, password, username, license, timezoneName); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); error = e.toString(); } Intent reply = new Intent(ACTION_REGISTER_USER_RESULT); reply.putExtra(REGISTER_USER_STATUS, error == null); reply.putExtra(REGISTER_USER_ERROR, error); boolean b = LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } }); } else if (action.equals(ACTION_GET_PROJECT_NEWS)) { int projectId = intent.getIntExtra(PROJECT_ID, 0); SerializableJSONArray results = getProjectNews(projectId); Intent reply = new Intent(ACTION_PROJECT_NEWS_RESULT); reply.putExtra(RESULTS, results); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_PROJECT_OBSERVATIONS)) { int projectId = intent.getIntExtra(PROJECT_ID, 0); BetterJSONObject results = getProjectObservations(projectId); results = getMinimalObservationResults(results); mApp.setServiceResult(ACTION_PROJECT_OBSERVATIONS_RESULT, results); Intent reply = new Intent(ACTION_PROJECT_OBSERVATIONS_RESULT); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_PROJECT_IDENTIFIERS)) { int projectId = intent.getIntExtra(PROJECT_ID, 0); BetterJSONObject results = getProjectIdentifiers(projectId); results = getMinimalObserverResults(results); Intent reply = new Intent(ACTION_PROJECT_IDENTIFIERS_RESULT); mApp.setServiceResult(ACTION_PROJECT_IDENTIFIERS_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_PROJECT_OBSERVERS)) { int projectId = intent.getIntExtra(PROJECT_ID, 0); BetterJSONObject results = getProjectObservers(projectId); results = getMinimalObserverResults(results); Intent reply = new Intent(ACTION_PROJECT_OBSERVERS_RESULT); mApp.setServiceResult(ACTION_PROJECT_OBSERVERS_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_PROJECT_SPECIES)) { int projectId = intent.getIntExtra(PROJECT_ID, 0); BetterJSONObject results = getProjectSpecies(projectId); results = getMinimalSpeciesResults(results); Intent reply = new Intent(ACTION_PROJECT_SPECIES_RESULT); mApp.setServiceResult(ACTION_PROJECT_SPECIES_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DELETE_ANNOTATION)) { String uuid = intent.getStringExtra(UUID); BetterJSONObject results = deleteAnnotation(uuid); Intent reply = new Intent(DELETE_ANNOTATION_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DELETE_ANNOTATION_VOTE)) { String uuid = intent.getStringExtra(UUID); BetterJSONObject results = deleteAnnotationVote(uuid); Intent reply = new Intent(DELETE_ANNOTATION_VOTE_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DELETE_ID_CAN_BE_IMPROVED_VOTE)) { int obsId = intent.getIntExtra(OBSERVATION_ID, 0); BetterJSONObject result = deleteIdCanBeImprovedVote(obsId); Intent reply = new Intent(DELETE_ID_CAN_BE_IMPROVED_VOTE_RESULT); reply.putExtra(DELETE_ID_CAN_BE_IMPROVED_VOTE_RESULT, result); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_ID_CAN_BE_IMPROVED_VOTE)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); BetterJSONObject result = voteIdCanBeImproved(observationId, true); Intent reply = new Intent(ID_CAN_BE_IMPROVED_RESULT); reply.putExtra(ID_CAN_BE_IMPROVED_RESULT, result); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_ID_CANNOT_BE_IMPROVED_VOTE)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); BetterJSONObject result = voteIdCanBeImproved(observationId, false); Intent reply = new Intent(ID_CANNOT_BE_IMPROVED_RESULT); reply.putExtra(ID_CANNOT_BE_IMPROVED_RESULT, result); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SET_ANNOTATION_VALUE)) { int obsId = intent.getIntExtra(OBSERVATION_ID, 0); int attributeId = intent.getIntExtra(ATTRIBUTE_ID, 0); int valueId = intent.getIntExtra(VALUE_ID, 0); BetterJSONObject results = setAnnotationValue(obsId, attributeId, valueId); Intent reply = new Intent(SET_ANNOTATION_VALUE_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_DATA_QUALITY_METRICS)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); BetterJSONObject results = getDataQualityMetrics(observationId); Intent reply = new Intent(DATA_QUALITY_METRICS_RESULT); reply.putExtra(DATA_QUALITY_METRICS_RESULT, results); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DELETE_DATA_QUALITY_VOTE)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); String metric = intent.getStringExtra(METRIC); BetterJSONObject result = deleteDataQualityMetricVote(observationId, metric); Intent reply = new Intent(DELETE_DATA_QUALITY_VOTE_RESULT); reply.putExtra(SUCCESS, result != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_AGREE_DATA_QUALITY)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); String metric = intent.getStringExtra(METRIC); BetterJSONObject results = agreeDataQualityMetric(observationId, metric, true); Intent reply = new Intent(AGREE_DATA_QUALITY_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DISAGREE_DATA_QUALITY)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); String metric = intent.getStringExtra(METRIC); BetterJSONObject results = agreeDataQualityMetric(observationId, metric, false); Intent reply = new Intent(DISAGREE_DATA_QUALITY_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_AGREE_ANNOTATION)) { String uuid = intent.getStringExtra(UUID); BetterJSONObject results = agreeAnnotation(uuid, true); Intent reply = new Intent(AGREE_ANNOTATION_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DISAGREE_ANNOTATION)) { String uuid = intent.getStringExtra(UUID); BetterJSONObject results = agreeAnnotation(uuid, false); Intent reply = new Intent(DISAGREE_ANNOTATION_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_ALL_ATTRIBUTES)) { BetterJSONObject results = getAllAttributes(); Intent reply = new Intent(GET_ALL_ATTRIBUTES_RESULT); mApp.setServiceResult(GET_ALL_ATTRIBUTES_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_ATTRIBUTES_FOR_TAXON)) { BetterJSONObject taxon = (BetterJSONObject) intent.getSerializableExtra(TAXON); BetterJSONObject results = getAttributesForTaxon(taxon != null ? taxon.getJSONObject() : null); Intent reply = new Intent(GET_ATTRIBUTES_FOR_TAXON_RESULT); mApp.setServiceResult(GET_ATTRIBUTES_FOR_TAXON_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_TAXON_SUGGESTIONS)) { String obsFilename = intent.getStringExtra(OBS_PHOTO_FILENAME); String obsUrl = intent.getStringExtra(OBS_PHOTO_URL); Double longitude = intent.getDoubleExtra(LONGITUDE, 0); Double latitude = intent.getDoubleExtra(LATITUDE, 0); Timestamp observedOn = (Timestamp) intent.getSerializableExtra(OBSERVED_ON); File tempFile = null; if (obsFilename == null) { // It's an online observation - need to download the image first. try { tempFile = File.createTempFile("online_photo", ".jpeg", getCacheDir()); if (!downloadToFile(obsUrl, tempFile.getAbsolutePath())) { Intent reply = new Intent(ACTION_GET_TAXON_SUGGESTIONS_RESULT); reply.putExtra(TAXON_SUGGESTIONS, (Serializable) null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); return; } obsFilename = tempFile.getAbsolutePath(); } catch (IOException e) { Logger.tag(TAG).error(e); } } // Resize photo to 299x299 max String resizedPhotoFilename = ImageUtils.resizeImage(this, obsFilename, null, 299); if (tempFile != null) { tempFile.delete(); } BetterJSONObject taxonSuggestions = getTaxonSuggestions(resizedPhotoFilename, latitude, longitude, observedOn); File resizedFile = new File(resizedPhotoFilename); resizedFile.delete(); Intent reply = new Intent(ACTION_GET_TAXON_SUGGESTIONS_RESULT); reply.putExtra(TAXON_SUGGESTIONS, taxonSuggestions); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_TAXON_NEW)) { int taxonId = intent.getIntExtra(TAXON_ID, 0); BetterJSONObject taxon = getTaxonNew(taxonId); Intent reply = new Intent(ACTION_GET_TAXON_NEW_RESULT); mApp.setServiceResult(ACTION_GET_TAXON_NEW_RESULT, taxon); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_TAXON)) { int taxonId = intent.getIntExtra(TAXON_ID, 0); BetterJSONObject taxon = getTaxon(taxonId); Intent reply = new Intent(ACTION_GET_TAXON_RESULT); reply.putExtra(TAXON_RESULT, taxon); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SEARCH_PLACES)) { String query = intent.getStringExtra(QUERY); int page = intent.getIntExtra(PAGE_NUMBER, 1); BetterJSONObject results = searchAutoComplete("places", query, page); Intent reply = new Intent(SEARCH_PLACES_RESULT); mApp.setServiceResult(SEARCH_PLACES_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SEARCH_USERS)) { String query = intent.getStringExtra(QUERY); int page = intent.getIntExtra(PAGE_NUMBER, 1); BetterJSONObject results = searchAutoComplete("users", query, page); Intent reply = new Intent(SEARCH_USERS_RESULT); mApp.setServiceResult(SEARCH_USERS_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(QUERY, query); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SEARCH_TAXA)) { String query = intent.getStringExtra(QUERY); int page = intent.getIntExtra(PAGE_NUMBER, 1); BetterJSONObject results = searchAutoComplete("taxa", query, page); Intent reply = new Intent(SEARCH_TAXA_RESULT); mApp.setServiceResult(SEARCH_TAXA_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_UPDATE_CURRENT_USER_DETAILS)) { BetterJSONObject params = (BetterJSONObject) intent.getSerializableExtra(USER); BetterJSONObject user = updateCurrentUserDetails(params.getJSONObject()); Intent reply = new Intent(UPDATE_CURRENT_USER_DETAILS_RESULT); reply.putExtra(USER, user); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_REFRESH_CURRENT_USER_SETTINGS)) { BetterJSONObject user = getCurrentUserDetails(); if (user != null) { // Update settings mApp.setShowScientificNameFirst(user.getJSONObject().optBoolean("prefers_scientific_name_first", false)); // Refresh privileges JSONArray privileges = user.getJSONArray("privileges").getJSONArray(); Set<String> privilegesSet = new HashSet<>(); for (int i = 0; i < privileges.length(); i++) { privilegesSet.add(privileges.optString(i)); } mApp.setUserPrivileges(privilegesSet); // Refresh muted users JSONArray mutedUsers = user.getJSONArray("muted_user_ids").getJSONArray(); Set<Integer> mutedSet = new HashSet<>(); for (int i = 0; i < mutedUsers.length(); i++) { mutedSet.add(mutedUsers.optInt(i)); } mApp.setMutedUsers(mutedSet); JSONArray arr = user.getJSONObject().optJSONArray("roles"); HashSet roles = new HashSet(); for (int i = 0; i < arr.length(); i++) { roles.add(arr.optString(i)); } mApp.setUserRoles(roles); Intent reply = new Intent(REFRESH_CURRENT_USER_SETTINGS_RESULT); reply.putExtra(USER, user); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_DELETE_PINNED_LOCATION)) { String id = intent.getStringExtra(ID); boolean success = deletePinnedLocation(id); } else if (action.equals(ACTION_PIN_LOCATION)) { Double latitude = intent.getDoubleExtra(LATITUDE, 0); Double longitude = intent.getDoubleExtra(LONGITUDE, 0); Double accuracy = intent.getDoubleExtra(ACCURACY, 0); String geoprivacy = intent.getStringExtra(GEOPRIVACY); String title = intent.getStringExtra(TITLE); boolean success = pinLocation(latitude, longitude, accuracy, geoprivacy, title); } else if (action.equals(ACTION_GET_PLACE_DETAILS)) { long placeId = intent.getIntExtra(PLACE_ID, 0); BetterJSONObject place = getPlaceDetails(placeId); Intent reply = new Intent(PLACE_DETAILS_RESULT); reply.putExtra(PLACE, place); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_SPECIFIC_USER_DETAILS)) { String username = intent.getStringExtra(USERNAME); BetterJSONObject user = getUserDetails(username); Intent reply = new Intent(USER_DETAILS_RESULT); reply.putExtra(USER, user); reply.putExtra(USERNAME, username); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_CURRENT_LOCATION)) { getLocation(new IOnLocation() { @Override public void onLocation(Location location) { Intent reply = new Intent(GET_CURRENT_LOCATION_RESULT); reply.putExtra(LOCATION, location); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } }); } else if (action.equals(ACTION_GET_MISSIONS_BY_TAXON)) { final String username = intent.getStringExtra(USERNAME); final Integer taxonId = intent.getIntExtra(TAXON_ID, 0); final float expandLocationByDegrees = intent.getFloatExtra(EXPAND_LOCATION_BY_DEGREES, 0); getLocation(new IOnLocation() { @Override public void onLocation(Location location) { if (location == null) { // No place Intent reply = new Intent(MISSIONS_BY_TAXON_RESULT); mApp.setServiceResult(MISSIONS_BY_TAXON_RESULT, null); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(TAXON_ID, taxonId); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); return; } BetterJSONObject missions = getMissions(location, username, taxonId, expandLocationByDegrees); missions = getMinimalSpeciesResults(missions); Intent reply = new Intent(MISSIONS_BY_TAXON_RESULT); mApp.setServiceResult(MISSIONS_BY_TAXON_RESULT, missions); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(TAXON_ID, taxonId); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } }); } else if (action.equals(ACTION_GET_TAXON_OBSERVATION_BOUNDS)) { final Integer taxonId = intent.getIntExtra(TAXON_ID, 0); BetterJSONObject bounds = getTaxonObservationsBounds(taxonId); Intent reply = new Intent(TAXON_OBSERVATION_BOUNDS_RESULT); reply.putExtra(TAXON_OBSERVATION_BOUNDS_RESULT, bounds); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_RECOMMENDED_MISSIONS)) { final String username = intent.getStringExtra(USERNAME); final float expandLocationByDegrees = intent.getFloatExtra(EXPAND_LOCATION_BY_DEGREES, 0); getLocation(new IOnLocation() { @Override public void onLocation(Location location) { if (location == null) { // No place Intent reply = new Intent(RECOMMENDED_MISSIONS_RESULT); mApp.setServiceResult(RECOMMENDED_MISSIONS_RESULT, null); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); return; } BetterJSONObject missions = getMissions(location, username, null, expandLocationByDegrees); missions = getMinimalSpeciesResults(missions); Intent reply = new Intent(RECOMMENDED_MISSIONS_RESULT); mApp.setServiceResult(RECOMMENDED_MISSIONS_RESULT, missions); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } }); } else if (action.equals(ACTION_GET_USER_SPECIES_COUNT)) { String username = intent.getStringExtra(USERNAME); BetterJSONObject speciesCount = getUserSpeciesCount(username); speciesCount = getMinimalSpeciesResults(speciesCount); Intent reply = new Intent(SPECIES_COUNT_RESULT); mApp.setServiceResult(SPECIES_COUNT_RESULT, speciesCount); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(USERNAME, username); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_LIFE_LIST)) { int lifeListId = intent.getIntExtra(LIFE_LIST_ID, 0); BetterJSONObject lifeList = getUserLifeList(lifeListId); Intent reply = new Intent(LIFE_LIST_RESULT); mApp.setServiceResult(LIFE_LIST_RESULT, lifeList); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_USER_OBSERVATIONS)) { String username = intent.getStringExtra(USERNAME); JSONObject observations = getUserObservations(username); if (observations != null) { BetterJSONObject minimalObs = getMinimalObservationResults(new BetterJSONObject(observations)); observations = minimalObs != null ? minimalObs.getJSONObject() : null; } Intent reply = new Intent(USER_OBSERVATIONS_RESULT); mApp.setServiceResult(USER_OBSERVATIONS_RESULT, observations != null ? new BetterJSONObject(observations) : null); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(USERNAME, username); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SEARCH_USER_OBSERVATIONS)) { String query = intent.getStringExtra(QUERY); SerializableJSONArray observations = searchUserObservation(query); Intent reply = new Intent(USER_SEARCH_OBSERVATIONS_RESULT); mApp.setServiceResult(USER_SEARCH_OBSERVATIONS_RESULT, observations); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(QUERY, query); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_VIEWED_UPDATE)) { Integer obsId = intent.getIntExtra(OBSERVATION_ID, 0); setUserViewedUpdate(obsId); } else if (action.equals(ACTION_GET_USER_UPDATES)) { Boolean following = intent.getBooleanExtra(FOLLOWING, false); SerializableJSONArray updates = getUserUpdates(following); Intent reply; if (following) { reply = new Intent(UPDATES_FOLLOWING_RESULT); mApp.setServiceResult(UPDATES_FOLLOWING_RESULT, updates); } else { reply = new Intent(UPDATES_RESULT); mApp.setServiceResult(UPDATES_RESULT, updates); } reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_USER_IDENTIFICATIONS)) { String username = intent.getStringExtra(USERNAME); BetterJSONObject identifications = getUserIdentifications(username); identifications = getMinimalIdentificationResults(identifications); Intent reply = new Intent(IDENTIFICATIONS_RESULT); mApp.setServiceResult(IDENTIFICATIONS_RESULT, identifications); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(USERNAME, username); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_EXPLORE_GET_OBSERVERS)) { ExploreSearchFilters filters = (ExploreSearchFilters) intent.getSerializableExtra(FILTERS); int pageNumber = intent.getIntExtra(PAGE_NUMBER, 1); int pageSize = intent.getIntExtra(PAGE_SIZE, EXPLORE_DEFAULT_RESULTS_PER_PAGE); String uuid = intent.getStringExtra(UUID); BetterJSONObject results = getExploreResults("observers", filters, pageNumber, pageSize, null); results = getMinimalObserverResults(results); Intent reply = new Intent(EXPLORE_GET_OBSERVERS_RESULT); mApp.setServiceResult(EXPLORE_GET_OBSERVERS_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(UUID, uuid); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_EXPLORE_GET_IDENTIFIERS)) { ExploreSearchFilters filters = (ExploreSearchFilters) intent.getSerializableExtra(FILTERS); int pageNumber = intent.getIntExtra(PAGE_NUMBER, 1); int pageSize = intent.getIntExtra(PAGE_SIZE, EXPLORE_DEFAULT_RESULTS_PER_PAGE); String uuid = intent.getStringExtra(UUID); BetterJSONObject results = getExploreResults("identifiers", filters, pageNumber, pageSize, null); results = getMinimalObserverResults(results); Intent reply = new Intent(EXPLORE_GET_IDENTIFIERS_RESULT); mApp.setServiceResult(EXPLORE_GET_IDENTIFIERS_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(UUID, uuid); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_EXPLORE_GET_SPECIES)) { ExploreSearchFilters filters = (ExploreSearchFilters) intent.getSerializableExtra(FILTERS); int pageNumber = intent.getIntExtra(PAGE_NUMBER, 1); int pageSize = intent.getIntExtra(PAGE_SIZE, EXPLORE_DEFAULT_RESULTS_PER_PAGE); String uuid = intent.getStringExtra(UUID); BetterJSONObject results = getExploreResults("species_counts", filters, pageNumber, pageSize, null); results = getMinimalSpeciesResults(results); Intent reply = new Intent(EXPLORE_GET_SPECIES_RESULT); mApp.setServiceResult(EXPLORE_GET_SPECIES_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(UUID, uuid); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_EXPLORE_GET_OBSERVATIONS)) { ExploreSearchFilters filters = (ExploreSearchFilters) intent.getSerializableExtra(FILTERS); int pageNumber = intent.getIntExtra(PAGE_NUMBER, 1); int pageSize = intent.getIntExtra(PAGE_SIZE, EXPLORE_DEFAULT_RESULTS_PER_PAGE); String uuid = intent.getStringExtra(UUID); BetterJSONObject observations = getExploreResults(null, filters, pageNumber, pageSize, "observation.id"); observations = getMinimalObservationResults(observations); Intent reply = new Intent(EXPLORE_GET_OBSERVATIONS_RESULT); mApp.setServiceResult(EXPLORE_GET_OBSERVATIONS_RESULT, observations); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(UUID, uuid); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_ADD_COMMENT)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); String body = intent.getStringExtra(COMMENT_BODY); addComment(observationId, body); // Wait a little before refreshing the observation details - so we'll let the server update the comment // list (otherwise, it won't return the new comment) try { Thread.sleep(1000); } catch (InterruptedException e) { Logger.tag(TAG).error(e); } // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); if (observationJson == null) { reply.putExtra(OBSERVATION_RESULT, (Serializable)null); reply.putExtra(OBSERVATION_JSON_RESULT, (String)null); } else { Observation observation = new Observation(new BetterJSONObject(observationJson)); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observation != null ? observationJson.toString() : null); } LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_UPDATE_COMMENT)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int commentId = intent.getIntExtra(COMMENT_ID, 0); String body = intent.getStringExtra(COMMENT_BODY); updateComment(commentId, observationId, body); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_DELETE_COMMENT)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int commentId = intent.getIntExtra(COMMENT_ID, 0); deleteComment(commentId); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_GUIDE_XML)) { int guideId = intent.getIntExtra(ACTION_GUIDE_ID, 0); String guideXMLFilename = getGuideXML(guideId); if (guideXMLFilename == null) { // Failed to get the guide XML - try and find the offline version, if available GuideXML guideXml = new GuideXML(this, String.valueOf(guideId)); if (guideXml.isGuideDownloaded()) { guideXMLFilename = guideXml.getOfflineGuideXmlFilePath(); } } Intent reply = new Intent(ACTION_GUIDE_XML_RESULT); reply.putExtra(GUIDE_XML_RESULT, guideXMLFilename); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_CLEAR_OLD_PHOTOS_CACHE)) { // Clear out the old cached photos if (!mIsClearingOldPhotosCache) { mIsClearingOldPhotosCache = true; clearOldCachedPhotos(); mIsClearingOldPhotosCache = false; } } else if (action.equals(ACTION_UPDATE_USER_NETWORK)) { int siteId = intent.getIntExtra(NETWORK_SITE_ID, 0); updateUserNetwork(siteId); } else if (action.equals(ACTION_UPDATE_USER_DETAILS)) { String username = intent.getStringExtra(ACTION_USERNAME); String fullName = intent.getStringExtra(ACTION_FULL_NAME); String bio = intent.getStringExtra(ACTION_USER_BIO); String password = intent.getStringExtra(ACTION_USER_PASSWORD); String email = intent.getStringExtra(ACTION_USER_EMAIL); String userPic = intent.getStringExtra(ACTION_USER_PIC); boolean deletePic = intent.getBooleanExtra(ACTION_USER_DELETE_PIC, false); JSONObject newUser = updateUser(username, email, password, fullName, bio, userPic, deletePic); if ((newUser != null) && (!newUser.has("errors"))) { SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); String prevLogin = mLogin; mLogin = newUser.optString("login"); editor.putString("username", mLogin); if (!newUser.has("user_icon_url") || newUser.isNull("user_icon_url")) { editor.putString("user_icon_url", null); } else { editor.putString("user_icon_url", newUser.has("medium_user_icon_url") ? newUser.optString("medium_user_icon_url") : newUser.optString("user_icon_url")); } editor.putString("user_bio", newUser.optString("description")); editor.putString("user_email", newUser.optString("email", email)); editor.putString("user_full_name", newUser.optString("name")); editor.apply(); if ((prevLogin != null) && (!prevLogin.equals(mLogin))) { // Update observations with the new username ContentValues cv = new ContentValues(); cv.put("user_login", mLogin); // Update its sync at time so we won't update the remote servers later on (since we won't // accidentally consider this an updated record) cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); int count = getContentResolver().update(Observation.CONTENT_URI, cv, "(user_login = ?) AND (id IS NOT NULL)", new String[]{prevLogin}); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "Updated %d synced observations with new user login %s from %s", count, mLogin, prevLogin)); cv = new ContentValues(); cv.put("user_login", mLogin); count = getContentResolver().update(Observation.CONTENT_URI, cv, "(user_login = ?) AND (id IS NULL)", new String[]{ prevLogin }); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "Updated %d new observations with new user login %s from %s", count, mLogin, prevLogin)); } } Intent reply = new Intent(ACTION_UPDATE_USER_DETAILS_RESULT); reply.putExtra(USER, newUser != null ? new BetterJSONObject(newUser) : null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_USER_DETAILS)) { BetterJSONObject user = null; boolean authenticationFailed = false; boolean isDeleted = false; try { user = getUserDetails(); } catch (AuthenticationException exc) { Logger.tag(TAG).error(exc); // See if user was deleted via the website isDeleted = isUserDeleted(mLogin); if (!isDeleted) { // This means the user has changed his password on the website authenticationFailed = true; } } Intent reply = new Intent(ACTION_GET_USER_DETAILS_RESULT); reply.putExtra(USER, user); reply.putExtra(AUTHENTICATION_FAILED, authenticationFailed); reply.putExtra(USER_DELETED, isDeleted); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_TAXA_FOR_GUIDE)) { int guideId = intent.getIntExtra(ACTION_GUIDE_ID, 0); SerializableJSONArray taxa = getTaxaForGuide(guideId); mApp.setServiceResult(ACTION_TAXA_FOR_GUIDES_RESULT, taxa); Intent reply = new Intent(ACTION_TAXA_FOR_GUIDES_RESULT); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_ALL_GUIDES)) { SerializableJSONArray guides = getAllGuides(); mApp.setServiceResult(ACTION_ALL_GUIDES_RESULT, guides); Intent reply = new Intent(ACTION_ALL_GUIDES_RESULT); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_MY_GUIDES)) { SerializableJSONArray guides = null; guides = getMyGuides(); Intent reply = new Intent(ACTION_MY_GUIDES_RESULT); reply.putExtra(GUIDES_RESULT, guides); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_NEAR_BY_GUIDES)) { getLocation(new IOnLocation() { @Override public void onLocation(Location location) { if (location == null) { // No place enabled Intent reply = new Intent(ACTION_NEAR_BY_GUIDES_RESULT); reply.putExtra(GUIDES_RESULT, new SerializableJSONArray()); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } else { SerializableJSONArray guides = null; try { guides = getNearByGuides(location); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); } Intent reply = new Intent(ACTION_NEAR_BY_GUIDES_RESULT); reply.putExtra(GUIDES_RESULT, guides); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } } }); } else if (action.equals(ACTION_GET_NEARBY_PROJECTS)) { getLocation(new IOnLocation() { @Override public void onLocation(Location location) { if (location == null) { // No place enabled Intent reply = new Intent(ACTION_NEARBY_PROJECTS_RESULT); mApp.setServiceResult(ACTION_NEARBY_PROJECTS_RESULT, new SerializableJSONArray()); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } else { SerializableJSONArray projects = null; try { projects = getNearByProjects(location); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); } Intent reply = new Intent(ACTION_NEARBY_PROJECTS_RESULT); mApp.setServiceResult(ACTION_NEARBY_PROJECTS_RESULT, projects); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } } }); } else if (action.equals(ACTION_GET_FEATURED_PROJECTS)) { SerializableJSONArray projects = getFeaturedProjects(); Intent reply = new Intent(ACTION_FEATURED_PROJECTS_RESULT); reply.putExtra(PROJECTS_RESULT, projects); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_JOINED_PROJECTS_ONLINE)) { SerializableJSONArray projects = null; if (mCredentials != null) { projects = getJoinedProjects(); } Intent reply = new Intent(ACTION_JOINED_PROJECTS_RESULT); mApp.setServiceResult(ACTION_JOINED_PROJECTS_RESULT, projects); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_JOINED_PROJECTS)) { SerializableJSONArray projects = null; if (mCredentials != null) { projects = getJoinedProjectsOffline(); } Intent reply = new Intent(ACTION_JOINED_PROJECTS_RESULT); reply.putExtra(PROJECTS_RESULT, projects); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_REMOVE_OBSERVATION_FROM_PROJECT)) { int observationId = intent.getExtras().getInt(OBSERVATION_ID); int projectId = intent.getExtras().getInt(PROJECT_ID); BetterJSONObject result = removeObservationFromProject(observationId, projectId); } else if (action.equals(ACTION_ADD_OBSERVATION_TO_PROJECT)) { int observationId = intent.getExtras().getInt(OBSERVATION_ID); int projectId = intent.getExtras().getInt(PROJECT_ID); BetterJSONObject result = addObservationToProject(observationId, projectId); Intent reply = new Intent(ADD_OBSERVATION_TO_PROJECT_RESULT); reply.putExtra(ADD_OBSERVATION_TO_PROJECT_RESULT, result); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_REDOWNLOAD_OBSERVATIONS_FOR_TAXON)) { redownloadOldObservationsForTaxonNames(); } else if (action.equals(ACTION_DELETE_ACCOUNT)) { boolean success = deleteAccount(); Intent reply = new Intent(DELETE_ACCOUNT_RESULT); reply.putExtra(SUCCESS, success); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SYNC_JOINED_PROJECTS)) { saveJoinedProjects(); } else if (action.equals(ACTION_GET_NOTIFICATION_COUNTS)) { BetterJSONObject notificationCounts = getNotificationCounts(); Intent reply = new Intent(ACTION_NOTIFICATION_COUNTS_RESULT); reply.putExtra(NOTIFICATIONS, notificationCounts); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_POST_FLAG)) { String flaggableType = intent.getExtras().getString(FLAGGABLE_TYPE); Integer flaggableId = intent.getExtras().getInt(FLAGGABLE_ID); String flag = intent.getExtras().getString(FLAG); String flagExplanation = intent.getExtras().getString(FLAG_EXPLANATION); boolean success = postFlag(flaggableType, flaggableId, flag, flagExplanation); Intent reply = new Intent(ACTION_POST_FLAG_RESULT); reply.putExtra(SUCCESS, success); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_UNMUTE_USER)) { Integer userId = intent.getExtras().getInt(USER); boolean success = unmuteUser(userId); Intent reply = new Intent(ACTION_UNMUTE_USER_RESULT); reply.putExtra(SUCCESS, success); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_MUTE_USER)) { Integer userId = intent.getExtras().getInt(USER); boolean success = muteUser(userId); Intent reply = new Intent(ACTION_MUTE_USER_RESULT); reply.putExtra(SUCCESS, success); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_POST_MESSAGE)) { Integer toUser = intent.getExtras().getInt(TO_USER); Integer threadId = intent.getExtras().containsKey(THREAD_ID) ? intent.getExtras().getInt(THREAD_ID) : null; String subject = intent.getExtras().getString(SUBJECT); String body = intent.getExtras().getString(BODY); BetterJSONObject response = postMessage(toUser, threadId, subject, body); Intent reply = new Intent(ACTION_POST_MESSAGE_RESULT); mApp.setServiceResult(ACTION_POST_MESSAGE_RESULT, response); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_MESSAGES)) { String query = intent.getExtras() != null ? intent.getExtras().getString(QUERY) : null; String box = intent.getExtras() != null ? intent.getExtras().getString(BOX) : null; boolean groupByThreads = intent.getExtras() != null ? intent.getExtras().getBoolean(GROUP_BY_THREADS) : false; Integer messageId = (intent.getExtras() != null && intent.getExtras().containsKey(MESSAGE_ID)) ? intent.getExtras().getInt(MESSAGE_ID) : null; BetterJSONObject messages = getMessages(query, box, groupByThreads, messageId); Intent reply = new Intent(ACTION_MESSAGES_RESULT); mApp.setServiceResult(ACTION_MESSAGES_RESULT, messages); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(QUERY, query); reply.putExtra(MESSAGE_ID, messageId); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_CHECK_LIST)) { int id = intent.getExtras().getInt(CHECK_LIST_ID); SerializableJSONArray checkList = getCheckList(id); Intent reply = new Intent(ACTION_CHECK_LIST_RESULT); reply.putExtra(CHECK_LIST_RESULT, checkList); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_FLAG_OBSERVATION_AS_CAPTIVE)) { int id = intent.getExtras().getInt(OBSERVATION_ID); flagObservationAsCaptive(id); } else if (action.equals(ACTION_GET_NEWS)) { SerializableJSONArray news = getNews(); Intent reply = new Intent(ACTION_NEWS_RESULT); reply.putExtra(RESULTS, news); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_AND_SAVE_OBSERVATION)) { int id = intent.getExtras().getInt(OBSERVATION_ID); Observation observation = getAndDownloadObservation(id); Intent reply = new Intent(ACTION_GET_AND_SAVE_OBSERVATION_RESULT); reply.putExtra(OBSERVATION_RESULT, observation); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_OBSERVATION)) { int id = intent.getExtras().getInt(OBSERVATION_ID); boolean getProjects = intent.getExtras().getBoolean(GET_PROJECTS); JSONObject observationJson = getObservationJson(id, false, getProjects); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); synchronized (mObservationLock) { String jsonString = observationJson != null ? observationJson.toString() : null; Observation observation = observationJson == null ? null : new Observation(new BetterJSONObject(jsonString)); mApp.setServiceResult(ACTION_OBSERVATION_RESULT, observation); mApp.setServiceResult(OBSERVATION_JSON_RESULT, observationJson != null ? jsonString : null); } reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_JOIN_PROJECT)) { int id = intent.getExtras().getInt(PROJECT_ID); joinProject(id); } else if (action.equals(ACTION_LEAVE_PROJECT)) { int id = intent.getExtras().getInt(PROJECT_ID); leaveProject(id); } else if (action.equals(ACTION_PULL_OBSERVATIONS)) { // Download observations without uploading any new ones if (!mIsSyncing && !mApp.getIsSyncing()) { mIsSyncing = true; mApp.setIsSyncing(mIsSyncing); syncRemotelyDeletedObs(); boolean successful = getUserObservations(0); if (successful) { // Update last sync time long lastSync = System.currentTimeMillis(); mPreferences.edit().putLong("last_sync_time", lastSync).commit(); mPreferences.edit().putLong("last_user_details_refresh_time", 0); // Force to refresh user details mPreferences.edit().putLong("last_user_notifications_refresh_time", 0); // Force to refresh user notification counts } else { mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), R.string.could_not_download_observations, Toast.LENGTH_LONG).show(); } }); } } } else if (action.equals(ACTION_DELETE_OBSERVATIONS)) { if (!mIsSyncing && !mApp.getIsSyncing()) { long[] idsToDelete = null; idsToDelete = intent.getExtras().getLongArray(OBS_IDS_TO_DELETE); Logger.tag(TAG).debug("DeleteObservations: Calling delete obs"); mIsSyncing = true; mApp.setIsSyncing(mIsSyncing); deleteObservations(idsToDelete); } else { // Already in middle of syncing dontStopSync = true; } } else if (action.equals(ACTION_SYNC)) { if (!mIsSyncing && !mApp.getIsSyncing()) { long[] idsToSync = null; if (intent.hasExtra(OBS_IDS_TO_SYNC)) { idsToSync = intent.getExtras().getLongArray(OBS_IDS_TO_SYNC); } mIsSyncing = true; mApp.setIsSyncing(mIsSyncing); syncObservations(idsToSync); // Update last sync time long lastSync = System.currentTimeMillis(); mPreferences.edit().putLong("last_sync_time", lastSync).commit(); } else { // Already in middle of syncing dontStopSync = true; } } } catch (IllegalArgumentException e) { // Handle weird exception raised when sendBroadcast causes serialization of BetterJSONObject // and that causes an IllegalArgumentException (see only once). Logger.tag(TAG).error(e); mIsSyncing = false; } catch (CancelSyncException e) { cancelSyncRequested = true; mApp.setCancelSync(false); mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); } catch (SyncFailedException e) { syncFailed = true; mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); } catch (AuthenticationException e) { if (!mPassive) { requestCredentials(); } mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); } finally { mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); if (mIsSyncing && !dontStopSync && (action.equals(ACTION_SYNC) || action.equals(ACTION_FIRST_SYNC) || action.equals(ACTION_PULL_OBSERVATIONS) || action.equals(ACTION_DELETE_OBSERVATIONS))) { mIsSyncing = false; mApp.setIsSyncing(mIsSyncing); Logger.tag(TAG).info("Sending ACTION_SYNC_COMPLETE"); // Notify the rest of the app of the completion of the sync Intent reply = new Intent(ACTION_SYNC_COMPLETE); reply.putExtra(SYNC_CANCELED, cancelSyncRequested); reply.putExtra(SYNC_FAILED, syncFailed); reply.putExtra(FIRST_SYNC, action.equals(ACTION_FIRST_SYNC)); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } } private boolean deletePinnedLocation(String id) throws AuthenticationException { JSONArray result = delete(String.format(Locale.ENGLISH, "%s/saved_locations/%s.json", HOST, id), null); if (result != null) { return true; } else { return false; } } private boolean pinLocation(Double latitude, Double longitude, Double accuracy, String geoprivacy, String title) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("saved_location[latitude]", latitude.toString())); params.add(new BasicNameValuePair("saved_location[longitude]", longitude.toString())); params.add(new BasicNameValuePair("saved_location[positional_accuracy]", accuracy.toString())); params.add(new BasicNameValuePair("saved_location[geoprivacy]", geoprivacy)); params.add(new BasicNameValuePair("saved_location[title]", title)); JSONArray result = post(HOST + "/saved_locations.json", params); if (result != null) { return true; } else { return false; } } private void syncObservations(long[] idsToSync) throws AuthenticationException, CancelSyncException, SyncFailedException { try { Logger.tag(TAG).debug("syncObservations: enter"); JSONObject eventParams = new JSONObject(); eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, mApp.getAutoSync() ? AnalyticsClient.EVENT_VALUE_AUTOMATIC_UPLOAD : AnalyticsClient.EVENT_VALUE_MANUAL_FULL_UPLOAD); Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "is_deleted = 1 AND user_login = '" + mLogin + "'", null, Observation.DEFAULT_SORT_ORDER); eventParams.put(AnalyticsClient.EVENT_PARAM_NUM_DELETES, c.getCount()); Logger.tag(TAG).debug("syncObservations: to be deleted: " + c.getCount()); c.close(); c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "(_updated_at > _synced_at AND _synced_at IS NOT NULL AND user_login = '" + mLogin + "') OR " + "(id IS NULL AND _updated_at > _created_at)", null, Observation.SYNC_ORDER); eventParams.put(AnalyticsClient.EVENT_PARAM_NUM_UPLOADS, c.getCount()); Logger.tag(TAG).debug("syncObservations: uploads: " + c.getCount()); c.close(); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_SYNC_OBS, eventParams); } catch (JSONException e) { Logger.tag(TAG).error(e); } if (idsToSync == null) { mApp.notify(getString(R.string.preparing), getString(R.string.preparing)); Logger.tag(TAG).debug("syncObservations: Calling syncRemotelyDeletedObs"); if (!syncRemotelyDeletedObs()) throw new SyncFailedException(); // First, download remote observations (new/updated) Logger.tag(TAG).debug("syncObservations: Calling getUserObservations"); if (!getUserObservations(0)) throw new SyncFailedException(); Logger.tag(TAG).debug("syncObservations: After calling getUserObservations"); } else { mProjectObservations = new ArrayList<SerializableJSONArray>(); mProjectFieldValues = new Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>>(); } Set<Integer> observationIdsToSync = new HashSet<>(); Cursor c; if (idsToSync != null) { // User chose to sync specific observations only for (long id : idsToSync) { observationIdsToSync.add(Integer.valueOf((int)id)); } Logger.tag(TAG).debug("syncObservations: observationIdsToSync multi-selection: " + observationIdsToSync); } else { // Gather the list of observations that need syncing (because they're new, been updated // or had their photos/project fields updated // Any new/updated observations c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "(_synced_at IS NULL) OR (_updated_at > _synced_at AND _synced_at IS NOT NULL)", null, Observation.DEFAULT_SORT_ORDER); c.moveToFirst(); while (!c.isAfterLast()) { Integer internalId = c.getInt(c.getColumnIndexOrThrow(Observation._ID)); // Make sure observation is not currently being edited by user (split-observation bug) observationIdsToSync.add(internalId); c.moveToNext(); } c.close(); Logger.tag(TAG).debug("syncObservations: observationIdsToSync: " + observationIdsToSync); // Any observation that has new/updated/deleted photos c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(_synced_at IS NULL) OR (_updated_at > _synced_at AND _synced_at IS NOT NULL AND id IS NOT NULL) OR " + "(is_deleted = 1)", null, ObservationPhoto.DEFAULT_SORT_ORDER); c.moveToFirst(); while (!c.isAfterLast()) { int internalObsId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto._OBSERVATION_ID)); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_id = " + internalObsId, null, Observation.DEFAULT_SORT_ORDER); int obsCount = obsc.getCount(); obsc.close(); if (obsCount == 0) { // Observation photo belongs to an observation that no longer exists - delete it int obsPhotoId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto._ID)); Logger.tag(TAG).error("Observation photo " + obsPhotoId + " belongs to an observation that no longer exists: " + internalObsId + " - deleting it"); getContentResolver().delete( ContentUris.withAppendedId(ObservationPhoto.CONTENT_URI, obsPhotoId), null, null); } else { observationIdsToSync.add(internalObsId); } c.moveToNext(); } c.close(); Logger.tag(TAG).debug("syncObservations: observationIdsToSync 2: " + observationIdsToSync); // Any observation that has new/deleted sounds c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "(id IS NULL) OR (is_deleted = 1)", null, ObservationSound.DEFAULT_SORT_ORDER); c.moveToFirst(); while (!c.isAfterLast()) { observationIdsToSync.add(c.getInt(c.getColumnIndexOrThrow(ObservationSound._OBSERVATION_ID))); c.moveToNext(); } c.close(); Logger.tag(TAG).debug("syncObservations: observationIdsToSync 2b: " + observationIdsToSync); // Any observation that has new/updated project fields. c = getContentResolver().query(ProjectFieldValue.CONTENT_URI, ProjectFieldValue.PROJECTION, "(_synced_at IS NULL) OR (_updated_at > _synced_at AND _synced_at IS NOT NULL)", null, ProjectFieldValue.DEFAULT_SORT_ORDER); c.moveToFirst(); while (!c.isAfterLast()) { observationIdsToSync.add(c.getInt(c.getColumnIndexOrThrow(ProjectFieldValue.OBSERVATION_ID))); c.moveToNext(); } c.close(); } Logger.tag(TAG).debug("syncObservations: observationIdsToSync 3: " + observationIdsToSync); List<Integer> obsIdsToRemove = new ArrayList<>(); for (Integer obsId : observationIdsToSync) { c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_id = " + obsId, null, Observation.DEFAULT_SORT_ORDER); if (c.getCount() == 0) { obsIdsToRemove.add(obsId); c.close(); continue; } c.moveToFirst(); if (c.getInt(c.getColumnIndexOrThrow(Observation.IS_DELETED)) == 1) { obsIdsToRemove.add(obsId); } c.close(); } Logger.tag(TAG).debug("syncObservations: obsIdsToRemove: " + obsIdsToRemove); for (Integer obsId : observationIdsToSync) { // Make sure observation is not currently being edited by user (split-observation bug) if (mApp.isObservationCurrentlyBeingEdited(obsId)) { Logger.tag(TAG).error("syncObservations: Observation " + obsId + " is currently being edited - not syncing it"); obsIdsToRemove.add(obsId); } } Logger.tag(TAG).debug("syncObservations: obsIdsToRemove 2: " + obsIdsToRemove); for (Integer obsId : obsIdsToRemove) { observationIdsToSync.remove(obsId); } Logger.tag(TAG).debug("syncObservations: observationIdsToSync: " + observationIdsToSync); c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_id in (" + StringUtils.join(observationIdsToSync, ",") + ")", null, Observation.DEFAULT_SYNC_ORDER); c.moveToFirst(); while (!c.isAfterLast()) { int totalObs = c.getCount(); mApp.notify(getString(R.string.syncing_observations), getResources().getQuantityString( R.plurals.syncing_x_out_of_y_observations, totalObs, (c.getPosition() + 1), totalObs ) ); Observation observation = new Observation(c); // Make sure observation is not currently being edited by user (split-observation bug) if (mApp.isObservationCurrentlyBeingEdited(observation._id)) { Logger.tag(TAG).error("syncObservations: Observation " + observation._id + " is currently being edited - not syncing it"); continue; } mCurrentObservationProgress = 0.0f; mTotalProgressForObservation = getTotalProgressForObservation(observation); increaseProgressForObservation(observation); mApp.setObservationIdBeingSynced(observation._id); Logger.tag(TAG).debug("syncObservations: Syncing " + observation._id + ": " + observation.toString()); if ((observation._synced_at == null) || ((observation._updated_at != null) && (observation._updated_at.after(observation._synced_at))) || (observation.id == null)) { postObservation(observation); increaseProgressForObservation(observation); } Logger.tag(TAG).debug("syncObservations: Finished Syncing " + observation._id + " - now uploading photos"); postPhotos(observation); Logger.tag(TAG).debug("syncObservations: Finished uploading photos " + observation._id); deleteObservationPhotos(observation); // Delete locally-removed observation photos postSounds(observation); Logger.tag(TAG).debug("syncObservations: Finished uploading sounds " + observation._id); deleteObservationSounds(observation); // Delete locally-removed observation sounds syncObservationFields(observation); postProjectObservations(observation); Logger.tag(TAG).debug("syncObservations: Finished delete photos, obs fields and project obs - " + observation._id); c.moveToNext(); } c.close(); if (idsToSync == null) { Logger.tag(TAG).debug("syncObservations: Calling delete obs"); deleteObservations(null); // Delete locally-removed observations Logger.tag(TAG).debug("syncObservations: Calling saveJoinedProj"); // General project data mApp.notify(SYNC_PHOTOS_NOTIFICATION, getString(R.string.projects), getString(R.string.cleaning_up), getString(R.string.syncing)); saveJoinedProjects(); Logger.tag(TAG).debug("syncObservations: Calling storeProjObs"); storeProjectObservations(); redownloadOldObservations(); } Logger.tag(TAG).debug("syncObservations: Done"); mPreferences.edit().putLong("last_user_details_refresh_time", 0); // Force to refresh user details mPreferences.edit().putLong("last_user_notifications_refresh_time", 0); // Force to refresh user notification counts } private int mTotalProgressForObservation = 0; private float mCurrentObservationProgress = 0; private void increaseProgressForObservation(Observation observation) { float currentProgress = mCurrentObservationProgress; float step = (100.0f / mTotalProgressForObservation); float newProgress = currentProgress + step; if (newProgress >= 99) newProgress = 100f; // Round to 100 in case of fractions (since otherwise, we'll get to 99.99999 and similar mCurrentObservationProgress = newProgress; // Notify the client of the new progress (so we'll update the progress bars) Intent reply = new Intent(OBSERVATION_SYNC_PROGRESS); reply.putExtra(OBSERVATION_ID, observation.id); reply.putExtra(OBSERVATION_ID_INTERNAL, observation._id); reply.putExtra(PROGRESS, newProgress); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } // Adds observation UUIDs to photos and sounds that are missing them private void addObservationUUIDsToPhotosAndSounds() { Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[] { ObservationPhoto._OBSERVATION_ID, ObservationPhoto._ID, ObservationPhoto.ID }, "observation_uuid is NULL", null, ObservationPhoto.DEFAULT_SORT_ORDER); int count = c.getCount(); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "addObservationUUIDsToPhotosAndSounds: Adding UUIDs to %d photos", count)); c.moveToFirst(); while (!c.isAfterLast()) { int obsInternalId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto._OBSERVATION_ID)); int obsPhotoId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto.ID)); int obsPhotoInternalId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto._ID)); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, new String[] { Observation.UUID }, "_id = " + obsInternalId, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); String uuid = obsc.getString(obsc.getColumnIndexOrThrow(Observation.UUID)); ContentValues cv = new ContentValues(); cv.put(ObservationPhoto.OBSERVATION_UUID, uuid); // Update its sync at time so we won't update the remote servers later on (since we won't // accidentally consider this an updated record) cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); Uri photoUri = ContentUris.withAppendedId(ObservationPhoto.CONTENT_URI, obsPhotoInternalId); getContentResolver().update(photoUri, cv, null, null); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "addObservationUUIDsToPhotosAndSounds - Adding observation_uuid %s to photo: id = %d; _id: %d", uuid, obsPhotoId, obsPhotoInternalId)); } obsc.close(); c.moveToNext(); } c.close(); c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "observation_uuid is NULL", null, ObservationSound.DEFAULT_SORT_ORDER); count = c.getCount(); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "addObservationUUIDsToPhotosAndSounds: Adding UUIDs to %d sounds", count)); c.moveToFirst(); while (!c.isAfterLast()) { ObservationSound sound = new ObservationSound(c); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, new String[] { Observation.UUID }, "id = " + sound.observation_id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); String uuid = obsc.getString(obsc.getColumnIndexOrThrow(Observation.UUID)); sound.observation_uuid = uuid; ContentValues cv = sound.getContentValues(); getContentResolver().update(sound.getUri(), cv, null, null); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "addObservationUUIDsToPhotosAndSounds - Adding observation_uuid %s to sound: %s", uuid, sound)); } obsc.close(); c.moveToNext(); } c.close(); } private BetterJSONObject getMinimalIdentificationResults(BetterJSONObject results) { if (results == null) return null; SerializableJSONArray innerResults = results.getJSONArray("results"); if (innerResults == null) return null; JSONArray identificationResults = innerResults.getJSONArray(); if (identificationResults != null) { JSONArray minimizedResults = new JSONArray(); for (int i = 0; i < identificationResults.length(); i++) { JSONObject item = identificationResults.optJSONObject(i); minimizedResults.put(getMinimalIdentification(item)); } results.put("results", minimizedResults); } return results; } private BetterJSONObject getMinimalObserverResults(BetterJSONObject results) { if (results == null) return null; SerializableJSONArray innerResults = results.getJSONArray("results"); if (innerResults == null) return null; JSONArray observerResults = innerResults.getJSONArray(); if (observerResults != null) { JSONArray minimizedResults = new JSONArray(); for (int i = 0; i < observerResults.length(); i++) { JSONObject item = observerResults.optJSONObject(i); minimizedResults.put(getMinimalObserver(item)); } results.put("results", minimizedResults); } return results; } private BetterJSONObject getMinimalSpeciesResults(BetterJSONObject results) { if (results == null) return null; SerializableJSONArray innerResults = results.getJSONArray("results"); if (innerResults == null) return null; // Minimize results - save only basic info for each observation (better memory usage) JSONArray speciesResults = innerResults.getJSONArray(); JSONArray minimizedResults = new JSONArray(); if (speciesResults != null) { for (int i = 0; i < speciesResults.length(); i++) { JSONObject item = speciesResults.optJSONObject(i); minimizedResults.put(getMinimalSpecies(item)); } results.put("results", minimizedResults); } return results; } private BetterJSONObject getMinimalObservationResults(BetterJSONObject results) { if (results == null) return null; SerializableJSONArray innerResults = results.getJSONArray("results"); if (innerResults == null) return null; // Minimize results - save only basic info for each observation (better memory usage) JSONArray observationResults = innerResults.getJSONArray(); JSONArray minimizedObservations = new JSONArray(); if (observationResults != null) { for (int i = 0; i < observationResults.length(); i++) { JSONObject item = observationResults.optJSONObject(i); minimizedObservations.put(getMinimalObservation(item)); } results.put("results", minimizedObservations); } return results; } // Returns a minimal version of an observation JSON (used to lower memory usage) private JSONObject getMinimalObservation(JSONObject observation) { JSONObject minimaldObs = new JSONObject(); try { minimaldObs.put("id", observation.optInt("id")); minimaldObs.put("quality_grade", observation.optString("quality_grade")); if (observation.has("observed_on") && !observation.isNull("observed_on")) minimaldObs.put("observed_on", observation.optString("observed_on")); if (observation.has("time_observed_at") && !observation.isNull("time_observed_at")) minimaldObs.put("time_observed_at", observation.optString("time_observed_at")); if (observation.has("species_guess") && !observation.isNull("species_guess")) minimaldObs.put("species_guess", observation.optString("species_guess")); if (observation.has("place_guess") && !observation.isNull("place_guess")) minimaldObs.put("place_guess", observation.optString("place_guess")); if (observation.has("latitude") && !observation.isNull("latitude")) minimaldObs.put("latitude", observation.optString("latitude")); if (observation.has("longitude") && !observation.isNull("longitude")) minimaldObs.put("longitude", observation.optString("longitude")); if (observation.has("observed_on") && !observation.isNull("observed_on")) minimaldObs.put("observed_on", observation.optString("observed_on")); if (observation.has("comments_count") && !observation.isNull("comments_count")) minimaldObs.put("comments_count", observation.optInt("comments_count")); if (observation.has("identifications_count") && !observation.isNull("identifications_count")) minimaldObs.put("identifications_count", observation.optInt("identifications_count")); minimaldObs.put("taxon", getMinimalTaxon(observation.optJSONObject("taxon"))); if (observation.has("iconic_taxon_name")) minimaldObs.put("iconic_taxon_name", observation.optString("iconic_taxon_name")); if (observation.has("observation_photos") && !observation.isNull("observation_photos")) { JSONArray minimalObsPhotos = new JSONArray(); JSONArray obsPhotos = observation.optJSONArray("observation_photos"); for (int i = 0; i < obsPhotos.length(); i++) { minimalObsPhotos.put(getMinimalPhoto(obsPhotos.optJSONObject(i))); } minimaldObs.put("observation_photos", minimalObsPhotos); } if (observation.has("sounds") && !observation.isNull("sounds")) { JSONArray minimalObsSounds = new JSONArray(); JSONArray obsSounds = observation.optJSONArray("sounds"); for (int i = 0; i < obsSounds.length(); i++) { minimalObsSounds.put(getMinimalSound(obsSounds.optJSONObject(i))); } minimaldObs.put("sounds", minimalObsSounds); } if (observation.has("user")) { JSONObject user = observation.optJSONObject("user"); minimaldObs.put("user", getMinimalUser(user)); } } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimaldObs; } // Returns a minimal version of an identification JSON (used to lower memory usage) private JSONObject getMinimalIdentification(JSONObject identification) { JSONObject minimalObserver = new JSONObject(); if (identification == null) return null; try { if (identification.has("observation")) minimalObserver.put("observation", getMinimalObservation(identification.optJSONObject("observation"))); if (identification.has("taxon")) minimalObserver.put("taxon", getMinimalTaxon(identification.optJSONObject("taxon"))); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalObserver; } // Returns a minimal version of an observer JSON (used to lower memory usage) private JSONObject getMinimalObserver(JSONObject observer) { JSONObject minimalObserver = new JSONObject(); if (observer == null) return null; try { if (observer.has("observation_count")) minimalObserver.put("observation_count", observer.optInt("observation_count")); if (observer.has("count")) minimalObserver.put("count", observer.optInt("count")); if (observer.has("user")) { JSONObject user = observer.optJSONObject("user"); minimalObserver.put("user", getMinimalUser(user)); } } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalObserver; } // Returns a minimal version of a user JSON (used to lower memory usage) private JSONObject getMinimalUser(JSONObject user) { JSONObject minimalUser = new JSONObject(); if (user == null) return null; try { minimalUser.put("login", user.optString("login")); minimalUser.put("icon_url", user.optString("icon_url")); if (user.has("observations_count")) minimalUser.put("observations_count", user.optInt("observations_count")); if (user.has("identifications_count")) minimalUser.put("identifications_count", user.optInt("identifications_count")); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalUser; } // Returns a minimal version of a species JSON (used to lower memory usage) private JSONObject getMinimalSpecies(JSONObject species) { JSONObject minimalSpecies = new JSONObject(); if (species == null) return null; try { minimalSpecies.put("count", species.optInt("count")); minimalSpecies.put("taxon", getMinimalTaxon(species.optJSONObject("taxon"))); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalSpecies; } // Returns a minimal version of a sound JSON (used to lower memory usage) private JSONObject getMinimalSound(JSONObject sound) { JSONObject minimalSound = new JSONObject(); if (sound == null) return null; try { minimalSound.put("id", sound.optInt("id")); minimalSound.put("file_url", sound.optString("file_url")); minimalSound.put("file_content_type", sound.optString("file_content_type")); minimalSound.put("attribution", sound.optString("attribution")); minimalSound.put("subtype", sound.optString("subtype")); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalSound; } // Returns a minimal version of a photo JSON (used to lower memory usage) private JSONObject getMinimalPhoto(JSONObject photo) { JSONObject minimalPhoto = new JSONObject(); if (photo == null) return null; try { minimalPhoto.put("id", photo.optInt("id")); minimalPhoto.put("position", photo.optInt("position")); if (photo.has("photo") && !photo.isNull("photo")) { JSONObject innerPhoto = new JSONObject(); innerPhoto.put("id", photo.optJSONObject("photo").optInt("id")); innerPhoto.put("url", photo.optJSONObject("photo").optString("url")); minimalPhoto.put("photo", innerPhoto); } } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalPhoto; } // Returns a minimal version of a taxon JSON (used to lower memory usage) private JSONObject getMinimalTaxon(JSONObject taxon) { JSONObject minimalTaxon = new JSONObject(); if (taxon == null) return null; try { minimalTaxon.put("id", taxon.optInt("id")); minimalTaxon.put("name", taxon.optString("name")); minimalTaxon.put("rank", taxon.optString("rank")); minimalTaxon.put("rank_level", taxon.optInt("rank_level")); minimalTaxon.put("iconic_taxon_name", taxon.optString("iconic_taxon_name")); if (taxon.has("taxon_names")) minimalTaxon.put("taxon_names", taxon.optJSONArray("taxon_names")); if (taxon.has("default_name")) minimalTaxon.put("default_name", taxon.optJSONObject("default_name")); if (taxon.has("common_name")) minimalTaxon.put("common_name", taxon.optJSONObject("common_name")); if (taxon.has("preferred_common_name")) minimalTaxon.put("preferred_common_name", taxon.optString("preferred_common_name")); if (taxon.has("english_common_name")) minimalTaxon.put("english_common_name", taxon.optString("english_common_name")); if (taxon.has("observations_count")) minimalTaxon.put("observations_count", taxon.optInt("observations_count")); if (taxon.has("default_photo") && !taxon.isNull("default_photo")) { JSONObject minimalPhoto = new JSONObject(); JSONObject defaultPhoto = taxon.optJSONObject("default_photo"); if (defaultPhoto.has("medium_url") && !defaultPhoto.isNull("medium_url")) { minimalPhoto.put("medium_url", defaultPhoto.optString("medium_url")); } else { minimalPhoto.put("photo_url", defaultPhoto.optString("photo_url")); } minimalTaxon.put("default_photo", minimalPhoto); } } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalTaxon; } private int getTotalProgressForObservation(Observation observation) { int obsCount = 0; if ((observation._synced_at == null) || ((observation._updated_at != null) && (observation._updated_at.after(observation._synced_at)))) { obsCount = 1; } int photoCount; int externalObsId = observation.id != null ? observation.id : observation._id; Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "((_synced_at IS NULL) OR (_updated_at > _synced_at AND _synced_at IS NOT NULL AND id IS NOT NULL) OR (is_deleted = 1)) AND " + "((observation_id = ?) OR (_observation_id = ?))", new String[]{String.valueOf(externalObsId), String.valueOf(observation._id)}, ObservationPhoto.DEFAULT_SORT_ORDER); photoCount = c.getCount(); c.close(); int projectFieldCount; c = getContentResolver().query(ProjectFieldValue.CONTENT_URI, ProjectFieldValue.PROJECTION, "((_synced_at IS NULL) OR (_updated_at > _synced_at AND _synced_at IS NOT NULL)) AND " + "((observation_id = ?) OR (observation_id = ?))", new String[]{String.valueOf(externalObsId), String.valueOf(observation._id)}, ProjectFieldValue.DEFAULT_SORT_ORDER); projectFieldCount = c.getCount(); c.close(); int projectObservationCount; c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "((is_deleted = 1) OR (is_new = 1)) AND " + "((observation_id = ?) OR (observation_id = ?))", new String[]{String.valueOf(externalObsId), String.valueOf(observation._id)}, ProjectObservation.DEFAULT_SORT_ORDER); projectObservationCount = c.getCount(); c.close(); int soundCount; c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "((is_deleted = 1) OR (id is NULL)) AND " + "((observation_id = ?) OR (_observation_id = ?))", new String[]{String.valueOf(externalObsId), String.valueOf(observation._id)}, ObservationSound.DEFAULT_SORT_ORDER); soundCount = c.getCount(); c.close(); return 1 + // We start off with some progress (one "part") obsCount + // For the observation upload itself (only if new/update) photoCount + // For photos soundCount + // For sounds projectFieldCount + // For updated/new obs project fields projectObservationCount; // For updated/new observation project fields } // Re-download old local observations and update their taxon names (preferred common names) - used when user switches language private void redownloadOldObservationsForTaxonNames() throws AuthenticationException { // Get most recent observation Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "(id IS NOT NULL)", null, "id DESC"); c.moveToFirst(); if (c.getCount() == 0) { c.close(); return; } Integer currentObsId = c.getInt(c.getColumnIndexOrThrow(Observation.ID)) + 1; c.moveToLast(); Integer lastObsId = c.getInt(c.getColumnIndexOrThrow(Observation.ID)); c.close(); JSONArray results = null; int obsCount = 0; do { Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames: " + currentObsId); String url = API_HOST + "/observations?user_id=" + Uri.encode(mLogin) + "&per_page=100&id_below=" + currentObsId; Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); url += "&locale=" + deviceLanguage; JSONArray json = get(url, true); Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames - downloaded"); if (json == null || json.length() == 0) { break; } Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames - downloaded 2"); results = json.optJSONObject(0).optJSONArray("results"); Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames - downloaded 3"); for (int i = 0; i < results.length(); i++) { JSONObject currentObs = results.optJSONObject(i); int currentId = currentObs.optInt("id"); c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = ?", new String[]{String.valueOf(currentId)}, Observation.DEFAULT_SORT_ORDER); Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames - Updating taxon details for obs: " + currentId); if (c.getCount() == 0) { c.close(); continue; } // Update current observation's taxon preferred common name Observation obs = new Observation(c); c.close(); obs.setPreferredCommonName(currentObs); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "redownloadOldObservationsForTaxonNames - Common name for observation %d: %s", currentId, obs.preferred_common_name)); ContentValues cv = obs.getContentValues(); if (!obs._updated_at.after(obs._synced_at)) { // Update its sync at time so we won't update the remote servers later on (since we won't // accidentally consider this an updated record) cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); } getContentResolver().update(obs.getUri(), cv, null, null); currentObsId = obs.id; obsCount++; if (obsCount > MAX_OBSVERATIONS_TO_REDOWNLOAD) break; } } while ((results.length() > 0) && (currentObsId > lastObsId) && (obsCount <= MAX_OBSVERATIONS_TO_REDOWNLOAD)); Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames - finished"); mApp.setLastLocale(); } // Re-download any observations that have photos saved in the "old" way private void redownloadOldObservations() throws AuthenticationException { // Find all observations that have photos saved in the old way Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(photo_filename IS NULL) AND (photo_url IS NULL)", null, ObservationPhoto.DEFAULT_SORT_ORDER); c.moveToFirst(); Logger.tag(TAG).debug("redownloadOldObservations: " + c.getCount()); while (!c.isAfterLast()) { Integer obsId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto.OBSERVATION_ID)); Logger.tag(TAG).debug("redownloadOldObservations: " + new ObservationPhoto(c)); // Delete the observation photo Integer obsPhotoId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto.ID)); getContentResolver().delete(ObservationPhoto.CONTENT_URI, "id = " + obsPhotoId, null); // Re-download this observation String url = HOST + "/observations/" + Uri.encode(mLogin) + ".json?extra=observation_photos,projects,fields"; Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); url += "&locale=" + deviceLanguage; JSONArray json = get(url, true); if (json != null && json.length() > 0) { syncJson(json, true); } c.moveToNext(); } c.close(); } private BetterJSONObject getHistogram(int taxonId, boolean researchGrade) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/observations/histogram?taxon_id=%d&", API_HOST, taxonId); if (researchGrade) { url += "quality_grade=research"; } else { url += "verifiable=true"; } JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getPopularFieldValues(int taxonId) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/observations/popular_field_values?taxon_id=%d&verifiable=true", API_HOST, taxonId); JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getTaxonSuggestions(String photoFilename, Double latitude, Double longitude, Timestamp observedOn) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String date = observedOn != null ? new SimpleDateFormat("yyyy-MM-dd").format(observedOn) : null; ArrayList<NameValuePair> params = new ArrayList<>(); String url = String.format(Locale.ENGLISH, API_HOST + "/computervision/score_image"); params.add(new BasicNameValuePair("locale", deviceLanguage)); params.add(new BasicNameValuePair("lat", latitude.toString())); params.add(new BasicNameValuePair("lng", longitude.toString())); if (date != null) params.add(new BasicNameValuePair("observed_on", date)); params.add(new BasicNameValuePair("image", photoFilename)); JSONArray json = request(url, "post", params, null, true, true, true); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); if (!res.has("results")) return null; return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getTaxonNew(int id) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/taxa/" + id + "?locale=" + deviceLanguage; JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); if (!res.has("results")) return null; JSONObject taxon = res.getJSONArray("results").getJSONObject(0); return new BetterJSONObject(taxon); } catch (JSONException e) { return null; } } private BetterJSONObject setAnnotationValue(int observationId, int attributeId, int valueId) throws AuthenticationException { String url = API_HOST + "/annotations"; JSONObject params = new JSONObject(); try { params.put("resource_type", "Observation"); params.put("resource_id", observationId); params.put("controlled_attribute_id", attributeId); params.put("controlled_value_id", valueId); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } JSONArray json = post(url, params); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject agreeAnnotation(String uuid, boolean agree) throws AuthenticationException { String url = API_HOST + "/votes/vote/annotation/" + uuid; JSONObject params = new JSONObject(); try { if (!agree) params.put("vote", "bad"); params.put("id", uuid); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } JSONArray json = post(url, params); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject deleteAnnotationVote(String uuid) throws AuthenticationException { String url = API_HOST + "/votes/unvote/annotation/" + uuid; JSONArray json = delete(url, null); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject voteIdCanBeImproved(int obsId, boolean yes) throws AuthenticationException { String url = API_HOST + "/votes/vote/observation/" + obsId; JSONObject params = new JSONObject(); try { params.put("vote", yes ? "yes" : "no"); params.put("id", obsId); params.put("scope", "needs_id"); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } JSONArray json = post(url, params); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject deleteIdCanBeImprovedVote(int obsId) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/votes/unvote/observation/%d?id=%d&scope=needs_id", API_HOST, obsId, obsId); JSONArray json = delete(url, null); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getDataQualityMetrics(Integer observationId) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/observations/%d/quality_metrics?id=%d", API_HOST, observationId, observationId); JSONArray json = get(url, true); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); if (!res.has("results")) return null; return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject agreeDataQualityMetric(Integer observationId, String metric, boolean agree) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/observations/%d/quality/%s", API_HOST, observationId, metric); JSONObject params = new JSONObject(); try { params.put("agree", agree ? "true" : "false"); params.put("id", observationId); params.put("metric", metric); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } JSONArray json = post(url, params); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject deleteDataQualityMetricVote(Integer observationId, String metric) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/observations/%d/quality/%s?id=%d&metric=%s", API_HOST, observationId, metric, observationId, metric); JSONArray json = delete(url, null); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject deleteAnnotation(String uuid) throws AuthenticationException { String url = API_HOST + "/annotations/" + uuid; JSONArray json = delete(url, null); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getAllAttributes() throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/controlled_terms?locale=" + deviceLanguage; JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); if (!res.has("results")) return null; return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getAttributesForTaxon(JSONObject taxon) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); JSONArray ancestors = taxon != null ? taxon.optJSONArray("ancestor_ids") : null; String url; if (ancestors != null) { String ancestry = ""; for (int i = 0; i < ancestors.length(); i++) { int currentTaxonId = ancestors.optInt(i); ancestry += String.format(Locale.ENGLISH, "%d,", currentTaxonId); } ancestry += String.format(Locale.ENGLISH, "%d", taxon.optInt("id")); url = API_HOST + "/controlled_terms/for_taxon?taxon_id=" + ancestry + "&ttl=-1&locale=" + deviceLanguage; } else { url = API_HOST + "/controlled_terms?ttl=-1&locale=" + deviceLanguage; } JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); if (!res.has("results")) return null; return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getTaxon(int id) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = String.format(Locale.ENGLISH, "%s/taxa/%d.json?locale=%s", HOST, id, deviceLanguage); JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); } catch (JSONException e) { return null; } return new BetterJSONObject(res); } private boolean postProjectObservations(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { if (observation.id == null) { // Observation not synced yet - cannot sync its project associations yet return true; } // First, delete any project-observations that were deleted by the user Cursor c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "is_deleted = 1 AND observation_id = ?", new String[]{String.valueOf(observation.id)}, ProjectObservation.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { checkForCancelSync(); ProjectObservation projectObservation = new ProjectObservation(c); // Clean the errors for the observation mApp.setErrorsForObservation(projectObservation.observation_id, projectObservation.project_id, new JSONArray()); try { // Remove obs from project BetterJSONObject result = removeObservationFromProject(projectObservation.observation_id, projectObservation.project_id); if (result == null) { c.close(); throw new SyncFailedException(); } increaseProgressForObservation(observation); } catch (Exception exc) { // In case we're trying to delete a project-observation that wasn't synced yet c.close(); throw new SyncFailedException(); } getContentResolver().delete(ProjectObservation.CONTENT_URI, "_id = ?", new String[]{String.valueOf(projectObservation._id)}); c.moveToNext(); } c.close(); // Next, add new project observations c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "is_new = 1 AND observation_id = ?", new String[]{String.valueOf(observation.id)}, ProjectObservation.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { checkForCancelSync(); ProjectObservation projectObservation = new ProjectObservation(c); BetterJSONObject result = addObservationToProject(projectObservation.observation_id, projectObservation.project_id); if ((result == null) && (mResponseErrors == null)) { c.close(); throw new SyncFailedException(); } increaseProgressForObservation(observation); if (mResponseErrors != null) { handleProjectFieldErrors(projectObservation.observation_id, projectObservation.project_id); } else { // Unmark as new projectObservation.is_new = false; ContentValues cv = projectObservation.getContentValues(); getContentResolver().update(projectObservation.getUri(), cv, null, null); // Clean the errors for the observation mApp.setErrorsForObservation(projectObservation.observation_id, projectObservation.project_id, new JSONArray()); } c.moveToNext(); } c.close(); return true; } private boolean postProjectObservations() throws AuthenticationException, CancelSyncException, SyncFailedException { // First, delete any project-observations that were deleted by the user Cursor c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "is_deleted = 1", null, ProjectObservation.DEFAULT_SORT_ORDER); if (c.getCount() > 0) { mApp.notify(SYNC_PHOTOS_NOTIFICATION, getString(R.string.projects), getString(R.string.syncing_observation_fields), getString(R.string.syncing)); } c.moveToFirst(); while (c.isAfterLast() == false) { checkForCancelSync(); ProjectObservation projectObservation = new ProjectObservation(c); // Clean the errors for the observation mApp.setErrorsForObservation(projectObservation.observation_id, projectObservation.project_id, new JSONArray()); try { // Remove obs from project BetterJSONObject result = removeObservationFromProject(projectObservation.observation_id, projectObservation.project_id); if (result == null) { c.close(); throw new SyncFailedException(); } } catch (Exception exc) { // In case we're trying to delete a project-observation that wasn't synced yet c.close(); throw new SyncFailedException(); } c.moveToNext(); } c.close(); // Now it's safe to delete all of the project-observations locally getContentResolver().delete(ProjectObservation.CONTENT_URI, "is_deleted = 1", null); // Next, add new project observations c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "is_new = 1", null, ProjectObservation.DEFAULT_SORT_ORDER); if (c.getCount() > 0) { mApp.notify(SYNC_PHOTOS_NOTIFICATION, getString(R.string.projects), getString(R.string.syncing_observation_fields), getString(R.string.syncing)); } c.moveToFirst(); while (c.isAfterLast() == false) { checkForCancelSync(); ProjectObservation projectObservation = new ProjectObservation(c); BetterJSONObject result = addObservationToProject(projectObservation.observation_id, projectObservation.project_id); if ((result == null) && (mResponseErrors == null)) { c.close(); throw new SyncFailedException(); } mApp.setObservationIdBeingSynced(projectObservation.observation_id); if (mResponseErrors != null) { handleProjectFieldErrors(projectObservation.observation_id, projectObservation.project_id); } else { // Unmark as new projectObservation.is_new = false; ContentValues cv = projectObservation.getContentValues(); getContentResolver().update(projectObservation.getUri(), cv, null, null); // Clean the errors for the observation mApp.setErrorsForObservation(projectObservation.observation_id, projectObservation.project_id, new JSONArray()); } c.moveToNext(); } c.close(); mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); // Finally, retrieve all project observations storeProjectObservations(); return true; } private boolean handleProjectFieldErrors(int observationId, int projectId) { SerializableJSONArray errors = new SerializableJSONArray(mResponseErrors); // Couldn't add the observation to the project (probably didn't pass validation) String error; try { error = errors.getJSONArray().getString(0); } catch (JSONException e) { return false; } Cursor c2 = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = '" + observationId + "'", null, Observation.DEFAULT_SORT_ORDER); c2.moveToFirst(); if (c2.getCount() == 0) { c2.close(); return false; } Observation observation = new Observation(c2); c2.close(); c2 = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = '" + projectId + "'", null, Project.DEFAULT_SORT_ORDER); c2.moveToFirst(); if (c2.getCount() == 0) { c2.close(); return false; } Project project = new Project(c2); c2.close(); // Remember the errors for this observation (to be shown in the observation editor screen) JSONArray formattedErrors = new JSONArray(); JSONArray unformattedErrors = errors.getJSONArray(); for (int i = 0; i < unformattedErrors.length(); i++) { try { formattedErrors.put(String.format(Locale.ENGLISH, getString(R.string.failed_to_add_to_project), project.title, unformattedErrors.getString(i))); } catch (JSONException e) { Logger.tag(TAG).error(e); } } mApp.setErrorsForObservation(observation.id, project.id, formattedErrors); final String errorMessage = String.format(Locale.ENGLISH, getString(R.string.failed_to_add_obs_to_project), observation.species_guess == null ? getString(R.string.unknown) : observation.species_guess, project.title, error); // Display toast in this main thread handler (since otherwise it won't get displayed) mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_LONG).show(); } }); try { JSONObject eventParams = new JSONObject(); eventParams.put(AnalyticsClient.EVENT_PARAM_ALERT, errorMessage); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_SYNC_FAILED, eventParams); } catch (JSONException e) { Logger.tag(TAG).error(e); } return true; } private void storeProjectObservations() { for (int j = 0; j < mProjectObservations.size(); j++) { SerializableJSONArray arr = mProjectObservations.get(j); if (arr == null) continue; JSONArray projectObservations = mProjectObservations.get(j).getJSONArray(); for (int i = 0; i < projectObservations.length(); i++) { JSONObject jsonProjectObservation; try { jsonProjectObservation = projectObservations.getJSONObject(i); ProjectObservation projectObservation = new ProjectObservation(new BetterJSONObject(jsonProjectObservation)); ContentValues cv = projectObservation.getContentValues(); Cursor c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "project_id = " + projectObservation.project_id + " AND observation_id = " + projectObservation.observation_id, null, ProjectObservation.DEFAULT_SORT_ORDER); if (c.getCount() == 0) { getContentResolver().insert(ProjectObservation.CONTENT_URI, cv); } c.close(); } catch (JSONException e) { Logger.tag(TAG).error(e); } } } } private boolean deleteAccount() throws AuthenticationException { String username = mApp.currentUserLogin(); JSONArray result = delete( String.format(Locale.ENGLISH, "%s/users/%s.json?confirmation_code=%s&confirmation=%s", HOST, username, username, username), null); if (result == null) { Logger.tag(TAG).debug("deleteAccount error: " + mLastStatusCode); return false; } return true; } private boolean saveJoinedProjects() throws AuthenticationException, CancelSyncException, SyncFailedException { SerializableJSONArray projects = getJoinedProjects(); checkForCancelSync(); if (projects == null) { throw new SyncFailedException(); } JSONArray arr = projects.getJSONArray(); // Retrieve all currently-joined project IDs List<Integer> projectIds = new ArrayList<Integer>(); HashMap<Integer, JSONObject> projectByIds = new HashMap<Integer, JSONObject>(); for (int i = 0; i < arr.length(); i++) { try { JSONObject jsonProject = arr.getJSONObject(i); int id = jsonProject.getInt("id"); projectIds.add(id); projectByIds.put(id, jsonProject); } catch (JSONException exc) { Logger.tag(TAG).error(exc); } } // Check which projects were un-joined and remove them locally try { int count = getContentResolver().delete(Project.CONTENT_URI, "id not in (" + StringUtils.join(projectIds, ',') + ")", null); } catch (Exception exc) { Logger.tag(TAG).error(exc); throw new SyncFailedException(); } // Add any newly-joined projects for (Map.Entry<Integer, JSONObject> entry : projectByIds.entrySet()) { int id = entry.getKey(); JSONObject jsonProject = entry.getValue(); Cursor c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = ?", new String[]{String.valueOf(id)}, null); if (c.getCount() == 0) { Project project = new Project(new BetterJSONObject(jsonProject)); ContentValues cv = project.getContentValues(); getContentResolver().insert(Project.CONTENT_URI, cv); } c.close(); } return true; } private boolean deleteObservationSounds(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { // Remotely delete any locally-removed observation sounds Cursor c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "is_deleted = 1 AND _observation_id = ?", new String[]{String.valueOf(observation._id)}, ObservationSound.DEFAULT_SORT_ORDER); String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); // for each observation DELETE to /sounds/:id c.moveToFirst(); while (c.isAfterLast() == false) { ObservationSound os = new ObservationSound(c); Logger.tag(TAG).debug("deleteObservationSounds: " + os); if (os.id != null) { Logger.tag(TAG).debug("deleteObservationSounds: Deleting " + os); JSONArray result = delete(inatHost + "/observation_sounds/" + os.id + ".json", null); if (result == null) { Logger.tag(TAG).debug("deleteObservationSounds: Deletion error: " + mLastStatusCode); if (mLastStatusCode != HttpStatus.SC_NOT_FOUND) { // Ignore the case where the sound was remotely deleted Logger.tag(TAG).debug("deleteObservationSounds: Not a 404 error"); c.close(); throw new SyncFailedException(); } } } increaseProgressForObservation(observation); int count = getContentResolver().delete(ObservationSound.CONTENT_URI, "id = ? or _id = ?", new String[]{String.valueOf(os.id), String.valueOf(os._id)}); Logger.tag(TAG).debug("deleteObservationSounds: Deleted from DB: " + count); c.moveToNext(); } c.close(); checkForCancelSync(); return true; } private boolean deleteObservationPhotos(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { // Remotely delete any locally-removed observation photos Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "is_deleted = 1 AND _observation_id = ?", new String[]{String.valueOf(observation._id)}, ObservationPhoto.DEFAULT_SORT_ORDER); // for each observation DELETE to /observation_photos/:id c.moveToFirst(); while (c.isAfterLast() == false) { ObservationPhoto op = new ObservationPhoto(c); Logger.tag(TAG).debug("deleteObservationPhotos: " + op + "::::" + op._synced_at); if (op._synced_at != null) { if (op.id != null) { Logger.tag(TAG).debug("deleteObservationPhotos: Deleting " + op); JSONArray result = delete(HOST + "/observation_photos/" + op.id + ".json", null); if (result == null) { Logger.tag(TAG).debug("deleteObservationPhotos: Deletion error: " + mLastStatusCode); if (mLastStatusCode != HttpStatus.SC_NOT_FOUND) { // Ignore the case where the photo was remotely deleted Logger.tag(TAG).debug("deleteObservationPhotos: Not a 404 error"); c.close(); throw new SyncFailedException(); } } } } increaseProgressForObservation(observation); int count = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "id = ? or _id = ?", new String[]{String.valueOf(op.id), String.valueOf(op._id)}); Logger.tag(TAG).debug("deleteObservationPhotos: Deleted from DB: " + count); c.moveToNext(); } c.close(); checkForCancelSync(); return true; } private boolean deleteObservations(long[] idsToDelete) throws AuthenticationException, CancelSyncException, SyncFailedException { Cursor c; if (idsToDelete != null) { // Remotely delete selected observations only c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_id in (" + StringUtils.join(ArrayUtils.toObject(idsToDelete), ",") + ")", null, Observation.DEFAULT_SORT_ORDER); } else { // Remotely delete any locally-removed observations (marked for deletion) c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "is_deleted = 1", null, Observation.DEFAULT_SORT_ORDER); } Logger.tag(TAG).debug("deleteObservations: Deleting " + c.getCount()); if (c.getCount() > 0) { mApp.notify(getString(R.string.deleting_observations), getString(R.string.deleting_observations)); } // for each observation DELETE to /observations/:id ArrayList<Integer> obsIds = new ArrayList<Integer>(); ArrayList<String> obsUUIDs = new ArrayList<String>(); ArrayList<Integer> internalObsIds = new ArrayList<Integer>(); c.moveToFirst(); while (c.isAfterLast() == false) { Observation observation = new Observation(c); Logger.tag(TAG).debug("deleteObservations: Deleting " + observation); JSONArray results = delete(HOST + "/observations/" + observation.id + ".json", null); if (results == null) { c.close(); throw new SyncFailedException(); } obsIds.add(observation.id); obsUUIDs.add('"' + observation.uuid + '"'); internalObsIds.add(observation._id); c.moveToNext(); } Logger.tag(TAG).debug("deleteObservations: Deleted IDs: " + obsIds); c.close(); // Now it's safe to delete all of the observations locally getContentResolver().delete(Observation.CONTENT_URI, "is_deleted = 1", null); // Delete associated project-fields and photos int count1 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_id in (" + StringUtils.join(obsIds, ",") + ")", null); int count2 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_uuid in (" + StringUtils.join(obsUUIDs, ",") + ")", null); int count3 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_id in (" + StringUtils.join(obsIds, ",") + ")", null); int count4 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_uuid in (" + StringUtils.join(obsUUIDs, ",") + ")", null); int count5 = getContentResolver().delete(ProjectObservation.CONTENT_URI, "observation_id in (" + StringUtils.join(obsIds, ",") + ")", null); int count6 = getContentResolver().delete(ProjectFieldValue.CONTENT_URI, "observation_id in (" + StringUtils.join(obsIds, ",") + ")", null); int count7 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "_observation_id in (" + StringUtils.join(internalObsIds, ",") + ")", null); int count8 = getContentResolver().delete(ObservationSound.CONTENT_URI, "_observation_id in (" + StringUtils.join(internalObsIds, ",") + ")", null); Logger.tag(TAG).debug("deleteObservations: " + count1 + ":" + count2 + ":" + count3 + ":" + count4 + ":" + count5 + ":" + count6 + ":" + count7 + ":" + count8); checkForCancelSync(); return true; } private void checkForCancelSync() throws CancelSyncException { if (mApp.getCancelSync()) throw new CancelSyncException(); } private JSONObject removeFavorite(int observationId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); JSONArray result = delete(HOST + "/votes/unvote/observation/" + observationId + ".json", null); if (result != null) { try { return result.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } else { return null; } } private JSONObject addFavorite(int observationId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); JSONArray result = post(HOST + "/votes/vote/observation/" + observationId + ".json", (JSONObject) null); if (result != null) { try { return result.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } else { return null; } } private JSONObject agreeIdentification(int observationId, int taxonId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("identification[observation_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("identification[taxon_id]", new Integer(taxonId).toString())); JSONArray result = post(HOST + "/identifications.json", params); if (result != null) { try { return result.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } else { return null; } } private JSONObject removeIdentification(int identificationId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); JSONArray result = delete(HOST + "/identifications/" + identificationId + ".json", null); if (result != null) { try { return result.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } else { return null; } } private void setUserViewedUpdate(int obsId) throws AuthenticationException { put(HOST + "/observations/" + obsId + "/viewed_updates", (JSONObject) null); } private void restoreIdentification(int identificationId) throws AuthenticationException { JSONObject paramsJson = new JSONObject(); JSONObject paramsJsonIdentification = new JSONObject(); try { paramsJsonIdentification.put("current", true); paramsJson.put("identification", paramsJsonIdentification); JSONArray arrayResult = put(API_HOST + "/identifications/" + identificationId, paramsJson); } catch (JSONException e) { Logger.tag(TAG).error(e); } } private void updateIdentification(int observationId, int identificationId, int taxonId, String body) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("identification[observation_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("identification[taxon_id]", new Integer(taxonId).toString())); params.add(new BasicNameValuePair("identification[body]", body)); JSONArray arrayResult = put(HOST + "/identifications/" + identificationId + ".json", params); } private void addIdentification(int observationId, int taxonId, String body, boolean disagreement, boolean fromVision) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("identification[observation_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("identification[taxon_id]", new Integer(taxonId).toString())); if (body != null) params.add(new BasicNameValuePair("identification[body]", body)); params.add(new BasicNameValuePair("identification[disagreement]", String.valueOf(disagreement))); params.add(new BasicNameValuePair("identification[vision]", String.valueOf(fromVision))); JSONArray arrayResult = post(HOST + "/identifications.json", params); if (arrayResult != null) { BetterJSONObject result; try { result = new BetterJSONObject(arrayResult.getJSONObject(0)); JSONObject jsonObservation = result.getJSONObject("observation"); Observation remoteObservation = new Observation(new BetterJSONObject(jsonObservation)); Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + remoteObservation.id, null, Observation.DEFAULT_SORT_ORDER); // update local observation c.moveToFirst(); if (c.isAfterLast() == false) { Observation observation = new Observation(c); boolean isModified = observation.merge(remoteObservation); ContentValues cv = observation.getContentValues(); if (observation._updated_at.before(remoteObservation.updated_at)) { // Remote observation is newer (and thus has overwritten the local one) - update its // sync at time so we won't update the remote servers later on (since we won't // accidentally consider this an updated record) cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); } if (isModified) { // Only update the DB if needed getContentResolver().update(observation.getUri(), cv, null, null); } } c.close(); } catch (JSONException e) { Logger.tag(TAG).error(e); } } } // Updates a user's inat network settings private JSONObject updateUserTimezone(String timezone) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user[time_zone]", timezone)); try { JSONObject paramsJson = new JSONObject(); JSONObject userJson = new JSONObject(); userJson.put("time_zone", timezone); paramsJson.put("user", userJson); JSONArray array = put(API_HOST + "/users/" + mLogin, paramsJson); if ((mResponseErrors != null) || (array == null)) { // Couldn't update user return null; } else { return array.optJSONObject(0); } } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } // Updates a user's inat network settings private JSONObject updateUserNetwork(int siteId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user[site_id]", String.valueOf(siteId))); JSONArray array = put(HOST + "/users/" + mLogin + ".json", params); if ((mResponseErrors != null) || (array == null)) { // Couldn't update user return null; } else { return array.optJSONObject(0); } } // Updates a user's profile private JSONObject updateUser(String username, String email, String password, String fullName, String bio, String userPic, boolean deletePic) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user[login]", username)); params.add(new BasicNameValuePair("user[name]", fullName)); params.add(new BasicNameValuePair("user[description]", bio)); params.add(new BasicNameValuePair("user[email]", email)); if ((password != null) && (password.length() > 0)) { params.add(new BasicNameValuePair("user[password]", password)); params.add(new BasicNameValuePair("user[password_confirmation]", password)); } if (deletePic) { // Delete profile pic params.add(new BasicNameValuePair("icon_delete", "true")); } else if (userPic != null) { // New profile pic params.add(new BasicNameValuePair("user[icon]", userPic)); } JSONArray array = put(HOST + "/users/" + mLogin + ".json", params); if ((mResponseErrors != null) || (array == null)) { // Couldn't update user return null; } else { return array.optJSONObject(0); } } interface IOnTimezone { void onTimezone(String timezoneName); } private void getTimezoneByCurrentLocation(IOnTimezone cb) { getLocation(new IOnLocation() { @Override public void onLocation(Location location) { if (location == null) { // Couldn't retrieve current location cb.onTimezone(null); return; } // Convert coordinates to timezone GeoApiContext context = new GeoApiContext.Builder() .apiKey(getString(R.string.gmaps2_api_key)) .build(); LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude()); String zoneIdName = null; try { TimeZone zone = TimeZoneApi.getTimeZone(context, currentLocation).await(); zoneIdName = zone.getID(); } catch (NoClassDefFoundError exc) { // Not working on older Androids Logger.tag(TAG).error(exc); cb.onTimezone(null); return; } catch (Exception exc) { // Couldn't convert coordinates to timezone Logger.tag(TAG).error(exc); cb.onTimezone(null); return; } // Next, convert from standard zone name into iNaturalist-API-accepted name if (!TIMEZONE_ID_TO_INAT_TIMEZONE.containsKey(zoneIdName)) { // Timezone is unsupported by iNaturalist cb.onTimezone(null); return; } String zoneName = TIMEZONE_ID_TO_INAT_TIMEZONE.get(zoneIdName); cb.onTimezone(zoneName); } }); } // Registers a user - returns an error message in case of an error (null if successful) private String registerUser(String email, String password, String username, String license, String timezone) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user[email]", email)); params.add(new BasicNameValuePair("user[login]", username)); params.add(new BasicNameValuePair("user[password]", password)); params.add(new BasicNameValuePair("user[password_confirmation]", password)); String inatNetwork = mApp.getInaturalistNetworkMember(); params.add(new BasicNameValuePair("user[site_id]", mApp.getStringResourceByName("inat_site_id_" + inatNetwork))); params.add(new BasicNameValuePair("user[preferred_observation_license]", license)); params.add(new BasicNameValuePair("user[preferred_photo_license]", license)); params.add(new BasicNameValuePair("user[preferred_sound_license]", license)); Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); params.add(new BasicNameValuePair("user[locale]", deviceLanguage)); if (timezone != null) { params.add(new BasicNameValuePair("user[time_zone]", timezone)); } post(HOST + "/users.json", params, false); if (mResponseErrors != null) { // Couldn't create user try { return mResponseErrors.getString(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } else { return null; } } private void updateComment(int commentId, int observationId, String body) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("comment[parent_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("comment[parent_type]", "Observation")); params.add(new BasicNameValuePair("comment[body]", body)); put(HOST + "/comments/" + commentId + ".json", params); } private void deleteComment(int commentId) throws AuthenticationException { delete(HOST + "/comments/" + commentId + ".json", null); } private void addComment(int observationId, String body) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("comment[parent_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("comment[parent_type]", "Observation")); params.add(new BasicNameValuePair("comment[body]", body)); post(HOST + "/comments.json", params); } private boolean postObservation(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLexicon = deviceLocale.getLanguage(); if (observation.id != null) { // Update observation Logger.tag(TAG).debug("postObservation: Updating existing " + observation.id + ":" + observation._id); JSONArray response = request(API_HOST + "/observations/" + observation.id + "?locale=" + deviceLexicon, "put", null, observationToJsonObject(observation, false), true, true, false); if (response == null) { Logger.tag(TAG).debug("postObservation: Error for " + observation.id + ":" + observation._id + ":" + mLastStatusCode); // Some sort of error if ((mLastStatusCode >= 400) && (mLastStatusCode < 500)) { // Observation doesn't exist anymore (deleted remotely, and due to network // issues we didn't get any notification of this) - so delete the observation // locally. Logger.tag(TAG).debug("postObservation: Deleting obs " + observation.id + ":" + observation._id); getContentResolver().delete(Observation.CONTENT_URI, "id = " + observation.id, null); // Delete associated project-fields and photos int count1 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_id = " + observation.id, null); int count2 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_uuid = \"" + observation.uuid + "\"", null); int count3 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_id = " + observation.id, null); int count4 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_uuid = \"" + observation.uuid + "\"", null); int count5 = getContentResolver().delete(ProjectObservation.CONTENT_URI, "observation_id = " + observation.id, null); int count6 = getContentResolver().delete(ProjectFieldValue.CONTENT_URI, "observation_id = " + observation.id, null); Logger.tag(TAG).debug("postObservation: After delete: " + count1 + ":" + count2 + ":" + count3 + ":" + count4 + ":" + count5 + ":" + count6); return true; } } boolean success = handleObservationResponse(observation, response); if (!success) { throw new SyncFailedException(); } return true; } // New observation String inatNetwork = mApp.getInaturalistNetworkMember(); JSONObject observationParams = observationToJsonObject(observation, true); Logger.tag(TAG).debug("postObservation: New obs"); Logger.tag(TAG).debug(observationParams.toString()); boolean success = handleObservationResponse( observation, request(API_HOST + "/observations?locale=" + deviceLexicon, "post", null, observationParams, true, true, false) ); if (!success) { throw new SyncFailedException(); } return true; } private JSONObject getObservationJson(int id, boolean authenticated, boolean includeNewProjects) throws AuthenticationException { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = String.format(Locale.ENGLISH, "%s/observations/%d?locale=%s&%s", API_HOST, id, deviceLanguage, includeNewProjects ? "include_new_projects=true" : ""); JSONArray json = get(url, authenticated); if (json == null || json.length() == 0) { return null; } try { JSONArray results = json.getJSONObject(0).getJSONArray("results"); if (results.length() == 0) return null; return results.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private Observation getAndDownloadObservation(int id) throws AuthenticationException { // Download the observation JSONObject json = getObservationJson(id, true, true); if (json == null) return null; Observation obs = new Observation(new BetterJSONObject(json)); // Save the downloaded observation if (mProjectObservations == null) mProjectObservations = new ArrayList<SerializableJSONArray>(); if (mProjectFieldValues == null) mProjectFieldValues = new Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>>(); JSONArray arr = new JSONArray(); arr.put(json); syncJson(arr, true); return obs; } private boolean postSounds(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { Integer observationId = observation.id; ObservationSound os; int createdCount = 0; ContentValues cv; Logger.tag(TAG).debug("postSounds: " + observationId + ":" + observation); // query observation sounds where id is null (i.e. new sounds) Cursor c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "(id IS NULL) AND (observation_uuid = ?) AND ((is_deleted == 0) OR (is_deleted IS NULL))", new String[]{observation.uuid}, ObservationSound.DEFAULT_SORT_ORDER); Logger.tag(TAG).debug("postSounds: New sounds: " + c.getCount()); if (c.getCount() == 0) { c.close(); return true; } checkForCancelSync(); // for each observation POST to /sounds c.moveToFirst(); while (c.isAfterLast() == false) { os = new ObservationSound(c); Logger.tag(TAG).debug("postSounds: Posting sound - " + os); if (os.file_url != null) { // Online sound Logger.tag(TAG).debug("postSounds: Skipping because file_url is not null"); c.moveToNext(); continue; } if ((os.filename == null) || !(new File(os.filename)).exists()) { // Local (cached) sound was deleted - probably because the user deleted the app's cache Logger.tag(TAG).debug("postSounds: Posting sound - filename doesn't exist: " + os.filename); // First, delete this photo record getContentResolver().delete(ObservationSound.CONTENT_URI, "_id = ?", new String[]{String.valueOf(os._id)}); // Set errors for this obs - to notify the user that we couldn't upload the obs sounds JSONArray errors = new JSONArray(); errors.put(getString(R.string.deleted_sounds_from_cache_error)); mApp.setErrorsForObservation(os.observation_id, 0, errors); // Move to next observation sound c.moveToNext(); checkForCancelSync(); continue; } ArrayList<NameValuePair> params = os.getParams(); params.add(new BasicNameValuePair("audio", os.filename)); JSONArray response; String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); response = request( inatHost + "/observation_sounds.json", "post", params, null, true, true, false); try { if (response == null || response.length() != 1) { c.close(); throw new SyncFailedException(); } JSONObject json = response.getJSONObject(0); BetterJSONObject j = new BetterJSONObject(json); ObservationSound jsonObservationSound = new ObservationSound(j); Logger.tag(TAG).debug("postSounds: Response for POST: "); Logger.tag(TAG).debug(json.toString()); Logger.tag(TAG).debug("postSounds: Response for POST 2: " + jsonObservationSound); os.merge(jsonObservationSound); Logger.tag(TAG).debug("postSounds: Response for POST 3: " + os); cv = os.getContentValues(); Logger.tag(TAG).debug("postSounds - Setting _SYNCED_AT - " + os.id + ":" + os._id + ":" + os._observation_id + ":" + os.observation_id); getContentResolver().update(os.getUri(), cv, null, null); createdCount += 1; increaseProgressForObservation(observation); } catch (JSONException e) { Logger.tag(TAG).error("JSONException: " + e.toString()); } c.moveToNext(); checkForCancelSync(); } c.close(); c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "(id IS NULL) AND (observation_uuid = ?) AND ((is_deleted == 0) OR (is_deleted IS NULL))", new String[]{observation.uuid}, ObservationSound.DEFAULT_SORT_ORDER); int currentCount = c.getCount(); Logger.tag(TAG).debug("postSounds: currentCount = " + currentCount); c.close(); if (currentCount == 0) { // Sync completed successfully return true; } else { // Sync failed throw new SyncFailedException(); } } private boolean postPhotos(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { Integer observationId = observation.id; ObservationPhoto op; int createdCount = 0; ContentValues cv; Logger.tag(TAG).debug("postPhotos: " + observationId + ":" + observation); if (observationId != null) { // See if there any photos in an invalid state Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_updated_at > _synced_at AND _synced_at IS NOT NULL AND id IS NULL AND observation_id = ?", new String[]{String.valueOf(observationId)}, ObservationPhoto.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { op = new ObservationPhoto(c); // Shouldn't happen - a photo with null external ID is marked as sync - unmark it op._synced_at = null; Logger.tag(TAG).debug("postPhotos: Updating with _synced_at = null: " + op); getContentResolver().update(op.getUri(), op.getContentValues(), null, null); c.moveToNext(); } c.close(); c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_synced_at IS NULL AND id IS NOT NULL AND observation_id = ?", new String[]{String.valueOf(observationId)}, ObservationPhoto.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { op = new ObservationPhoto(c); // Shouldn't happen - a photo with an external ID is marked as never been synced cv = op.getContentValues(); cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(op.getUri(), cv, null, null); c.moveToNext(); } c.close(); // update photos - for each observation PUT to /observation_photos/:id c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_updated_at > _synced_at AND _synced_at IS NOT NULL AND id IS NOT NULL AND observation_uuid = ? AND ((is_deleted == 0) OR (is_deleted IS NULL))", new String[]{observation.uuid}, ObservationPhoto.DEFAULT_SORT_ORDER); int updatedCount = c.getCount(); Logger.tag(TAG).debug("postPhotos: Updating photos: " + updatedCount); c.moveToFirst(); while (c.isAfterLast() == false) { checkForCancelSync(); op = new ObservationPhoto(c); ArrayList<NameValuePair> params = op.getParams(); String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); params.add(new BasicNameValuePair("site_id", mApp.getStringResourceByName("inat_site_id_" + inatNetwork))); Logger.tag(TAG).debug("postPhotos: Updating " + op + ":" + params); JSONArray response = put(inatHost + "/observation_photos/" + op.id + ".json", params); try { if (response == null || response.length() != 1) { Logger.tag(TAG).debug("postPhotos: Failed updating " + op.id); c.close(); throw new SyncFailedException(); } increaseProgressForObservation(observation); JSONObject json = response.getJSONObject(0); BetterJSONObject j = new BetterJSONObject(json); ObservationPhoto jsonObservationPhoto = new ObservationPhoto(j); Logger.tag(TAG).debug("postPhotos after put: " + j); Logger.tag(TAG).debug("postPhotos after put 2: " + jsonObservationPhoto); op.merge(jsonObservationPhoto); Logger.tag(TAG).debug("postPhotos after put 3 - merge: " + op); cv = op.getContentValues(); Logger.tag(TAG).debug("postPhotos: Setting _SYNCED_AT - " + op.id + ":" + op._id + ":" + op._observation_id + ":" + op.observation_id); cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(op.getUri(), cv, null, null); createdCount += 1; } catch (JSONException e) { Logger.tag(TAG).error("JSONException: " + e.toString()); } c.moveToNext(); } c.close(); } // query observation photos where _synced_at is null (i.e. new photos) Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(_synced_at IS NULL) AND (id IS NULL) AND (observation_uuid = ?) AND ((is_deleted == 0) OR (is_deleted IS NULL))", new String[]{observation.uuid}, ObservationPhoto.DEFAULT_SORT_ORDER); Logger.tag(TAG).debug("postPhotos: New photos: " + c.getCount()); if (c.getCount() == 0) { c.close(); return true; } checkForCancelSync(); // for each observation POST to /observation_photos c.moveToFirst(); while (c.isAfterLast() == false) { op = new ObservationPhoto(c); Logger.tag(TAG).debug("postPhotos: Posting photo - " + op); if (op.photo_url != null) { // Online photo Logger.tag(TAG).debug("postPhotos: Skipping because photo_url is not null"); c.moveToNext(); continue; } ArrayList<NameValuePair> params = op.getParams(); String imgFilePath = op.photo_filename; if (imgFilePath == null) { // Observation photo is saved in the "old" way (prior to latest change in the way we store photos) Logger.tag(TAG).debug("postPhotos: Posting photo - photo_filename is null"); if (op._photo_id != null) { Uri photoUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, op._photo_id); Cursor pc = getContentResolver().query(photoUri, new String[]{MediaStore.MediaColumns._ID, MediaStore.Images.Media.DATA}, null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER); if (pc != null) { if (pc.getCount() > 0) { pc.moveToFirst(); imgFilePath = pc.getString(pc.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); } pc.close(); } } } if ((imgFilePath == null) || !(new File(imgFilePath)).exists()) { // Local (cached) photo was deleted - probably because the user deleted the app's cache Logger.tag(TAG).debug("postPhotos: Posting photo - still problematic photo filename: " + imgFilePath); // First, delete this photo record getContentResolver().delete(ObservationPhoto.CONTENT_URI, "_id = ?", new String[]{String.valueOf(op._id)}); // Set errors for this obs - to notify the user that we couldn't upload the obs photos JSONArray errors = new JSONArray(); errors.put(getString(R.string.deleted_photos_from_cache_error)); mApp.setErrorsForObservation(op.observation_id, 0, errors); // Move to next observation photo c.moveToNext(); checkForCancelSync(); continue; } params.add(new BasicNameValuePair("file", imgFilePath)); String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); params.add(new BasicNameValuePair("site_id", mApp.getStringResourceByName("inat_site_id_" + inatNetwork))); JSONArray response; Logger.tag(TAG).debug("postPhotos: POSTing new photo: " + params); response = post(inatHost + "/observation_photos.json", params, true); try { if (response == null || response.length() != 1) { c.close(); throw new SyncFailedException(); } increaseProgressForObservation(observation); JSONObject json = response.getJSONObject(0); BetterJSONObject j = new BetterJSONObject(json); ObservationPhoto jsonObservationPhoto = new ObservationPhoto(j); Logger.tag(TAG).debug("postPhotos: Response for POST: "); Logger.tag(TAG).debug(json.toString()); Logger.tag(TAG).debug("postPhotos: Response for POST 2: " + jsonObservationPhoto); op.merge(jsonObservationPhoto); Logger.tag(TAG).debug("postPhotos: Response for POST 3: " + op); cv = op.getContentValues(); Logger.tag(TAG).debug("postPhotos - Setting _SYNCED_AT - " + op.id + ":" + op._id + ":" + op._observation_id + ":" + op.observation_id); cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(op.getUri(), cv, null, null); createdCount += 1; } catch (JSONException e) { Logger.tag(TAG).error("JSONException: " + e.toString()); } c.moveToNext(); checkForCancelSync(); } c.close(); c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(_synced_at IS NULL) AND ((_observation_id = ? OR observation_id = ?)) AND ((is_deleted == 0) OR (is_deleted IS NULL))", new String[]{String.valueOf(observation._id), String.valueOf(observation.id)}, ObservationPhoto.DEFAULT_SORT_ORDER); int currentCount = c.getCount(); Logger.tag(TAG).debug("postPhotos: currentCount = " + currentCount); c.close(); if (currentCount == 0) { // Sync completed successfully return true; } else { // Sync failed throw new SyncFailedException(); } } // Warms the images cache by pre-loading a remote image private void warmUpImageCache(final String url) { Handler handler = new Handler(Looper.getMainLooper()); // Need to run on main thread handler.post(new Runnable() { @Override public void run() { Picasso.with(INaturalistService.this).load(url).into(new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { // cache is now warmed up } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }); } }); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } // Goes over cached photos that were uploaded and that are old enough and deletes them // to clear out storage space (they're replaced with their online version, so it'll be // accessible by the user). private void clearOldCachedPhotos() { if (!isNetworkAvailable()) return; if (!mApp.loggedIn()) return; Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_updated_at = _synced_at AND _synced_at IS NOT NULL AND id IS NOT NULL AND " + "photo_filename IS NOT NULL AND observation_id IS NOT NULL", new String[]{}, ObservationPhoto.DEFAULT_SORT_ORDER); int totalCount = c.getCount(); int photosReplacedCount = 0; Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - %d available cached photos", totalCount)); while ((totalCount > OLD_PHOTOS_MAX_COUNT) && (!c.isAfterLast()) && (photosReplacedCount < MAX_PHOTO_REPLACEMENTS_PER_RUN)) { ObservationPhoto op = new ObservationPhoto(c); Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - clearing photo %d: %s", photosReplacedCount, op.toString())); File obsPhotoFile = new File(op.photo_filename); if (op.photo_url == null) { // No photo URL defined - download the observation and get the external URL for that photo Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - No photo_url found for obs photo: %s", op.toString())); boolean foundPhoto = false; try { JSONObject json = getObservationJson(op.observation_id, false, false); if (json != null) { Observation obs = new Observation(new BetterJSONObject(json)); for (int i = 0; i < obs.photos.size(); i++) { if ((obs.photos.get(i).id != null) && (op.id != null)) { if (obs.photos.get(i).id.equals(op.id)) { // Found the appropriate photo - update the URL op.photo_url = obs.photos.get(i).photo_url; Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - foundPhoto: %s", op.photo_url)); foundPhoto = true; break; } } } } } catch (AuthenticationException e) { Logger.tag(TAG).error(e); } Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - foundPhoto: %s", foundPhoto)); if (!foundPhoto) { // Couldn't download remote URL for the observation photo - don't delete it c.moveToNext(); continue; } } if (obsPhotoFile.exists()) { // Delete the local cached photo file boolean success = obsPhotoFile.delete(); Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - deleted photo: %s: %s", success, obsPhotoFile.toString())); } // Update the obs photo record with the remote photo URL Logger.tag(TAG).debug("OP - clearOldCachedPhotos - Setting _SYNCED_AT - " + op.id + ":" + op._id + ":" + op._observation_id + ":" + op.observation_id); op.photo_filename = null; ContentValues cv = op.getContentValues(); cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(op.getUri(), cv, null, null); // Warm up the cache for the image warmUpImageCache(op.photo_url); photosReplacedCount += 1; c.moveToNext(); } c.close(); } private String getGuideXML(Integer guideId) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = HOST + "/guides/" + guideId.toString() + ".xml?locale=" + deviceLanguage; try { OkHttpClient client = new OkHttpClient().newBuilder() .followRedirects(true) .followSslRedirects(true) .connectTimeout(HTTP_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS) .writeTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .readTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { return null; } InputStream buffer = new BufferedInputStream(response.body().byteStream()); File outputFile = File.createTempFile(guideId.toString() + ".xml", null, getBaseContext().getCacheDir()); OutputStream output = new FileOutputStream(outputFile); int count = 0; byte data[] = new byte[1024]; while ((count = buffer.read(data)) != -1) { output.write(data, 0, count); } // flushing output output.flush(); // closing streams output.close(); buffer.close(); response.close(); // Return the downloaded full file name return outputFile.getAbsolutePath(); } catch (IOException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getCurrentUserDetails() throws AuthenticationException { String url = API_HOST + "/users/me"; JSONArray json = get(url, true); try { if (json == null) return null; if (json.length() == 0) return null; JSONObject user = json.getJSONObject(0).getJSONArray("results").getJSONObject(0); return new BetterJSONObject(user); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject updateCurrentUserDetails(JSONObject params) throws AuthenticationException { JSONObject input = new JSONObject(); try { input.put("user", params); } catch (JSONException e) { Logger.tag(TAG).error(e); } JSONArray json = request(API_HOST + "/users/" + mApp.currentUserLogin(), "put", null, input, true, true, false); try { if (json == null) return null; if (json.length() == 0) return null; return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getUserDetails(String username) throws AuthenticationException { String url = HOST + "/users/" + username + ".json"; JSONArray json = get(url, false); try { if (json == null) return null; if (json.length() == 0) return null; return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private SerializableJSONArray searchUserObservation(String query) throws AuthenticationException { String url = null; try { StringBuilder sb = new StringBuilder(INaturalistService.HOST + "/observations/" + mLogin + ".json"); sb.append("?per_page=100"); sb.append("&q="); sb.append(URLEncoder.encode(query, "utf8")); sb.append("&extra=observation_photos,projects,fields"); Locale deviceLocale = getResources().getConfiguration().locale; String deviceLexicon = deviceLocale.getLanguage(); sb.append("&locale="); sb.append(deviceLexicon); url = sb.toString(); } catch (UnsupportedEncodingException e) { Logger.tag(TAG).error(e); return null; } JSONArray json = get(url, true); if (json == null) return null; if (json.length() == 0) return null; return new SerializableJSONArray(json); } private BetterJSONObject searchAutoComplete(String type, String query, int page) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/" + type + "/autocomplete?geo=true&locale=" + deviceLanguage + "&per_page=50&page=" + page + "&q=" + Uri.encode(query); JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private JSONObject getUserObservations(String username) throws AuthenticationException { String url = API_HOST + "/observations?per_page=30&user_id=" + username; JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return json.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private SerializableJSONArray getUserUpdates(boolean following) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/observations/updates?locale=" + deviceLanguage + "&per_page=200&observations_by=" + (following ? "following" : "owner"); JSONArray json = request(url, "get", null, null, true, true, false); // Use JWT Token authentication if (json == null) return null; if (json.length() == 0) return null; try { JSONObject resObject = json.getJSONObject(0); JSONArray results = json.getJSONObject(0).getJSONArray("results"); return new SerializableJSONArray(results); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getUserIdentifications(String username) throws AuthenticationException { String url = API_HOST + "/identifications?user_id=" + username + "&own_observation=false&per_page=30"; JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getExploreResults(String command, ExploreSearchFilters filters, int pageNumber, int pageSize, String orderBy) throws AuthenticationException { if (filters == null) return null; Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url; if (command == null) { url = String.format(Locale.ENGLISH, "%s/observations%s?locale=%s&page=%d&per_page=%d&ordered_by=%s&order=desc&return_bounds=true&%s", API_HOST, command == null ? "" : "/" + command, deviceLanguage, pageNumber, pageSize, orderBy == null ? "" : orderBy, filters.toUrlQueryString()); } else if (command.equals("species_counts")) { url = String.format(Locale.ENGLISH, "%s/observations/%s?locale=%s&page=%d&per_page=%d&%s", API_HOST, command, deviceLanguage, pageNumber, pageSize, filters.toUrlQueryString()); } else { url = String.format(Locale.ENGLISH, "%s/observations/%s?page=%d&per_page=%d&%s", API_HOST, command, pageNumber, pageSize, filters.toUrlQueryString()); } JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getUserSpeciesCount(String username) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/observations/species_counts?place_id=any&verifiable=any&user_id=" + username + "&locale=" + deviceLanguage; JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getUserLifeList(int lifeListId) throws AuthenticationException { String url = HOST + "/life_lists/" + lifeListId + ".json"; JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getPlaceDetails(long placeId) throws AuthenticationException { String url = API_HOST + "/places/" + placeId; JSONArray json = get(url, false); try { if (json == null) return null; if (json.length() == 0) return null; JSONArray results = json.getJSONObject(0).getJSONArray("results"); return new BetterJSONObject(results.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private boolean isUserDeleted(String username) { try { JSONArray result = get(API_HOST + "/users/" + username, false); } catch (AuthenticationException e) { e.printStackTrace(); } return mLastStatusCode == HttpStatus.SC_NOT_FOUND; } private BetterJSONObject getUserDetails() throws AuthenticationException { String url = HOST + "/users/edit.json"; JSONArray json = get(url, true); try { if (json == null) return null; if (json.length() == 0) return null; return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getProjectObservations(int projectId) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/observations?project_id=" + projectId + "&per_page=50&locale=" + deviceLanguage; JSONArray json = get(url); if (json == null) return new BetterJSONObject(); try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private BetterJSONObject getTaxonObservationsBounds(Integer taxonId) { String url = API_HOST + "/observations?per_page=1&return_bounds=true&taxon_id=" + taxonId; JSONArray json = null; try { json = get(url, false); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); return null; } if (json == null) return null; if (json.length() == 0) return null; try { JSONObject response = json.getJSONObject(0); return new BetterJSONObject(response.getJSONObject("total_bounds")); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getMissions(Location location, String username, Integer taxonId, float expandLocationByDegress) { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/observations/species_counts?locale=" + deviceLanguage + "&verifiable=true&hrank=species&oauth_application_id=2,3"; if (expandLocationByDegress == 0) { url += "&lat=" + location.getLatitude() + "&lng=" + location.getLongitude(); } else { // Search for taxa in a bounding box expanded by a certain number of degrees (used to expand // our search in case we can't find any close taxa) url += String.format(Locale.ENGLISH, "&nelat=%f&nelng=%f&swlat=%f&swlng=%f", location.getLatitude() + expandLocationByDegress, location.getLongitude() + expandLocationByDegress, location.getLatitude() - expandLocationByDegress, location.getLongitude() - expandLocationByDegress); } if (username != null) { // Taxa unobserved by a specific user url += "&unobserved_by_user_id=" + username; } if (taxonId != null) { // Taxa under a specific category (e.g. fungi) url += "&taxon_id=" + taxonId; } // Make sure to show only taxa observable for the current months (+/- 1 month from current one) Calendar c = Calendar.getInstance(); int month = c.get(Calendar.MONTH); url += String.format(Locale.ENGLISH, "&month=%d,%d,%d", modulo(month - 1, 12) + 1, month + 1, modulo(month + 1, 12) + 1); JSONArray json = null; try { json = get(url, false); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); return null; } if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getProjectSpecies(int projectId) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/observations/species_counts?project_id=" + projectId + "&locale=" + deviceLanguage; JSONArray json = get(url); try { if (json == null) return new BetterJSONObject(); return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private SerializableJSONArray getNews() throws AuthenticationException { String url = HOST + "/posts/for_user.json"; JSONArray json = get(url, mCredentials != null); // If user is logged-in, returns his news (using an authenticated endpoint) return new SerializableJSONArray(json); } private SerializableJSONArray getProjectNews(int projectId) throws AuthenticationException { String url = HOST + "/projects/" + projectId + "/journal.json"; JSONArray json = get(url); return new SerializableJSONArray(json); } private BetterJSONObject getProjectObservers(int projectId) throws AuthenticationException { String url = API_HOST + "/observations/observers?project_id=" + projectId; JSONArray json = get(url); try { if (json == null) return new BetterJSONObject(); return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private BetterJSONObject getProjectIdentifiers(int projectId) throws AuthenticationException { String url = API_HOST + "/observations/identifiers?project_id=" + projectId; JSONArray json = get(url); try { if (json == null) return new BetterJSONObject(); return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private SerializableJSONArray getTaxaForGuide(Integer guideId) throws AuthenticationException { String url = HOST + "/guide_taxa.json?guide_id=" + guideId.toString(); JSONArray json = get(url); try { if (json == null) return new SerializableJSONArray(); return new SerializableJSONArray(json.getJSONObject(0).getJSONArray("guide_taxa")); } catch (JSONException e) { Logger.tag(TAG).error(e); return new SerializableJSONArray(); } } private SerializableJSONArray getAllGuides() throws AuthenticationException { String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); // Just retrieve the first page results (if the user wants to find more guides, // he can search for guides) String url = inatHost + "/guides.json?per_page=200&page=1"; JSONArray results = get(url); return new SerializableJSONArray(results); } private SerializableJSONArray getMyGuides() throws AuthenticationException { JSONArray json = null; String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); String url = inatHost + "/guides.json?by=you&per_page=200"; if (mCredentials != null) { try { json = get(url, true); } catch (Exception exc) { Logger.tag(TAG).error(exc); } } if (json == null) { json = new JSONArray(); } // Build a list of result guide IDs int i = 0; List<String> guideIds = new ArrayList<String>(); while (i < json.length()) { try { JSONObject guide = json.getJSONObject(i); guideIds.add(String.valueOf(guide.getInt("id"))); } catch (JSONException e) { Logger.tag(TAG).error(e); } i++; } // Add any offline guides List<GuideXML> offlineGuides = GuideXML.getAllOfflineGuides(this); List<JSONObject> guidesJson = new ArrayList<JSONObject>(); for (GuideXML guide : offlineGuides) { JSONObject guideJson = new JSONObject(); if (guideIds.contains(guide.getID())) { // Guide already found in current guide results - no need to add it again continue; } try { guideJson.put("id", Integer.valueOf(guide.getID())); guideJson.put("title", guide.getTitle()); guideJson.put("description", guide.getDescription()); // TODO - no support for "icon_url" (not found in XML file) } catch (JSONException e) { Logger.tag(TAG).error(e); } json.put(guideJson); } return new SerializableJSONArray(json); } private SerializableJSONArray getNearByGuides(Location location) throws AuthenticationException { if (location == null) { // No place found - return an empty result Logger.tag(TAG).error("Current place is null"); return new SerializableJSONArray(); } double lat = location.getLatitude(); double lon = location.getLongitude(); String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); String url = inatHost + String.format(Locale.ENGLISH, "/guides.json?latitude=%s&longitude=%s&per_page=200", lat, lon); Logger.tag(TAG).debug(url); JSONArray json = get(url); return new SerializableJSONArray(json); } private SerializableJSONArray getNearByProjects(Location location) throws AuthenticationException { if (location == null) { // No place found - return an empty result Logger.tag(TAG).error("Current place is null"); return new SerializableJSONArray(); } double lat = location.getLatitude(); double lon = location.getLongitude(); String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); String url = inatHost + String.format(Locale.ENGLISH, "/projects.json?latitude=%s&longitude=%s", lat, lon); Logger.tag(TAG).error(url); JSONArray json = get(url); if (json == null) { return new SerializableJSONArray(); } // Determine which projects are already joined for (int i = 0; i < json.length(); i++) { Cursor c; try { c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = '" + json.getJSONObject(i).getInt("id") + "'", null, Project.DEFAULT_SORT_ORDER); c.moveToFirst(); int count = c.getCount(); c.close(); if (count > 0) { json.getJSONObject(i).put("joined", true); } } catch (JSONException e) { Logger.tag(TAG).error(e); continue; } } return new SerializableJSONArray(json); } private SerializableJSONArray getFeaturedProjects() throws AuthenticationException { String inatNetwork = mApp.getInaturalistNetworkMember(); String siteId = mApp.getStringResourceByName("inat_site_id_" + inatNetwork); String url = API_HOST + "/projects?featured=true&site_id=" + siteId; JSONArray json = get(url); if (json == null) { return new SerializableJSONArray(); } JSONArray results; try { results = json.getJSONObject(0).getJSONArray("results"); } catch (JSONException e) { Logger.tag(TAG).error(e); return new SerializableJSONArray(); } // Determine which projects are already joined for (int i = 0; i < results.length(); i++) { Cursor c; try { c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = '" + results.getJSONObject(i).getInt("id") + "'", null, Project.DEFAULT_SORT_ORDER); c.moveToFirst(); int count = c.getCount(); c.close(); if (count > 0) { results.getJSONObject(i).put("joined", true); } } catch (JSONException e) { Logger.tag(TAG).error(e); continue; } } return new SerializableJSONArray(results); } private void addProjectFields(JSONArray jsonFields) { int projectId = -1; ArrayList<ProjectField> projectFields = new ArrayList<ProjectField>(); for (int i = 0; i < jsonFields.length(); i++) { try { BetterJSONObject jsonField = new BetterJSONObject(jsonFields.getJSONObject(i)); ProjectField field = new ProjectField(jsonField); projectId = field.project_id; projectFields.add(field); } catch (JSONException e) { Logger.tag(TAG).error(e); } } if (projectId != -1) { // First, delete all previous project fields (for that project) getContentResolver().delete(ProjectField.CONTENT_URI, "(project_id IS NOT NULL) and (project_id = " + projectId + ")", null); // Next, re-add all project fields for (int i = 0; i < projectFields.size(); i++) { ProjectField field = projectFields.get(i); getContentResolver().insert(ProjectField.CONTENT_URI, field.getContentValues()); } } } public void flagObservationAsCaptive(int obsId) throws AuthenticationException { post(String.format(Locale.ENGLISH, "%s/observations/%d/quality/wild.json?agree=false", HOST, obsId), (JSONObject) null); } public void joinProject(int projectId) throws AuthenticationException { post(String.format(Locale.ENGLISH, "%s/projects/%d/join.json", HOST, projectId), (JSONObject) null); try { JSONArray result = get(String.format(Locale.ENGLISH, "%s/projects/%d.json", HOST, projectId)); if (result == null) return; BetterJSONObject jsonProject = new BetterJSONObject(result.getJSONObject(0)); Project project = new Project(jsonProject); // Add joined project locally ContentValues cv = project.getContentValues(); getContentResolver().insert(Project.CONTENT_URI, cv); // Save project fields addProjectFields(jsonProject.getJSONArray("project_observation_fields").getJSONArray()); } catch (JSONException e) { Logger.tag(TAG).error(e); } } public void leaveProject(int projectId) throws AuthenticationException { delete(String.format(Locale.ENGLISH, "%s/projects/%d/leave.json", HOST, projectId), null); // Remove locally saved project (because we left it) getContentResolver().delete(Project.CONTENT_URI, "(id IS NOT NULL) and (id = " + projectId + ")", null); } private BetterJSONObject removeObservationFromProject(int observationId, int projectId) throws AuthenticationException { if (ensureCredentials() == false) { return null; } String url = String.format(Locale.ENGLISH, "%s/projects/%d/remove.json?observation_id=%d", HOST, projectId, observationId); JSONArray json = request(url, "delete", null, null, true, true, false); if (json == null) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private BetterJSONObject addObservationToProject(int observationId, int projectId) throws AuthenticationException { if (ensureCredentials() == false) { return null; } String url = HOST + "/project_observations.json"; ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("project_observation[observation_id]", String.valueOf(observationId))); params.add(new BasicNameValuePair("project_observation[project_id]", String.valueOf(projectId))); JSONArray json = post(url, params); if (json == null) { return null; } try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private boolean postFlag(String flaggableType, Integer flaggableId, String flag, String flagExplanation) throws AuthenticationException { String url = String.format("%s/flags", API_HOST); JSONObject content = new JSONObject(); try { JSONObject flagObject = new JSONObject(); flagObject.put("flaggable_type", flaggableType); flagObject.put("flaggable_id", flaggableId); flagObject.put("flag", flag); content.put("flag", flagObject); if (flagExplanation != null) content.put("flag_explanation", flagExplanation); } catch (JSONException e) { e.printStackTrace(); } JSONArray json = post(url, content); return mLastStatusCode == HttpStatus.SC_OK; } private boolean muteUser(Integer userId) throws AuthenticationException { String url = String.format("%s/users/%d/mute", API_HOST, userId); JSONObject content = new JSONObject(); JSONArray json = post(url, content); return mLastStatusCode == HttpStatus.SC_OK; } private boolean unmuteUser(Integer userId) throws AuthenticationException { String url = String.format("%s/users/%d/mute", API_HOST, userId); JSONObject content = new JSONObject(); JSONArray json = delete(url, null); return mLastStatusCode == HttpStatus.SC_OK; } private BetterJSONObject postMessage(Integer toUser, Integer threadId, String subject, String body) throws AuthenticationException { String url = String.format("%s/messages", API_HOST); JSONObject message = new JSONObject(); JSONObject content = new JSONObject(); try { message.put("to_user_id", toUser); if (threadId != null) message.put("thread_id", threadId); message.put("subject", subject); message.put("body", body); content.put("message", message); } catch (JSONException e) { e.printStackTrace(); } JSONArray json = post(url, content); if (json == null) { return null; } try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private BetterJSONObject getNotificationCounts() throws AuthenticationException { String url = String.format("%s/users/notification_counts", API_HOST); JSONArray json = get(url); if (json == null) { return null; } try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private BetterJSONObject getMessages(String searchQuery, String box, boolean groupByThreads, Integer messageId) throws AuthenticationException { String url = messageId == null ? String.format("%s/messages?q=%s&box=%s&threads=%s&per_page=200", API_HOST, searchQuery != null ? URLEncoder.encode(searchQuery) : "", box != null ? box : "inbox", groupByThreads) : String.format("%s/messages/%d", API_HOST, messageId); JSONArray json = get(url); if (json == null) { return null; } try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private SerializableJSONArray getCheckList(int id) throws AuthenticationException { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = String.format(Locale.ENGLISH, "%s/lists/%d.json?per_page=50&locale=%s", HOST, id, deviceLanguage); JSONArray json = get(url); if (json == null) { return null; } try { return new SerializableJSONArray(json.getJSONObject(0).getJSONArray("listed_taxa")); } catch (JSONException e) { Logger.tag(TAG).error(e); return new SerializableJSONArray(); } } public static boolean hasJoinedProject(Context context, int projectId) { Cursor c = context.getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = " + projectId, null, Project.DEFAULT_SORT_ORDER); int count = c.getCount(); c.close(); return count > 0; } private SerializableJSONArray getJoinedProjectsOffline() { JSONArray projects = new JSONArray(); Cursor c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, null, null, Project.DEFAULT_SORT_ORDER); c.moveToFirst(); int index = 0; while (c.isAfterLast() == false) { Project project = new Project(c); JSONObject jsonProject = project.toJSONObject(); try { jsonProject.put("joined", true); projects.put(index, jsonProject); } catch (JSONException e) { Logger.tag(TAG).error(e); } c.moveToNext(); index++; } c.close(); return new SerializableJSONArray(projects); } private SerializableJSONArray getJoinedProjects() throws AuthenticationException { if (ensureCredentials() == false) { return null; } String url = HOST + "/projects/user/" + Uri.encode(mLogin) + ".json"; JSONArray json = get(url, true); JSONArray finalJson = new JSONArray(); if (json == null) { return null; } for (int i = 0; i < json.length(); i++) { try { JSONObject obj = json.getJSONObject(i); JSONObject project = obj.getJSONObject("project"); project.put("joined", true); finalJson.put(project); // Save project fields addProjectFields(project.getJSONArray("project_observation_fields")); } catch (JSONException e) { Logger.tag(TAG).error(e); } } return new SerializableJSONArray(finalJson); } @SuppressLint("NewApi") private int getAdditionalUserObservations(int maxCount) throws AuthenticationException { if (ensureCredentials() == false) { return -1; } Integer lastId = mPreferences.getInt("last_downloaded_id", 0); if (lastId == 0) { Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "(is_deleted = 0 OR is_deleted is NULL) AND (user_login = '" + mLogin + "')", null, Observation.DEFAULT_SORT_ORDER); if (c.getCount() > 0) { c.moveToLast(); BetterCursor bc = new BetterCursor(c); lastId = bc.getInteger(Observation.ID); } else { lastId = Integer.MAX_VALUE; } c.close(); } String url = API_HOST + "/observations?user_id=" + Uri.encode(mLogin) + "&per_page=" + maxCount + "&id_below=" + lastId; Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); url += "&locale=" + deviceLanguage; mProjectObservations = new ArrayList<SerializableJSONArray>(); mProjectFieldValues = new Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>>(); JSONArray json = get(url, true); if (json != null && json.length() > 0) { try { JSONArray results = json.getJSONObject(0).getJSONArray("results"); JSONArray newResults = new JSONArray(); int minId = Integer.MAX_VALUE; // Remove any observations that were previously downloaded for (int i = 0; i < results.length(); i++) { int currentId = results.getJSONObject(i).getInt("id"); Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_id = ?", new String[]{String.valueOf(currentId)}, Observation.DEFAULT_SORT_ORDER); if (currentId < minId) { minId = currentId; } if (c.getCount() == 0) { newResults.put(results.getJSONObject(i)); } c.close(); } syncJson(newResults, true); if (results.length() == 0) { mPreferences.edit().putInt("last_downloaded_id", mPreferences.getInt("last_downloaded_id", 0)).commit(); } else { mPreferences.edit().putInt("last_downloaded_id", minId).commit(); } return results.length(); } catch (JSONException e) { Logger.tag(TAG).error(e); return -1; } } else { return -1; } } @SuppressLint("NewApi") private boolean syncRemotelyDeletedObs() throws AuthenticationException, CancelSyncException { if (ensureCredentials() == false) { return false; } String url = API_HOST + "/observations/deleted"; long lastSync = mPreferences.getLong("last_sync_time", 0); if (lastSync == 0) { Logger.tag(TAG).debug("syncRemotelyDeletedObs: First time syncing, no need to delete observations"); return true; } Timestamp lastSyncTS = new Timestamp(lastSync); url += String.format(Locale.ENGLISH, "?since=%s", URLEncoder.encode(new SimpleDateFormat("yyyy-MM-dd").format(lastSyncTS))); JSONArray json = get(url, true); if (json != null && json.length() > 0) { // Delete any local observations which were deleted remotely by the user JSONArray results = null; try { results = json.getJSONObject(0).getJSONArray("results"); } catch (JSONException e) { Logger.tag(TAG).error(e); return false; } if (results.length() == 0) return true; ArrayList<String> ids = new ArrayList<>(); ArrayList<String> uuids = new ArrayList<>(); for (int i = 0; i < results.length(); i++) { String id = String.valueOf(results.optInt(i)); ids.add(id); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); Observation obs = new Observation(obsc); uuids.add('"' + obs.uuid + '"'); } obsc.close(); } String deletedIds = StringUtils.join(ids, ","); String deletedUUIDs = uuids.size() > 0 ? StringUtils.join(uuids, ",") : null; Logger.tag(TAG).debug("syncRemotelyDeletedObs: " + deletedIds); getContentResolver().delete(Observation.CONTENT_URI, "(id IN (" + deletedIds + "))", null); // Delete associated project-fields and photos int count1 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_id in (" + deletedIds + ")", null); int count2 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_id in (" + deletedIds + ")", null); int count3 = getContentResolver().delete(ProjectObservation.CONTENT_URI, "observation_id in (" + deletedIds + ")", null); int count4 = getContentResolver().delete(ProjectFieldValue.CONTENT_URI, "observation_id in (" + deletedIds + ")", null); if (deletedUUIDs != null) { int count5 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_uuid in (" + deletedUUIDs + ")", null); int count6 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_uuid in (" + deletedUUIDs + ")", null); } } checkForCancelSync(); return (json != null); } @SuppressLint("NewApi") private boolean getUserObservations(int maxCount) throws AuthenticationException, CancelSyncException { if (ensureCredentials() == false) { return false; } String url = API_HOST + "/observations?user_id=" + mLogin; long lastSync = mPreferences.getLong("last_sync_time", 0); Timestamp lastSyncTS = new Timestamp(lastSync); url += String.format(Locale.ENGLISH, "&updated_since=%s&order_by=created_at&order=desc&extra=observation_photos,projects,fields", URLEncoder.encode(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(lastSyncTS))); if (maxCount == 0) { maxCount = 200; } if (maxCount > 0) { // Retrieve only a certain number of observations url += String.format(Locale.ENGLISH, "&per_page=%d&page=1", maxCount); } Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); url += "&locale=" + deviceLanguage; mProjectObservations = new ArrayList<SerializableJSONArray>(); mProjectFieldValues = new Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>>(); JSONArray json = get(url, true); if (json != null && json.length() > 0) { Logger.tag(TAG).debug("getUserObservations"); JSONArray results = null; try { results = json.getJSONObject(0).getJSONArray("results"); } catch (JSONException e) { Logger.tag(TAG).error(e); return false; } syncJson(results, true); return true; } checkForCancelSync(); return (json != null); } private boolean syncObservationFields(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { if ((observation.id == null) || (mProjectFieldValues == null)) { // Observation hasn't been synced yet - no way to sync its project fields return true; } // First, remotely update the observation fields which were modified Cursor c = getContentResolver().query(ProjectFieldValue.CONTENT_URI, ProjectFieldValue.PROJECTION, "_updated_at > _synced_at AND _synced_at IS NOT NULL AND observation_id = ?", new String[]{String.valueOf(observation.id)}, ProjectFieldValue.DEFAULT_SORT_ORDER); c.moveToFirst(); if ((c.getCount() == 0) && (mProjectFieldValues.size() == 0)) { c.close(); return true; } while (c.isAfterLast() == false) { checkForCancelSync(); ProjectFieldValue localField = new ProjectFieldValue(c); increaseProgressForObservation(observation); if (!mProjectFieldValues.containsKey(Integer.valueOf(localField.observation_id))) { // Need to retrieve remote observation fields to see how to sync the fields JSONArray jsonResult = get(HOST + "/observations/" + localField.observation_id + ".json"); if (jsonResult != null) { Hashtable<Integer, ProjectFieldValue> fields = new Hashtable<Integer, ProjectFieldValue>(); try { JSONArray jsonFields = jsonResult.getJSONObject(0).getJSONArray("observation_field_values"); for (int j = 0; j < jsonFields.length(); j++) { JSONObject jsonField = jsonFields.getJSONObject(j); JSONObject observationField = jsonField.getJSONObject("observation_field"); int id = observationField.optInt("id", jsonField.getInt("observation_field_id")); fields.put(id, new ProjectFieldValue(new BetterJSONObject(jsonField))); } } catch (JSONException e) { Logger.tag(TAG).error(e); } mProjectFieldValues.put(localField.observation_id, fields); checkForCancelSync(); } else { c.close(); throw new SyncFailedException(); } } Hashtable<Integer, ProjectFieldValue> fields = mProjectFieldValues.get(Integer.valueOf(localField.observation_id)); boolean shouldOverwriteRemote = false; ProjectFieldValue remoteField = null; if (fields == null) { c.moveToNext(); continue; } if (!fields.containsKey(Integer.valueOf(localField.field_id))) { // No remote field - add it shouldOverwriteRemote = true; } else { remoteField = fields.get(Integer.valueOf(localField.field_id)); if ((remoteField.updated_at != null) && (remoteField.updated_at.before(localField._updated_at))) { shouldOverwriteRemote = true; } } if (shouldOverwriteRemote) { // Overwrite remote value ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("observation_field_value[observation_id]", Integer.valueOf(localField.observation_id).toString())); params.add(new BasicNameValuePair("observation_field_value[observation_field_id]", Integer.valueOf(localField.field_id).toString())); params.add(new BasicNameValuePair("observation_field_value[value]", localField.value)); JSONArray result = post(HOST + "/observation_field_values.json", params); if (result == null) { if (mResponseErrors == null) { c.close(); throw new SyncFailedException(); } else { Cursor c2 = getContentResolver().query(ProjectField.CONTENT_URI, ProjectField.PROJECTION, "field_id = " + localField.field_id, null, Project.DEFAULT_SORT_ORDER); c2.moveToFirst(); if (c2.getCount() > 0) { ProjectField projectField = new ProjectField(c2); handleProjectFieldErrors(localField.observation_id, projectField.project_id); } c2.close(); c.moveToNext(); checkForCancelSync(); continue; } } } else { // Overwrite local value localField.created_at = remoteField.created_at; localField.id = remoteField.id; localField.observation_id = remoteField.observation_id; localField.field_id = remoteField.field_id; localField.value = remoteField.value; localField.updated_at = remoteField.updated_at; } ContentValues cv = localField.getContentValues(); cv.put(ProjectFieldValue._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(localField.getUri(), cv, null, null); fields.remove(Integer.valueOf(localField.field_id)); c.moveToNext(); checkForCancelSync(); } c.close(); // Next, add any new observation fields Hashtable<Integer, ProjectFieldValue> fields = mProjectFieldValues.get(Integer.valueOf(observation.id)); if (fields == null) { return true; } for (ProjectFieldValue field : fields.values()) { ContentValues cv = field.getContentValues(); cv.put(ProjectFieldValue._SYNCED_AT, System.currentTimeMillis()); getContentResolver().insert(ProjectFieldValue.CONTENT_URI, cv); c = getContentResolver().query(ProjectField.CONTENT_URI, ProjectField.PROJECTION, "field_id = " + field.field_id, null, Project.DEFAULT_SORT_ORDER); if (c.getCount() == 0) { // This observation has a non-project custom field - add it as well boolean success = addProjectField(field.field_id); if (!success) { c.close(); throw new SyncFailedException(); } } c.close(); } return true; } private boolean syncObservationFields() throws AuthenticationException, CancelSyncException, SyncFailedException { // First, remotely update the observation fields which were modified Cursor c = getContentResolver().query(ProjectFieldValue.CONTENT_URI, ProjectFieldValue.PROJECTION, "_updated_at > _synced_at AND _synced_at IS NOT NULL", null, ProjectFieldValue.DEFAULT_SORT_ORDER); c.moveToFirst(); if ((c.getCount() > 0) || (mProjectFieldValues.size() > 0)) { mApp.notify(SYNC_PHOTOS_NOTIFICATION, getString(R.string.projects), getString(R.string.syncing_observation_fields), getString(R.string.syncing)); } else { c.close(); return true; } while (c.isAfterLast() == false) { checkForCancelSync(); ProjectFieldValue localField = new ProjectFieldValue(c); // Make sure that the local field has an *external* observation id (i.e. the observation // it belongs to has been synced) Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = ? AND _synced_at IS NOT NULL AND _id != ?", new String[]{localField.observation_id.toString(), localField.observation_id.toString()}, ProjectFieldValue.DEFAULT_SORT_ORDER); int count = obsc.getCount(); obsc.close(); if (count == 0) { c.moveToNext(); continue; } mApp.setObservationIdBeingSynced(localField.observation_id); if (!mProjectFieldValues.containsKey(Integer.valueOf(localField.observation_id))) { // Need to retrieve remote observation fields to see how to sync the fields JSONArray jsonResult = get(HOST + "/observations/" + localField.observation_id + ".json"); if (jsonResult != null) { Hashtable<Integer, ProjectFieldValue> fields = new Hashtable<Integer, ProjectFieldValue>(); try { JSONArray jsonFields = jsonResult.getJSONObject(0).getJSONArray("observation_field_values"); for (int j = 0; j < jsonFields.length(); j++) { JSONObject jsonField = jsonFields.getJSONObject(j); JSONObject observationField = jsonField.getJSONObject("observation_field"); int id = observationField.optInt("id", jsonField.getInt("observation_field_id")); fields.put(id, new ProjectFieldValue(new BetterJSONObject(jsonField))); } } catch (JSONException e) { Logger.tag(TAG).error(e); } mProjectFieldValues.put(localField.observation_id, fields); checkForCancelSync(); } else { mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); c.close(); throw new SyncFailedException(); } } Hashtable<Integer, ProjectFieldValue> fields = mProjectFieldValues.get(Integer.valueOf(localField.observation_id)); boolean shouldOverwriteRemote = false; ProjectFieldValue remoteField = null; if (fields == null) { c.moveToNext(); continue; } if (!fields.containsKey(Integer.valueOf(localField.field_id))) { // No remote field - add it shouldOverwriteRemote = true; } else { remoteField = fields.get(Integer.valueOf(localField.field_id)); if (remoteField.updated_at.before(localField._updated_at)) { shouldOverwriteRemote = true; } } if (shouldOverwriteRemote) { // Overwrite remote value ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("observation_field_value[observation_id]", Integer.valueOf(localField.observation_id).toString())); params.add(new BasicNameValuePair("observation_field_value[observation_field_id]", Integer.valueOf(localField.field_id).toString())); params.add(new BasicNameValuePair("observation_field_value[value]", localField.value)); JSONArray result = post(HOST + "/observation_field_values.json", params); if (result == null) { if (mResponseErrors == null) { c.close(); throw new SyncFailedException(); } else { Cursor c2 = getContentResolver().query(ProjectField.CONTENT_URI, ProjectField.PROJECTION, "field_id = " + localField.field_id, null, Project.DEFAULT_SORT_ORDER); c2.moveToFirst(); if (c2.getCount() > 0) { ProjectField projectField = new ProjectField(c2); handleProjectFieldErrors(localField.observation_id, projectField.project_id); } c2.close(); c.moveToNext(); checkForCancelSync(); continue; } } } else { // Overwrite local value localField.created_at = remoteField.created_at; localField.id = remoteField.id; localField.observation_id = remoteField.observation_id; localField.field_id = remoteField.field_id; localField.value = remoteField.value; localField.updated_at = remoteField.updated_at; } ContentValues cv = localField.getContentValues(); cv.put(ProjectFieldValue._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(localField.getUri(), cv, null, null); fields.remove(Integer.valueOf(localField.field_id)); c.moveToNext(); checkForCancelSync(); } c.close(); mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); // Next, add any new observation fields for (Hashtable<Integer, ProjectFieldValue> fields : mProjectFieldValues.values()) { for (ProjectFieldValue field : fields.values()) { ContentValues cv = field.getContentValues(); cv.put(ProjectFieldValue._SYNCED_AT, System.currentTimeMillis()); getContentResolver().insert(ProjectFieldValue.CONTENT_URI, cv); c = getContentResolver().query(ProjectField.CONTENT_URI, ProjectField.PROJECTION, "field_id = " + field.field_id, null, Project.DEFAULT_SORT_ORDER); if (c.getCount() == 0) { // This observation has a non-project custom field - add it as well boolean success = addProjectField(field.field_id); if (!success) { c.close(); throw new SyncFailedException(); } } c.close(); } } return true; } private boolean addProjectField(int fieldId) throws AuthenticationException { try { JSONArray result = get(String.format(Locale.ENGLISH, "%s/observation_fields/%d.json", HOST, fieldId)); if (result == null) return false; BetterJSONObject jsonObj; jsonObj = new BetterJSONObject(result.getJSONObject(0)); ProjectField field = new ProjectField(jsonObj); getContentResolver().insert(ProjectField.CONTENT_URI, field.getContentValues()); return true; } catch (JSONException e) { Logger.tag(TAG).error(e); return false; } } private void getNearbyObservations(Intent intent) throws AuthenticationException { Bundle extras = intent.getExtras(); Double minx = extras.getDouble("minx"); Double maxx = extras.getDouble("maxx"); Double miny = extras.getDouble("miny"); Double maxy = extras.getDouble("maxy"); Double lat = extras.getDouble("lat"); Double lng = extras.getDouble("lng"); Boolean clearMapLimit = extras.getBoolean("clear_map_limit", false); Integer page = extras.getInt("page", 0); Integer perPage = extras.getInt("per_page", NEAR_BY_OBSERVATIONS_PER_PAGE); String url = HOST; if (extras.containsKey("username")) { url = HOST + "/observations/" + extras.getString("username") + ".json?extra=observation_photos"; } else { url = HOST + "/observations.json?extra=observation_photos"; } url += "&captive=false&page=" + page + "&per_page=" + perPage; if (extras.containsKey("taxon_id")) { url += "&taxon_id=" + extras.getInt("taxon_id"); } if (extras.containsKey("location_id")) { url += "&place_id=" + extras.getInt("location_id"); } else if (!clearMapLimit) { if ((lat != null) && (lng != null) && !((lat == 0) && (lng == 0))) { url += "&lat=" + lat; url += "&lng=" + lng; } else { url += "&swlat=" + miny; url += "&nelat=" + maxy; url += "&swlng=" + minx; url += "&nelng=" + maxx; } } if (extras.containsKey("project_id")) { url += "&projects[]=" + extras.getInt("project_id"); } Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); url += "&locale=" + deviceLanguage; Logger.tag(TAG).debug("Near by observations URL: " + url); mNearByObservationsUrl = url; JSONArray json = get(url, mApp.loggedIn()); Intent reply = new Intent(ACTION_NEARBY); reply.putExtra("minx", minx); reply.putExtra("maxx", maxx); reply.putExtra("miny", miny); reply.putExtra("maxy", maxy); if (json == null) { reply.putExtra("error", String.format(Locale.ENGLISH, getString(R.string.couldnt_load_nearby_observations), "")); } else { //syncJson(json, false); } if (url.equalsIgnoreCase(mNearByObservationsUrl)) { // Only send the reply if a new near by observations request hasn't been made yet mApp.setServiceResult(ACTION_NEARBY, new SerializableJSONArray(json)); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } private JSONArray put(String url, ArrayList<NameValuePair> params) throws AuthenticationException { params.add(new BasicNameValuePair("_method", "PUT")); return request(url, "put", params, null, true); } private JSONArray put(String url, JSONObject jsonContent) throws AuthenticationException { return request(url, "put", null, jsonContent, true); } private JSONArray delete(String url, ArrayList<NameValuePair> params) throws AuthenticationException { return request(url, "delete", params, null, true); } private JSONArray post(String url, ArrayList<NameValuePair> params, boolean authenticated) throws AuthenticationException { return request(url, "post", params, null, authenticated); } private JSONArray post(String url, ArrayList<NameValuePair> params) throws AuthenticationException { return request(url, "post", params, null, true); } private JSONArray post(String url, JSONObject jsonContent) throws AuthenticationException { return request(url, "post", null, jsonContent, true); } private JSONArray get(String url) throws AuthenticationException { return get(url, false); } private JSONArray get(String url, boolean authenticated) throws AuthenticationException { return request(url, "get", null, null, authenticated); } private JSONArray request(String url, String method, ArrayList<NameValuePair> params, JSONObject jsonContent, boolean authenticated) throws AuthenticationException { return request(url, method, params, jsonContent, authenticated, false, false); } private String getAnonymousJWTToken() { String anonymousApiSecret = getString(R.string.jwt_anonymous_api_secret); if (anonymousApiSecret == null) return null; Map<String, Object> claims = new HashMap<>(); claims.put("application", "android"); claims.put("exp", (System.currentTimeMillis() / 1000) + 300); String compactJwt = Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS512, anonymousApiSecret.getBytes()) .compact(); return compactJwt; } private String getJWTToken() { if (mPreferences == null) mPreferences = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); String jwtToken = mPreferences.getString("jwt_token", null); Long jwtTokenExpiration = mPreferences.getLong("jwt_token_expiration", 0); if ((jwtToken == null) || ((System.currentTimeMillis() - jwtTokenExpiration) / 1000 > JWT_TOKEN_EXPIRATION_MINS * 60)) { // JWT Tokens expire after 30 mins - if the token is non-existent or older than 25 mins (safe margin) - ask for a new one try { JSONArray result = get(HOST + "/users/api_token.json", true); if ((result == null) || (result.length() == 0)) return null; // Get newest JWT Token jwtToken = result.getJSONObject(0).getString("api_token"); jwtTokenExpiration = System.currentTimeMillis(); SharedPreferences.Editor editor = mPreferences.edit(); editor.putString("jwt_token", jwtToken); editor.putLong("jwt_token_expiration", jwtTokenExpiration); editor.commit(); return jwtToken; } catch (Exception e) { Logger.tag(TAG).error(e); return null; } } else { // Current JWT token is still fresh/valid - return it as-is return jwtToken; } } private JSONArray request(String url, String method, ArrayList<NameValuePair> params, JSONObject jsonContent, boolean authenticated, boolean useJWTToken, boolean allowAnonymousJWTToken) throws AuthenticationException { OkHttpClient client = new OkHttpClient().newBuilder() .followRedirects(true) .followSslRedirects(true) .connectTimeout(HTTP_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS) .writeTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .readTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .build(); Request.Builder requestBuilder = new Request.Builder() .addHeader("User-Agent", getUserAgent(mApp)) .url(url); mRetryAfterDate = null; mServiceUnavailable = false; Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "URL: %s - %s (params: %s / %s)", method, url, (params != null ? params.toString() : "null"), (jsonContent != null ? jsonContent.toString() : "null"))); method = method.toUpperCase(); RequestBody requestBody = null; if ((jsonContent == null) && (params == null) && (method.equals("PUT") || method.equals("POST"))) { // PUT/POST with empty body requestBody = RequestBody.create(null, new byte[]{}); } else if (jsonContent != null) { // PUT/POST with JSON body content requestBuilder.addHeader("Content-type", "application/json"); requestBody = RequestBody.create(JSON, jsonContent.toString()); } else if (params != null) { // PUT/POST with "Standard" multipart encoding MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder() .setType(MultipartBody.FORM); for (int i = 0; i < params.size(); i++) { if (params.get(i).getName().equalsIgnoreCase("image") || params.get(i).getName().equalsIgnoreCase("file") || params.get(i).getName().equalsIgnoreCase("user[icon]") || params.get(i).getName().equalsIgnoreCase("audio")) { // If the key equals to "image", we use FileBody to transfer the data String value = params.get(i).getValue(); MediaType mediaType; if (value != null) { String name; if (params.get(i).getName().equalsIgnoreCase("audio")) { name = "file"; requestBuilder.addHeader("Accept", "application/json"); mediaType = MediaType.parse("audio/" + value.substring(value.lastIndexOf(".") + 1)); } else { name = params.get(i).getName(); mediaType = MediaType.parse("image/" + value.substring(value.lastIndexOf(".") + 1)); } File file = new File(value); requestBodyBuilder.addFormDataPart(name, file.getName(), RequestBody.create(mediaType, file)); } } else { // Normal string data requestBodyBuilder.addFormDataPart(params.get(i).getName(), params.get(i).getValue()); } } requestBody = requestBodyBuilder.build(); } if (url.startsWith(API_HOST) && (mCredentials != null)) { // For the node API, if we're logged in, *always* use JWT authentication authenticated = true; useJWTToken = true; } if (authenticated) { if (useJWTToken && allowAnonymousJWTToken && (mCredentials == null)) { // User not logged in, but allow using anonymous JWT requestBuilder.addHeader("Authorization", getAnonymousJWTToken()); } else { ensureCredentials(); if (useJWTToken) { // Use JSON Web Token for this request String jwtToken = getJWTToken(); if (jwtToken == null) { // Could not renew JWT token for some reason (either connectivity issues or user changed password) Logger.tag(TAG).error("JWT Token is null"); throw new AuthenticationException(); } requestBuilder.addHeader("Authorization", jwtToken); } else if (mLoginType == LoginType.PASSWORD) { // Old-style password authentication requestBuilder.addHeader("Authorization", "Basic " + mCredentials); } else { // OAuth2 token (Facebook/G+/etc) requestBuilder.addHeader("Authorization", "Bearer " + mCredentials); } } } try { mResponseErrors = null; Request request = requestBuilder.method(method, requestBody).build(); Response response = client.newCall(request).execute(); Logger.tag(TAG).debug("Response: " + response.code() + ": " + response.message()); mLastStatusCode = response.code(); if (response.isSuccessful()) { String content = response.body().string(); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "(for URL: %s - %s (params: %s / %s))", method, url, (params != null ? params.toString() : "null"), (jsonContent != null ? jsonContent.toString() : "null"))); Logger.tag(TAG).debug(content); JSONArray json = null; try { json = new JSONArray(content); } catch (JSONException e) { try { JSONObject jo = new JSONObject(content); json = new JSONArray(); json.put(jo); } catch (JSONException e2) { } } mResponseHeaders = response.headers(); response.close(); try { if ((json != null) && (json.length() > 0)) { JSONObject result = json.getJSONObject(0); if (result.has("errors")) { // Error response Logger.tag(TAG).error("Got an error response: " + result.get("errors").toString()); mResponseErrors = result.getJSONArray("errors"); return null; } } } catch (JSONException e) { Logger.tag(TAG).error(e); } if ((content != null) && (content.length() == 0)) { // In case it's just non content (but OK HTTP status code) - so there's no error json = new JSONArray(); } return json; } else { response.close(); // HTTP error of some kind - Check for response code switch (mLastStatusCode) { case HTTP_UNAUTHORIZED: // Authentication error throw new AuthenticationException(); case HTTP_UNAVAILABLE: Logger.tag(TAG).error("503 server unavailable"); mServiceUnavailable = true; // Find out if there's a "Retry-After" header List<String> headers = response.headers("Retry-After"); if (headers.size() > 0) { for (String timestampString : headers) { Logger.tag(TAG).error("Retry after raw string: " + timestampString); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); try { mRetryAfterDate = format.parse(timestampString); Logger.tag(TAG).error("Retry after: " + mRetryAfterDate); break; } catch (ParseException e) { Logger.tag(TAG).error(e); try { // Try parsing it as a seconds-delay value int secondsDelay = Integer.valueOf(timestampString); Logger.tag(TAG).error("Retry after: " + secondsDelay); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, secondsDelay); mRetryAfterDate = calendar.getTime(); break; } catch (NumberFormatException exc) { Logger.tag(TAG).error(exc); } } } } // Show service not available message to user mHandler.post(() -> { String errorMessage; if (mRetryAfterDate == null) { // No specific retry time errorMessage = getString(R.string.please_try_again_in_a_few_hours); } else { // Specific retry time Date currentTime = Calendar.getInstance().getTime(); long differenceSeconds = (mRetryAfterDate.getTime() - currentTime.getTime()) / 1000; long delay; String delayType; if (differenceSeconds < 60) { delayType = getString(R.string.seconds_value); delay = differenceSeconds; } else if (differenceSeconds < 60 * 60) { delayType = getString(R.string.minutes); delay = (differenceSeconds / 60); } else { delayType = getString(R.string.hours); delay = (differenceSeconds / (60 * 60)); } errorMessage = String.format(getString(R.string.please_try_again_in_x), delay, delayType); } if (System.currentTimeMillis() - mLastServiceUnavailableNotification > 30000) { // Make sure we won't notify the user about this too often mLastServiceUnavailableNotification = System.currentTimeMillis(); Toast.makeText(getApplicationContext(), getString(R.string.service_temporarily_unavailable) + " " + errorMessage, Toast.LENGTH_LONG).show(); } }); break; case HTTP_GONE: // TODO create notification that informs user some observations have been deleted on the server, // click should take them to an activity that lets them decide whether to delete them locally // or post them as new observations break; default: } return null; } } catch (IOException e) { Logger.tag(TAG).error("Error for URL " + url + ":" + e); Logger.tag(TAG).error(e); // Test out the Internet connection in multiple ways (helps pin-pointing issue) performConnectivityTest(); } return null; } private void performConnectivityTest() { long currentTime = System.currentTimeMillis(); // Perform connectivity test once every 5 minutes at most if (currentTime - mLastConnectionTest < 5 * 60 * 1000) { return; } mLastConnectionTest = currentTime; Logger.tag(TAG).info("Performing connectivity test"); contactUrl("https://api.inaturalist.org/v1/taxa/1"); contactUrl("http://api.inaturalist.org/v1/taxa/1"); contactUrl("https://www.inaturalist.org/taxa/1.json"); contactUrl("http://www.inaturalist.org/taxa/1.json"); contactUrl("https://www.naturalista.mx/taxa/1.json"); contactUrl("http://www.naturalista.mx/taxa/1.json"); contactUrl("https://www.google.com"); contactUrl("http://www.example.com"); } private void contactUrl(String url) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); try { Logger.tag(TAG).info("Contacting " + url); Response response = client.newCall(request).execute(); Logger.tag(TAG).info("isSuccessful: " + response.isSuccessful() + "; response code = " + response.code()); response.close(); } catch (IOException e) { Logger.tag(TAG).error("Failed contacting " + url); Logger.tag(TAG).error(e); } } private boolean ensureCredentials() throws AuthenticationException { if (mCredentials != null) { return true; } // request login unless passive if (!mPassive) { throw new AuthenticationException(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { stopForeground(true); } else { stopSelf(); } return false; } private void requestCredentials() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { stopForeground(true); } else { stopSelf(); } mApp.sweepingNotify(AUTH_NOTIFICATION, getString(R.string.please_sign_in), getString(R.string.please_sign_in_description), null); } // Returns an array of two strings: access token + iNat username public static String[] verifyCredentials(Context context, String username, String oauth2Token, LoginType authType, boolean askForScopeDeletion) { String grantType = null; String url = HOST + (authType == LoginType.OAUTH_PASSWORD ? "/oauth/token" : "/oauth/assertion_token"); OkHttpClient client = new OkHttpClient().newBuilder() .followRedirects(true) .followSslRedirects(true) .connectTimeout(HTTP_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS) .writeTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .readTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .build(); FormBody.Builder requestBodyBuilder = new FormBody.Builder() .add("format", "json") .add("client_id", INaturalistApp.getAppContext().getString(R.string.oauth_client_id)); if (authType == LoginType.FACEBOOK) { grantType = "facebook"; } else if (authType == LoginType.GOOGLE) { grantType = "google"; } else if (authType == LoginType.OAUTH_PASSWORD) { grantType = "password"; } requestBodyBuilder.add("grant_type", grantType); if (authType == LoginType.OAUTH_PASSWORD) { requestBodyBuilder.add("password", oauth2Token); requestBodyBuilder.add("username", username); requestBodyBuilder.add("client_secret", INaturalistApp.getAppContext().getString(R.string.oauth_client_secret)); } else { requestBodyBuilder.add("assertion", oauth2Token); } if (askForScopeDeletion) { requestBodyBuilder.add("scope", "login write account_delete"); } RequestBody requestBody = requestBodyBuilder.build(); Request request = new Request.Builder() .addHeader("User-Agent", getUserAgent(context)) .url(url) .post(requestBody) .build(); try { Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { Logger.tag(TAG).error("Authentication failed: " + response.code() + ": " + response.message()); return null; } String content = response.body().string(); response.close(); // Upgrade to an access token JSONObject json = new JSONObject(content); String accessToken = json.getString("access_token"); // Next, find the iNat username (since we currently only have the FB/Google email) request = new Request.Builder() .addHeader("User-Agent", getUserAgent(context)) .addHeader("Authorization", "Bearer " + accessToken) .url(HOST + "/users/edit.json") .build(); response = client.newCall(request).execute(); if (!response.isSuccessful()) { Logger.tag(TAG).error("Authentication failed (edit.json): " + response.code() + ": " + response.message()); return null; } content = response.body().string(); response.close(); Logger.tag(TAG).debug(String.format("RESP2: %s", content)); json = new JSONObject(content); if (!json.has("login")) { return null; } String returnedUsername = json.getString("login"); return new String[]{accessToken, returnedUsername}; } catch (IOException e) { Logger.tag(TAG).warn("Error for URL " + url, e); } catch (JSONException e) { Logger.tag(TAG).error(e); } return null; } /** Create a file Uri for saving an image or video */ private Uri getOutputMediaFileUri(Observation observation) { ContentValues values = new ContentValues(); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String name = "observation_" + observation.created_at.getTime() + "_" + timeStamp; values.put(android.provider.MediaStore.Images.Media.TITLE, name); return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } public void syncJson(JSONArray json, boolean isUser) { synchronized (mSyncJsonLock) { ArrayList<Integer> ids = new ArrayList<Integer>(); ArrayList<Integer> existingIds = new ArrayList<Integer>(); ArrayList<Integer> newIds = new ArrayList<Integer>(); HashMap<Integer, Observation> jsonObservationsById = new HashMap<Integer, Observation>(); Observation observation; Observation jsonObservation; if (mSyncedJSONs.contains(json.toString())) { // Already synced this exact JSON recently Logger.tag(TAG).info("Skipping syncJSON - already synced same JSON"); return; } mSyncedJSONs.add(json.toString()); BetterJSONObject o; Logger.tag(TAG).debug("syncJson: " + isUser); Logger.tag(TAG).debug(json.toString()); for (int i = 0; i < json.length(); i++) { try { o = new BetterJSONObject(json.getJSONObject(i)); ids.add(o.getInt("id")); Observation obs = new Observation(o); jsonObservationsById.put(o.getInt("id"), obs); if (isUser) { // Save the project observations aside (will be later used in the syncing of project observations) mProjectObservations.add(o.getJSONArray("project_observations")); // Save project field values Hashtable<Integer, ProjectFieldValue> fields = new Hashtable<Integer, ProjectFieldValue>(); JSONArray jsonFields = o.getJSONArray(o.has("ofvs") ? "ofvs" : "observation_field_values").getJSONArray(); for (int j = 0; j < jsonFields.length(); j++) { BetterJSONObject field = new BetterJSONObject(jsonFields.getJSONObject(j)); int fieldId; if (field.has("observation_field")) { fieldId = field.getJSONObject("observation_field").getInt("id"); } else { fieldId = field.getInt("field_id"); } fields.put(fieldId, new ProjectFieldValue(field)); } mProjectFieldValues.put(o.getInt("id"), fields); } } catch (JSONException e) { Logger.tag(TAG).error("syncJson: JSONException: " + e.toString()); } } // find obs with existing ids String joinedIds = StringUtils.join(ids, ","); // TODO why doesn't selectionArgs work for id IN (?) Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id IN (" + joinedIds + ")", null, Observation.DEFAULT_SORT_ORDER); // update existing c.moveToFirst(); ContentValues cv; while (c.isAfterLast() == false) { observation = new Observation(c); jsonObservation = jsonObservationsById.get(observation.id); boolean isModified = observation.merge(jsonObservation); Logger.tag(TAG).debug("syncJson - updating existing: " + observation.id + ":" + observation._id + ":" + observation.preferred_common_name + ":" + observation.taxon_id); Logger.tag(TAG).debug("syncJson - remote obs: " + jsonObservation.id + ":" + jsonObservation.preferred_common_name + ":" + jsonObservation.taxon_id); cv = observation.getContentValues(); if (observation._updated_at.before(jsonObservation.updated_at)) { // Remote observation is newer (and thus has overwritten the local one) - update its // sync at time so we won't update the remote servers later on (since we won't // accidentally consider this an updated record) cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); } // Add any new photos that were added remotely ArrayList<Integer> observationPhotoIds = new ArrayList<Integer>(); ArrayList<Integer> existingObservationPhotoIds = new ArrayList<Integer>(); Cursor pc = getContentResolver().query( ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(observation_id = " + observation.id + ")", null, null); pc.moveToFirst(); while (pc.isAfterLast() == false) { int photoId = pc.getInt(pc.getColumnIndexOrThrow(ObservationPhoto.ID)); if (photoId != 0) { existingObservationPhotoIds.add(photoId); } pc.moveToNext(); } pc.close(); Logger.tag(TAG).debug("syncJson: Adding photos for obs " + observation.id + ":" + existingObservationPhotoIds.toString()); Logger.tag(TAG).debug("syncJson: JsonObservation: " + jsonObservation + ":" + jsonObservation.photos); for (int j = 0; j < jsonObservation.photos.size(); j++) { ObservationPhoto photo = jsonObservation.photos.get(j); photo._observation_id = jsonObservation._id; if (photo.id == null) { Logger.tag(TAG).warn("syncJson: Null photo ID! " + photo); continue; } observationPhotoIds.add(photo.id); if (existingObservationPhotoIds.contains(photo.id)) { Logger.tag(TAG).debug("syncJson: photo " + photo.id + " has already been added, skipping..."); continue; } ContentValues opcv = photo.getContentValues(); // So we won't re-add this photo as though it was a local photo Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo.id + ":" + photo._id + ":" + photo._observation_id + ":" + photo.observation_id); opcv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); opcv.put(ObservationPhoto._OBSERVATION_ID, photo.observation_id); opcv.put(ObservationPhoto._PHOTO_ID, photo._photo_id); opcv.put(ObservationPhoto.ID, photo.id); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + photo.observation_id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); Observation obs = new Observation(obsc); opcv.put(ObservationPhoto.OBSERVATION_UUID, obs.uuid); } obsc.close(); try { getContentResolver().insert(ObservationPhoto.CONTENT_URI, opcv); } catch (SQLException ex) { // Happens when the photo already exists - ignore Logger.tag(TAG).error(ex); } } // Delete photos that were synced but weren't present in the remote response, // indicating they were deleted elsewhere String joinedPhotoIds = StringUtils.join(observationPhotoIds, ","); String where = "observation_id = " + observation.id + " AND id IS NOT NULL"; if (observationPhotoIds.size() > 0) { where += " AND id NOT in (" + joinedPhotoIds + ")"; } Logger.tag(TAG).debug("syncJson: Deleting local photos: " + where); Logger.tag(TAG).debug("syncJson: Deleting local photos, IDs: " + observationPhotoIds); int deleteCount = getContentResolver().delete( ObservationPhoto.CONTENT_URI, where, null); Logger.tag(TAG).debug("syncJson: Deleting local photos: " + deleteCount); if (deleteCount > 0) { Crashlytics.log(1, TAG, String.format(Locale.ENGLISH, "Warning: Deleted %d photos locally after sever did not contain those IDs - observation id: %s, photo ids: %s", deleteCount, observation.id, joinedPhotoIds)); } // Add any new sounds that were added remotely ArrayList<Integer> observationSoundIds = new ArrayList<Integer>(); ArrayList<Integer> existingObservationSoundIds = new ArrayList<Integer>(); Cursor sc = getContentResolver().query( ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "(observation_id = " + observation.id + ")", null, null); sc.moveToFirst(); while (sc.isAfterLast() == false) { int soundId = sc.getInt(sc.getColumnIndexOrThrow(ObservationSound.ID)); if (soundId != 0) { existingObservationSoundIds.add(soundId); } sc.moveToNext(); } sc.close(); Logger.tag(TAG).debug("syncJson: Adding sounds for obs " + observation.id + ":" + existingObservationSoundIds.toString()); Logger.tag(TAG).debug("syncJson: JsonObservation: " + jsonObservation + ":" + jsonObservation.sounds); for (int j = 0; j < jsonObservation.sounds.size(); j++) { ObservationSound sound = jsonObservation.sounds.get(j); sound._observation_id = jsonObservation._id; if (sound.id == null) { Logger.tag(TAG).warn("syncJson: Null sound ID! " + sound); continue; } observationSoundIds.add(sound.id); if (existingObservationSoundIds.contains(sound.id)) { Logger.tag(TAG).debug("syncJson: sound " + sound.id + " has already been added, skipping..."); continue; } ContentValues oscv = sound.getContentValues(); oscv.put(ObservationSound._OBSERVATION_ID, sound.observation_id); oscv.put(ObservationSound.ID, sound.id); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + sound.observation_id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); Observation obs = new Observation(obsc); oscv.put(ObservationSound.OBSERVATION_UUID, obs.uuid); } obsc.close(); try { getContentResolver().insert(ObservationSound.CONTENT_URI, oscv); } catch (SQLException ex) { // Happens when the sound already exists - ignore Logger.tag(TAG).error(ex); } } // Delete sounds that were synced but weren't present in the remote response, // indicating they were deleted elsewhere String joinedSoundIds = StringUtils.join(observationSoundIds, ","); where = "observation_id = " + observation.id + " AND id IS NOT NULL"; if (observationSoundIds.size() > 0) { where += " AND id NOT in (" + joinedSoundIds + ")"; } Logger.tag(TAG).debug("syncJson: Deleting local sounds: " + where); Logger.tag(TAG).debug("syncJson: Deleting local sounds, IDs: " + observationSoundIds); deleteCount = getContentResolver().delete( ObservationSound.CONTENT_URI, where, null); Logger.tag(TAG).debug("syncJson: Deleting local sounds: " + deleteCount); if (deleteCount > 0) { Crashlytics.log(1, TAG, String.format(Locale.ENGLISH, "Warning: Deleted %d sounds locally after server did not contain those IDs - observation id: %s, sound ids: %s", deleteCount, observation.id, joinedSoundIds)); } if (isModified) { // Only update the DB if needed Logger.tag(TAG).debug("syncJson: Updating observation: " + observation.id + ":" + observation._id); getContentResolver().update(observation.getUri(), cv, null, null); } existingIds.add(observation.id); c.moveToNext(); } c.close(); // insert new List<Observation> newObservations = new ArrayList<Observation>(); newIds = (ArrayList<Integer>) CollectionUtils.subtract(ids, existingIds); Collections.sort(newIds); Logger.tag(TAG).debug("syncJson: Adding new observations: " + newIds); for (int i = 0; i < newIds.size(); i++) { jsonObservation = jsonObservationsById.get(newIds.get(i)); Cursor c2 = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = ?", new String[]{String.valueOf(jsonObservation.id)}, Observation.DEFAULT_SORT_ORDER); int count = c2.getCount(); c2.close(); if (count > 0) { Logger.tag(TAG).debug("syncJson: Observation " + jsonObservation.id + " already exists locally - not adding"); continue; } cv = jsonObservation.getContentValues(); cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); cv.put(Observation.LAST_COMMENTS_COUNT, jsonObservation.comments_count); cv.put(Observation.LAST_IDENTIFICATIONS_COUNT, jsonObservation.identifications_count); Uri newObs = getContentResolver().insert(Observation.CONTENT_URI, cv); Long newObsId = ContentUris.parseId(newObs); jsonObservation._id = Integer.valueOf(newObsId.toString()); Logger.tag(TAG).debug("syncJson: Adding new obs: " + jsonObservation); newObservations.add(jsonObservation); } if (isUser) { for (int i = 0; i < newObservations.size(); i++) { jsonObservation = newObservations.get(i); // Save new observation's sounds Logger.tag(TAG).debug("syncJson: Saving new obs' sounds: " + jsonObservation + ":" + jsonObservation.sounds); for (int j = 0; j < jsonObservation.sounds.size(); j++) { ObservationSound sound = jsonObservation.sounds.get(j); c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "id = ?", new String[]{String.valueOf(sound.id)}, ObservationSound.DEFAULT_SORT_ORDER); if (c.getCount() > 0) { // Sound already exists - don't save Logger.tag(TAG).debug("syncJson: Sound already exists - skipping: " + sound.id); c.close(); continue; } c.close(); sound._observation_id = jsonObservation._id; ContentValues opcv = sound.getContentValues(); Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + sound.id + ":" + sound._id + ":" + sound._observation_id + ":" + sound.observation_id); Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + sound); opcv.put(ObservationSound._OBSERVATION_ID, sound._observation_id); opcv.put(ObservationSound._ID, sound.id); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + sound.observation_id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); Observation obs = new Observation(obsc); opcv.put(ObservationSound.OBSERVATION_UUID, obs.uuid); } obsc.close(); try { getContentResolver().insert(ObservationSound.CONTENT_URI, opcv); } catch (SQLException ex) { // Happens when the sound already exists - ignore Logger.tag(TAG).error(ex); } } // Save the new observation's photos Logger.tag(TAG).debug("syncJson: Saving new obs' photos: " + jsonObservation + ":" + jsonObservation.photos); for (int j = 0; j < jsonObservation.photos.size(); j++) { ObservationPhoto photo = jsonObservation.photos.get(j); if (photo.uuid == null) { c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_id = ?", new String[]{String.valueOf(photo.id)}, ObservationPhoto.DEFAULT_SORT_ORDER); } else { c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "uuid = ?", new String[]{String.valueOf(photo.uuid)}, ObservationPhoto.DEFAULT_SORT_ORDER); } if (c.getCount() > 0) { // Photo already exists - don't save Logger.tag(TAG).debug("syncJson: Photo already exists - skipping: " + photo.id); c.close(); continue; } c.close(); photo._observation_id = jsonObservation._id; ContentValues opcv = photo.getContentValues(); Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo.id + ":" + photo._id + ":" + photo._observation_id + ":" + photo.observation_id); Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo); opcv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); // So we won't re-add this photo as though it was a local photo opcv.put(ObservationPhoto._OBSERVATION_ID, photo._observation_id); opcv.put(ObservationPhoto._PHOTO_ID, photo._photo_id); opcv.put(ObservationPhoto._ID, photo.id); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + photo.observation_id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); Observation obs = new Observation(obsc); opcv.put(ObservationPhoto.OBSERVATION_UUID, obs.uuid); } obsc.close(); try { getContentResolver().insert(ObservationPhoto.CONTENT_URI, opcv); } catch (SQLException ex) { // Happens when the photo already exists - ignore Logger.tag(TAG).error(ex); } } } } if (isUser) { storeProjectObservations(); } if (mSyncedJSONs.size() > 5) { mSyncedJSONs.remove(0); } } } private JSONObject observationToJsonObject(Observation observation, boolean isPOST) { JSONObject obs = observation.toJSONObject(true); try { if (isPOST) { String inatNetwork = mApp.getInaturalistNetworkMember(); obs.put("site_id", mApp.getStringResourceByName("inat_site_id_" + inatNetwork)); } if (obs.has("longitude") && !obs.isNull("longitude")) { if (obs.getString("longitude").equals("0.0")) { // Handle edge cases where long/lat was saved as 0.0 - just don't send a location obs.remove("longitude"); } } if (obs.has("latitude") && !obs.isNull("latitude")) { if (obs.getString("latitude").equals("0.0")) { // Handle edge cases where long/lat was saved as 0.0 - just don't send a location obs.remove("latitude"); } } JSONObject obsContainer = new JSONObject(); obsContainer.put("observation", obs); obsContainer.put("ignore_photos", true); return obsContainer; } catch (JSONException exc) { Logger.tag(TAG).error(exc); return null; } } private ArrayList<NameValuePair> paramsForObservation(Observation observation, boolean isPOST) { ArrayList<NameValuePair> params = observation.getParams(); params.add(new BasicNameValuePair("ignore_photos", "true")); if (isPOST) { String inatNetwork = mApp.getInaturalistNetworkMember(); params.add(new BasicNameValuePair("site_id", mApp.getStringResourceByName("inat_site_id_" + inatNetwork))); } return params; } private boolean handleObservationResponse(Observation observation, JSONArray response) { try { if (response == null || response.length() != 1) { return false; } JSONObject json = response.getJSONObject(0); BetterJSONObject o = new BetterJSONObject(json); Logger.tag(TAG).debug("handleObservationResponse: Observation: " + observation); Logger.tag(TAG).debug("handleObservationResponse: JSON: "); Logger.tag(TAG).debug(json.toString()); if ((json.has("error") && !json.isNull("error")) || ((mLastStatusCode >= 400) && (mLastStatusCode < 500))) { // Error Logger.tag(TAG).debug("handleObservationResponse - error response (probably validation error)"); JSONObject original = json.optJSONObject("error").optJSONObject("original"); if ((original != null) && (original.has("error")) && (!original.isNull("error"))) { JSONArray errors = new JSONArray(); errors.put(original.optString("error").trim()); mApp.setErrorsForObservation(observation.id != null ? observation.id : observation._id, 0, errors); } return false; } else if (mLastStatusCode == HTTP_UNAVAILABLE) { // Server not available Logger.tag(TAG).error("503 - server not available"); return false; } Observation jsonObservation = new Observation(o); Logger.tag(TAG).debug("handleObservationResponse: jsonObservation: " + jsonObservation); observation.merge(jsonObservation); Logger.tag(TAG).debug("handleObservationResponse: merged obs: " + observation); ContentValues cv = observation.getContentValues(); cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(observation.getUri(), cv, null, null); } catch (JSONException e) { Logger.tag(TAG).error(e); return false; } return true; } private class AuthenticationException extends Exception { private static final long serialVersionUID = 1L; } public interface IOnLocation { void onLocation(Location location); } private Location getLocationFromGPS() { LocationManager locationManager = (LocationManager) mApp.getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = locationManager.getBestProvider(criteria, false); if (provider == null) return null; Location location = locationManager.getLastKnownLocation(provider); Logger.tag(TAG).error("getLocationFromGPS: " + location); mLastLocation = location; return location; } private Location getLastKnownLocationFromClient() { Location location = null; try { location = LocationServices.FusedLocationApi.getLastLocation(mLocationClient); } catch (IllegalStateException ex) { Logger.tag(TAG).error(ex); } Logger.tag(TAG).error("getLastKnownLocationFromClient: " + location); if (location == null) { // Failed - try and return last place using GPS return getLocationFromGPS(); } else { mLastLocation = location; return location; } } private void getLocation(final IOnLocation callback) { if (!mApp.isLocationEnabled(null)) { Logger.tag(TAG).error("getLocation: Location not enabled"); // Location not enabled new Thread(new Runnable() { @Override public void run() { callback.onLocation(null); } }).start(); return; } int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); Logger.tag(TAG).error("getLocation: resultCode = " + resultCode); if (ConnectionResult.SUCCESS == resultCode) { // User Google Play services if available if ((mLocationClient != null) && (mLocationClient.isConnected())) { // Location client already initialized and connected - use it new Thread(new Runnable() { @Override public void run() { callback.onLocation(getLastKnownLocationFromClient()); } }).start(); } else { // Connect to the place services mLocationClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(new ConnectionCallbacks() { @Override public void onConnected(Bundle bundle) { // Connected successfully new Thread(new Runnable() { @Override public void run() { callback.onLocation(getLastKnownLocationFromClient()); mLocationClient.disconnect(); } }).start(); } @Override public void onConnectionSuspended(int i) { } }) .addOnConnectionFailedListener(new OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult connectionResult) { // Couldn't connect new Thread(new Runnable() { @Override public void run() { callback.onLocation(null); mLocationClient.disconnect(); } }).start(); } }) .build(); mLocationClient.connect(); } } else { // Use GPS alone for place new Thread(new Runnable() { @Override public void run() { callback.onLocation(getLocationFromGPS()); } }).start(); } } @Override public void onDestroy() { mIsStopped = true; super.onDestroy(); } public static String getUserAgent(Context context) { PackageInfo info = null; try { info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { Logger.tag(TAG).error(e); } String userAgent = USER_AGENT.replace("%BUILD%", info != null ? String.valueOf(info.versionCode) : String.valueOf(INaturalistApp.VERSION)); userAgent = userAgent.replace("%VERSION%", info != null ? info.versionName : String.valueOf(INaturalistApp.VERSION)); return userAgent; } private int modulo(int x, int y) { int result = x % y; if (result < 0) { result += y; } return result; } private boolean downloadToFile(String uri, String outputFilename) { HttpURLConnection conn = null; StringBuilder jsonResults = new StringBuilder(); try { URL url = new URL(uri); conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); FileOutputStream output = new FileOutputStream(outputFilename); int read; byte[] buff = new byte[1024]; while ((read = in.read(buff)) != -1) { output.write(buff, 0, read); } output.close(); conn.disconnect(); } catch (MalformedURLException e) { return false; } catch (IOException e) { return false; } return true; } }
iNaturalist/src/main/java/org/inaturalist/android/INaturalistService.java
package org.inaturalist.android; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.Charset; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.tinylog.Logger; import com.crashlytics.android.Crashlytics; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import com.google.maps.GeoApiContext; import com.google.maps.TimeZoneApi; import com.google.maps.model.LatLng; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import android.annotation.SuppressLint; import android.app.IntentService; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.SQLException; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.provider.MediaStore; import androidx.core.app.NotificationCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import android.widget.Toast; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import static java.net.HttpURLConnection.HTTP_GONE; import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; import static java.net.HttpURLConnection.HTTP_UNAVAILABLE; public class INaturalistService extends IntentService { // How many observations should we initially download for the user private static final int INITIAL_SYNC_OBSERVATION_COUNT = 100; private static final int JWT_TOKEN_EXPIRATION_MINS = 25; // JWT Tokens expire after 30 mins - consider 25 mins as the max time (safe margin) private static final int OLD_PHOTOS_MAX_COUNT = 100; // Number of cached photos to save before removing them and turning them into online photos private static final int MAX_PHOTO_REPLACEMENTS_PER_RUN = 50; // Max number of photo replacements we'll do per run public static final String IS_SHARED_ON_APP = "is_shared_on_app"; private static final Map<String, String> TIMEZONE_ID_TO_INAT_TIMEZONE; private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); private static final long HTTP_CONNECTION_TIMEOUT_SECONDS = 10; private static final long HTTP_READ_WRITE_TIMEOUT_SECONDS = 40; static { TIMEZONE_ID_TO_INAT_TIMEZONE = new HashMap(); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Algiers", "West Central Africa"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Cairo", "Cairo"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Casablanca", "Casablanca"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Harare", "Harare"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Johannesburg", "Pretoria"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Monrovia", "Monrovia"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Africa/Nairobi", "Nairobi"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Argentina/Buenos_Aires", "Buenos Aires"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Bogota", "Bogota"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Caracas", "Caracas"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Chicago", "Central Time (US & Canada)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Chihuahua", "Chihuahua"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Denver", "Mountain Time (US & Canada)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Godthab", "Greenland"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Guatemala", "Central America"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Guyana", "Georgetown"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Halifax", "Atlantic Time (Canada)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Indiana/Indianapolis", "Indiana (East)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Juneau", "Alaska"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/La_Paz", "La Paz"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Lima", "Lima"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Los_Angeles", "Pacific Time (US & Canada)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Mazatlan", "Mazatlan"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Mexico_City", "Mexico City"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Monterrey", "Monterrey"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Montevideo", "Montevideo"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/New_York", "Eastern Time (US & Canada)"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Phoenix", "Arizona"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Regina", "Saskatchewan"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Santiago", "Santiago"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Sao_Paulo", "Brasilia"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/St_Johns", "Newfoundland"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("America/Tijuana", "Tijuana"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Almaty", "Almaty"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Baghdad", "Baghdad"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Baku", "Baku"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Bangkok", "Bangkok"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Chongqing", "Chongqing"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Colombo", "Sri Jayawardenepura"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Dhaka", "Dhaka"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Hong_Kong", "Hong Kong"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Irkutsk", "Irkutsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Jakarta", "Jakarta"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Jerusalem", "Jerusalem"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kabul", "Kabul"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kamchatka", "Kamchatka"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Karachi", "Karachi"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kathmandu", "Kathmandu"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kolkata", "Kolkata"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Krasnoyarsk", "Krasnoyarsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kuala_Lumpur", "Kuala Lumpur"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Kuwait", "Kuwait"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Magadan", "Magadan"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Muscat", "Muscat"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Novosibirsk", "Novosibirsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Rangoon", "Rangoon"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Riyadh", "Riyadh"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Seoul", "Seoul"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Shanghai", "Beijing"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Singapore", "Singapore"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Srednekolymsk", "Srednekolymsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Taipei", "Taipei"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Tashkent", "Tashkent"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Tbilisi", "Tbilisi"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Tehran", "Tehran"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Tokyo", "Tokyo"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Ulaanbaatar", "Ulaanbaatar"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Urumqi", "Urumqi"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Vladivostok", "Vladivostok"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Yakutsk", "Yakutsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Yekaterinburg", "Ekaterinburg"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Asia/Yerevan", "Yerevan"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Atlantic/Azores", "Azores"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Atlantic/Cape_Verde", "Cape Verde Is."); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Atlantic/South_Georgia", "Mid-Atlantic"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Adelaide", "Adelaide"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Brisbane", "Brisbane"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Darwin", "Darwin"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Hobart", "Hobart"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Melbourne", "Melbourne"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Perth", "Perth"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Australia/Sydney", "Sydney"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Etc/UTC", "UTC"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Amsterdam", "Amsterdam"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Athens", "Athens"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Belgrade", "Belgrade"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Berlin", "Berlin"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Bratislava", "Bratislava"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Brussels", "Brussels"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Bucharest", "Bucharest"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Budapest", "Budapest"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Copenhagen", "Copenhagen"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Dublin", "Dublin"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Helsinki", "Helsinki"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Istanbul", "Istanbul"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Kaliningrad", "Kaliningrad"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Kiev", "Kyiv"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Lisbon", "Lisbon"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Ljubljana", "Ljubljana"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/London", "London"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Madrid", "Madrid"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Minsk", "Minsk"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Moscow", "Moscow"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Paris", "Paris"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Prague", "Prague"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Riga", "Riga"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Rome", "Rome"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Samara", "Samara"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Sarajevo", "Sarajevo"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Skopje", "Skopje"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Sofia", "Sofia"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Stockholm", "Stockholm"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Tallinn", "Tallinn"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Vienna", "Vienna"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Vilnius", "Vilnius"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Volgograd", "Volgograd"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Warsaw", "Warsaw"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Europe/Zagreb", "Zagreb"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Apia", "Samoa"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Auckland", "Auckland"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Chatham", "Chatham Is."); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Fakaofo", "Tokelau Is."); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Fiji", "Fiji"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Guadalcanal", "Solomon Is."); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Guam", "Guam"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Honolulu", "Hawaii"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Majuro", "Marshall Is."); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Midway", "Midway Island"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Noumea", "New Caledonia"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Pago_Pago", "American Samoa"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Port_Moresby", "Port Moresby"); TIMEZONE_ID_TO_INAT_TIMEZONE.put("Pacific/Tongatapu", "Nuku'alofa"); } private static final int MAX_OBSVERATIONS_TO_REDOWNLOAD = 100; // Happens when user switches language and we need the new taxon name in that language public static final String USER = "user"; public static final String AUTHENTICATION_FAILED = "authentication_failed"; public static final String USER_DELETED = "user_deleted"; public static final String IDENTIFICATION_ID = "identification_id"; public static final String OBSERVATION_ID = "observation_id"; public static final String GET_PROJECTS = "get_projects"; public static final String OBSERVATION_ID_INTERNAL = "observation_id_internal"; public static final String METRIC = "metric"; public static final String ATTRIBUTE_ID = "attribute_id"; public static final String VALUE_ID = "value_id"; public static final String FOLLOWING = "following"; public static final String FIELD_ID = "field_id"; public static final String COMMENT_ID = "comment_id"; public static final String OBSERVATION_RESULT = "observation_result"; public static final String HISTOGRAM_RESULT = "histogram_result"; public static final String POPULAR_FIELD_VALUES_RESULT = "popular_field_values_result"; public static final String USER_OBSERVATIONS_RESULT = "user_observations_result"; public static final String USER_SEARCH_OBSERVATIONS_RESULT = "user_search_observations_result"; public static final String OBSERVATION_JSON_RESULT = "observation_json_result"; public static final String SUCCESS = "success"; public static final String FLAGGABLE_TYPE = "flaggable_type"; public static final String FLAGGABLE_ID = "flaggable_id"; public static final String FLAG = "flag"; public static final String FLAG_EXPLANATION = "flag_explanation"; public static final String OBSERVATION_COUNT = "observation_count"; public static final String PROJECTS_RESULT = "projects_result"; public static final String IDENTIFICATIONS_RESULT = "identifications_result"; public static final String EXPLORE_GET_OBSERVATIONS_RESULT = "explore_get_observations_result"; public static final String EXPLORE_GET_SPECIES_RESULT = "explore_get_species_result"; public static final String EXPLORE_GET_IDENTIFIERS_RESULT = "explore_get_identifiers_result"; public static final String EXPLORE_GET_OBSERVERS_RESULT = "explore_get_observers_result"; public static final String GET_ATTRIBUTES_FOR_TAXON_RESULT = "get_attributes_for_taxon_result"; public static final String GET_ALL_ATTRIBUTES_RESULT = "get_all_attributes_result"; public static final String DELETE_ANNOTATION_RESULT = "delete_annotation_result"; public static final String DELETE_ANNOTATION_VOTE_RESULT = "delete_annotation_vote_result"; public static final String DELETE_DATA_QUALITY_VOTE_RESULT = "delete_data_quality_vote_result"; public static final String SET_ANNOTATION_VALUE_RESULT = "set_annotation_value_result"; public static final String DATA_QUALITY_METRICS_RESULT = "data_quality_metrics_result"; public static final String AGREE_ANNOTATION_RESULT = "agree_annotation_result"; public static final String DELETE_ID_CAN_BE_IMPROVED_VOTE_RESULT = "delete_id_can_be_improved_vote_result"; public static final String ID_CAN_BE_IMPROVED_RESULT = "id_can_be_improved_result"; public static final String ID_CANNOT_BE_IMPROVED_RESULT = "id_cannot_be_improved_result"; public static final String AGREE_DATA_QUALITY_RESULT = "agree_data_quality_result"; public static final String DISAGREE_DATA_QUALITY_RESULT = "disagree_data_quality_result"; public static final String DISAGREE_ANNOTATION_RESULT = "disagree_annotation_result"; public static final String UPDATES_RESULT = "updates_results"; public static final String UPDATES_FOLLOWING_RESULT = "updates_following_results"; public static final String LIFE_LIST_RESULT = "life_list_result"; public static final String SPECIES_COUNT_RESULT = "species_count_result"; public static final String RECOMMENDED_MISSIONS_RESULT = "recommended_missions_result"; public static final String MISSIONS_BY_TAXON_RESULT = "missions_by_taxon_result"; public static final String GET_CURRENT_LOCATION_RESULT = "get_current_location_result"; public static final String TAXON_OBSERVATION_BOUNDS_RESULT = "taxon_observation_bounds_result"; public static final String USER_DETAILS_RESULT = "user_details_result"; public static final String PLACE_DETAILS_RESULT = "place_details_result"; public static final String REFRESH_CURRENT_USER_SETTINGS_RESULT = "refresh_current_user_settings_result"; public static final String UPDATE_CURRENT_USER_DETAILS_RESULT = "update_current_user_details_result"; public static final String OBSERVATION_SYNC_PROGRESS = "observation_sync_progress"; public static final String ADD_OBSERVATION_TO_PROJECT_RESULT = "add_observation_to_project_result"; public static final String DELETE_ACCOUNT_RESULT = "delete_account_result"; public static final String TAXON_ID = "taxon_id"; public static final String RESEARCH_GRADE = "research_grade"; public static final String TAXON = "taxon"; public static final String UUID = "uuid"; public static final String NETWORK_SITE_ID = "network_site_id"; public static final String COMMENT_BODY = "comment_body"; public static final String IDENTIFICATION_BODY = "id_body"; public static final String DISAGREEMENT = "disagreement"; public static final String FROM_VISION = "from_vision"; public static final String PROJECT_ID = "project_id"; public static final String CHECK_LIST_ID = "check_list_id"; public static final String ACTION_CHECK_LIST_RESULT = "action_check_list_result"; public static final String ACTION_MESSAGES_RESULT = "action_messages_result"; public static final String ACTION_NOTIFICATION_COUNTS_RESULT = "action_notification_counts_result"; public static final String ACTION_POST_MESSAGE_RESULT = "action_post_message_result"; public static final String ACTION_MUTE_USER_RESULT = "action_mute_user_result"; public static final String ACTION_POST_FLAG_RESULT = "action_post_flag_result"; public static final String ACTION_UNMUTE_USER_RESULT = "action_unmute_user_result"; public static final String CHECK_LIST_RESULT = "check_list_result"; public static final String ACTION_GET_TAXON_RESULT = "action_get_taxon_result"; public static final String SEARCH_TAXA_RESULT = "search_taxa_result"; public static final String SEARCH_USERS_RESULT = "search_users_result"; public static final String SEARCH_PLACES_RESULT = "search_places_result"; public static final String ACTION_GET_TAXON_NEW_RESULT = "action_get_taxon_new_result"; public static final String ACTION_GET_TAXON_SUGGESTIONS_RESULT = "action_get_taxon_suggestions_result"; public static final String TAXON_RESULT = "taxon_result"; public static final String TAXON_SUGGESTIONS = "taxon_suggestions"; public static final String GUIDE_XML_RESULT = "guide_xml_result"; public static final String EMAIL = "email"; public static final String OBS_PHOTO_FILENAME = "obs_photo_filename"; public static final String OBS_PHOTO_URL = "obs_photo_url"; public static final String LONGITUDE = "longitude"; public static final String ACCURACY = "accuracy"; public static final String TITLE = "title"; public static final String GEOPRIVACY = "geoprivacy"; public static final String LATITUDE = "latitude"; public static final String OBSERVED_ON = "observed_on"; public static final String USERNAME = "username"; public static final String PLACE = "place"; public static final String PLACE_ID = "place_id"; public static final String LOCATION = "location"; public static final String FILTERS = "filters"; public static final String PROGRESS = "progress"; public static final String EXPAND_LOCATION_BY_DEGREES = "expand_location_by_degrees"; public static final String QUERY = "query"; public static final String BOX = "box"; public static final String GROUP_BY_THREADS = "group_by_threads"; public static final String MESSAGE_ID = "message_id"; public static final String NOTIFICATIONS = "notifications"; public static final String TO_USER = "to_user"; public static final String THREAD_ID = "thread_id"; public static final String SUBJECT = "subject"; public static final String BODY = "body"; public static final String OBSERVATIONS = "observations"; public static final String IDENTIFICATIONS = "identifications"; public static final String LIFE_LIST_ID = "life_list_id"; public static final String PASSWORD = "password"; public static final String LICENSE = "license"; public static final String RESULTS = "results"; public static final String LIFE_LIST = "life_list"; public static final String REGISTER_USER_ERROR = "error"; public static final String REGISTER_USER_STATUS = "status"; public static final String SYNC_CANCELED = "sync_canceled"; public static final String SYNC_FAILED = "sync_failed"; public static final String FIRST_SYNC = "first_sync"; public static final String PAGE_NUMBER = "page_number"; public static final String PAGE_SIZE = "page_size"; public static final String ID = "id"; public static final String OBS_IDS_TO_SYNC = "obs_ids_to_sync"; public static final String OBS_IDS_TO_DELETE = "obs_ids_to_delete"; public static final int NEAR_BY_OBSERVATIONS_PER_PAGE = 25; public static final int EXPLORE_DEFAULT_RESULTS_PER_PAGE = 30; public static String TAG = "INaturalistService"; public static String HOST = "https://www.inaturalist.org"; public static String API_HOST = "https://api.inaturalist.org/v1"; public static String USER_AGENT = "iNaturalist/%VERSION% (" + "Build %BUILD%; " + "Android " + System.getProperty("os.version") + " " + android.os.Build.VERSION.INCREMENTAL + "; " + "SDK " + android.os.Build.VERSION.SDK_INT + "; " + android.os.Build.DEVICE + " " + android.os.Build.MODEL + " " + android.os.Build.PRODUCT + "; OS Version " + android.os.Build.VERSION.RELEASE + ")"; public static String ACTION_GET_HISTOGRAM = "action_get_histogram"; public static String ACTION_GET_POPULAR_FIELD_VALUES = "action_get_popular_field_values"; public static String ACTION_ADD_MISSING_OBS_UUID = "action_add_missing_obs_uuid"; public static String ACTION_REGISTER_USER = "register_user"; public static String ACTION_PASSIVE_SYNC = "passive_sync"; public static String ACTION_GET_ADDITIONAL_OBS = "get_additional_observations"; public static String ACTION_ADD_IDENTIFICATION = "add_identification"; public static String ACTION_ADD_PROJECT_FIELD = "add_project_field"; public static String ACTION_ADD_FAVORITE = "add_favorite"; public static String ACTION_REMOVE_FAVORITE = "remove_favorite"; public static String ACTION_GET_TAXON = "get_taxon"; public static String ACTION_SEARCH_TAXA = "search_taxa"; public static String ACTION_SEARCH_USERS = "search_users"; public static String ACTION_SEARCH_PLACES = "search_places"; public static String ACTION_GET_TAXON_NEW = "get_taxon_new"; public static String ACTION_GET_TAXON_SUGGESTIONS = "get_taxon_suggestions"; public static String ACTION_FIRST_SYNC = "first_sync"; public static String ACTION_PULL_OBSERVATIONS = "pull_observations"; public static String ACTION_DELETE_OBSERVATIONS = "delete_observations"; public static String ACTION_GET_OBSERVATION = "get_observation"; public static String ACTION_GET_AND_SAVE_OBSERVATION = "get_and_save_observation"; public static String ACTION_FLAG_OBSERVATION_AS_CAPTIVE = "flag_observation_as_captive"; public static String ACTION_GET_CHECK_LIST = "get_check_list"; public static String ACTION_GET_MESSAGES = "get_messages"; public static String ACTION_GET_NOTIFICATION_COUNTS = "get_notification_counts"; public static String ACTION_POST_MESSAGE = "post_message"; public static String ACTION_MUTE_USER = "mute_user"; public static String ACTION_POST_FLAG = "post_flag"; public static String ACTION_UNMUTE_USER = "unmute_user"; public static String ACTION_JOIN_PROJECT = "join_project"; public static String ACTION_LEAVE_PROJECT = "leave_project"; public static String ACTION_GET_JOINED_PROJECTS = "get_joined_projects"; public static String ACTION_GET_JOINED_PROJECTS_ONLINE = "get_joined_projects_online"; public static String ACTION_GET_NEARBY_PROJECTS = "get_nearby_projects"; public static String ACTION_GET_FEATURED_PROJECTS = "get_featured_projects"; public static String ACTION_ADD_OBSERVATION_TO_PROJECT = "add_observation_to_project"; public static String ACTION_REMOVE_OBSERVATION_FROM_PROJECT = "remove_observation_from_project"; public static String ACTION_REDOWNLOAD_OBSERVATIONS_FOR_TAXON = "redownload_observations_for_taxon"; public static String ACTION_SYNC_JOINED_PROJECTS = "sync_joined_projects"; public static String ACTION_DELETE_ACCOUNT = "delete_account"; public static String ACTION_GET_ALL_GUIDES = "get_all_guides"; public static String ACTION_GET_MY_GUIDES = "get_my_guides"; public static String ACTION_GET_NEAR_BY_GUIDES = "get_near_by_guides"; public static String ACTION_TAXA_FOR_GUIDE = "get_taxa_for_guide"; public static String ACTION_GET_USER_DETAILS = "get_user_details"; public static String ACTION_UPDATE_USER_DETAILS = "update_user_details"; public static String ACTION_CLEAR_OLD_PHOTOS_CACHE = "clear_old_photos_cache"; public static String ACTION_GET_ATTRIBUTES_FOR_TAXON = "get_attributes_for_taxon"; public static String ACTION_GET_ALL_ATTRIBUTES = "get_all_attributes"; public static String ACTION_DELETE_ANNOTATION = "delete_annotation"; public static String ACTION_AGREE_ANNOTATION = "agree_annotation"; public static String ACTION_AGREE_DATA_QUALITY = "agree_data_quality"; public static String ACTION_DISAGREE_DATA_QUALITY = "disagree_data_quality"; public static String ACTION_DELETE_ID_CAN_BE_IMPROVED_VOTE = "delete_id_can_be_improved_vote"; public static String ACTION_ID_CAN_BE_IMPROVED_VOTE = "id_can_be_improved_vote"; public static String ACTION_ID_CANNOT_BE_IMPROVED_VOTE = "id_cannot_be_improved_vote"; public static String ACTION_DELETE_ANNOTATION_VOTE = "delete_annotation_vote"; public static String ACTION_DELETE_DATA_QUALITY_VOTE = "delete_data_quality_vote"; public static String ACTION_GET_DATA_QUALITY_METRICS = "get_data_quality_metrics"; public static String ACTION_SET_ANNOTATION_VALUE = "set_annotation_value"; public static String ACTION_DISAGREE_ANNOTATION = "disagree_annotation"; public static String ACTION_GET_PROJECT_NEWS = "get_project_news"; public static String ACTION_GET_NEWS = "get_news"; public static String ACTION_GET_PROJECT_OBSERVATIONS = "get_project_observations"; public static String ACTION_GET_PROJECT_SPECIES = "get_project_species"; public static String ACTION_GET_PROJECT_OBSERVERS = "get_project_observers"; public static String ACTION_GET_PROJECT_IDENTIFIERS = "get_project_identifiers"; public static String ACTION_PROJECT_OBSERVATIONS_RESULT = "get_project_observations_result"; public static String ACTION_PROJECT_NEWS_RESULT = "get_project_news_result"; public static String ACTION_NEWS_RESULT = "get_news_result"; public static String ACTION_PROJECT_SPECIES_RESULT = "get_project_species_result"; public static String ACTION_PROJECT_OBSERVERS_RESULT = "get_project_observers_result"; public static String ACTION_PROJECT_IDENTIFIERS_RESULT = "get_project_identifiers_result"; public static String ACTION_SYNC = "sync"; public static String ACTION_NEARBY = "nearby"; public static String ACTION_AGREE_ID = "agree_id"; public static String ACTION_REMOVE_ID = "remove_id"; public static String ACTION_UPDATE_ID = "update_id"; public static String ACTION_RESTORE_ID = "restore_id"; public static String ACTION_GUIDE_ID = "guide_id"; public static String ACTION_ADD_COMMENT = "add_comment"; public static String ACTION_UPDATE_COMMENT = "update_comment"; public static String ACTION_DELETE_COMMENT = "delete_comment"; public static String ACTION_SYNC_COMPLETE = "sync_complete"; public static String ACTION_GET_AND_SAVE_OBSERVATION_RESULT = "get_and_save_observation_result"; public static String ACTION_GET_ADDITIONAL_OBS_RESULT = "get_additional_obs_result"; public static String ACTION_OBSERVATION_RESULT = "action_observation_result"; public static String ACTION_JOINED_PROJECTS_RESULT = "joined_projects_result"; public static String ACTION_NEARBY_PROJECTS_RESULT = "nearby_projects_result"; public static String ACTION_FEATURED_PROJECTS_RESULT = "featured_projects_result"; public static String ACTION_ALL_GUIDES_RESULT = "all_guides_results"; public static String ACTION_MY_GUIDES_RESULT = "my_guides_results"; public static String ACTION_NEAR_BY_GUIDES_RESULT = "near_by_guides_results"; public static String ACTION_TAXA_FOR_GUIDES_RESULT = "taxa_for_guides_results"; public static String ACTION_GET_USER_DETAILS_RESULT = "get_user_details_result"; public static String ACTION_UPDATE_USER_DETAILS_RESULT = "update_user_details_result"; public static String ACTION_GUIDE_XML_RESULT = "guide_xml_result"; public static String ACTION_GUIDE_XML = "guide_xml"; public static String GUIDES_RESULT = "guides_result"; public static String ACTION_USERNAME = "username"; public static String ACTION_FULL_NAME = "full_name"; public static String ACTION_USER_BIO = "user_bio"; public static String ACTION_USER_PASSWORD = "user_password"; public static String ACTION_USER_EMAIL = "user_email"; public static String ACTION_USER_PIC = "user_pic"; public static String ACTION_USER_DELETE_PIC = "user_delete_pic"; public static String ACTION_REGISTER_USER_RESULT = "register_user_result"; public static String TAXA_GUIDE_RESULT = "taxa_guide_result"; public static String ACTION_GET_SPECIFIC_USER_DETAILS = "get_specific_user_details"; public static String ACTION_GET_PLACE_DETAILS = "get_place_details"; public static String ACTION_PIN_LOCATION = "pin_location"; public static String ACTION_DELETE_PINNED_LOCATION = "delete_pinned_location"; public static String ACTION_REFRESH_CURRENT_USER_SETTINGS = "refresh_current_user_settings"; public static String ACTION_UPDATE_CURRENT_USER_DETAILS = "update_current_user_details"; public static String ACTION_GET_CURRENT_LOCATION = "get_current_location"; public static String ACTION_GET_LIFE_LIST = "get_life_list"; public static String ACTION_GET_USER_SPECIES_COUNT = "get_species_count"; public static String ACTION_GET_USER_IDENTIFICATIONS = "get_user_identifications"; public static String ACTION_GET_USER_UPDATES = "get_user_udpates"; public static String ACTION_EXPLORE_GET_OBSERVATIONS = "explore_get_observations"; public static String ACTION_EXPLORE_GET_SPECIES = "explore_get_species"; public static String ACTION_EXPLORE_GET_IDENTIFIERS = "explore_get_identifiers"; public static String ACTION_EXPLORE_GET_OBSERVERS = "explore_get_observers"; public static String ACTION_VIEWED_UPDATE = "viewed_update"; public static String ACTION_GET_USER_OBSERVATIONS = "get_user_observations"; public static String ACTION_GET_RECOMMENDED_MISSIONS = "get_recommended_missions"; public static String ACTION_GET_MISSIONS_BY_TAXON = "get_missions_by_taxon"; public static String ACTION_SEARCH_USER_OBSERVATIONS = "search_user_observations"; public static String ACTION_GET_TAXON_OBSERVATION_BOUNDS = "get_taxon_observation_bounds"; public static String ACTION_UPDATE_USER_NETWORK = "update_user_network"; public static Integer SYNC_OBSERVATIONS_NOTIFICATION = 1; public static Integer SYNC_PHOTOS_NOTIFICATION = 2; public static Integer AUTH_NOTIFICATION = 3; private String mLogin; private String mCredentials; private SharedPreferences mPreferences; private boolean mPassive; private INaturalistApp mApp; private LoginType mLoginType; private boolean mIsStopped = false; private boolean mIsSyncing; private boolean mIsClearingOldPhotosCache; private long mLastConnectionTest = 0; private Handler mHandler; private GoogleApiClient mLocationClient; private ArrayList<SerializableJSONArray> mProjectObservations; private Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>> mProjectFieldValues; private Headers mResponseHeaders = null; private Date mRetryAfterDate = null; private long mLastServiceUnavailableNotification = 0; private boolean mServiceUnavailable = false; private JSONArray mResponseErrors; private String mNearByObservationsUrl; private int mLastStatusCode = 0; private Object mObservationLock = new Object(); private Location mLastLocation = null; public enum LoginType { PASSWORD, GOOGLE, FACEBOOK, OAUTH_PASSWORD }; public INaturalistService() { super("INaturalistService"); mHandler = new Handler(); } @Override public void onCreate() { super.onCreate(); Logger.tag(TAG).info("Service onCreate"); startIntentForeground(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Logger.tag(TAG).info("Service onStartCommand"); startIntentForeground(); return super.onStartCommand(intent, flags, startId); } private void startIntentForeground() { String channelId = "inaturalist_service"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { Logger.tag(TAG).info("Service startIntentForeground"); // See: https://stackoverflow.com/a/46449975/1233767 NotificationChannel channel = new NotificationChannel(channelId, " ", NotificationManager.IMPORTANCE_LOW); ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId) .setOngoing(false) .setPriority(NotificationCompat.PRIORITY_MIN) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.running_in_background_notfication)) .setCategory(Notification.CATEGORY_SERVICE) .setSmallIcon(R.drawable.ic_notification); Notification notification = builder.build(); startForeground(101, notification); } } @Override protected void onHandleIntent(final Intent intent) { new Thread(new Runnable() { @Override public void run() { onHandleIntentWorker(intent); } }).start(); } protected void onHandleIntentWorker(final Intent intent) { boolean cancelSyncRequested = false; boolean syncFailed = false; boolean dontStopSync = false; mPreferences = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); mLogin = mPreferences.getString("username", null); mCredentials = mPreferences.getString("credentials", null); mLoginType = LoginType.valueOf(mPreferences.getString("login_type", LoginType.OAUTH_PASSWORD.toString())); mApp = (INaturalistApp) getApplicationContext(); if (intent == null) return; String action = intent.getAction(); if (action == null) return; mPassive = action.equals(ACTION_PASSIVE_SYNC); Logger.tag(TAG).debug("Service: " + action); try { if (action.equals(ACTION_NEARBY)) { Boolean getLocation = intent.getBooleanExtra("get_location", false); final float locationExpansion = intent.getFloatExtra("location_expansion", 0); if (!getLocation) { getNearbyObservations(intent); } else { // Retrieve current place before getting nearby observations getLocation(new IOnLocation() { @Override public void onLocation(Location location) { final Intent newIntent = new Intent(intent); if (location != null) { if (locationExpansion == 0) { newIntent.putExtra("lat", location.getLatitude()); newIntent.putExtra("lng", location.getLongitude()); } else { // Expand place by requested degrees (to make sure results are returned from this API) newIntent.putExtra("minx", location.getLongitude() - locationExpansion); newIntent.putExtra("miny", location.getLatitude() - locationExpansion); newIntent.putExtra("maxx", location.getLongitude() + locationExpansion); newIntent.putExtra("maxy", location.getLatitude() + locationExpansion); } } try { getNearbyObservations(newIntent); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); } } }); } } else if (action.equals(ACTION_FIRST_SYNC)) { mIsSyncing = true; mApp.setIsSyncing(mIsSyncing); saveJoinedProjects(); boolean success = getUserObservations(INITIAL_SYNC_OBSERVATION_COUNT); // Get total obs count BetterJSONObject user = getUserDetails(); if (user == null) { throw new SyncFailedException(); } int totalObsCount = user.getInt("observations_count"); mPreferences.edit().putInt("observation_count", totalObsCount).commit(); Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "(is_deleted = 0 OR is_deleted is NULL) AND (user_login = '" + mLogin + "')", null, Observation.DEFAULT_SORT_ORDER); c.moveToLast(); if (c.getCount() > 0) { BetterCursor bc = new BetterCursor(c); int lastId = bc.getInteger(Observation.ID); mPreferences.edit().putInt("last_downloaded_id", lastId).commit(); } else { // No observations - probably a new user // Update the user's timezone (in case we registered via FB/G+) getTimezoneByCurrentLocation(new IOnTimezone() { @Override public void onTimezone(String timezoneName) { Logger.tag(TAG).debug("Detected Timezone: " + timezoneName); if (timezoneName != null) { try { updateUserTimezone(timezoneName); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); } } } }); } c.close(); if (success) { long lastSync = System.currentTimeMillis(); mPreferences.edit().putLong("last_sync_time", lastSync).commit(); } if (!success) throw new SyncFailedException(); syncObservationFields(); postProjectObservations(); } else if (action.equals(ACTION_GET_HISTOGRAM)) { int taxonId = intent.getIntExtra(TAXON_ID, 0); boolean researchGrade = intent.getBooleanExtra(RESEARCH_GRADE, false); BetterJSONObject results = getHistogram(taxonId, researchGrade); Intent reply = new Intent(HISTOGRAM_RESULT); reply.putExtra(HISTOGRAM_RESULT, results); reply.putExtra(RESEARCH_GRADE, researchGrade); reply.putExtra(TAXON_ID, taxonId); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_ADD_MISSING_OBS_UUID)) { addObservationUUIDsToPhotosAndSounds(); } else if (action.equals(ACTION_GET_POPULAR_FIELD_VALUES)) { int taxonId = intent.getIntExtra(TAXON_ID, 0); BetterJSONObject results = getPopularFieldValues(taxonId); Intent reply = new Intent(POPULAR_FIELD_VALUES_RESULT); reply.putExtra(POPULAR_FIELD_VALUES_RESULT, results); reply.putExtra(TAXON_ID, taxonId); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_AGREE_ID)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int taxonId = intent.getIntExtra(TAXON_ID, 0); boolean disagreement = intent.getBooleanExtra(DISAGREEMENT, false); addIdentification(observationId, taxonId, null, disagreement, false); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_RESTORE_ID)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int identificationId = intent.getIntExtra(IDENTIFICATION_ID, 0); restoreIdentification(identificationId); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_UPDATE_ID)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int taxonId = intent.getIntExtra(TAXON_ID, 0); int identificationId = intent.getIntExtra(IDENTIFICATION_ID, 0); String body = intent.getStringExtra(IDENTIFICATION_BODY); updateIdentification(observationId, identificationId, taxonId, body); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_REMOVE_ID)) { int id = intent.getIntExtra(IDENTIFICATION_ID, 0); int observationId = intent.getIntExtra(OBSERVATION_ID, 0); JSONObject result = removeIdentification(id); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_ADD_FAVORITE)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); addFavorite(observationId); } else if (action.equals(ACTION_REMOVE_FAVORITE)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); removeFavorite(observationId); } else if (action.equals(ACTION_GET_ADDITIONAL_OBS)) { int obsCount = getAdditionalUserObservations(20); Intent reply = new Intent(ACTION_GET_ADDITIONAL_OBS_RESULT); reply.putExtra(SUCCESS, obsCount > -1); reply.putExtra(OBSERVATION_COUNT, obsCount); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_ADD_IDENTIFICATION)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int taxonId = intent.getIntExtra(TAXON_ID, 0); String body = intent.getStringExtra(IDENTIFICATION_BODY); boolean disagreement = intent.getBooleanExtra(DISAGREEMENT, false); boolean fromVision = intent.getBooleanExtra(FROM_VISION, false); addIdentification(observationId, taxonId, body, disagreement, fromVision); // Wait a little before refreshing the observation details - so we'll let the server update the ID // list (otherwise, it won't return the new ID) try { Thread.sleep(1000); } catch (InterruptedException e) { Logger.tag(TAG).error(e); } // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_ADD_PROJECT_FIELD)) { int fieldId = intent.getIntExtra(FIELD_ID, 0); addProjectField(fieldId); } else if (action.equals(ACTION_REGISTER_USER)) { String email = intent.getStringExtra(EMAIL); String password = intent.getStringExtra(PASSWORD); String username = intent.getStringExtra(USERNAME); String license = intent.getStringExtra(LICENSE); getTimezoneByCurrentLocation(new IOnTimezone() { @Override public void onTimezone(String timezoneName) { Logger.tag(TAG).debug("Detected Timezone: " + timezoneName); String error = null; try { error = registerUser(email, password, username, license, timezoneName); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); error = e.toString(); } Intent reply = new Intent(ACTION_REGISTER_USER_RESULT); reply.putExtra(REGISTER_USER_STATUS, error == null); reply.putExtra(REGISTER_USER_ERROR, error); boolean b = LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } }); } else if (action.equals(ACTION_GET_PROJECT_NEWS)) { int projectId = intent.getIntExtra(PROJECT_ID, 0); SerializableJSONArray results = getProjectNews(projectId); Intent reply = new Intent(ACTION_PROJECT_NEWS_RESULT); reply.putExtra(RESULTS, results); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_PROJECT_OBSERVATIONS)) { int projectId = intent.getIntExtra(PROJECT_ID, 0); BetterJSONObject results = getProjectObservations(projectId); results = getMinimalObservationResults(results); mApp.setServiceResult(ACTION_PROJECT_OBSERVATIONS_RESULT, results); Intent reply = new Intent(ACTION_PROJECT_OBSERVATIONS_RESULT); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_PROJECT_IDENTIFIERS)) { int projectId = intent.getIntExtra(PROJECT_ID, 0); BetterJSONObject results = getProjectIdentifiers(projectId); results = getMinimalObserverResults(results); Intent reply = new Intent(ACTION_PROJECT_IDENTIFIERS_RESULT); mApp.setServiceResult(ACTION_PROJECT_IDENTIFIERS_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_PROJECT_OBSERVERS)) { int projectId = intent.getIntExtra(PROJECT_ID, 0); BetterJSONObject results = getProjectObservers(projectId); results = getMinimalObserverResults(results); Intent reply = new Intent(ACTION_PROJECT_OBSERVERS_RESULT); mApp.setServiceResult(ACTION_PROJECT_OBSERVERS_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_PROJECT_SPECIES)) { int projectId = intent.getIntExtra(PROJECT_ID, 0); BetterJSONObject results = getProjectSpecies(projectId); results = getMinimalSpeciesResults(results); Intent reply = new Intent(ACTION_PROJECT_SPECIES_RESULT); mApp.setServiceResult(ACTION_PROJECT_SPECIES_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DELETE_ANNOTATION)) { String uuid = intent.getStringExtra(UUID); BetterJSONObject results = deleteAnnotation(uuid); Intent reply = new Intent(DELETE_ANNOTATION_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DELETE_ANNOTATION_VOTE)) { String uuid = intent.getStringExtra(UUID); BetterJSONObject results = deleteAnnotationVote(uuid); Intent reply = new Intent(DELETE_ANNOTATION_VOTE_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DELETE_ID_CAN_BE_IMPROVED_VOTE)) { int obsId = intent.getIntExtra(OBSERVATION_ID, 0); BetterJSONObject result = deleteIdCanBeImprovedVote(obsId); Intent reply = new Intent(DELETE_ID_CAN_BE_IMPROVED_VOTE_RESULT); reply.putExtra(DELETE_ID_CAN_BE_IMPROVED_VOTE_RESULT, result); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_ID_CAN_BE_IMPROVED_VOTE)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); BetterJSONObject result = voteIdCanBeImproved(observationId, true); Intent reply = new Intent(ID_CAN_BE_IMPROVED_RESULT); reply.putExtra(ID_CAN_BE_IMPROVED_RESULT, result); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_ID_CANNOT_BE_IMPROVED_VOTE)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); BetterJSONObject result = voteIdCanBeImproved(observationId, false); Intent reply = new Intent(ID_CANNOT_BE_IMPROVED_RESULT); reply.putExtra(ID_CANNOT_BE_IMPROVED_RESULT, result); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SET_ANNOTATION_VALUE)) { int obsId = intent.getIntExtra(OBSERVATION_ID, 0); int attributeId = intent.getIntExtra(ATTRIBUTE_ID, 0); int valueId = intent.getIntExtra(VALUE_ID, 0); BetterJSONObject results = setAnnotationValue(obsId, attributeId, valueId); Intent reply = new Intent(SET_ANNOTATION_VALUE_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_DATA_QUALITY_METRICS)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); BetterJSONObject results = getDataQualityMetrics(observationId); Intent reply = new Intent(DATA_QUALITY_METRICS_RESULT); reply.putExtra(DATA_QUALITY_METRICS_RESULT, results); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DELETE_DATA_QUALITY_VOTE)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); String metric = intent.getStringExtra(METRIC); BetterJSONObject result = deleteDataQualityMetricVote(observationId, metric); Intent reply = new Intent(DELETE_DATA_QUALITY_VOTE_RESULT); reply.putExtra(SUCCESS, result != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_AGREE_DATA_QUALITY)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); String metric = intent.getStringExtra(METRIC); BetterJSONObject results = agreeDataQualityMetric(observationId, metric, true); Intent reply = new Intent(AGREE_DATA_QUALITY_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DISAGREE_DATA_QUALITY)) { Integer observationId = intent.getIntExtra(OBSERVATION_ID, 0); String metric = intent.getStringExtra(METRIC); BetterJSONObject results = agreeDataQualityMetric(observationId, metric, false); Intent reply = new Intent(DISAGREE_DATA_QUALITY_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_AGREE_ANNOTATION)) { String uuid = intent.getStringExtra(UUID); BetterJSONObject results = agreeAnnotation(uuid, true); Intent reply = new Intent(AGREE_ANNOTATION_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_DISAGREE_ANNOTATION)) { String uuid = intent.getStringExtra(UUID); BetterJSONObject results = agreeAnnotation(uuid, false); Intent reply = new Intent(DISAGREE_ANNOTATION_RESULT); reply.putExtra(SUCCESS, results != null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_ALL_ATTRIBUTES)) { BetterJSONObject results = getAllAttributes(); Intent reply = new Intent(GET_ALL_ATTRIBUTES_RESULT); mApp.setServiceResult(GET_ALL_ATTRIBUTES_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_ATTRIBUTES_FOR_TAXON)) { BetterJSONObject taxon = (BetterJSONObject) intent.getSerializableExtra(TAXON); BetterJSONObject results = getAttributesForTaxon(taxon != null ? taxon.getJSONObject() : null); Intent reply = new Intent(GET_ATTRIBUTES_FOR_TAXON_RESULT); mApp.setServiceResult(GET_ATTRIBUTES_FOR_TAXON_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_TAXON_SUGGESTIONS)) { String obsFilename = intent.getStringExtra(OBS_PHOTO_FILENAME); String obsUrl = intent.getStringExtra(OBS_PHOTO_URL); Double longitude = intent.getDoubleExtra(LONGITUDE, 0); Double latitude = intent.getDoubleExtra(LATITUDE, 0); Timestamp observedOn = (Timestamp) intent.getSerializableExtra(OBSERVED_ON); File tempFile = null; if (obsFilename == null) { // It's an online observation - need to download the image first. try { tempFile = File.createTempFile("online_photo", ".jpeg", getCacheDir()); if (!downloadToFile(obsUrl, tempFile.getAbsolutePath())) { Intent reply = new Intent(ACTION_GET_TAXON_SUGGESTIONS_RESULT); reply.putExtra(TAXON_SUGGESTIONS, (Serializable) null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); return; } obsFilename = tempFile.getAbsolutePath(); } catch (IOException e) { Logger.tag(TAG).error(e); } } // Resize photo to 299x299 max String resizedPhotoFilename = ImageUtils.resizeImage(this, obsFilename, null, 299); if (tempFile != null) { tempFile.delete(); } BetterJSONObject taxonSuggestions = getTaxonSuggestions(resizedPhotoFilename, latitude, longitude, observedOn); File resizedFile = new File(resizedPhotoFilename); resizedFile.delete(); Intent reply = new Intent(ACTION_GET_TAXON_SUGGESTIONS_RESULT); reply.putExtra(TAXON_SUGGESTIONS, taxonSuggestions); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_TAXON_NEW)) { int taxonId = intent.getIntExtra(TAXON_ID, 0); BetterJSONObject taxon = getTaxonNew(taxonId); Intent reply = new Intent(ACTION_GET_TAXON_NEW_RESULT); mApp.setServiceResult(ACTION_GET_TAXON_NEW_RESULT, taxon); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_TAXON)) { int taxonId = intent.getIntExtra(TAXON_ID, 0); BetterJSONObject taxon = getTaxon(taxonId); Intent reply = new Intent(ACTION_GET_TAXON_RESULT); reply.putExtra(TAXON_RESULT, taxon); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SEARCH_PLACES)) { String query = intent.getStringExtra(QUERY); int page = intent.getIntExtra(PAGE_NUMBER, 1); BetterJSONObject results = searchAutoComplete("places", query, page); Intent reply = new Intent(SEARCH_PLACES_RESULT); mApp.setServiceResult(SEARCH_PLACES_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SEARCH_USERS)) { String query = intent.getStringExtra(QUERY); int page = intent.getIntExtra(PAGE_NUMBER, 1); BetterJSONObject results = searchAutoComplete("users", query, page); Intent reply = new Intent(SEARCH_USERS_RESULT); mApp.setServiceResult(SEARCH_USERS_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(QUERY, query); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SEARCH_TAXA)) { String query = intent.getStringExtra(QUERY); int page = intent.getIntExtra(PAGE_NUMBER, 1); BetterJSONObject results = searchAutoComplete("taxa", query, page); Intent reply = new Intent(SEARCH_TAXA_RESULT); mApp.setServiceResult(SEARCH_TAXA_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_UPDATE_CURRENT_USER_DETAILS)) { BetterJSONObject params = (BetterJSONObject) intent.getSerializableExtra(USER); BetterJSONObject user = updateCurrentUserDetails(params.getJSONObject()); Intent reply = new Intent(UPDATE_CURRENT_USER_DETAILS_RESULT); reply.putExtra(USER, user); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_REFRESH_CURRENT_USER_SETTINGS)) { BetterJSONObject user = getCurrentUserDetails(); if (user != null) { // Update settings mApp.setShowScientificNameFirst(user.getJSONObject().optBoolean("prefers_scientific_name_first", false)); // Refresh privileges JSONArray privileges = user.getJSONArray("privileges").getJSONArray(); Set<String> privilegesSet = new HashSet<>(); for (int i = 0; i < privileges.length(); i++) { privilegesSet.add(privileges.optString(i)); } mApp.setUserPrivileges(privilegesSet); // Refresh muted users JSONArray mutedUsers = user.getJSONArray("muted_user_ids").getJSONArray(); Set<Integer> mutedSet = new HashSet<>(); for (int i = 0; i < mutedUsers.length(); i++) { mutedSet.add(mutedUsers.optInt(i)); } mApp.setMutedUsers(mutedSet); JSONArray arr = user.getJSONObject().optJSONArray("roles"); HashSet roles = new HashSet(); for (int i = 0; i < arr.length(); i++) { roles.add(arr.optString(i)); } mApp.setUserRoles(roles); Intent reply = new Intent(REFRESH_CURRENT_USER_SETTINGS_RESULT); reply.putExtra(USER, user); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_DELETE_PINNED_LOCATION)) { String id = intent.getStringExtra(ID); boolean success = deletePinnedLocation(id); } else if (action.equals(ACTION_PIN_LOCATION)) { Double latitude = intent.getDoubleExtra(LATITUDE, 0); Double longitude = intent.getDoubleExtra(LONGITUDE, 0); Double accuracy = intent.getDoubleExtra(ACCURACY, 0); String geoprivacy = intent.getStringExtra(GEOPRIVACY); String title = intent.getStringExtra(TITLE); boolean success = pinLocation(latitude, longitude, accuracy, geoprivacy, title); } else if (action.equals(ACTION_GET_PLACE_DETAILS)) { long placeId = intent.getIntExtra(PLACE_ID, 0); BetterJSONObject place = getPlaceDetails(placeId); Intent reply = new Intent(PLACE_DETAILS_RESULT); reply.putExtra(PLACE, place); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_SPECIFIC_USER_DETAILS)) { String username = intent.getStringExtra(USERNAME); BetterJSONObject user = getUserDetails(username); Intent reply = new Intent(USER_DETAILS_RESULT); reply.putExtra(USER, user); reply.putExtra(USERNAME, username); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_CURRENT_LOCATION)) { getLocation(new IOnLocation() { @Override public void onLocation(Location location) { Intent reply = new Intent(GET_CURRENT_LOCATION_RESULT); reply.putExtra(LOCATION, location); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } }); } else if (action.equals(ACTION_GET_MISSIONS_BY_TAXON)) { final String username = intent.getStringExtra(USERNAME); final Integer taxonId = intent.getIntExtra(TAXON_ID, 0); final float expandLocationByDegrees = intent.getFloatExtra(EXPAND_LOCATION_BY_DEGREES, 0); getLocation(new IOnLocation() { @Override public void onLocation(Location location) { if (location == null) { // No place Intent reply = new Intent(MISSIONS_BY_TAXON_RESULT); mApp.setServiceResult(MISSIONS_BY_TAXON_RESULT, null); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(TAXON_ID, taxonId); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); return; } BetterJSONObject missions = getMissions(location, username, taxonId, expandLocationByDegrees); missions = getMinimalSpeciesResults(missions); Intent reply = new Intent(MISSIONS_BY_TAXON_RESULT); mApp.setServiceResult(MISSIONS_BY_TAXON_RESULT, missions); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(TAXON_ID, taxonId); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } }); } else if (action.equals(ACTION_GET_TAXON_OBSERVATION_BOUNDS)) { final Integer taxonId = intent.getIntExtra(TAXON_ID, 0); BetterJSONObject bounds = getTaxonObservationsBounds(taxonId); Intent reply = new Intent(TAXON_OBSERVATION_BOUNDS_RESULT); reply.putExtra(TAXON_OBSERVATION_BOUNDS_RESULT, bounds); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_RECOMMENDED_MISSIONS)) { final String username = intent.getStringExtra(USERNAME); final float expandLocationByDegrees = intent.getFloatExtra(EXPAND_LOCATION_BY_DEGREES, 0); getLocation(new IOnLocation() { @Override public void onLocation(Location location) { if (location == null) { // No place Intent reply = new Intent(RECOMMENDED_MISSIONS_RESULT); mApp.setServiceResult(RECOMMENDED_MISSIONS_RESULT, null); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); return; } BetterJSONObject missions = getMissions(location, username, null, expandLocationByDegrees); missions = getMinimalSpeciesResults(missions); Intent reply = new Intent(RECOMMENDED_MISSIONS_RESULT); mApp.setServiceResult(RECOMMENDED_MISSIONS_RESULT, missions); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } }); } else if (action.equals(ACTION_GET_USER_SPECIES_COUNT)) { String username = intent.getStringExtra(USERNAME); BetterJSONObject speciesCount = getUserSpeciesCount(username); speciesCount = getMinimalSpeciesResults(speciesCount); Intent reply = new Intent(SPECIES_COUNT_RESULT); mApp.setServiceResult(SPECIES_COUNT_RESULT, speciesCount); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(USERNAME, username); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_LIFE_LIST)) { int lifeListId = intent.getIntExtra(LIFE_LIST_ID, 0); BetterJSONObject lifeList = getUserLifeList(lifeListId); Intent reply = new Intent(LIFE_LIST_RESULT); mApp.setServiceResult(LIFE_LIST_RESULT, lifeList); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_USER_OBSERVATIONS)) { String username = intent.getStringExtra(USERNAME); JSONObject observations = getUserObservations(username); if (observations != null) { BetterJSONObject minimalObs = getMinimalObservationResults(new BetterJSONObject(observations)); observations = minimalObs != null ? minimalObs.getJSONObject() : null; } Intent reply = new Intent(USER_OBSERVATIONS_RESULT); mApp.setServiceResult(USER_OBSERVATIONS_RESULT, observations != null ? new BetterJSONObject(observations) : null); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(USERNAME, username); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SEARCH_USER_OBSERVATIONS)) { String query = intent.getStringExtra(QUERY); SerializableJSONArray observations = searchUserObservation(query); Intent reply = new Intent(USER_SEARCH_OBSERVATIONS_RESULT); mApp.setServiceResult(USER_SEARCH_OBSERVATIONS_RESULT, observations); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(QUERY, query); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_VIEWED_UPDATE)) { Integer obsId = intent.getIntExtra(OBSERVATION_ID, 0); setUserViewedUpdate(obsId); } else if (action.equals(ACTION_GET_USER_UPDATES)) { Boolean following = intent.getBooleanExtra(FOLLOWING, false); SerializableJSONArray updates = getUserUpdates(following); Intent reply; if (following) { reply = new Intent(UPDATES_FOLLOWING_RESULT); mApp.setServiceResult(UPDATES_FOLLOWING_RESULT, updates); } else { reply = new Intent(UPDATES_RESULT); mApp.setServiceResult(UPDATES_RESULT, updates); } reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_USER_IDENTIFICATIONS)) { String username = intent.getStringExtra(USERNAME); BetterJSONObject identifications = getUserIdentifications(username); identifications = getMinimalIdentificationResults(identifications); Intent reply = new Intent(IDENTIFICATIONS_RESULT); mApp.setServiceResult(IDENTIFICATIONS_RESULT, identifications); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(USERNAME, username); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_EXPLORE_GET_OBSERVERS)) { ExploreSearchFilters filters = (ExploreSearchFilters) intent.getSerializableExtra(FILTERS); int pageNumber = intent.getIntExtra(PAGE_NUMBER, 1); int pageSize = intent.getIntExtra(PAGE_SIZE, EXPLORE_DEFAULT_RESULTS_PER_PAGE); String uuid = intent.getStringExtra(UUID); BetterJSONObject results = getExploreResults("observers", filters, pageNumber, pageSize, null); results = getMinimalObserverResults(results); Intent reply = new Intent(EXPLORE_GET_OBSERVERS_RESULT); mApp.setServiceResult(EXPLORE_GET_OBSERVERS_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(UUID, uuid); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_EXPLORE_GET_IDENTIFIERS)) { ExploreSearchFilters filters = (ExploreSearchFilters) intent.getSerializableExtra(FILTERS); int pageNumber = intent.getIntExtra(PAGE_NUMBER, 1); int pageSize = intent.getIntExtra(PAGE_SIZE, EXPLORE_DEFAULT_RESULTS_PER_PAGE); String uuid = intent.getStringExtra(UUID); BetterJSONObject results = getExploreResults("identifiers", filters, pageNumber, pageSize, null); results = getMinimalObserverResults(results); Intent reply = new Intent(EXPLORE_GET_IDENTIFIERS_RESULT); mApp.setServiceResult(EXPLORE_GET_IDENTIFIERS_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(UUID, uuid); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_EXPLORE_GET_SPECIES)) { ExploreSearchFilters filters = (ExploreSearchFilters) intent.getSerializableExtra(FILTERS); int pageNumber = intent.getIntExtra(PAGE_NUMBER, 1); int pageSize = intent.getIntExtra(PAGE_SIZE, EXPLORE_DEFAULT_RESULTS_PER_PAGE); String uuid = intent.getStringExtra(UUID); BetterJSONObject results = getExploreResults("species_counts", filters, pageNumber, pageSize, null); results = getMinimalSpeciesResults(results); Intent reply = new Intent(EXPLORE_GET_SPECIES_RESULT); mApp.setServiceResult(EXPLORE_GET_SPECIES_RESULT, results); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(UUID, uuid); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_EXPLORE_GET_OBSERVATIONS)) { ExploreSearchFilters filters = (ExploreSearchFilters) intent.getSerializableExtra(FILTERS); int pageNumber = intent.getIntExtra(PAGE_NUMBER, 1); int pageSize = intent.getIntExtra(PAGE_SIZE, EXPLORE_DEFAULT_RESULTS_PER_PAGE); String uuid = intent.getStringExtra(UUID); BetterJSONObject observations = getExploreResults(null, filters, pageNumber, pageSize, "observation.id"); observations = getMinimalObservationResults(observations); Intent reply = new Intent(EXPLORE_GET_OBSERVATIONS_RESULT); mApp.setServiceResult(EXPLORE_GET_OBSERVATIONS_RESULT, observations); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(UUID, uuid); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_ADD_COMMENT)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); String body = intent.getStringExtra(COMMENT_BODY); addComment(observationId, body); // Wait a little before refreshing the observation details - so we'll let the server update the comment // list (otherwise, it won't return the new comment) try { Thread.sleep(1000); } catch (InterruptedException e) { Logger.tag(TAG).error(e); } // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); if (observationJson == null) { reply.putExtra(OBSERVATION_RESULT, (Serializable)null); reply.putExtra(OBSERVATION_JSON_RESULT, (String)null); } else { Observation observation = new Observation(new BetterJSONObject(observationJson)); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observation != null ? observationJson.toString() : null); } LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_UPDATE_COMMENT)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int commentId = intent.getIntExtra(COMMENT_ID, 0); String body = intent.getStringExtra(COMMENT_BODY); updateComment(commentId, observationId, body); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_DELETE_COMMENT)) { int observationId = intent.getIntExtra(OBSERVATION_ID, 0); int commentId = intent.getIntExtra(COMMENT_ID, 0); deleteComment(commentId); // Reload the observation at the end (need to refresh comment/ID list) JSONObject observationJson = getObservationJson(observationId, false, false); if (observationJson != null) { Observation observation = new Observation(new BetterJSONObject(observationJson)); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); reply.putExtra(OBSERVATION_RESULT, observation); reply.putExtra(OBSERVATION_JSON_RESULT, observationJson.toString()); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } else if (action.equals(ACTION_GUIDE_XML)) { int guideId = intent.getIntExtra(ACTION_GUIDE_ID, 0); String guideXMLFilename = getGuideXML(guideId); if (guideXMLFilename == null) { // Failed to get the guide XML - try and find the offline version, if available GuideXML guideXml = new GuideXML(this, String.valueOf(guideId)); if (guideXml.isGuideDownloaded()) { guideXMLFilename = guideXml.getOfflineGuideXmlFilePath(); } } Intent reply = new Intent(ACTION_GUIDE_XML_RESULT); reply.putExtra(GUIDE_XML_RESULT, guideXMLFilename); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_CLEAR_OLD_PHOTOS_CACHE)) { // Clear out the old cached photos if (!mIsClearingOldPhotosCache) { mIsClearingOldPhotosCache = true; clearOldCachedPhotos(); mIsClearingOldPhotosCache = false; } } else if (action.equals(ACTION_UPDATE_USER_NETWORK)) { int siteId = intent.getIntExtra(NETWORK_SITE_ID, 0); updateUserNetwork(siteId); } else if (action.equals(ACTION_UPDATE_USER_DETAILS)) { String username = intent.getStringExtra(ACTION_USERNAME); String fullName = intent.getStringExtra(ACTION_FULL_NAME); String bio = intent.getStringExtra(ACTION_USER_BIO); String password = intent.getStringExtra(ACTION_USER_PASSWORD); String email = intent.getStringExtra(ACTION_USER_EMAIL); String userPic = intent.getStringExtra(ACTION_USER_PIC); boolean deletePic = intent.getBooleanExtra(ACTION_USER_DELETE_PIC, false); JSONObject newUser = updateUser(username, email, password, fullName, bio, userPic, deletePic); if ((newUser != null) && (!newUser.has("errors"))) { SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); String prevLogin = mLogin; mLogin = newUser.optString("login"); editor.putString("username", mLogin); if (!newUser.has("user_icon_url") || newUser.isNull("user_icon_url")) { editor.putString("user_icon_url", null); } else { editor.putString("user_icon_url", newUser.has("medium_user_icon_url") ? newUser.optString("medium_user_icon_url") : newUser.optString("user_icon_url")); } editor.putString("user_bio", newUser.optString("description")); editor.putString("user_email", newUser.optString("email", email)); editor.putString("user_full_name", newUser.optString("name")); editor.apply(); if ((prevLogin != null) && (!prevLogin.equals(mLogin))) { // Update observations with the new username ContentValues cv = new ContentValues(); cv.put("user_login", mLogin); // Update its sync at time so we won't update the remote servers later on (since we won't // accidentally consider this an updated record) cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); int count = getContentResolver().update(Observation.CONTENT_URI, cv, "(user_login = ?) AND (id IS NOT NULL)", new String[]{prevLogin}); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "Updated %d synced observations with new user login %s from %s", count, mLogin, prevLogin)); cv = new ContentValues(); cv.put("user_login", mLogin); count = getContentResolver().update(Observation.CONTENT_URI, cv, "(user_login = ?) AND (id IS NULL)", new String[]{ prevLogin }); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "Updated %d new observations with new user login %s from %s", count, mLogin, prevLogin)); } } Intent reply = new Intent(ACTION_UPDATE_USER_DETAILS_RESULT); reply.putExtra(USER, newUser != null ? new BetterJSONObject(newUser) : null); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_USER_DETAILS)) { BetterJSONObject user = null; boolean authenticationFailed = false; boolean isDeleted = false; try { user = getUserDetails(); } catch (AuthenticationException exc) { Logger.tag(TAG).error(exc); // See if user was deleted via the website isDeleted = isUserDeleted(mLogin); if (!isDeleted) { // This means the user has changed his password on the website authenticationFailed = true; } } Intent reply = new Intent(ACTION_GET_USER_DETAILS_RESULT); reply.putExtra(USER, user); reply.putExtra(AUTHENTICATION_FAILED, authenticationFailed); reply.putExtra(USER_DELETED, isDeleted); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_TAXA_FOR_GUIDE)) { int guideId = intent.getIntExtra(ACTION_GUIDE_ID, 0); SerializableJSONArray taxa = getTaxaForGuide(guideId); mApp.setServiceResult(ACTION_TAXA_FOR_GUIDES_RESULT, taxa); Intent reply = new Intent(ACTION_TAXA_FOR_GUIDES_RESULT); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_ALL_GUIDES)) { SerializableJSONArray guides = getAllGuides(); mApp.setServiceResult(ACTION_ALL_GUIDES_RESULT, guides); Intent reply = new Intent(ACTION_ALL_GUIDES_RESULT); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_MY_GUIDES)) { SerializableJSONArray guides = null; guides = getMyGuides(); Intent reply = new Intent(ACTION_MY_GUIDES_RESULT); reply.putExtra(GUIDES_RESULT, guides); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_NEAR_BY_GUIDES)) { getLocation(new IOnLocation() { @Override public void onLocation(Location location) { if (location == null) { // No place enabled Intent reply = new Intent(ACTION_NEAR_BY_GUIDES_RESULT); reply.putExtra(GUIDES_RESULT, new SerializableJSONArray()); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } else { SerializableJSONArray guides = null; try { guides = getNearByGuides(location); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); } Intent reply = new Intent(ACTION_NEAR_BY_GUIDES_RESULT); reply.putExtra(GUIDES_RESULT, guides); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } } }); } else if (action.equals(ACTION_GET_NEARBY_PROJECTS)) { getLocation(new IOnLocation() { @Override public void onLocation(Location location) { if (location == null) { // No place enabled Intent reply = new Intent(ACTION_NEARBY_PROJECTS_RESULT); mApp.setServiceResult(ACTION_NEARBY_PROJECTS_RESULT, new SerializableJSONArray()); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } else { SerializableJSONArray projects = null; try { projects = getNearByProjects(location); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); } Intent reply = new Intent(ACTION_NEARBY_PROJECTS_RESULT); mApp.setServiceResult(ACTION_NEARBY_PROJECTS_RESULT, projects); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(INaturalistService.this).sendBroadcast(reply); } } }); } else if (action.equals(ACTION_GET_FEATURED_PROJECTS)) { SerializableJSONArray projects = getFeaturedProjects(); Intent reply = new Intent(ACTION_FEATURED_PROJECTS_RESULT); reply.putExtra(PROJECTS_RESULT, projects); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_JOINED_PROJECTS_ONLINE)) { SerializableJSONArray projects = null; if (mCredentials != null) { projects = getJoinedProjects(); } Intent reply = new Intent(ACTION_JOINED_PROJECTS_RESULT); mApp.setServiceResult(ACTION_JOINED_PROJECTS_RESULT, projects); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_JOINED_PROJECTS)) { SerializableJSONArray projects = null; if (mCredentials != null) { projects = getJoinedProjectsOffline(); } Intent reply = new Intent(ACTION_JOINED_PROJECTS_RESULT); reply.putExtra(PROJECTS_RESULT, projects); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_REMOVE_OBSERVATION_FROM_PROJECT)) { int observationId = intent.getExtras().getInt(OBSERVATION_ID); int projectId = intent.getExtras().getInt(PROJECT_ID); BetterJSONObject result = removeObservationFromProject(observationId, projectId); } else if (action.equals(ACTION_ADD_OBSERVATION_TO_PROJECT)) { int observationId = intent.getExtras().getInt(OBSERVATION_ID); int projectId = intent.getExtras().getInt(PROJECT_ID); BetterJSONObject result = addObservationToProject(observationId, projectId); Intent reply = new Intent(ADD_OBSERVATION_TO_PROJECT_RESULT); reply.putExtra(ADD_OBSERVATION_TO_PROJECT_RESULT, result); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_REDOWNLOAD_OBSERVATIONS_FOR_TAXON)) { redownloadOldObservationsForTaxonNames(); } else if (action.equals(ACTION_DELETE_ACCOUNT)) { boolean success = deleteAccount(); Intent reply = new Intent(DELETE_ACCOUNT_RESULT); reply.putExtra(SUCCESS, success); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_SYNC_JOINED_PROJECTS)) { saveJoinedProjects(); } else if (action.equals(ACTION_GET_NOTIFICATION_COUNTS)) { BetterJSONObject notificationCounts = getNotificationCounts(); Intent reply = new Intent(ACTION_NOTIFICATION_COUNTS_RESULT); reply.putExtra(NOTIFICATIONS, notificationCounts); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_POST_FLAG)) { String flaggableType = intent.getExtras().getString(FLAGGABLE_TYPE); Integer flaggableId = intent.getExtras().getInt(FLAGGABLE_ID); String flag = intent.getExtras().getString(FLAG); String flagExplanation = intent.getExtras().getString(FLAG_EXPLANATION); boolean success = postFlag(flaggableType, flaggableId, flag, flagExplanation); Intent reply = new Intent(ACTION_POST_FLAG_RESULT); reply.putExtra(SUCCESS, success); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_UNMUTE_USER)) { Integer userId = intent.getExtras().getInt(USER); boolean success = unmuteUser(userId); Intent reply = new Intent(ACTION_UNMUTE_USER_RESULT); reply.putExtra(SUCCESS, success); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_MUTE_USER)) { Integer userId = intent.getExtras().getInt(USER); boolean success = muteUser(userId); Intent reply = new Intent(ACTION_MUTE_USER_RESULT); reply.putExtra(SUCCESS, success); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_POST_MESSAGE)) { Integer toUser = intent.getExtras().getInt(TO_USER); Integer threadId = intent.getExtras().containsKey(THREAD_ID) ? intent.getExtras().getInt(THREAD_ID) : null; String subject = intent.getExtras().getString(SUBJECT); String body = intent.getExtras().getString(BODY); BetterJSONObject response = postMessage(toUser, threadId, subject, body); Intent reply = new Intent(ACTION_POST_MESSAGE_RESULT); mApp.setServiceResult(ACTION_POST_MESSAGE_RESULT, response); reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_MESSAGES)) { String query = intent.getExtras() != null ? intent.getExtras().getString(QUERY) : null; String box = intent.getExtras() != null ? intent.getExtras().getString(BOX) : null; boolean groupByThreads = intent.getExtras() != null ? intent.getExtras().getBoolean(GROUP_BY_THREADS) : false; Integer messageId = (intent.getExtras() != null && intent.getExtras().containsKey(MESSAGE_ID)) ? intent.getExtras().getInt(MESSAGE_ID) : null; BetterJSONObject messages = getMessages(query, box, groupByThreads, messageId); Intent reply = new Intent(ACTION_MESSAGES_RESULT); mApp.setServiceResult(ACTION_MESSAGES_RESULT, messages); reply.putExtra(IS_SHARED_ON_APP, true); reply.putExtra(QUERY, query); reply.putExtra(MESSAGE_ID, messageId); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_CHECK_LIST)) { int id = intent.getExtras().getInt(CHECK_LIST_ID); SerializableJSONArray checkList = getCheckList(id); Intent reply = new Intent(ACTION_CHECK_LIST_RESULT); reply.putExtra(CHECK_LIST_RESULT, checkList); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_FLAG_OBSERVATION_AS_CAPTIVE)) { int id = intent.getExtras().getInt(OBSERVATION_ID); flagObservationAsCaptive(id); } else if (action.equals(ACTION_GET_NEWS)) { SerializableJSONArray news = getNews(); Intent reply = new Intent(ACTION_NEWS_RESULT); reply.putExtra(RESULTS, news); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_AND_SAVE_OBSERVATION)) { int id = intent.getExtras().getInt(OBSERVATION_ID); Observation observation = getAndDownloadObservation(id); Intent reply = new Intent(ACTION_GET_AND_SAVE_OBSERVATION_RESULT); reply.putExtra(OBSERVATION_RESULT, observation); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_GET_OBSERVATION)) { int id = intent.getExtras().getInt(OBSERVATION_ID); boolean getProjects = intent.getExtras().getBoolean(GET_PROJECTS); JSONObject observationJson = getObservationJson(id, false, getProjects); Intent reply = new Intent(ACTION_OBSERVATION_RESULT); synchronized (mObservationLock) { String jsonString = observationJson != null ? observationJson.toString() : null; Observation observation = observationJson == null ? null : new Observation(new BetterJSONObject(jsonString)); mApp.setServiceResult(ACTION_OBSERVATION_RESULT, observation); mApp.setServiceResult(OBSERVATION_JSON_RESULT, observationJson != null ? jsonString : null); } reply.putExtra(IS_SHARED_ON_APP, true); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } else if (action.equals(ACTION_JOIN_PROJECT)) { int id = intent.getExtras().getInt(PROJECT_ID); joinProject(id); } else if (action.equals(ACTION_LEAVE_PROJECT)) { int id = intent.getExtras().getInt(PROJECT_ID); leaveProject(id); } else if (action.equals(ACTION_PULL_OBSERVATIONS)) { // Download observations without uploading any new ones if (!mIsSyncing && !mApp.getIsSyncing()) { mIsSyncing = true; mApp.setIsSyncing(mIsSyncing); syncRemotelyDeletedObs(); boolean successful = getUserObservations(0); if (successful) { // Update last sync time long lastSync = System.currentTimeMillis(); mPreferences.edit().putLong("last_sync_time", lastSync).commit(); mPreferences.edit().putLong("last_user_details_refresh_time", 0); // Force to refresh user details mPreferences.edit().putLong("last_user_notifications_refresh_time", 0); // Force to refresh user notification counts } else { mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), R.string.could_not_download_observations, Toast.LENGTH_LONG).show(); } }); } } } else if (action.equals(ACTION_DELETE_OBSERVATIONS)) { if (!mIsSyncing && !mApp.getIsSyncing()) { long[] idsToDelete = null; idsToDelete = intent.getExtras().getLongArray(OBS_IDS_TO_DELETE); Logger.tag(TAG).debug("DeleteObservations: Calling delete obs"); mIsSyncing = true; mApp.setIsSyncing(mIsSyncing); deleteObservations(idsToDelete); } else { // Already in middle of syncing dontStopSync = true; } } else if (action.equals(ACTION_SYNC)) { if (!mIsSyncing && !mApp.getIsSyncing()) { long[] idsToSync = null; if (intent.hasExtra(OBS_IDS_TO_SYNC)) { idsToSync = intent.getExtras().getLongArray(OBS_IDS_TO_SYNC); } mIsSyncing = true; mApp.setIsSyncing(mIsSyncing); syncObservations(idsToSync); // Update last sync time long lastSync = System.currentTimeMillis(); mPreferences.edit().putLong("last_sync_time", lastSync).commit(); } else { // Already in middle of syncing dontStopSync = true; } } } catch (IllegalArgumentException e) { // Handle weird exception raised when sendBroadcast causes serialization of BetterJSONObject // and that causes an IllegalArgumentException (see only once). Logger.tag(TAG).error(e); mIsSyncing = false; } catch (CancelSyncException e) { cancelSyncRequested = true; mApp.setCancelSync(false); mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); } catch (SyncFailedException e) { syncFailed = true; mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); } catch (AuthenticationException e) { if (!mPassive) { requestCredentials(); } mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); } finally { mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); if (mIsSyncing && !dontStopSync && (action.equals(ACTION_SYNC) || action.equals(ACTION_FIRST_SYNC) || action.equals(ACTION_PULL_OBSERVATIONS) || action.equals(ACTION_DELETE_OBSERVATIONS))) { mIsSyncing = false; mApp.setIsSyncing(mIsSyncing); Logger.tag(TAG).info("Sending ACTION_SYNC_COMPLETE"); // Notify the rest of the app of the completion of the sync Intent reply = new Intent(ACTION_SYNC_COMPLETE); reply.putExtra(SYNC_CANCELED, cancelSyncRequested); reply.putExtra(SYNC_FAILED, syncFailed); reply.putExtra(FIRST_SYNC, action.equals(ACTION_FIRST_SYNC)); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } } private boolean deletePinnedLocation(String id) throws AuthenticationException { JSONArray result = delete(String.format(Locale.ENGLISH, "%s/saved_locations/%s.json", HOST, id), null); if (result != null) { return true; } else { return false; } } private boolean pinLocation(Double latitude, Double longitude, Double accuracy, String geoprivacy, String title) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("saved_location[latitude]", latitude.toString())); params.add(new BasicNameValuePair("saved_location[longitude]", longitude.toString())); params.add(new BasicNameValuePair("saved_location[positional_accuracy]", accuracy.toString())); params.add(new BasicNameValuePair("saved_location[geoprivacy]", geoprivacy)); params.add(new BasicNameValuePair("saved_location[title]", title)); JSONArray result = post(HOST + "/saved_locations.json", params); if (result != null) { return true; } else { return false; } } private void syncObservations(long[] idsToSync) throws AuthenticationException, CancelSyncException, SyncFailedException { try { Logger.tag(TAG).debug("syncObservations: enter"); JSONObject eventParams = new JSONObject(); eventParams.put(AnalyticsClient.EVENT_PARAM_VIA, mApp.getAutoSync() ? AnalyticsClient.EVENT_VALUE_AUTOMATIC_UPLOAD : AnalyticsClient.EVENT_VALUE_MANUAL_FULL_UPLOAD); Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "is_deleted = 1 AND user_login = '" + mLogin + "'", null, Observation.DEFAULT_SORT_ORDER); eventParams.put(AnalyticsClient.EVENT_PARAM_NUM_DELETES, c.getCount()); Logger.tag(TAG).debug("syncObservations: to be deleted: " + c.getCount()); c.close(); c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "(_updated_at > _synced_at AND _synced_at IS NOT NULL AND user_login = '" + mLogin + "') OR " + "(id IS NULL AND _updated_at > _created_at)", null, Observation.SYNC_ORDER); eventParams.put(AnalyticsClient.EVENT_PARAM_NUM_UPLOADS, c.getCount()); Logger.tag(TAG).debug("syncObservations: uploads: " + c.getCount()); c.close(); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_SYNC_OBS, eventParams); } catch (JSONException e) { Logger.tag(TAG).error(e); } if (idsToSync == null) { mApp.notify(getString(R.string.preparing), getString(R.string.preparing)); Logger.tag(TAG).debug("syncObservations: Calling syncRemotelyDeletedObs"); if (!syncRemotelyDeletedObs()) throw new SyncFailedException(); // First, download remote observations (new/updated) Logger.tag(TAG).debug("syncObservations: Calling getUserObservations"); if (!getUserObservations(0)) throw new SyncFailedException(); Logger.tag(TAG).debug("syncObservations: After calling getUserObservations"); } else { mProjectObservations = new ArrayList<SerializableJSONArray>(); mProjectFieldValues = new Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>>(); } Set<Integer> observationIdsToSync = new HashSet<>(); Cursor c; if (idsToSync != null) { // User chose to sync specific observations only for (long id : idsToSync) { observationIdsToSync.add(Integer.valueOf((int)id)); } Logger.tag(TAG).debug("syncObservations: observationIdsToSync multi-selection: " + observationIdsToSync); } else { // Gather the list of observations that need syncing (because they're new, been updated // or had their photos/project fields updated // Any new/updated observations c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "(_synced_at IS NULL) OR (_updated_at > _synced_at AND _synced_at IS NOT NULL)", null, Observation.DEFAULT_SORT_ORDER); c.moveToFirst(); while (!c.isAfterLast()) { Integer internalId = c.getInt(c.getColumnIndexOrThrow(Observation._ID)); // Make sure observation is not currently being edited by user (split-observation bug) observationIdsToSync.add(internalId); c.moveToNext(); } c.close(); Logger.tag(TAG).debug("syncObservations: observationIdsToSync: " + observationIdsToSync); // Any observation that has new/updated/deleted photos c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(_synced_at IS NULL) OR (_updated_at > _synced_at AND _synced_at IS NOT NULL AND id IS NOT NULL) OR " + "(is_deleted = 1)", null, ObservationPhoto.DEFAULT_SORT_ORDER); c.moveToFirst(); while (!c.isAfterLast()) { int internalObsId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto._OBSERVATION_ID)); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_id = " + internalObsId, null, Observation.DEFAULT_SORT_ORDER); int obsCount = obsc.getCount(); obsc.close(); if (obsCount == 0) { // Observation photo belongs to an observation that no longer exists - delete it int obsPhotoId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto._ID)); Logger.tag(TAG).error("Observation photo " + obsPhotoId + " belongs to an observation that no longer exists: " + internalObsId + " - deleting it"); getContentResolver().delete( ContentUris.withAppendedId(ObservationPhoto.CONTENT_URI, obsPhotoId), null, null); } else { observationIdsToSync.add(internalObsId); } c.moveToNext(); } c.close(); Logger.tag(TAG).debug("syncObservations: observationIdsToSync 2: " + observationIdsToSync); // Any observation that has new/deleted sounds c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "(id IS NULL) OR (is_deleted = 1)", null, ObservationSound.DEFAULT_SORT_ORDER); c.moveToFirst(); while (!c.isAfterLast()) { observationIdsToSync.add(c.getInt(c.getColumnIndexOrThrow(ObservationSound._OBSERVATION_ID))); c.moveToNext(); } c.close(); Logger.tag(TAG).debug("syncObservations: observationIdsToSync 2b: " + observationIdsToSync); // Any observation that has new/updated project fields. c = getContentResolver().query(ProjectFieldValue.CONTENT_URI, ProjectFieldValue.PROJECTION, "(_synced_at IS NULL) OR (_updated_at > _synced_at AND _synced_at IS NOT NULL)", null, ProjectFieldValue.DEFAULT_SORT_ORDER); c.moveToFirst(); while (!c.isAfterLast()) { observationIdsToSync.add(c.getInt(c.getColumnIndexOrThrow(ProjectFieldValue.OBSERVATION_ID))); c.moveToNext(); } c.close(); } Logger.tag(TAG).debug("syncObservations: observationIdsToSync 3: " + observationIdsToSync); List<Integer> obsIdsToRemove = new ArrayList<>(); for (Integer obsId : observationIdsToSync) { c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_id = " + obsId, null, Observation.DEFAULT_SORT_ORDER); if (c.getCount() == 0) { obsIdsToRemove.add(obsId); c.close(); continue; } c.moveToFirst(); if (c.getInt(c.getColumnIndexOrThrow(Observation.IS_DELETED)) == 1) { obsIdsToRemove.add(obsId); } c.close(); } Logger.tag(TAG).debug("syncObservations: obsIdsToRemove: " + obsIdsToRemove); for (Integer obsId : observationIdsToSync) { // Make sure observation is not currently being edited by user (split-observation bug) if (mApp.isObservationCurrentlyBeingEdited(obsId)) { Logger.tag(TAG).error("syncObservations: Observation " + obsId + " is currently being edited - not syncing it"); obsIdsToRemove.add(obsId); } } Logger.tag(TAG).debug("syncObservations: obsIdsToRemove 2: " + obsIdsToRemove); for (Integer obsId : obsIdsToRemove) { observationIdsToSync.remove(obsId); } Logger.tag(TAG).debug("syncObservations: observationIdsToSync: " + observationIdsToSync); c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_id in (" + StringUtils.join(observationIdsToSync, ",") + ")", null, Observation.DEFAULT_SYNC_ORDER); c.moveToFirst(); while (!c.isAfterLast()) { int totalObs = c.getCount(); mApp.notify(getString(R.string.syncing_observations), getResources().getQuantityString( R.plurals.syncing_x_out_of_y_observations, totalObs, (c.getPosition() + 1), totalObs ) ); Observation observation = new Observation(c); // Make sure observation is not currently being edited by user (split-observation bug) if (mApp.isObservationCurrentlyBeingEdited(observation._id)) { Logger.tag(TAG).error("syncObservations: Observation " + observation._id + " is currently being edited - not syncing it"); continue; } mCurrentObservationProgress = 0.0f; mTotalProgressForObservation = getTotalProgressForObservation(observation); increaseProgressForObservation(observation); mApp.setObservationIdBeingSynced(observation._id); Logger.tag(TAG).debug("syncObservations: Syncing " + observation._id + ": " + observation.toString()); if ((observation._synced_at == null) || ((observation._updated_at != null) && (observation._updated_at.after(observation._synced_at))) || (observation.id == null)) { postObservation(observation); increaseProgressForObservation(observation); } Logger.tag(TAG).debug("syncObservations: Finished Syncing " + observation._id + " - now uploading photos"); postPhotos(observation); Logger.tag(TAG).debug("syncObservations: Finished uploading photos " + observation._id); deleteObservationPhotos(observation); // Delete locally-removed observation photos postSounds(observation); Logger.tag(TAG).debug("syncObservations: Finished uploading sounds " + observation._id); deleteObservationSounds(observation); // Delete locally-removed observation sounds syncObservationFields(observation); postProjectObservations(observation); Logger.tag(TAG).debug("syncObservations: Finished delete photos, obs fields and project obs - " + observation._id); c.moveToNext(); } c.close(); if (idsToSync == null) { Logger.tag(TAG).debug("syncObservations: Calling delete obs"); deleteObservations(null); // Delete locally-removed observations Logger.tag(TAG).debug("syncObservations: Calling saveJoinedProj"); // General project data mApp.notify(SYNC_PHOTOS_NOTIFICATION, getString(R.string.projects), getString(R.string.cleaning_up), getString(R.string.syncing)); saveJoinedProjects(); Logger.tag(TAG).debug("syncObservations: Calling storeProjObs"); storeProjectObservations(); redownloadOldObservations(); } Logger.tag(TAG).debug("syncObservations: Done"); mPreferences.edit().putLong("last_user_details_refresh_time", 0); // Force to refresh user details mPreferences.edit().putLong("last_user_notifications_refresh_time", 0); // Force to refresh user notification counts } private int mTotalProgressForObservation = 0; private float mCurrentObservationProgress = 0; private void increaseProgressForObservation(Observation observation) { float currentProgress = mCurrentObservationProgress; float step = (100.0f / mTotalProgressForObservation); float newProgress = currentProgress + step; if (newProgress >= 99) newProgress = 100f; // Round to 100 in case of fractions (since otherwise, we'll get to 99.99999 and similar mCurrentObservationProgress = newProgress; // Notify the client of the new progress (so we'll update the progress bars) Intent reply = new Intent(OBSERVATION_SYNC_PROGRESS); reply.putExtra(OBSERVATION_ID, observation.id); reply.putExtra(OBSERVATION_ID_INTERNAL, observation._id); reply.putExtra(PROGRESS, newProgress); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } // Adds observation UUIDs to photos and sounds that are missing them private void addObservationUUIDsToPhotosAndSounds() { Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, new String[] { ObservationPhoto._OBSERVATION_ID, ObservationPhoto._ID, ObservationPhoto.ID }, "observation_uuid is NULL", null, ObservationPhoto.DEFAULT_SORT_ORDER); int count = c.getCount(); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "addObservationUUIDsToPhotosAndSounds: Adding UUIDs to %d photos", count)); c.moveToFirst(); while (!c.isAfterLast()) { int obsInternalId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto._OBSERVATION_ID)); int obsPhotoId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto.ID)); int obsPhotoInternalId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto._ID)); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, new String[] { Observation.UUID }, "_id = " + obsInternalId, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); String uuid = obsc.getString(obsc.getColumnIndexOrThrow(Observation.UUID)); ContentValues cv = new ContentValues(); cv.put(ObservationPhoto.OBSERVATION_UUID, uuid); // Update its sync at time so we won't update the remote servers later on (since we won't // accidentally consider this an updated record) cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); Uri photoUri = ContentUris.withAppendedId(ObservationPhoto.CONTENT_URI, obsPhotoInternalId); getContentResolver().update(photoUri, cv, null, null); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "addObservationUUIDsToPhotosAndSounds - Adding observation_uuid %s to photo: id = %d; _id: %d", uuid, obsPhotoId, obsPhotoInternalId)); } obsc.close(); c.moveToNext(); } c.close(); c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "observation_uuid is NULL", null, ObservationSound.DEFAULT_SORT_ORDER); count = c.getCount(); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "addObservationUUIDsToPhotosAndSounds: Adding UUIDs to %d sounds", count)); c.moveToFirst(); while (!c.isAfterLast()) { ObservationSound sound = new ObservationSound(c); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, new String[] { Observation.UUID }, "id = " + sound.observation_id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); String uuid = obsc.getString(obsc.getColumnIndexOrThrow(Observation.UUID)); sound.observation_uuid = uuid; ContentValues cv = sound.getContentValues(); getContentResolver().update(sound.getUri(), cv, null, null); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "addObservationUUIDsToPhotosAndSounds - Adding observation_uuid %s to sound: %s", uuid, sound)); } obsc.close(); c.moveToNext(); } c.close(); } private BetterJSONObject getMinimalIdentificationResults(BetterJSONObject results) { if (results == null) return null; SerializableJSONArray innerResults = results.getJSONArray("results"); if (innerResults == null) return null; JSONArray identificationResults = innerResults.getJSONArray(); if (identificationResults != null) { JSONArray minimizedResults = new JSONArray(); for (int i = 0; i < identificationResults.length(); i++) { JSONObject item = identificationResults.optJSONObject(i); minimizedResults.put(getMinimalIdentification(item)); } results.put("results", minimizedResults); } return results; } private BetterJSONObject getMinimalObserverResults(BetterJSONObject results) { if (results == null) return null; SerializableJSONArray innerResults = results.getJSONArray("results"); if (innerResults == null) return null; JSONArray observerResults = innerResults.getJSONArray(); if (observerResults != null) { JSONArray minimizedResults = new JSONArray(); for (int i = 0; i < observerResults.length(); i++) { JSONObject item = observerResults.optJSONObject(i); minimizedResults.put(getMinimalObserver(item)); } results.put("results", minimizedResults); } return results; } private BetterJSONObject getMinimalSpeciesResults(BetterJSONObject results) { if (results == null) return null; SerializableJSONArray innerResults = results.getJSONArray("results"); if (innerResults == null) return null; // Minimize results - save only basic info for each observation (better memory usage) JSONArray speciesResults = innerResults.getJSONArray(); JSONArray minimizedResults = new JSONArray(); if (speciesResults != null) { for (int i = 0; i < speciesResults.length(); i++) { JSONObject item = speciesResults.optJSONObject(i); minimizedResults.put(getMinimalSpecies(item)); } results.put("results", minimizedResults); } return results; } private BetterJSONObject getMinimalObservationResults(BetterJSONObject results) { if (results == null) return null; SerializableJSONArray innerResults = results.getJSONArray("results"); if (innerResults == null) return null; // Minimize results - save only basic info for each observation (better memory usage) JSONArray observationResults = innerResults.getJSONArray(); JSONArray minimizedObservations = new JSONArray(); if (observationResults != null) { for (int i = 0; i < observationResults.length(); i++) { JSONObject item = observationResults.optJSONObject(i); minimizedObservations.put(getMinimalObservation(item)); } results.put("results", minimizedObservations); } return results; } // Returns a minimal version of an observation JSON (used to lower memory usage) private JSONObject getMinimalObservation(JSONObject observation) { JSONObject minimaldObs = new JSONObject(); try { minimaldObs.put("id", observation.optInt("id")); minimaldObs.put("quality_grade", observation.optString("quality_grade")); if (observation.has("observed_on") && !observation.isNull("observed_on")) minimaldObs.put("observed_on", observation.optString("observed_on")); if (observation.has("time_observed_at") && !observation.isNull("time_observed_at")) minimaldObs.put("time_observed_at", observation.optString("time_observed_at")); if (observation.has("species_guess") && !observation.isNull("species_guess")) minimaldObs.put("species_guess", observation.optString("species_guess")); if (observation.has("place_guess") && !observation.isNull("place_guess")) minimaldObs.put("place_guess", observation.optString("place_guess")); if (observation.has("latitude") && !observation.isNull("latitude")) minimaldObs.put("latitude", observation.optString("latitude")); if (observation.has("longitude") && !observation.isNull("longitude")) minimaldObs.put("longitude", observation.optString("longitude")); if (observation.has("observed_on") && !observation.isNull("observed_on")) minimaldObs.put("observed_on", observation.optString("observed_on")); if (observation.has("comments_count") && !observation.isNull("comments_count")) minimaldObs.put("comments_count", observation.optInt("comments_count")); if (observation.has("identifications_count") && !observation.isNull("identifications_count")) minimaldObs.put("identifications_count", observation.optInt("identifications_count")); minimaldObs.put("taxon", getMinimalTaxon(observation.optJSONObject("taxon"))); if (observation.has("iconic_taxon_name")) minimaldObs.put("iconic_taxon_name", observation.optString("iconic_taxon_name")); if (observation.has("observation_photos") && !observation.isNull("observation_photos")) { JSONArray minimalObsPhotos = new JSONArray(); JSONArray obsPhotos = observation.optJSONArray("observation_photos"); for (int i = 0; i < obsPhotos.length(); i++) { minimalObsPhotos.put(getMinimalPhoto(obsPhotos.optJSONObject(i))); } minimaldObs.put("observation_photos", minimalObsPhotos); } if (observation.has("sounds") && !observation.isNull("sounds")) { JSONArray minimalObsSounds = new JSONArray(); JSONArray obsSounds = observation.optJSONArray("sounds"); for (int i = 0; i < obsSounds.length(); i++) { minimalObsSounds.put(getMinimalSound(obsSounds.optJSONObject(i))); } minimaldObs.put("sounds", minimalObsSounds); } if (observation.has("user")) { JSONObject user = observation.optJSONObject("user"); minimaldObs.put("user", getMinimalUser(user)); } } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimaldObs; } // Returns a minimal version of an identification JSON (used to lower memory usage) private JSONObject getMinimalIdentification(JSONObject identification) { JSONObject minimalObserver = new JSONObject(); if (identification == null) return null; try { if (identification.has("observation")) minimalObserver.put("observation", getMinimalObservation(identification.optJSONObject("observation"))); if (identification.has("taxon")) minimalObserver.put("taxon", getMinimalTaxon(identification.optJSONObject("taxon"))); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalObserver; } // Returns a minimal version of an observer JSON (used to lower memory usage) private JSONObject getMinimalObserver(JSONObject observer) { JSONObject minimalObserver = new JSONObject(); if (observer == null) return null; try { if (observer.has("observation_count")) minimalObserver.put("observation_count", observer.optInt("observation_count")); if (observer.has("count")) minimalObserver.put("count", observer.optInt("count")); if (observer.has("user")) { JSONObject user = observer.optJSONObject("user"); minimalObserver.put("user", getMinimalUser(user)); } } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalObserver; } // Returns a minimal version of a user JSON (used to lower memory usage) private JSONObject getMinimalUser(JSONObject user) { JSONObject minimalUser = new JSONObject(); if (user == null) return null; try { minimalUser.put("login", user.optString("login")); minimalUser.put("icon_url", user.optString("icon_url")); if (user.has("observations_count")) minimalUser.put("observations_count", user.optInt("observations_count")); if (user.has("identifications_count")) minimalUser.put("identifications_count", user.optInt("identifications_count")); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalUser; } // Returns a minimal version of a species JSON (used to lower memory usage) private JSONObject getMinimalSpecies(JSONObject species) { JSONObject minimalSpecies = new JSONObject(); if (species == null) return null; try { minimalSpecies.put("count", species.optInt("count")); minimalSpecies.put("taxon", getMinimalTaxon(species.optJSONObject("taxon"))); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalSpecies; } // Returns a minimal version of a sound JSON (used to lower memory usage) private JSONObject getMinimalSound(JSONObject sound) { JSONObject minimalSound = new JSONObject(); if (sound == null) return null; try { minimalSound.put("id", sound.optInt("id")); minimalSound.put("file_url", sound.optString("file_url")); minimalSound.put("file_content_type", sound.optString("file_content_type")); minimalSound.put("attribution", sound.optString("attribution")); minimalSound.put("subtype", sound.optString("subtype")); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalSound; } // Returns a minimal version of a photo JSON (used to lower memory usage) private JSONObject getMinimalPhoto(JSONObject photo) { JSONObject minimalPhoto = new JSONObject(); if (photo == null) return null; try { minimalPhoto.put("id", photo.optInt("id")); minimalPhoto.put("position", photo.optInt("position")); if (photo.has("photo") && !photo.isNull("photo")) { JSONObject innerPhoto = new JSONObject(); innerPhoto.put("id", photo.optJSONObject("photo").optInt("id")); innerPhoto.put("url", photo.optJSONObject("photo").optString("url")); minimalPhoto.put("photo", innerPhoto); } } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalPhoto; } // Returns a minimal version of a taxon JSON (used to lower memory usage) private JSONObject getMinimalTaxon(JSONObject taxon) { JSONObject minimalTaxon = new JSONObject(); if (taxon == null) return null; try { minimalTaxon.put("id", taxon.optInt("id")); minimalTaxon.put("name", taxon.optString("name")); minimalTaxon.put("rank", taxon.optString("rank")); minimalTaxon.put("rank_level", taxon.optInt("rank_level")); minimalTaxon.put("iconic_taxon_name", taxon.optString("iconic_taxon_name")); if (taxon.has("taxon_names")) minimalTaxon.put("taxon_names", taxon.optJSONArray("taxon_names")); if (taxon.has("default_name")) minimalTaxon.put("default_name", taxon.optJSONObject("default_name")); if (taxon.has("common_name")) minimalTaxon.put("common_name", taxon.optJSONObject("common_name")); if (taxon.has("preferred_common_name")) minimalTaxon.put("preferred_common_name", taxon.optString("preferred_common_name")); if (taxon.has("english_common_name")) minimalTaxon.put("english_common_name", taxon.optString("english_common_name")); if (taxon.has("observations_count")) minimalTaxon.put("observations_count", taxon.optInt("observations_count")); if (taxon.has("default_photo") && !taxon.isNull("default_photo")) { JSONObject minimalPhoto = new JSONObject(); JSONObject defaultPhoto = taxon.optJSONObject("default_photo"); if (defaultPhoto.has("medium_url") && !defaultPhoto.isNull("medium_url")) { minimalPhoto.put("medium_url", defaultPhoto.optString("medium_url")); } else { minimalPhoto.put("photo_url", defaultPhoto.optString("photo_url")); } minimalTaxon.put("default_photo", minimalPhoto); } } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } return minimalTaxon; } private int getTotalProgressForObservation(Observation observation) { int obsCount = 0; if ((observation._synced_at == null) || ((observation._updated_at != null) && (observation._updated_at.after(observation._synced_at)))) { obsCount = 1; } int photoCount; int externalObsId = observation.id != null ? observation.id : observation._id; Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "((_synced_at IS NULL) OR (_updated_at > _synced_at AND _synced_at IS NOT NULL AND id IS NOT NULL) OR (is_deleted = 1)) AND " + "((observation_id = ?) OR (_observation_id = ?))", new String[]{String.valueOf(externalObsId), String.valueOf(observation._id)}, ObservationPhoto.DEFAULT_SORT_ORDER); photoCount = c.getCount(); c.close(); int projectFieldCount; c = getContentResolver().query(ProjectFieldValue.CONTENT_URI, ProjectFieldValue.PROJECTION, "((_synced_at IS NULL) OR (_updated_at > _synced_at AND _synced_at IS NOT NULL)) AND " + "((observation_id = ?) OR (observation_id = ?))", new String[]{String.valueOf(externalObsId), String.valueOf(observation._id)}, ProjectFieldValue.DEFAULT_SORT_ORDER); projectFieldCount = c.getCount(); c.close(); int projectObservationCount; c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "((is_deleted = 1) OR (is_new = 1)) AND " + "((observation_id = ?) OR (observation_id = ?))", new String[]{String.valueOf(externalObsId), String.valueOf(observation._id)}, ProjectObservation.DEFAULT_SORT_ORDER); projectObservationCount = c.getCount(); c.close(); int soundCount; c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "((is_deleted = 1) OR (id is NULL)) AND " + "((observation_id = ?) OR (_observation_id = ?))", new String[]{String.valueOf(externalObsId), String.valueOf(observation._id)}, ObservationSound.DEFAULT_SORT_ORDER); soundCount = c.getCount(); c.close(); return 1 + // We start off with some progress (one "part") obsCount + // For the observation upload itself (only if new/update) photoCount + // For photos soundCount + // For sounds projectFieldCount + // For updated/new obs project fields projectObservationCount; // For updated/new observation project fields } // Re-download old local observations and update their taxon names (preferred common names) - used when user switches language private void redownloadOldObservationsForTaxonNames() throws AuthenticationException { // Get most recent observation Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "(id IS NOT NULL)", null, "id DESC"); c.moveToFirst(); if (c.getCount() == 0) { c.close(); return; } Integer currentObsId = c.getInt(c.getColumnIndexOrThrow(Observation.ID)) + 1; c.moveToLast(); Integer lastObsId = c.getInt(c.getColumnIndexOrThrow(Observation.ID)); c.close(); JSONArray results = null; int obsCount = 0; do { Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames: " + currentObsId); String url = API_HOST + "/observations?user_id=" + Uri.encode(mLogin) + "&per_page=100&id_below=" + currentObsId; Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); url += "&locale=" + deviceLanguage; JSONArray json = get(url, true); Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames - downloaded"); if (json == null || json.length() == 0) { break; } Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames - downloaded 2"); results = json.optJSONObject(0).optJSONArray("results"); Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames - downloaded 3"); for (int i = 0; i < results.length(); i++) { JSONObject currentObs = results.optJSONObject(i); int currentId = currentObs.optInt("id"); c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = ?", new String[]{String.valueOf(currentId)}, Observation.DEFAULT_SORT_ORDER); Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames - Updating taxon details for obs: " + currentId); if (c.getCount() == 0) { c.close(); continue; } // Update current observation's taxon preferred common name Observation obs = new Observation(c); c.close(); obs.setPreferredCommonName(currentObs); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "redownloadOldObservationsForTaxonNames - Common name for observation %d: %s", currentId, obs.preferred_common_name)); ContentValues cv = obs.getContentValues(); if (!obs._updated_at.after(obs._synced_at)) { // Update its sync at time so we won't update the remote servers later on (since we won't // accidentally consider this an updated record) cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); } getContentResolver().update(obs.getUri(), cv, null, null); currentObsId = obs.id; obsCount++; if (obsCount > MAX_OBSVERATIONS_TO_REDOWNLOAD) break; } } while ((results.length() > 0) && (currentObsId > lastObsId) && (obsCount <= MAX_OBSVERATIONS_TO_REDOWNLOAD)); Logger.tag(TAG).debug("redownloadOldObservationsForTaxonNames - finished"); mApp.setLastLocale(); } // Re-download any observations that have photos saved in the "old" way private void redownloadOldObservations() throws AuthenticationException { // Find all observations that have photos saved in the old way Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(photo_filename IS NULL) AND (photo_url IS NULL)", null, ObservationPhoto.DEFAULT_SORT_ORDER); c.moveToFirst(); Logger.tag(TAG).debug("redownloadOldObservations: " + c.getCount()); while (!c.isAfterLast()) { Integer obsId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto.OBSERVATION_ID)); Logger.tag(TAG).debug("redownloadOldObservations: " + new ObservationPhoto(c)); // Delete the observation photo Integer obsPhotoId = c.getInt(c.getColumnIndexOrThrow(ObservationPhoto.ID)); getContentResolver().delete(ObservationPhoto.CONTENT_URI, "id = " + obsPhotoId, null); // Re-download this observation String url = HOST + "/observations/" + Uri.encode(mLogin) + ".json?extra=observation_photos,projects,fields"; Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); url += "&locale=" + deviceLanguage; JSONArray json = get(url, true); if (json != null && json.length() > 0) { syncJson(json, true); } c.moveToNext(); } c.close(); } private BetterJSONObject getHistogram(int taxonId, boolean researchGrade) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/observations/histogram?taxon_id=%d&", API_HOST, taxonId); if (researchGrade) { url += "quality_grade=research"; } else { url += "verifiable=true"; } JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getPopularFieldValues(int taxonId) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/observations/popular_field_values?taxon_id=%d&verifiable=true", API_HOST, taxonId); JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getTaxonSuggestions(String photoFilename, Double latitude, Double longitude, Timestamp observedOn) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String date = observedOn != null ? new SimpleDateFormat("yyyy-MM-dd").format(observedOn) : null; ArrayList<NameValuePair> params = new ArrayList<>(); String url = String.format(Locale.ENGLISH, API_HOST + "/computervision/score_image"); params.add(new BasicNameValuePair("locale", deviceLanguage)); params.add(new BasicNameValuePair("lat", latitude.toString())); params.add(new BasicNameValuePair("lng", longitude.toString())); if (date != null) params.add(new BasicNameValuePair("observed_on", date)); params.add(new BasicNameValuePair("image", photoFilename)); JSONArray json = request(url, "post", params, null, true, true, true); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); if (!res.has("results")) return null; return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getTaxonNew(int id) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/taxa/" + id + "?locale=" + deviceLanguage; JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); if (!res.has("results")) return null; JSONObject taxon = res.getJSONArray("results").getJSONObject(0); return new BetterJSONObject(taxon); } catch (JSONException e) { return null; } } private BetterJSONObject setAnnotationValue(int observationId, int attributeId, int valueId) throws AuthenticationException { String url = API_HOST + "/annotations"; JSONObject params = new JSONObject(); try { params.put("resource_type", "Observation"); params.put("resource_id", observationId); params.put("controlled_attribute_id", attributeId); params.put("controlled_value_id", valueId); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } JSONArray json = post(url, params); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject agreeAnnotation(String uuid, boolean agree) throws AuthenticationException { String url = API_HOST + "/votes/vote/annotation/" + uuid; JSONObject params = new JSONObject(); try { if (!agree) params.put("vote", "bad"); params.put("id", uuid); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } JSONArray json = post(url, params); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject deleteAnnotationVote(String uuid) throws AuthenticationException { String url = API_HOST + "/votes/unvote/annotation/" + uuid; JSONArray json = delete(url, null); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject voteIdCanBeImproved(int obsId, boolean yes) throws AuthenticationException { String url = API_HOST + "/votes/vote/observation/" + obsId; JSONObject params = new JSONObject(); try { params.put("vote", yes ? "yes" : "no"); params.put("id", obsId); params.put("scope", "needs_id"); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } JSONArray json = post(url, params); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject deleteIdCanBeImprovedVote(int obsId) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/votes/unvote/observation/%d?id=%d&scope=needs_id", API_HOST, obsId, obsId); JSONArray json = delete(url, null); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getDataQualityMetrics(Integer observationId) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/observations/%d/quality_metrics?id=%d", API_HOST, observationId, observationId); JSONArray json = get(url, true); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); if (!res.has("results")) return null; return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject agreeDataQualityMetric(Integer observationId, String metric, boolean agree) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/observations/%d/quality/%s", API_HOST, observationId, metric); JSONObject params = new JSONObject(); try { params.put("agree", agree ? "true" : "false"); params.put("id", observationId); params.put("metric", metric); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } JSONArray json = post(url, params); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject deleteDataQualityMetricVote(Integer observationId, String metric) throws AuthenticationException { String url = String.format(Locale.ENGLISH, "%s/observations/%d/quality/%s?id=%d&metric=%s", API_HOST, observationId, metric, observationId, metric); JSONArray json = delete(url, null); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject deleteAnnotation(String uuid) throws AuthenticationException { String url = API_HOST + "/annotations/" + uuid; JSONArray json = delete(url, null); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getAllAttributes() throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/controlled_terms?locale=" + deviceLanguage; JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); if (!res.has("results")) return null; return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getAttributesForTaxon(JSONObject taxon) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); JSONArray ancestors = taxon != null ? taxon.optJSONArray("ancestor_ids") : null; String url; if (ancestors != null) { String ancestry = ""; for (int i = 0; i < ancestors.length(); i++) { int currentTaxonId = ancestors.optInt(i); ancestry += String.format(Locale.ENGLISH, "%d,", currentTaxonId); } ancestry += String.format(Locale.ENGLISH, "%d", taxon.optInt("id")); url = API_HOST + "/controlled_terms/for_taxon?taxon_id=" + ancestry + "&ttl=-1&locale=" + deviceLanguage; } else { url = API_HOST + "/controlled_terms?ttl=-1&locale=" + deviceLanguage; } JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); if (!res.has("results")) return null; return new BetterJSONObject(res); } catch (JSONException e) { return null; } } private BetterJSONObject getTaxon(int id) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = String.format(Locale.ENGLISH, "%s/taxa/%d.json?locale=%s", HOST, id, deviceLanguage); JSONArray json = get(url); if (json == null || json.length() == 0) { return null; } JSONObject res; try { res = (JSONObject) json.get(0); } catch (JSONException e) { return null; } return new BetterJSONObject(res); } private boolean postProjectObservations(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { if (observation.id == null) { // Observation not synced yet - cannot sync its project associations yet return true; } // First, delete any project-observations that were deleted by the user Cursor c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "is_deleted = 1 AND observation_id = ?", new String[]{String.valueOf(observation.id)}, ProjectObservation.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { checkForCancelSync(); ProjectObservation projectObservation = new ProjectObservation(c); // Clean the errors for the observation mApp.setErrorsForObservation(projectObservation.observation_id, projectObservation.project_id, new JSONArray()); try { // Remove obs from project BetterJSONObject result = removeObservationFromProject(projectObservation.observation_id, projectObservation.project_id); if (result == null) { c.close(); throw new SyncFailedException(); } increaseProgressForObservation(observation); } catch (Exception exc) { // In case we're trying to delete a project-observation that wasn't synced yet c.close(); throw new SyncFailedException(); } getContentResolver().delete(ProjectObservation.CONTENT_URI, "_id = ?", new String[]{String.valueOf(projectObservation._id)}); c.moveToNext(); } c.close(); // Next, add new project observations c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "is_new = 1 AND observation_id = ?", new String[]{String.valueOf(observation.id)}, ProjectObservation.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { checkForCancelSync(); ProjectObservation projectObservation = new ProjectObservation(c); BetterJSONObject result = addObservationToProject(projectObservation.observation_id, projectObservation.project_id); if ((result == null) && (mResponseErrors == null)) { c.close(); throw new SyncFailedException(); } increaseProgressForObservation(observation); if (mResponseErrors != null) { handleProjectFieldErrors(projectObservation.observation_id, projectObservation.project_id); } else { // Unmark as new projectObservation.is_new = false; ContentValues cv = projectObservation.getContentValues(); getContentResolver().update(projectObservation.getUri(), cv, null, null); // Clean the errors for the observation mApp.setErrorsForObservation(projectObservation.observation_id, projectObservation.project_id, new JSONArray()); } c.moveToNext(); } c.close(); return true; } private boolean postProjectObservations() throws AuthenticationException, CancelSyncException, SyncFailedException { // First, delete any project-observations that were deleted by the user Cursor c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "is_deleted = 1", null, ProjectObservation.DEFAULT_SORT_ORDER); if (c.getCount() > 0) { mApp.notify(SYNC_PHOTOS_NOTIFICATION, getString(R.string.projects), getString(R.string.syncing_observation_fields), getString(R.string.syncing)); } c.moveToFirst(); while (c.isAfterLast() == false) { checkForCancelSync(); ProjectObservation projectObservation = new ProjectObservation(c); // Clean the errors for the observation mApp.setErrorsForObservation(projectObservation.observation_id, projectObservation.project_id, new JSONArray()); try { // Remove obs from project BetterJSONObject result = removeObservationFromProject(projectObservation.observation_id, projectObservation.project_id); if (result == null) { c.close(); throw new SyncFailedException(); } } catch (Exception exc) { // In case we're trying to delete a project-observation that wasn't synced yet c.close(); throw new SyncFailedException(); } c.moveToNext(); } c.close(); // Now it's safe to delete all of the project-observations locally getContentResolver().delete(ProjectObservation.CONTENT_URI, "is_deleted = 1", null); // Next, add new project observations c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "is_new = 1", null, ProjectObservation.DEFAULT_SORT_ORDER); if (c.getCount() > 0) { mApp.notify(SYNC_PHOTOS_NOTIFICATION, getString(R.string.projects), getString(R.string.syncing_observation_fields), getString(R.string.syncing)); } c.moveToFirst(); while (c.isAfterLast() == false) { checkForCancelSync(); ProjectObservation projectObservation = new ProjectObservation(c); BetterJSONObject result = addObservationToProject(projectObservation.observation_id, projectObservation.project_id); if ((result == null) && (mResponseErrors == null)) { c.close(); throw new SyncFailedException(); } mApp.setObservationIdBeingSynced(projectObservation.observation_id); if (mResponseErrors != null) { handleProjectFieldErrors(projectObservation.observation_id, projectObservation.project_id); } else { // Unmark as new projectObservation.is_new = false; ContentValues cv = projectObservation.getContentValues(); getContentResolver().update(projectObservation.getUri(), cv, null, null); // Clean the errors for the observation mApp.setErrorsForObservation(projectObservation.observation_id, projectObservation.project_id, new JSONArray()); } c.moveToNext(); } c.close(); mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); // Finally, retrieve all project observations storeProjectObservations(); return true; } private boolean handleProjectFieldErrors(int observationId, int projectId) { SerializableJSONArray errors = new SerializableJSONArray(mResponseErrors); // Couldn't add the observation to the project (probably didn't pass validation) String error; try { error = errors.getJSONArray().getString(0); } catch (JSONException e) { return false; } Cursor c2 = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = '" + observationId + "'", null, Observation.DEFAULT_SORT_ORDER); c2.moveToFirst(); if (c2.getCount() == 0) { c2.close(); return false; } Observation observation = new Observation(c2); c2.close(); c2 = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = '" + projectId + "'", null, Project.DEFAULT_SORT_ORDER); c2.moveToFirst(); if (c2.getCount() == 0) { c2.close(); return false; } Project project = new Project(c2); c2.close(); // Remember the errors for this observation (to be shown in the observation editor screen) JSONArray formattedErrors = new JSONArray(); JSONArray unformattedErrors = errors.getJSONArray(); for (int i = 0; i < unformattedErrors.length(); i++) { try { formattedErrors.put(String.format(Locale.ENGLISH, getString(R.string.failed_to_add_to_project), project.title, unformattedErrors.getString(i))); } catch (JSONException e) { Logger.tag(TAG).error(e); } } mApp.setErrorsForObservation(observation.id, project.id, formattedErrors); final String errorMessage = String.format(Locale.ENGLISH, getString(R.string.failed_to_add_obs_to_project), observation.species_guess == null ? getString(R.string.unknown) : observation.species_guess, project.title, error); // Display toast in this main thread handler (since otherwise it won't get displayed) mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_LONG).show(); } }); try { JSONObject eventParams = new JSONObject(); eventParams.put(AnalyticsClient.EVENT_PARAM_ALERT, errorMessage); AnalyticsClient.getInstance().logEvent(AnalyticsClient.EVENT_NAME_SYNC_FAILED, eventParams); } catch (JSONException e) { Logger.tag(TAG).error(e); } return true; } private void storeProjectObservations() { for (int j = 0; j < mProjectObservations.size(); j++) { SerializableJSONArray arr = mProjectObservations.get(j); if (arr == null) continue; JSONArray projectObservations = mProjectObservations.get(j).getJSONArray(); for (int i = 0; i < projectObservations.length(); i++) { JSONObject jsonProjectObservation; try { jsonProjectObservation = projectObservations.getJSONObject(i); ProjectObservation projectObservation = new ProjectObservation(new BetterJSONObject(jsonProjectObservation)); ContentValues cv = projectObservation.getContentValues(); Cursor c = getContentResolver().query(ProjectObservation.CONTENT_URI, ProjectObservation.PROJECTION, "project_id = " + projectObservation.project_id + " AND observation_id = " + projectObservation.observation_id, null, ProjectObservation.DEFAULT_SORT_ORDER); if (c.getCount() == 0) { getContentResolver().insert(ProjectObservation.CONTENT_URI, cv); } c.close(); } catch (JSONException e) { Logger.tag(TAG).error(e); } } } } private boolean deleteAccount() throws AuthenticationException { String username = mApp.currentUserLogin(); JSONArray result = delete( String.format(Locale.ENGLISH, "%s/users/%s.json?confirmation_code=%s&confirmation=%s", HOST, username, username, username), null); if (result == null) { Logger.tag(TAG).debug("deleteAccount error: " + mLastStatusCode); return false; } return true; } private boolean saveJoinedProjects() throws AuthenticationException, CancelSyncException, SyncFailedException { SerializableJSONArray projects = getJoinedProjects(); checkForCancelSync(); if (projects == null) { throw new SyncFailedException(); } JSONArray arr = projects.getJSONArray(); // Retrieve all currently-joined project IDs List<Integer> projectIds = new ArrayList<Integer>(); HashMap<Integer, JSONObject> projectByIds = new HashMap<Integer, JSONObject>(); for (int i = 0; i < arr.length(); i++) { try { JSONObject jsonProject = arr.getJSONObject(i); int id = jsonProject.getInt("id"); projectIds.add(id); projectByIds.put(id, jsonProject); } catch (JSONException exc) { Logger.tag(TAG).error(exc); } } // Check which projects were un-joined and remove them locally try { int count = getContentResolver().delete(Project.CONTENT_URI, "id not in (" + StringUtils.join(projectIds, ',') + ")", null); } catch (Exception exc) { Logger.tag(TAG).error(exc); throw new SyncFailedException(); } // Add any newly-joined projects for (Map.Entry<Integer, JSONObject> entry : projectByIds.entrySet()) { int id = entry.getKey(); JSONObject jsonProject = entry.getValue(); Cursor c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = ?", new String[]{String.valueOf(id)}, null); if (c.getCount() == 0) { Project project = new Project(new BetterJSONObject(jsonProject)); ContentValues cv = project.getContentValues(); getContentResolver().insert(Project.CONTENT_URI, cv); } c.close(); } return true; } private boolean deleteObservationSounds(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { // Remotely delete any locally-removed observation sounds Cursor c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "is_deleted = 1 AND _observation_id = ?", new String[]{String.valueOf(observation._id)}, ObservationSound.DEFAULT_SORT_ORDER); String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); // for each observation DELETE to /sounds/:id c.moveToFirst(); while (c.isAfterLast() == false) { ObservationSound os = new ObservationSound(c); Logger.tag(TAG).debug("deleteObservationSounds: " + os); if (os.id != null) { Logger.tag(TAG).debug("deleteObservationSounds: Deleting " + os); JSONArray result = delete(inatHost + "/observation_sounds/" + os.id + ".json", null); if (result == null) { Logger.tag(TAG).debug("deleteObservationSounds: Deletion error: " + mLastStatusCode); if (mLastStatusCode != HttpStatus.SC_NOT_FOUND) { // Ignore the case where the sound was remotely deleted Logger.tag(TAG).debug("deleteObservationSounds: Not a 404 error"); c.close(); throw new SyncFailedException(); } } } increaseProgressForObservation(observation); int count = getContentResolver().delete(ObservationSound.CONTENT_URI, "id = ? or _id = ?", new String[]{String.valueOf(os.id), String.valueOf(os._id)}); Logger.tag(TAG).debug("deleteObservationSounds: Deleted from DB: " + count); c.moveToNext(); } c.close(); checkForCancelSync(); return true; } private boolean deleteObservationPhotos(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { // Remotely delete any locally-removed observation photos Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "is_deleted = 1 AND _observation_id = ?", new String[]{String.valueOf(observation._id)}, ObservationPhoto.DEFAULT_SORT_ORDER); // for each observation DELETE to /observation_photos/:id c.moveToFirst(); while (c.isAfterLast() == false) { ObservationPhoto op = new ObservationPhoto(c); Logger.tag(TAG).debug("deleteObservationPhotos: " + op + "::::" + op._synced_at); if (op._synced_at != null) { if (op.id != null) { Logger.tag(TAG).debug("deleteObservationPhotos: Deleting " + op); JSONArray result = delete(HOST + "/observation_photos/" + op.id + ".json", null); if (result == null) { Logger.tag(TAG).debug("deleteObservationPhotos: Deletion error: " + mLastStatusCode); if (mLastStatusCode != HttpStatus.SC_NOT_FOUND) { // Ignore the case where the photo was remotely deleted Logger.tag(TAG).debug("deleteObservationPhotos: Not a 404 error"); c.close(); throw new SyncFailedException(); } } } } increaseProgressForObservation(observation); int count = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "id = ? or _id = ?", new String[]{String.valueOf(op.id), String.valueOf(op._id)}); Logger.tag(TAG).debug("deleteObservationPhotos: Deleted from DB: " + count); c.moveToNext(); } c.close(); checkForCancelSync(); return true; } private boolean deleteObservations(long[] idsToDelete) throws AuthenticationException, CancelSyncException, SyncFailedException { Cursor c; if (idsToDelete != null) { // Remotely delete selected observations only c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_id in (" + StringUtils.join(ArrayUtils.toObject(idsToDelete), ",") + ")", null, Observation.DEFAULT_SORT_ORDER); } else { // Remotely delete any locally-removed observations (marked for deletion) c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "is_deleted = 1", null, Observation.DEFAULT_SORT_ORDER); } Logger.tag(TAG).debug("deleteObservations: Deleting " + c.getCount()); if (c.getCount() > 0) { mApp.notify(getString(R.string.deleting_observations), getString(R.string.deleting_observations)); } // for each observation DELETE to /observations/:id ArrayList<Integer> obsIds = new ArrayList<Integer>(); ArrayList<String> obsUUIDs = new ArrayList<String>(); ArrayList<Integer> internalObsIds = new ArrayList<Integer>(); c.moveToFirst(); while (c.isAfterLast() == false) { Observation observation = new Observation(c); Logger.tag(TAG).debug("deleteObservations: Deleting " + observation); JSONArray results = delete(HOST + "/observations/" + observation.id + ".json", null); if (results == null) { c.close(); throw new SyncFailedException(); } obsIds.add(observation.id); obsUUIDs.add('"' + observation.uuid + '"'); internalObsIds.add(observation._id); c.moveToNext(); } Logger.tag(TAG).debug("deleteObservations: Deleted IDs: " + obsIds); c.close(); // Now it's safe to delete all of the observations locally getContentResolver().delete(Observation.CONTENT_URI, "is_deleted = 1", null); // Delete associated project-fields and photos int count1 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_id in (" + StringUtils.join(obsIds, ",") + ")", null); int count2 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_uuid in (" + StringUtils.join(obsUUIDs, ",") + ")", null); int count3 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_id in (" + StringUtils.join(obsIds, ",") + ")", null); int count4 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_uuid in (" + StringUtils.join(obsUUIDs, ",") + ")", null); int count5 = getContentResolver().delete(ProjectObservation.CONTENT_URI, "observation_id in (" + StringUtils.join(obsIds, ",") + ")", null); int count6 = getContentResolver().delete(ProjectFieldValue.CONTENT_URI, "observation_id in (" + StringUtils.join(obsIds, ",") + ")", null); int count7 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "_observation_id in (" + StringUtils.join(internalObsIds, ",") + ")", null); int count8 = getContentResolver().delete(ObservationSound.CONTENT_URI, "_observation_id in (" + StringUtils.join(internalObsIds, ",") + ")", null); Logger.tag(TAG).debug("deleteObservations: " + count1 + ":" + count2 + ":" + count3 + ":" + count4 + ":" + count5 + ":" + count6 + ":" + count7 + ":" + count8); checkForCancelSync(); return true; } private void checkForCancelSync() throws CancelSyncException { if (mApp.getCancelSync()) throw new CancelSyncException(); } private JSONObject removeFavorite(int observationId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); JSONArray result = delete(HOST + "/votes/unvote/observation/" + observationId + ".json", null); if (result != null) { try { return result.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } else { return null; } } private JSONObject addFavorite(int observationId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); JSONArray result = post(HOST + "/votes/vote/observation/" + observationId + ".json", (JSONObject) null); if (result != null) { try { return result.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } else { return null; } } private JSONObject agreeIdentification(int observationId, int taxonId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("identification[observation_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("identification[taxon_id]", new Integer(taxonId).toString())); JSONArray result = post(HOST + "/identifications.json", params); if (result != null) { try { return result.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } else { return null; } } private JSONObject removeIdentification(int identificationId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); JSONArray result = delete(HOST + "/identifications/" + identificationId + ".json", null); if (result != null) { try { return result.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } else { return null; } } private void setUserViewedUpdate(int obsId) throws AuthenticationException { put(HOST + "/observations/" + obsId + "/viewed_updates", (JSONObject) null); } private void restoreIdentification(int identificationId) throws AuthenticationException { JSONObject paramsJson = new JSONObject(); JSONObject paramsJsonIdentification = new JSONObject(); try { paramsJsonIdentification.put("current", true); paramsJson.put("identification", paramsJsonIdentification); JSONArray arrayResult = put(API_HOST + "/identifications/" + identificationId, paramsJson); } catch (JSONException e) { Logger.tag(TAG).error(e); } } private void updateIdentification(int observationId, int identificationId, int taxonId, String body) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("identification[observation_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("identification[taxon_id]", new Integer(taxonId).toString())); params.add(new BasicNameValuePair("identification[body]", body)); JSONArray arrayResult = put(HOST + "/identifications/" + identificationId + ".json", params); } private void addIdentification(int observationId, int taxonId, String body, boolean disagreement, boolean fromVision) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("identification[observation_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("identification[taxon_id]", new Integer(taxonId).toString())); if (body != null) params.add(new BasicNameValuePair("identification[body]", body)); params.add(new BasicNameValuePair("identification[disagreement]", String.valueOf(disagreement))); params.add(new BasicNameValuePair("identification[vision]", String.valueOf(fromVision))); JSONArray arrayResult = post(HOST + "/identifications.json", params); if (arrayResult != null) { BetterJSONObject result; try { result = new BetterJSONObject(arrayResult.getJSONObject(0)); JSONObject jsonObservation = result.getJSONObject("observation"); Observation remoteObservation = new Observation(new BetterJSONObject(jsonObservation)); Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + remoteObservation.id, null, Observation.DEFAULT_SORT_ORDER); // update local observation c.moveToFirst(); if (c.isAfterLast() == false) { Observation observation = new Observation(c); boolean isModified = observation.merge(remoteObservation); ContentValues cv = observation.getContentValues(); if (observation._updated_at.before(remoteObservation.updated_at)) { // Remote observation is newer (and thus has overwritten the local one) - update its // sync at time so we won't update the remote servers later on (since we won't // accidentally consider this an updated record) cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); } if (isModified) { // Only update the DB if needed getContentResolver().update(observation.getUri(), cv, null, null); } } c.close(); } catch (JSONException e) { Logger.tag(TAG).error(e); } } } // Updates a user's inat network settings private JSONObject updateUserTimezone(String timezone) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user[time_zone]", timezone)); try { JSONObject paramsJson = new JSONObject(); JSONObject userJson = new JSONObject(); userJson.put("time_zone", timezone); paramsJson.put("user", userJson); JSONArray array = put(API_HOST + "/users/" + mLogin, paramsJson); if ((mResponseErrors != null) || (array == null)) { // Couldn't update user return null; } else { return array.optJSONObject(0); } } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } // Updates a user's inat network settings private JSONObject updateUserNetwork(int siteId) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user[site_id]", String.valueOf(siteId))); JSONArray array = put(HOST + "/users/" + mLogin + ".json", params); if ((mResponseErrors != null) || (array == null)) { // Couldn't update user return null; } else { return array.optJSONObject(0); } } // Updates a user's profile private JSONObject updateUser(String username, String email, String password, String fullName, String bio, String userPic, boolean deletePic) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user[login]", username)); params.add(new BasicNameValuePair("user[name]", fullName)); params.add(new BasicNameValuePair("user[description]", bio)); params.add(new BasicNameValuePair("user[email]", email)); if ((password != null) && (password.length() > 0)) { params.add(new BasicNameValuePair("user[password]", password)); params.add(new BasicNameValuePair("user[password_confirmation]", password)); } if (deletePic) { // Delete profile pic params.add(new BasicNameValuePair("icon_delete", "true")); } else if (userPic != null) { // New profile pic params.add(new BasicNameValuePair("user[icon]", userPic)); } JSONArray array = put(HOST + "/users/" + mLogin + ".json", params); if ((mResponseErrors != null) || (array == null)) { // Couldn't update user return null; } else { return array.optJSONObject(0); } } interface IOnTimezone { void onTimezone(String timezoneName); } private void getTimezoneByCurrentLocation(IOnTimezone cb) { getLocation(new IOnLocation() { @Override public void onLocation(Location location) { if (location == null) { // Couldn't retrieve current location cb.onTimezone(null); return; } // Convert coordinates to timezone GeoApiContext context = new GeoApiContext.Builder() .apiKey(getString(R.string.gmaps2_api_key)) .build(); LatLng currentLocation = new LatLng(location.getLatitude(), location.getLongitude()); String zoneIdName = null; try { TimeZone zone = TimeZoneApi.getTimeZone(context, currentLocation).await(); zoneIdName = zone.getID(); } catch (NoClassDefFoundError exc) { // Not working on older Androids Logger.tag(TAG).error(exc); cb.onTimezone(null); return; } catch (Exception exc) { // Couldn't convert coordinates to timezone Logger.tag(TAG).error(exc); cb.onTimezone(null); return; } // Next, convert from standard zone name into iNaturalist-API-accepted name if (!TIMEZONE_ID_TO_INAT_TIMEZONE.containsKey(zoneIdName)) { // Timezone is unsupported by iNaturalist cb.onTimezone(null); return; } String zoneName = TIMEZONE_ID_TO_INAT_TIMEZONE.get(zoneIdName); cb.onTimezone(zoneName); } }); } // Registers a user - returns an error message in case of an error (null if successful) private String registerUser(String email, String password, String username, String license, String timezone) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user[email]", email)); params.add(new BasicNameValuePair("user[login]", username)); params.add(new BasicNameValuePair("user[password]", password)); params.add(new BasicNameValuePair("user[password_confirmation]", password)); String inatNetwork = mApp.getInaturalistNetworkMember(); params.add(new BasicNameValuePair("user[site_id]", mApp.getStringResourceByName("inat_site_id_" + inatNetwork))); params.add(new BasicNameValuePair("user[preferred_observation_license]", license)); params.add(new BasicNameValuePair("user[preferred_photo_license]", license)); params.add(new BasicNameValuePair("user[preferred_sound_license]", license)); Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); params.add(new BasicNameValuePair("user[locale]", deviceLanguage)); if (timezone != null) { params.add(new BasicNameValuePair("user[time_zone]", timezone)); } post(HOST + "/users.json", params, false); if (mResponseErrors != null) { // Couldn't create user try { return mResponseErrors.getString(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } else { return null; } } private void updateComment(int commentId, int observationId, String body) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("comment[parent_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("comment[parent_type]", "Observation")); params.add(new BasicNameValuePair("comment[body]", body)); put(HOST + "/comments/" + commentId + ".json", params); } private void deleteComment(int commentId) throws AuthenticationException { delete(HOST + "/comments/" + commentId + ".json", null); } private void addComment(int observationId, String body) throws AuthenticationException { ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("comment[parent_id]", new Integer(observationId).toString())); params.add(new BasicNameValuePair("comment[parent_type]", "Observation")); params.add(new BasicNameValuePair("comment[body]", body)); post(HOST + "/comments.json", params); } private boolean postObservation(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLexicon = deviceLocale.getLanguage(); if (observation.id != null) { // Update observation Logger.tag(TAG).debug("postObservation: Updating existing " + observation.id + ":" + observation._id); JSONArray response = request(API_HOST + "/observations/" + observation.id + "?locale=" + deviceLexicon, "put", null, observationToJsonObject(observation, false), true, true, false); if (response == null) { Logger.tag(TAG).debug("postObservation: Error for " + observation.id + ":" + observation._id + ":" + mLastStatusCode); // Some sort of error if ((mLastStatusCode >= 400) && (mLastStatusCode < 500)) { // Observation doesn't exist anymore (deleted remotely, and due to network // issues we didn't get any notification of this) - so delete the observation // locally. Logger.tag(TAG).debug("postObservation: Deleting obs " + observation.id + ":" + observation._id); getContentResolver().delete(Observation.CONTENT_URI, "id = " + observation.id, null); // Delete associated project-fields and photos int count1 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_id = " + observation.id, null); int count2 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_uuid = \"" + observation.uuid + "\"", null); int count3 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_id = " + observation.id, null); int count4 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_uuid = \"" + observation.uuid + "\"", null); int count5 = getContentResolver().delete(ProjectObservation.CONTENT_URI, "observation_id = " + observation.id, null); int count6 = getContentResolver().delete(ProjectFieldValue.CONTENT_URI, "observation_id = " + observation.id, null); Logger.tag(TAG).debug("postObservation: After delete: " + count1 + ":" + count2 + ":" + count3 + ":" + count4 + ":" + count5 + ":" + count6); return true; } } boolean success = handleObservationResponse(observation, response); if (!success) { throw new SyncFailedException(); } return true; } // New observation String inatNetwork = mApp.getInaturalistNetworkMember(); JSONObject observationParams = observationToJsonObject(observation, true); Logger.tag(TAG).debug("postObservation: New obs"); Logger.tag(TAG).debug(observationParams.toString()); boolean success = handleObservationResponse( observation, request(API_HOST + "/observations?locale=" + deviceLexicon, "post", null, observationParams, true, true, false) ); if (!success) { throw new SyncFailedException(); } return true; } private JSONObject getObservationJson(int id, boolean authenticated, boolean includeNewProjects) throws AuthenticationException { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = String.format(Locale.ENGLISH, "%s/observations/%d?locale=%s&%s", API_HOST, id, deviceLanguage, includeNewProjects ? "include_new_projects=true" : ""); JSONArray json = get(url, authenticated); if (json == null || json.length() == 0) { return null; } try { JSONArray results = json.getJSONObject(0).getJSONArray("results"); if (results.length() == 0) return null; return results.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private Observation getAndDownloadObservation(int id) throws AuthenticationException { // Download the observation JSONObject json = getObservationJson(id, true, true); if (json == null) return null; Observation obs = new Observation(new BetterJSONObject(json)); // Save the downloaded observation if (mProjectObservations == null) mProjectObservations = new ArrayList<SerializableJSONArray>(); if (mProjectFieldValues == null) mProjectFieldValues = new Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>>(); JSONArray arr = new JSONArray(); arr.put(json); syncJson(arr, true); return obs; } private boolean postSounds(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { Integer observationId = observation.id; ObservationSound os; int createdCount = 0; ContentValues cv; Logger.tag(TAG).debug("postSounds: " + observationId + ":" + observation); // query observation sounds where id is null (i.e. new sounds) Cursor c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "(id IS NULL) AND (observation_uuid = ?) AND ((is_deleted == 0) OR (is_deleted IS NULL))", new String[]{observation.uuid}, ObservationSound.DEFAULT_SORT_ORDER); Logger.tag(TAG).debug("postSounds: New sounds: " + c.getCount()); if (c.getCount() == 0) { c.close(); return true; } checkForCancelSync(); // for each observation POST to /sounds c.moveToFirst(); while (c.isAfterLast() == false) { os = new ObservationSound(c); Logger.tag(TAG).debug("postSounds: Posting sound - " + os); if (os.file_url != null) { // Online sound Logger.tag(TAG).debug("postSounds: Skipping because file_url is not null"); c.moveToNext(); continue; } if ((os.filename == null) || !(new File(os.filename)).exists()) { // Local (cached) sound was deleted - probably because the user deleted the app's cache Logger.tag(TAG).debug("postSounds: Posting sound - filename doesn't exist: " + os.filename); // First, delete this photo record getContentResolver().delete(ObservationSound.CONTENT_URI, "_id = ?", new String[]{String.valueOf(os._id)}); // Set errors for this obs - to notify the user that we couldn't upload the obs sounds JSONArray errors = new JSONArray(); errors.put(getString(R.string.deleted_sounds_from_cache_error)); mApp.setErrorsForObservation(os.observation_id, 0, errors); // Move to next observation sound c.moveToNext(); checkForCancelSync(); continue; } ArrayList<NameValuePair> params = os.getParams(); params.add(new BasicNameValuePair("audio", os.filename)); JSONArray response; String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); response = request( inatHost + "/observation_sounds.json", "post", params, null, true, true, false); try { if (response == null || response.length() != 1) { c.close(); throw new SyncFailedException(); } JSONObject json = response.getJSONObject(0); BetterJSONObject j = new BetterJSONObject(json); ObservationSound jsonObservationSound = new ObservationSound(j); Logger.tag(TAG).debug("postSounds: Response for POST: "); Logger.tag(TAG).debug(json.toString()); Logger.tag(TAG).debug("postSounds: Response for POST 2: " + jsonObservationSound); os.merge(jsonObservationSound); Logger.tag(TAG).debug("postSounds: Response for POST 3: " + os); cv = os.getContentValues(); Logger.tag(TAG).debug("postSounds - Setting _SYNCED_AT - " + os.id + ":" + os._id + ":" + os._observation_id + ":" + os.observation_id); getContentResolver().update(os.getUri(), cv, null, null); createdCount += 1; increaseProgressForObservation(observation); } catch (JSONException e) { Logger.tag(TAG).error("JSONException: " + e.toString()); } c.moveToNext(); checkForCancelSync(); } c.close(); c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "(id IS NULL) AND (observation_uuid = ?) AND ((is_deleted == 0) OR (is_deleted IS NULL))", new String[]{observation.uuid}, ObservationSound.DEFAULT_SORT_ORDER); int currentCount = c.getCount(); Logger.tag(TAG).debug("postSounds: currentCount = " + currentCount); c.close(); if (currentCount == 0) { // Sync completed successfully return true; } else { // Sync failed throw new SyncFailedException(); } } private boolean postPhotos(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { Integer observationId = observation.id; ObservationPhoto op; int createdCount = 0; ContentValues cv; Logger.tag(TAG).debug("postPhotos: " + observationId + ":" + observation); if (observationId != null) { // See if there any photos in an invalid state Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_updated_at > _synced_at AND _synced_at IS NOT NULL AND id IS NULL AND observation_id = ?", new String[]{String.valueOf(observationId)}, ObservationPhoto.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { op = new ObservationPhoto(c); // Shouldn't happen - a photo with null external ID is marked as sync - unmark it op._synced_at = null; Logger.tag(TAG).debug("postPhotos: Updating with _synced_at = null: " + op); getContentResolver().update(op.getUri(), op.getContentValues(), null, null); c.moveToNext(); } c.close(); c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_synced_at IS NULL AND id IS NOT NULL AND observation_id = ?", new String[]{String.valueOf(observationId)}, ObservationPhoto.DEFAULT_SORT_ORDER); c.moveToFirst(); while (c.isAfterLast() == false) { op = new ObservationPhoto(c); // Shouldn't happen - a photo with an external ID is marked as never been synced cv = op.getContentValues(); cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(op.getUri(), cv, null, null); c.moveToNext(); } c.close(); // update photos - for each observation PUT to /observation_photos/:id c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_updated_at > _synced_at AND _synced_at IS NOT NULL AND id IS NOT NULL AND observation_uuid = ? AND ((is_deleted == 0) OR (is_deleted IS NULL))", new String[]{observation.uuid}, ObservationPhoto.DEFAULT_SORT_ORDER); int updatedCount = c.getCount(); Logger.tag(TAG).debug("postPhotos: Updating photos: " + updatedCount); c.moveToFirst(); while (c.isAfterLast() == false) { checkForCancelSync(); op = new ObservationPhoto(c); ArrayList<NameValuePair> params = op.getParams(); String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); params.add(new BasicNameValuePair("site_id", mApp.getStringResourceByName("inat_site_id_" + inatNetwork))); Logger.tag(TAG).debug("postPhotos: Updating " + op + ":" + params); JSONArray response = put(inatHost + "/observation_photos/" + op.id + ".json", params); try { if (response == null || response.length() != 1) { Logger.tag(TAG).debug("postPhotos: Failed updating " + op.id); c.close(); throw new SyncFailedException(); } increaseProgressForObservation(observation); JSONObject json = response.getJSONObject(0); BetterJSONObject j = new BetterJSONObject(json); ObservationPhoto jsonObservationPhoto = new ObservationPhoto(j); Logger.tag(TAG).debug("postPhotos after put: " + j); Logger.tag(TAG).debug("postPhotos after put 2: " + jsonObservationPhoto); op.merge(jsonObservationPhoto); Logger.tag(TAG).debug("postPhotos after put 3 - merge: " + op); cv = op.getContentValues(); Logger.tag(TAG).debug("postPhotos: Setting _SYNCED_AT - " + op.id + ":" + op._id + ":" + op._observation_id + ":" + op.observation_id); cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(op.getUri(), cv, null, null); createdCount += 1; } catch (JSONException e) { Logger.tag(TAG).error("JSONException: " + e.toString()); } c.moveToNext(); } c.close(); } // query observation photos where _synced_at is null (i.e. new photos) Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(_synced_at IS NULL) AND (id IS NULL) AND (observation_uuid = ?) AND ((is_deleted == 0) OR (is_deleted IS NULL))", new String[]{observation.uuid}, ObservationPhoto.DEFAULT_SORT_ORDER); Logger.tag(TAG).debug("postPhotos: New photos: " + c.getCount()); if (c.getCount() == 0) { c.close(); return true; } checkForCancelSync(); // for each observation POST to /observation_photos c.moveToFirst(); while (c.isAfterLast() == false) { op = new ObservationPhoto(c); Logger.tag(TAG).debug("postPhotos: Posting photo - " + op); if (op.photo_url != null) { // Online photo Logger.tag(TAG).debug("postPhotos: Skipping because photo_url is not null"); c.moveToNext(); continue; } ArrayList<NameValuePair> params = op.getParams(); String imgFilePath = op.photo_filename; if (imgFilePath == null) { // Observation photo is saved in the "old" way (prior to latest change in the way we store photos) Logger.tag(TAG).debug("postPhotos: Posting photo - photo_filename is null"); if (op._photo_id != null) { Uri photoUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, op._photo_id); Cursor pc = getContentResolver().query(photoUri, new String[]{MediaStore.MediaColumns._ID, MediaStore.Images.Media.DATA}, null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER); if (pc != null) { if (pc.getCount() > 0) { pc.moveToFirst(); imgFilePath = pc.getString(pc.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)); } pc.close(); } } } if ((imgFilePath == null) || !(new File(imgFilePath)).exists()) { // Local (cached) photo was deleted - probably because the user deleted the app's cache Logger.tag(TAG).debug("postPhotos: Posting photo - still problematic photo filename: " + imgFilePath); // First, delete this photo record getContentResolver().delete(ObservationPhoto.CONTENT_URI, "_id = ?", new String[]{String.valueOf(op._id)}); // Set errors for this obs - to notify the user that we couldn't upload the obs photos JSONArray errors = new JSONArray(); errors.put(getString(R.string.deleted_photos_from_cache_error)); mApp.setErrorsForObservation(op.observation_id, 0, errors); // Move to next observation photo c.moveToNext(); checkForCancelSync(); continue; } params.add(new BasicNameValuePair("file", imgFilePath)); String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); params.add(new BasicNameValuePair("site_id", mApp.getStringResourceByName("inat_site_id_" + inatNetwork))); JSONArray response; Logger.tag(TAG).debug("postPhotos: POSTing new photo: " + params); response = post(inatHost + "/observation_photos.json", params, true); try { if (response == null || response.length() != 1) { c.close(); throw new SyncFailedException(); } increaseProgressForObservation(observation); JSONObject json = response.getJSONObject(0); BetterJSONObject j = new BetterJSONObject(json); ObservationPhoto jsonObservationPhoto = new ObservationPhoto(j); Logger.tag(TAG).debug("postPhotos: Response for POST: "); Logger.tag(TAG).debug(json.toString()); Logger.tag(TAG).debug("postPhotos: Response for POST 2: " + jsonObservationPhoto); op.merge(jsonObservationPhoto); Logger.tag(TAG).debug("postPhotos: Response for POST 3: " + op); cv = op.getContentValues(); Logger.tag(TAG).debug("postPhotos - Setting _SYNCED_AT - " + op.id + ":" + op._id + ":" + op._observation_id + ":" + op.observation_id); cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(op.getUri(), cv, null, null); createdCount += 1; } catch (JSONException e) { Logger.tag(TAG).error("JSONException: " + e.toString()); } c.moveToNext(); checkForCancelSync(); } c.close(); c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(_synced_at IS NULL) AND ((_observation_id = ? OR observation_id = ?)) AND ((is_deleted == 0) OR (is_deleted IS NULL))", new String[]{String.valueOf(observation._id), String.valueOf(observation.id)}, ObservationPhoto.DEFAULT_SORT_ORDER); int currentCount = c.getCount(); Logger.tag(TAG).debug("postPhotos: currentCount = " + currentCount); c.close(); if (currentCount == 0) { // Sync completed successfully return true; } else { // Sync failed throw new SyncFailedException(); } } // Warms the images cache by pre-loading a remote image private void warmUpImageCache(final String url) { Handler handler = new Handler(Looper.getMainLooper()); // Need to run on main thread handler.post(new Runnable() { @Override public void run() { Picasso.with(INaturalistService.this).load(url).into(new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { // cache is now warmed up } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }); } }); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } // Goes over cached photos that were uploaded and that are old enough and deletes them // to clear out storage space (they're replaced with their online version, so it'll be // accessible by the user). private void clearOldCachedPhotos() { if (!isNetworkAvailable()) return; if (!mApp.loggedIn()) return; Cursor c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_updated_at = _synced_at AND _synced_at IS NOT NULL AND id IS NOT NULL AND " + "photo_filename IS NOT NULL AND observation_id IS NOT NULL", new String[]{}, ObservationPhoto.DEFAULT_SORT_ORDER); int totalCount = c.getCount(); int photosReplacedCount = 0; Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - %d available cached photos", totalCount)); while ((totalCount > OLD_PHOTOS_MAX_COUNT) && (!c.isAfterLast()) && (photosReplacedCount < MAX_PHOTO_REPLACEMENTS_PER_RUN)) { ObservationPhoto op = new ObservationPhoto(c); Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - clearing photo %d: %s", photosReplacedCount, op.toString())); File obsPhotoFile = new File(op.photo_filename); if (op.photo_url == null) { // No photo URL defined - download the observation and get the external URL for that photo Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - No photo_url found for obs photo: %s", op.toString())); boolean foundPhoto = false; try { JSONObject json = getObservationJson(op.observation_id, false, false); if (json != null) { Observation obs = new Observation(new BetterJSONObject(json)); for (int i = 0; i < obs.photos.size(); i++) { if ((obs.photos.get(i).id != null) && (op.id != null)) { if (obs.photos.get(i).id.equals(op.id)) { // Found the appropriate photo - update the URL op.photo_url = obs.photos.get(i).photo_url; Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - foundPhoto: %s", op.photo_url)); foundPhoto = true; break; } } } } } catch (AuthenticationException e) { Logger.tag(TAG).error(e); } Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - foundPhoto: %s", foundPhoto)); if (!foundPhoto) { // Couldn't download remote URL for the observation photo - don't delete it c.moveToNext(); continue; } } if (obsPhotoFile.exists()) { // Delete the local cached photo file boolean success = obsPhotoFile.delete(); Logger.tag(TAG).info(String.format(Locale.ENGLISH, "clearOldCachedPhotos - deleted photo: %s: %s", success, obsPhotoFile.toString())); } // Update the obs photo record with the remote photo URL Logger.tag(TAG).debug("OP - clearOldCachedPhotos - Setting _SYNCED_AT - " + op.id + ":" + op._id + ":" + op._observation_id + ":" + op.observation_id); op.photo_filename = null; ContentValues cv = op.getContentValues(); cv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(op.getUri(), cv, null, null); // Warm up the cache for the image warmUpImageCache(op.photo_url); photosReplacedCount += 1; c.moveToNext(); } c.close(); } private String getGuideXML(Integer guideId) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = HOST + "/guides/" + guideId.toString() + ".xml?locale=" + deviceLanguage; try { OkHttpClient client = new OkHttpClient().newBuilder() .followRedirects(true) .followSslRedirects(true) .connectTimeout(HTTP_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS) .writeTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .readTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .build(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { return null; } InputStream buffer = new BufferedInputStream(response.body().byteStream()); File outputFile = File.createTempFile(guideId.toString() + ".xml", null, getBaseContext().getCacheDir()); OutputStream output = new FileOutputStream(outputFile); int count = 0; byte data[] = new byte[1024]; while ((count = buffer.read(data)) != -1) { output.write(data, 0, count); } // flushing output output.flush(); // closing streams output.close(); buffer.close(); response.close(); // Return the downloaded full file name return outputFile.getAbsolutePath(); } catch (IOException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getCurrentUserDetails() throws AuthenticationException { String url = API_HOST + "/users/me"; JSONArray json = get(url, true); try { if (json == null) return null; if (json.length() == 0) return null; JSONObject user = json.getJSONObject(0).getJSONArray("results").getJSONObject(0); return new BetterJSONObject(user); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject updateCurrentUserDetails(JSONObject params) throws AuthenticationException { JSONObject input = new JSONObject(); try { input.put("user", params); } catch (JSONException e) { Logger.tag(TAG).error(e); } JSONArray json = request(API_HOST + "/users/" + mApp.currentUserLogin(), "put", null, input, true, true, false); try { if (json == null) return null; if (json.length() == 0) return null; return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getUserDetails(String username) throws AuthenticationException { String url = HOST + "/users/" + username + ".json"; JSONArray json = get(url, false); try { if (json == null) return null; if (json.length() == 0) return null; return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private SerializableJSONArray searchUserObservation(String query) throws AuthenticationException { String url = null; try { StringBuilder sb = new StringBuilder(INaturalistService.HOST + "/observations/" + mLogin + ".json"); sb.append("?per_page=100"); sb.append("&q="); sb.append(URLEncoder.encode(query, "utf8")); sb.append("&extra=observation_photos,projects,fields"); Locale deviceLocale = getResources().getConfiguration().locale; String deviceLexicon = deviceLocale.getLanguage(); sb.append("&locale="); sb.append(deviceLexicon); url = sb.toString(); } catch (UnsupportedEncodingException e) { Logger.tag(TAG).error(e); return null; } JSONArray json = get(url, true); if (json == null) return null; if (json.length() == 0) return null; return new SerializableJSONArray(json); } private BetterJSONObject searchAutoComplete(String type, String query, int page) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/" + type + "/autocomplete?geo=true&locale=" + deviceLanguage + "&per_page=50&page=" + page + "&q=" + Uri.encode(query); JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private JSONObject getUserObservations(String username) throws AuthenticationException { String url = API_HOST + "/observations?per_page=30&user_id=" + username; JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return json.getJSONObject(0); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private SerializableJSONArray getUserUpdates(boolean following) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/observations/updates?locale=" + deviceLanguage + "&per_page=200&observations_by=" + (following ? "following" : "owner"); JSONArray json = request(url, "get", null, null, true, true, false); // Use JWT Token authentication if (json == null) return null; if (json.length() == 0) return null; try { JSONObject resObject = json.getJSONObject(0); JSONArray results = json.getJSONObject(0).getJSONArray("results"); return new SerializableJSONArray(results); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getUserIdentifications(String username) throws AuthenticationException { String url = API_HOST + "/identifications?user_id=" + username + "&own_observation=false&per_page=30"; JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getExploreResults(String command, ExploreSearchFilters filters, int pageNumber, int pageSize, String orderBy) throws AuthenticationException { if (filters == null) return null; Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url; if (command == null) { url = String.format(Locale.ENGLISH, "%s/observations%s?locale=%s&page=%d&per_page=%d&ordered_by=%s&order=desc&return_bounds=true&%s", API_HOST, command == null ? "" : "/" + command, deviceLanguage, pageNumber, pageSize, orderBy == null ? "" : orderBy, filters.toUrlQueryString()); } else if (command.equals("species_counts")) { url = String.format(Locale.ENGLISH, "%s/observations/%s?locale=%s&page=%d&per_page=%d&%s", API_HOST, command, deviceLanguage, pageNumber, pageSize, filters.toUrlQueryString()); } else { url = String.format(Locale.ENGLISH, "%s/observations/%s?page=%d&per_page=%d&%s", API_HOST, command, pageNumber, pageSize, filters.toUrlQueryString()); } JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getUserSpeciesCount(String username) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/observations/species_counts?place_id=any&verifiable=any&user_id=" + username + "&locale=" + deviceLanguage; JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getUserLifeList(int lifeListId) throws AuthenticationException { String url = HOST + "/life_lists/" + lifeListId + ".json"; JSONArray json = get(url, false); if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getPlaceDetails(long placeId) throws AuthenticationException { String url = API_HOST + "/places/" + placeId; JSONArray json = get(url, false); try { if (json == null) return null; if (json.length() == 0) return null; JSONArray results = json.getJSONObject(0).getJSONArray("results"); return new BetterJSONObject(results.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private boolean isUserDeleted(String username) { try { JSONArray result = get(API_HOST + "/users/" + username, false); } catch (AuthenticationException e) { e.printStackTrace(); } return mLastStatusCode == HttpStatus.SC_NOT_FOUND; } private BetterJSONObject getUserDetails() throws AuthenticationException { String url = HOST + "/users/edit.json"; JSONArray json = get(url, true); try { if (json == null) return null; if (json.length() == 0) return null; return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getProjectObservations(int projectId) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/observations?project_id=" + projectId + "&per_page=50&locale=" + deviceLanguage; JSONArray json = get(url); if (json == null) return new BetterJSONObject(); try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private BetterJSONObject getTaxonObservationsBounds(Integer taxonId) { String url = API_HOST + "/observations?per_page=1&return_bounds=true&taxon_id=" + taxonId; JSONArray json = null; try { json = get(url, false); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); return null; } if (json == null) return null; if (json.length() == 0) return null; try { JSONObject response = json.getJSONObject(0); return new BetterJSONObject(response.getJSONObject("total_bounds")); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getMissions(Location location, String username, Integer taxonId, float expandLocationByDegress) { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/observations/species_counts?locale=" + deviceLanguage + "&verifiable=true&hrank=species&oauth_application_id=2,3"; if (expandLocationByDegress == 0) { url += "&lat=" + location.getLatitude() + "&lng=" + location.getLongitude(); } else { // Search for taxa in a bounding box expanded by a certain number of degrees (used to expand // our search in case we can't find any close taxa) url += String.format(Locale.ENGLISH, "&nelat=%f&nelng=%f&swlat=%f&swlng=%f", location.getLatitude() + expandLocationByDegress, location.getLongitude() + expandLocationByDegress, location.getLatitude() - expandLocationByDegress, location.getLongitude() - expandLocationByDegress); } if (username != null) { // Taxa unobserved by a specific user url += "&unobserved_by_user_id=" + username; } if (taxonId != null) { // Taxa under a specific category (e.g. fungi) url += "&taxon_id=" + taxonId; } // Make sure to show only taxa observable for the current months (+/- 1 month from current one) Calendar c = Calendar.getInstance(); int month = c.get(Calendar.MONTH); url += String.format(Locale.ENGLISH, "&month=%d,%d,%d", modulo(month - 1, 12) + 1, month + 1, modulo(month + 1, 12) + 1); JSONArray json = null; try { json = get(url, false); } catch (AuthenticationException e) { Logger.tag(TAG).error(e); return null; } if (json == null) return null; if (json.length() == 0) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private BetterJSONObject getProjectSpecies(int projectId) throws AuthenticationException { Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = API_HOST + "/observations/species_counts?project_id=" + projectId + "&locale=" + deviceLanguage; JSONArray json = get(url); try { if (json == null) return new BetterJSONObject(); return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private SerializableJSONArray getNews() throws AuthenticationException { String url = HOST + "/posts/for_user.json"; JSONArray json = get(url, mCredentials != null); // If user is logged-in, returns his news (using an authenticated endpoint) return new SerializableJSONArray(json); } private SerializableJSONArray getProjectNews(int projectId) throws AuthenticationException { String url = HOST + "/projects/" + projectId + "/journal.json"; JSONArray json = get(url); return new SerializableJSONArray(json); } private BetterJSONObject getProjectObservers(int projectId) throws AuthenticationException { String url = API_HOST + "/observations/observers?project_id=" + projectId; JSONArray json = get(url); try { if (json == null) return new BetterJSONObject(); return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private BetterJSONObject getProjectIdentifiers(int projectId) throws AuthenticationException { String url = API_HOST + "/observations/identifiers?project_id=" + projectId; JSONArray json = get(url); try { if (json == null) return new BetterJSONObject(); return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private SerializableJSONArray getTaxaForGuide(Integer guideId) throws AuthenticationException { String url = HOST + "/guide_taxa.json?guide_id=" + guideId.toString(); JSONArray json = get(url); try { if (json == null) return new SerializableJSONArray(); return new SerializableJSONArray(json.getJSONObject(0).getJSONArray("guide_taxa")); } catch (JSONException e) { Logger.tag(TAG).error(e); return new SerializableJSONArray(); } } private SerializableJSONArray getAllGuides() throws AuthenticationException { String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); // Just retrieve the first page results (if the user wants to find more guides, // he can search for guides) String url = inatHost + "/guides.json?per_page=200&page=1"; JSONArray results = get(url); return new SerializableJSONArray(results); } private SerializableJSONArray getMyGuides() throws AuthenticationException { JSONArray json = null; String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); String url = inatHost + "/guides.json?by=you&per_page=200"; if (mCredentials != null) { try { json = get(url, true); } catch (Exception exc) { Logger.tag(TAG).error(exc); } } if (json == null) { json = new JSONArray(); } // Build a list of result guide IDs int i = 0; List<String> guideIds = new ArrayList<String>(); while (i < json.length()) { try { JSONObject guide = json.getJSONObject(i); guideIds.add(String.valueOf(guide.getInt("id"))); } catch (JSONException e) { Logger.tag(TAG).error(e); } i++; } // Add any offline guides List<GuideXML> offlineGuides = GuideXML.getAllOfflineGuides(this); List<JSONObject> guidesJson = new ArrayList<JSONObject>(); for (GuideXML guide : offlineGuides) { JSONObject guideJson = new JSONObject(); if (guideIds.contains(guide.getID())) { // Guide already found in current guide results - no need to add it again continue; } try { guideJson.put("id", Integer.valueOf(guide.getID())); guideJson.put("title", guide.getTitle()); guideJson.put("description", guide.getDescription()); // TODO - no support for "icon_url" (not found in XML file) } catch (JSONException e) { Logger.tag(TAG).error(e); } json.put(guideJson); } return new SerializableJSONArray(json); } private SerializableJSONArray getNearByGuides(Location location) throws AuthenticationException { if (location == null) { // No place found - return an empty result Logger.tag(TAG).error("Current place is null"); return new SerializableJSONArray(); } double lat = location.getLatitude(); double lon = location.getLongitude(); String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); String url = inatHost + String.format(Locale.ENGLISH, "/guides.json?latitude=%s&longitude=%s&per_page=200", lat, lon); Logger.tag(TAG).debug(url); JSONArray json = get(url); return new SerializableJSONArray(json); } private SerializableJSONArray getNearByProjects(Location location) throws AuthenticationException { if (location == null) { // No place found - return an empty result Logger.tag(TAG).error("Current place is null"); return new SerializableJSONArray(); } double lat = location.getLatitude(); double lon = location.getLongitude(); String inatNetwork = mApp.getInaturalistNetworkMember(); String inatHost = mApp.getStringResourceByName("inat_host_" + inatNetwork); String url = inatHost + String.format(Locale.ENGLISH, "/projects.json?latitude=%s&longitude=%s", lat, lon); Logger.tag(TAG).error(url); JSONArray json = get(url); if (json == null) { return new SerializableJSONArray(); } // Determine which projects are already joined for (int i = 0; i < json.length(); i++) { Cursor c; try { c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = '" + json.getJSONObject(i).getInt("id") + "'", null, Project.DEFAULT_SORT_ORDER); c.moveToFirst(); int count = c.getCount(); c.close(); if (count > 0) { json.getJSONObject(i).put("joined", true); } } catch (JSONException e) { Logger.tag(TAG).error(e); continue; } } return new SerializableJSONArray(json); } private SerializableJSONArray getFeaturedProjects() throws AuthenticationException { String inatNetwork = mApp.getInaturalistNetworkMember(); String siteId = mApp.getStringResourceByName("inat_site_id_" + inatNetwork); String url = API_HOST + "/projects?featured=true&site_id=" + siteId; JSONArray json = get(url); if (json == null) { return new SerializableJSONArray(); } JSONArray results; try { results = json.getJSONObject(0).getJSONArray("results"); } catch (JSONException e) { Logger.tag(TAG).error(e); return new SerializableJSONArray(); } // Determine which projects are already joined for (int i = 0; i < results.length(); i++) { Cursor c; try { c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = '" + results.getJSONObject(i).getInt("id") + "'", null, Project.DEFAULT_SORT_ORDER); c.moveToFirst(); int count = c.getCount(); c.close(); if (count > 0) { results.getJSONObject(i).put("joined", true); } } catch (JSONException e) { Logger.tag(TAG).error(e); continue; } } return new SerializableJSONArray(results); } private void addProjectFields(JSONArray jsonFields) { int projectId = -1; ArrayList<ProjectField> projectFields = new ArrayList<ProjectField>(); for (int i = 0; i < jsonFields.length(); i++) { try { BetterJSONObject jsonField = new BetterJSONObject(jsonFields.getJSONObject(i)); ProjectField field = new ProjectField(jsonField); projectId = field.project_id; projectFields.add(field); } catch (JSONException e) { Logger.tag(TAG).error(e); } } if (projectId != -1) { // First, delete all previous project fields (for that project) getContentResolver().delete(ProjectField.CONTENT_URI, "(project_id IS NOT NULL) and (project_id = " + projectId + ")", null); // Next, re-add all project fields for (int i = 0; i < projectFields.size(); i++) { ProjectField field = projectFields.get(i); getContentResolver().insert(ProjectField.CONTENT_URI, field.getContentValues()); } } } public void flagObservationAsCaptive(int obsId) throws AuthenticationException { post(String.format(Locale.ENGLISH, "%s/observations/%d/quality/wild.json?agree=false", HOST, obsId), (JSONObject) null); } public void joinProject(int projectId) throws AuthenticationException { post(String.format(Locale.ENGLISH, "%s/projects/%d/join.json", HOST, projectId), (JSONObject) null); try { JSONArray result = get(String.format(Locale.ENGLISH, "%s/projects/%d.json", HOST, projectId)); if (result == null) return; BetterJSONObject jsonProject = new BetterJSONObject(result.getJSONObject(0)); Project project = new Project(jsonProject); // Add joined project locally ContentValues cv = project.getContentValues(); getContentResolver().insert(Project.CONTENT_URI, cv); // Save project fields addProjectFields(jsonProject.getJSONArray("project_observation_fields").getJSONArray()); } catch (JSONException e) { Logger.tag(TAG).error(e); } } public void leaveProject(int projectId) throws AuthenticationException { delete(String.format(Locale.ENGLISH, "%s/projects/%d/leave.json", HOST, projectId), null); // Remove locally saved project (because we left it) getContentResolver().delete(Project.CONTENT_URI, "(id IS NOT NULL) and (id = " + projectId + ")", null); } private BetterJSONObject removeObservationFromProject(int observationId, int projectId) throws AuthenticationException { if (ensureCredentials() == false) { return null; } String url = String.format(Locale.ENGLISH, "%s/projects/%d/remove.json?observation_id=%d", HOST, projectId, observationId); JSONArray json = request(url, "delete", null, null, true, true, false); if (json == null) return null; try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private BetterJSONObject addObservationToProject(int observationId, int projectId) throws AuthenticationException { if (ensureCredentials() == false) { return null; } String url = HOST + "/project_observations.json"; ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("project_observation[observation_id]", String.valueOf(observationId))); params.add(new BasicNameValuePair("project_observation[project_id]", String.valueOf(projectId))); JSONArray json = post(url, params); if (json == null) { return null; } try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return null; } } private boolean postFlag(String flaggableType, Integer flaggableId, String flag, String flagExplanation) throws AuthenticationException { String url = String.format("%s/flags", API_HOST); JSONObject content = new JSONObject(); try { JSONObject flagObject = new JSONObject(); flagObject.put("flaggable_type", flaggableType); flagObject.put("flaggable_id", flaggableId); flagObject.put("flag", flag); content.put("flag", flagObject); if (flagExplanation != null) content.put("flag_explanation", flagExplanation); } catch (JSONException e) { e.printStackTrace(); } JSONArray json = post(url, content); return mLastStatusCode == HttpStatus.SC_OK; } private boolean muteUser(Integer userId) throws AuthenticationException { String url = String.format("%s/users/%d/mute", API_HOST, userId); JSONObject content = new JSONObject(); JSONArray json = post(url, content); return mLastStatusCode == HttpStatus.SC_OK; } private boolean unmuteUser(Integer userId) throws AuthenticationException { String url = String.format("%s/users/%d/mute", API_HOST, userId); JSONObject content = new JSONObject(); JSONArray json = delete(url, null); return mLastStatusCode == HttpStatus.SC_OK; } private BetterJSONObject postMessage(Integer toUser, Integer threadId, String subject, String body) throws AuthenticationException { String url = String.format("%s/messages", API_HOST); JSONObject message = new JSONObject(); JSONObject content = new JSONObject(); try { message.put("to_user_id", toUser); if (threadId != null) message.put("thread_id", threadId); message.put("subject", subject); message.put("body", body); content.put("message", message); } catch (JSONException e) { e.printStackTrace(); } JSONArray json = post(url, content); if (json == null) { return null; } try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private BetterJSONObject getNotificationCounts() throws AuthenticationException { String url = String.format("%s/users/notification_counts", API_HOST); JSONArray json = get(url); if (json == null) { return null; } try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private BetterJSONObject getMessages(String searchQuery, String box, boolean groupByThreads, Integer messageId) throws AuthenticationException { String url = messageId == null ? String.format("%s/messages?q=%s&box=%s&threads=%s&per_page=200", API_HOST, searchQuery != null ? URLEncoder.encode(searchQuery) : "", box != null ? box : "inbox", groupByThreads) : String.format("%s/messages/%d", API_HOST, messageId); JSONArray json = get(url); if (json == null) { return null; } try { return new BetterJSONObject(json.getJSONObject(0)); } catch (JSONException e) { Logger.tag(TAG).error(e); return new BetterJSONObject(); } } private SerializableJSONArray getCheckList(int id) throws AuthenticationException { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); String url = String.format(Locale.ENGLISH, "%s/lists/%d.json?per_page=50&locale=%s", HOST, id, deviceLanguage); JSONArray json = get(url); if (json == null) { return null; } try { return new SerializableJSONArray(json.getJSONObject(0).getJSONArray("listed_taxa")); } catch (JSONException e) { Logger.tag(TAG).error(e); return new SerializableJSONArray(); } } public static boolean hasJoinedProject(Context context, int projectId) { Cursor c = context.getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, "id = " + projectId, null, Project.DEFAULT_SORT_ORDER); int count = c.getCount(); c.close(); return count > 0; } private SerializableJSONArray getJoinedProjectsOffline() { JSONArray projects = new JSONArray(); Cursor c = getContentResolver().query(Project.CONTENT_URI, Project.PROJECTION, null, null, Project.DEFAULT_SORT_ORDER); c.moveToFirst(); int index = 0; while (c.isAfterLast() == false) { Project project = new Project(c); JSONObject jsonProject = project.toJSONObject(); try { jsonProject.put("joined", true); projects.put(index, jsonProject); } catch (JSONException e) { Logger.tag(TAG).error(e); } c.moveToNext(); index++; } c.close(); return new SerializableJSONArray(projects); } private SerializableJSONArray getJoinedProjects() throws AuthenticationException { if (ensureCredentials() == false) { return null; } String url = HOST + "/projects/user/" + Uri.encode(mLogin) + ".json"; JSONArray json = get(url, true); JSONArray finalJson = new JSONArray(); if (json == null) { return null; } for (int i = 0; i < json.length(); i++) { try { JSONObject obj = json.getJSONObject(i); JSONObject project = obj.getJSONObject("project"); project.put("joined", true); finalJson.put(project); // Save project fields addProjectFields(project.getJSONArray("project_observation_fields")); } catch (JSONException e) { Logger.tag(TAG).error(e); } } return new SerializableJSONArray(finalJson); } @SuppressLint("NewApi") private int getAdditionalUserObservations(int maxCount) throws AuthenticationException { if (ensureCredentials() == false) { return -1; } Integer lastId = mPreferences.getInt("last_downloaded_id", 0); if (lastId == 0) { Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "(is_deleted = 0 OR is_deleted is NULL) AND (user_login = '" + mLogin + "')", null, Observation.DEFAULT_SORT_ORDER); if (c.getCount() > 0) { c.moveToLast(); BetterCursor bc = new BetterCursor(c); lastId = bc.getInteger(Observation.ID); } else { lastId = Integer.MAX_VALUE; } c.close(); } String url = API_HOST + "/observations?user_id=" + Uri.encode(mLogin) + "&per_page=" + maxCount + "&id_below=" + lastId; Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); url += "&locale=" + deviceLanguage; mProjectObservations = new ArrayList<SerializableJSONArray>(); mProjectFieldValues = new Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>>(); JSONArray json = get(url, true); if (json != null && json.length() > 0) { try { JSONArray results = json.getJSONObject(0).getJSONArray("results"); JSONArray newResults = new JSONArray(); int minId = Integer.MAX_VALUE; // Remove any observations that were previously downloaded for (int i = 0; i < results.length(); i++) { int currentId = results.getJSONObject(i).getInt("id"); Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "_id = ?", new String[]{String.valueOf(currentId)}, Observation.DEFAULT_SORT_ORDER); if (currentId < minId) { minId = currentId; } if (c.getCount() == 0) { newResults.put(results.getJSONObject(i)); } c.close(); } syncJson(newResults, true); if (results.length() == 0) { mPreferences.edit().putInt("last_downloaded_id", mPreferences.getInt("last_downloaded_id", 0)).commit(); } else { mPreferences.edit().putInt("last_downloaded_id", minId).commit(); } return results.length(); } catch (JSONException e) { Logger.tag(TAG).error(e); return -1; } } else { return -1; } } @SuppressLint("NewApi") private boolean syncRemotelyDeletedObs() throws AuthenticationException, CancelSyncException { if (ensureCredentials() == false) { return false; } String url = API_HOST + "/observations/deleted"; long lastSync = mPreferences.getLong("last_sync_time", 0); if (lastSync == 0) { Logger.tag(TAG).debug("syncRemotelyDeletedObs: First time syncing, no need to delete observations"); return true; } Timestamp lastSyncTS = new Timestamp(lastSync); url += String.format(Locale.ENGLISH, "?since=%s", URLEncoder.encode(new SimpleDateFormat("yyyy-MM-dd").format(lastSyncTS))); JSONArray json = get(url, true); if (json != null && json.length() > 0) { // Delete any local observations which were deleted remotely by the user JSONArray results = null; try { results = json.getJSONObject(0).getJSONArray("results"); } catch (JSONException e) { Logger.tag(TAG).error(e); return false; } if (results.length() == 0) return true; ArrayList<String> ids = new ArrayList<>(); ArrayList<String> uuids = new ArrayList<>(); for (int i = 0; i < results.length(); i++) { String id = String.valueOf(results.optInt(i)); ids.add(id); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); Observation obs = new Observation(obsc); uuids.add('"' + obs.uuid + '"'); } obsc.close(); } String deletedIds = StringUtils.join(ids, ","); String deletedUUIDs = uuids.size() > 0 ? StringUtils.join(uuids, ",") : null; Logger.tag(TAG).debug("syncRemotelyDeletedObs: " + deletedIds); getContentResolver().delete(Observation.CONTENT_URI, "(id IN (" + deletedIds + "))", null); // Delete associated project-fields and photos int count1 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_id in (" + deletedIds + ")", null); int count2 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_id in (" + deletedIds + ")", null); int count3 = getContentResolver().delete(ProjectObservation.CONTENT_URI, "observation_id in (" + deletedIds + ")", null); int count4 = getContentResolver().delete(ProjectFieldValue.CONTENT_URI, "observation_id in (" + deletedIds + ")", null); if (deletedUUIDs != null) { int count5 = getContentResolver().delete(ObservationPhoto.CONTENT_URI, "observation_uuid in (" + deletedUUIDs + ")", null); int count6 = getContentResolver().delete(ObservationSound.CONTENT_URI, "observation_uuid in (" + deletedUUIDs + ")", null); } } checkForCancelSync(); return (json != null); } @SuppressLint("NewApi") private boolean getUserObservations(int maxCount) throws AuthenticationException, CancelSyncException { if (ensureCredentials() == false) { return false; } String url = API_HOST + "/observations?user_id=" + mLogin; long lastSync = mPreferences.getLong("last_sync_time", 0); Timestamp lastSyncTS = new Timestamp(lastSync); url += String.format(Locale.ENGLISH, "&updated_since=%s&order_by=created_at&order=desc&extra=observation_photos,projects,fields", URLEncoder.encode(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(lastSyncTS))); if (maxCount == 0) { maxCount = 200; } if (maxCount > 0) { // Retrieve only a certain number of observations url += String.format(Locale.ENGLISH, "&per_page=%d&page=1", maxCount); } Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); url += "&locale=" + deviceLanguage; mProjectObservations = new ArrayList<SerializableJSONArray>(); mProjectFieldValues = new Hashtable<Integer, Hashtable<Integer, ProjectFieldValue>>(); JSONArray json = get(url, true); if (json != null && json.length() > 0) { Logger.tag(TAG).debug("getUserObservations"); JSONArray results = null; try { results = json.getJSONObject(0).getJSONArray("results"); } catch (JSONException e) { Logger.tag(TAG).error(e); return false; } syncJson(results, true); return true; } checkForCancelSync(); return (json != null); } private boolean syncObservationFields(Observation observation) throws AuthenticationException, CancelSyncException, SyncFailedException { if ((observation.id == null) || (mProjectFieldValues == null)) { // Observation hasn't been synced yet - no way to sync its project fields return true; } // First, remotely update the observation fields which were modified Cursor c = getContentResolver().query(ProjectFieldValue.CONTENT_URI, ProjectFieldValue.PROJECTION, "_updated_at > _synced_at AND _synced_at IS NOT NULL AND observation_id = ?", new String[]{String.valueOf(observation.id)}, ProjectFieldValue.DEFAULT_SORT_ORDER); c.moveToFirst(); if ((c.getCount() == 0) && (mProjectFieldValues.size() == 0)) { c.close(); return true; } while (c.isAfterLast() == false) { checkForCancelSync(); ProjectFieldValue localField = new ProjectFieldValue(c); increaseProgressForObservation(observation); if (!mProjectFieldValues.containsKey(Integer.valueOf(localField.observation_id))) { // Need to retrieve remote observation fields to see how to sync the fields JSONArray jsonResult = get(HOST + "/observations/" + localField.observation_id + ".json"); if (jsonResult != null) { Hashtable<Integer, ProjectFieldValue> fields = new Hashtable<Integer, ProjectFieldValue>(); try { JSONArray jsonFields = jsonResult.getJSONObject(0).getJSONArray("observation_field_values"); for (int j = 0; j < jsonFields.length(); j++) { JSONObject jsonField = jsonFields.getJSONObject(j); JSONObject observationField = jsonField.getJSONObject("observation_field"); int id = observationField.optInt("id", jsonField.getInt("observation_field_id")); fields.put(id, new ProjectFieldValue(new BetterJSONObject(jsonField))); } } catch (JSONException e) { Logger.tag(TAG).error(e); } mProjectFieldValues.put(localField.observation_id, fields); checkForCancelSync(); } else { c.close(); throw new SyncFailedException(); } } Hashtable<Integer, ProjectFieldValue> fields = mProjectFieldValues.get(Integer.valueOf(localField.observation_id)); boolean shouldOverwriteRemote = false; ProjectFieldValue remoteField = null; if (fields == null) { c.moveToNext(); continue; } if (!fields.containsKey(Integer.valueOf(localField.field_id))) { // No remote field - add it shouldOverwriteRemote = true; } else { remoteField = fields.get(Integer.valueOf(localField.field_id)); if ((remoteField.updated_at != null) && (remoteField.updated_at.before(localField._updated_at))) { shouldOverwriteRemote = true; } } if (shouldOverwriteRemote) { // Overwrite remote value ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("observation_field_value[observation_id]", Integer.valueOf(localField.observation_id).toString())); params.add(new BasicNameValuePair("observation_field_value[observation_field_id]", Integer.valueOf(localField.field_id).toString())); params.add(new BasicNameValuePair("observation_field_value[value]", localField.value)); JSONArray result = post(HOST + "/observation_field_values.json", params); if (result == null) { if (mResponseErrors == null) { c.close(); throw new SyncFailedException(); } else { Cursor c2 = getContentResolver().query(ProjectField.CONTENT_URI, ProjectField.PROJECTION, "field_id = " + localField.field_id, null, Project.DEFAULT_SORT_ORDER); c2.moveToFirst(); if (c2.getCount() > 0) { ProjectField projectField = new ProjectField(c2); handleProjectFieldErrors(localField.observation_id, projectField.project_id); } c2.close(); c.moveToNext(); checkForCancelSync(); continue; } } } else { // Overwrite local value localField.created_at = remoteField.created_at; localField.id = remoteField.id; localField.observation_id = remoteField.observation_id; localField.field_id = remoteField.field_id; localField.value = remoteField.value; localField.updated_at = remoteField.updated_at; } ContentValues cv = localField.getContentValues(); cv.put(ProjectFieldValue._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(localField.getUri(), cv, null, null); fields.remove(Integer.valueOf(localField.field_id)); c.moveToNext(); checkForCancelSync(); } c.close(); // Next, add any new observation fields Hashtable<Integer, ProjectFieldValue> fields = mProjectFieldValues.get(Integer.valueOf(observation.id)); if (fields == null) { return true; } for (ProjectFieldValue field : fields.values()) { ContentValues cv = field.getContentValues(); cv.put(ProjectFieldValue._SYNCED_AT, System.currentTimeMillis()); getContentResolver().insert(ProjectFieldValue.CONTENT_URI, cv); c = getContentResolver().query(ProjectField.CONTENT_URI, ProjectField.PROJECTION, "field_id = " + field.field_id, null, Project.DEFAULT_SORT_ORDER); if (c.getCount() == 0) { // This observation has a non-project custom field - add it as well boolean success = addProjectField(field.field_id); if (!success) { c.close(); throw new SyncFailedException(); } } c.close(); } return true; } private boolean syncObservationFields() throws AuthenticationException, CancelSyncException, SyncFailedException { // First, remotely update the observation fields which were modified Cursor c = getContentResolver().query(ProjectFieldValue.CONTENT_URI, ProjectFieldValue.PROJECTION, "_updated_at > _synced_at AND _synced_at IS NOT NULL", null, ProjectFieldValue.DEFAULT_SORT_ORDER); c.moveToFirst(); if ((c.getCount() > 0) || (mProjectFieldValues.size() > 0)) { mApp.notify(SYNC_PHOTOS_NOTIFICATION, getString(R.string.projects), getString(R.string.syncing_observation_fields), getString(R.string.syncing)); } else { c.close(); return true; } while (c.isAfterLast() == false) { checkForCancelSync(); ProjectFieldValue localField = new ProjectFieldValue(c); // Make sure that the local field has an *external* observation id (i.e. the observation // it belongs to has been synced) Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = ? AND _synced_at IS NOT NULL AND _id != ?", new String[]{localField.observation_id.toString(), localField.observation_id.toString()}, ProjectFieldValue.DEFAULT_SORT_ORDER); int count = obsc.getCount(); obsc.close(); if (count == 0) { c.moveToNext(); continue; } mApp.setObservationIdBeingSynced(localField.observation_id); if (!mProjectFieldValues.containsKey(Integer.valueOf(localField.observation_id))) { // Need to retrieve remote observation fields to see how to sync the fields JSONArray jsonResult = get(HOST + "/observations/" + localField.observation_id + ".json"); if (jsonResult != null) { Hashtable<Integer, ProjectFieldValue> fields = new Hashtable<Integer, ProjectFieldValue>(); try { JSONArray jsonFields = jsonResult.getJSONObject(0).getJSONArray("observation_field_values"); for (int j = 0; j < jsonFields.length(); j++) { JSONObject jsonField = jsonFields.getJSONObject(j); JSONObject observationField = jsonField.getJSONObject("observation_field"); int id = observationField.optInt("id", jsonField.getInt("observation_field_id")); fields.put(id, new ProjectFieldValue(new BetterJSONObject(jsonField))); } } catch (JSONException e) { Logger.tag(TAG).error(e); } mProjectFieldValues.put(localField.observation_id, fields); checkForCancelSync(); } else { mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); c.close(); throw new SyncFailedException(); } } Hashtable<Integer, ProjectFieldValue> fields = mProjectFieldValues.get(Integer.valueOf(localField.observation_id)); boolean shouldOverwriteRemote = false; ProjectFieldValue remoteField = null; if (fields == null) { c.moveToNext(); continue; } if (!fields.containsKey(Integer.valueOf(localField.field_id))) { // No remote field - add it shouldOverwriteRemote = true; } else { remoteField = fields.get(Integer.valueOf(localField.field_id)); if (remoteField.updated_at.before(localField._updated_at)) { shouldOverwriteRemote = true; } } if (shouldOverwriteRemote) { // Overwrite remote value ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("observation_field_value[observation_id]", Integer.valueOf(localField.observation_id).toString())); params.add(new BasicNameValuePair("observation_field_value[observation_field_id]", Integer.valueOf(localField.field_id).toString())); params.add(new BasicNameValuePair("observation_field_value[value]", localField.value)); JSONArray result = post(HOST + "/observation_field_values.json", params); if (result == null) { if (mResponseErrors == null) { c.close(); throw new SyncFailedException(); } else { Cursor c2 = getContentResolver().query(ProjectField.CONTENT_URI, ProjectField.PROJECTION, "field_id = " + localField.field_id, null, Project.DEFAULT_SORT_ORDER); c2.moveToFirst(); if (c2.getCount() > 0) { ProjectField projectField = new ProjectField(c2); handleProjectFieldErrors(localField.observation_id, projectField.project_id); } c2.close(); c.moveToNext(); checkForCancelSync(); continue; } } } else { // Overwrite local value localField.created_at = remoteField.created_at; localField.id = remoteField.id; localField.observation_id = remoteField.observation_id; localField.field_id = remoteField.field_id; localField.value = remoteField.value; localField.updated_at = remoteField.updated_at; } ContentValues cv = localField.getContentValues(); cv.put(ProjectFieldValue._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(localField.getUri(), cv, null, null); fields.remove(Integer.valueOf(localField.field_id)); c.moveToNext(); checkForCancelSync(); } c.close(); mApp.setObservationIdBeingSynced(INaturalistApp.NO_OBSERVATION); // Next, add any new observation fields for (Hashtable<Integer, ProjectFieldValue> fields : mProjectFieldValues.values()) { for (ProjectFieldValue field : fields.values()) { ContentValues cv = field.getContentValues(); cv.put(ProjectFieldValue._SYNCED_AT, System.currentTimeMillis()); getContentResolver().insert(ProjectFieldValue.CONTENT_URI, cv); c = getContentResolver().query(ProjectField.CONTENT_URI, ProjectField.PROJECTION, "field_id = " + field.field_id, null, Project.DEFAULT_SORT_ORDER); if (c.getCount() == 0) { // This observation has a non-project custom field - add it as well boolean success = addProjectField(field.field_id); if (!success) { c.close(); throw new SyncFailedException(); } } c.close(); } } return true; } private boolean addProjectField(int fieldId) throws AuthenticationException { try { JSONArray result = get(String.format(Locale.ENGLISH, "%s/observation_fields/%d.json", HOST, fieldId)); if (result == null) return false; BetterJSONObject jsonObj; jsonObj = new BetterJSONObject(result.getJSONObject(0)); ProjectField field = new ProjectField(jsonObj); getContentResolver().insert(ProjectField.CONTENT_URI, field.getContentValues()); return true; } catch (JSONException e) { Logger.tag(TAG).error(e); return false; } } private void getNearbyObservations(Intent intent) throws AuthenticationException { Bundle extras = intent.getExtras(); Double minx = extras.getDouble("minx"); Double maxx = extras.getDouble("maxx"); Double miny = extras.getDouble("miny"); Double maxy = extras.getDouble("maxy"); Double lat = extras.getDouble("lat"); Double lng = extras.getDouble("lng"); Boolean clearMapLimit = extras.getBoolean("clear_map_limit", false); Integer page = extras.getInt("page", 0); Integer perPage = extras.getInt("per_page", NEAR_BY_OBSERVATIONS_PER_PAGE); String url = HOST; if (extras.containsKey("username")) { url = HOST + "/observations/" + extras.getString("username") + ".json?extra=observation_photos"; } else { url = HOST + "/observations.json?extra=observation_photos"; } url += "&captive=false&page=" + page + "&per_page=" + perPage; if (extras.containsKey("taxon_id")) { url += "&taxon_id=" + extras.getInt("taxon_id"); } if (extras.containsKey("location_id")) { url += "&place_id=" + extras.getInt("location_id"); } else if (!clearMapLimit) { if ((lat != null) && (lng != null) && !((lat == 0) && (lng == 0))) { url += "&lat=" + lat; url += "&lng=" + lng; } else { url += "&swlat=" + miny; url += "&nelat=" + maxy; url += "&swlng=" + minx; url += "&nelng=" + maxx; } } if (extras.containsKey("project_id")) { url += "&projects[]=" + extras.getInt("project_id"); } Locale deviceLocale = getResources().getConfiguration().locale; String deviceLanguage = deviceLocale.getLanguage(); url += "&locale=" + deviceLanguage; Logger.tag(TAG).debug("Near by observations URL: " + url); mNearByObservationsUrl = url; JSONArray json = get(url, mApp.loggedIn()); Intent reply = new Intent(ACTION_NEARBY); reply.putExtra("minx", minx); reply.putExtra("maxx", maxx); reply.putExtra("miny", miny); reply.putExtra("maxy", maxy); if (json == null) { reply.putExtra("error", String.format(Locale.ENGLISH, getString(R.string.couldnt_load_nearby_observations), "")); } else { //syncJson(json, false); } if (url.equalsIgnoreCase(mNearByObservationsUrl)) { // Only send the reply if a new near by observations request hasn't been made yet mApp.setServiceResult(ACTION_NEARBY, new SerializableJSONArray(json)); LocalBroadcastManager.getInstance(this).sendBroadcast(reply); } } private JSONArray put(String url, ArrayList<NameValuePair> params) throws AuthenticationException { params.add(new BasicNameValuePair("_method", "PUT")); return request(url, "put", params, null, true); } private JSONArray put(String url, JSONObject jsonContent) throws AuthenticationException { return request(url, "put", null, jsonContent, true); } private JSONArray delete(String url, ArrayList<NameValuePair> params) throws AuthenticationException { return request(url, "delete", params, null, true); } private JSONArray post(String url, ArrayList<NameValuePair> params, boolean authenticated) throws AuthenticationException { return request(url, "post", params, null, authenticated); } private JSONArray post(String url, ArrayList<NameValuePair> params) throws AuthenticationException { return request(url, "post", params, null, true); } private JSONArray post(String url, JSONObject jsonContent) throws AuthenticationException { return request(url, "post", null, jsonContent, true); } private JSONArray get(String url) throws AuthenticationException { return get(url, false); } private JSONArray get(String url, boolean authenticated) throws AuthenticationException { return request(url, "get", null, null, authenticated); } private JSONArray request(String url, String method, ArrayList<NameValuePair> params, JSONObject jsonContent, boolean authenticated) throws AuthenticationException { return request(url, method, params, jsonContent, authenticated, false, false); } private String getAnonymousJWTToken() { String anonymousApiSecret = getString(R.string.jwt_anonymous_api_secret); if (anonymousApiSecret == null) return null; Map<String, Object> claims = new HashMap<>(); claims.put("application", "android"); claims.put("exp", (System.currentTimeMillis() / 1000) + 300); String compactJwt = Jwts.builder() .setClaims(claims) .signWith(SignatureAlgorithm.HS512, anonymousApiSecret.getBytes()) .compact(); return compactJwt; } private String getJWTToken() { if (mPreferences == null) mPreferences = getSharedPreferences("iNaturalistPreferences", MODE_PRIVATE); String jwtToken = mPreferences.getString("jwt_token", null); Long jwtTokenExpiration = mPreferences.getLong("jwt_token_expiration", 0); if ((jwtToken == null) || ((System.currentTimeMillis() - jwtTokenExpiration) / 1000 > JWT_TOKEN_EXPIRATION_MINS * 60)) { // JWT Tokens expire after 30 mins - if the token is non-existent or older than 25 mins (safe margin) - ask for a new one try { JSONArray result = get(HOST + "/users/api_token.json", true); if ((result == null) || (result.length() == 0)) return null; // Get newest JWT Token jwtToken = result.getJSONObject(0).getString("api_token"); jwtTokenExpiration = System.currentTimeMillis(); SharedPreferences.Editor editor = mPreferences.edit(); editor.putString("jwt_token", jwtToken); editor.putLong("jwt_token_expiration", jwtTokenExpiration); editor.commit(); return jwtToken; } catch (Exception e) { Logger.tag(TAG).error(e); return null; } } else { // Current JWT token is still fresh/valid - return it as-is return jwtToken; } } private JSONArray request(String url, String method, ArrayList<NameValuePair> params, JSONObject jsonContent, boolean authenticated, boolean useJWTToken, boolean allowAnonymousJWTToken) throws AuthenticationException { OkHttpClient client = new OkHttpClient().newBuilder() .followRedirects(true) .followSslRedirects(true) .connectTimeout(HTTP_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS) .writeTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .readTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .build(); Request.Builder requestBuilder = new Request.Builder() .addHeader("User-Agent", getUserAgent(mApp)) .url(url); mRetryAfterDate = null; mServiceUnavailable = false; Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "URL: %s - %s (params: %s / %s)", method, url, (params != null ? params.toString() : "null"), (jsonContent != null ? jsonContent.toString() : "null"))); method = method.toUpperCase(); RequestBody requestBody = null; if ((jsonContent == null) && (params == null) && (method.equals("PUT") || method.equals("POST"))) { // PUT/POST with empty body requestBody = RequestBody.create(null, new byte[]{}); } else if (jsonContent != null) { // PUT/POST with JSON body content requestBuilder.addHeader("Content-type", "application/json"); requestBody = RequestBody.create(JSON, jsonContent.toString()); } else if (params != null) { // PUT/POST with "Standard" multipart encoding MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder() .setType(MultipartBody.FORM); for (int i = 0; i < params.size(); i++) { if (params.get(i).getName().equalsIgnoreCase("image") || params.get(i).getName().equalsIgnoreCase("file") || params.get(i).getName().equalsIgnoreCase("user[icon]") || params.get(i).getName().equalsIgnoreCase("audio")) { // If the key equals to "image", we use FileBody to transfer the data String value = params.get(i).getValue(); MediaType mediaType; if (value != null) { String name; if (params.get(i).getName().equalsIgnoreCase("audio")) { name = "file"; requestBuilder.addHeader("Accept", "application/json"); mediaType = MediaType.parse("audio/" + value.substring(value.lastIndexOf(".") + 1)); } else { name = params.get(i).getName(); mediaType = MediaType.parse("image/" + value.substring(value.lastIndexOf(".") + 1)); } File file = new File(value); requestBodyBuilder.addFormDataPart(name, file.getName(), RequestBody.create(mediaType, file)); } } else { // Normal string data requestBodyBuilder.addFormDataPart(params.get(i).getName(), params.get(i).getValue()); } } requestBody = requestBodyBuilder.build(); } if (url.startsWith(API_HOST) && (mCredentials != null)) { // For the node API, if we're logged in, *always* use JWT authentication authenticated = true; useJWTToken = true; } if (authenticated) { if (useJWTToken && allowAnonymousJWTToken && (mCredentials == null)) { // User not logged in, but allow using anonymous JWT requestBuilder.addHeader("Authorization", getAnonymousJWTToken()); } else { ensureCredentials(); if (useJWTToken) { // Use JSON Web Token for this request String jwtToken = getJWTToken(); if (jwtToken == null) { // Could not renew JWT token for some reason (either connectivity issues or user changed password) Logger.tag(TAG).error("JWT Token is null"); throw new AuthenticationException(); } requestBuilder.addHeader("Authorization", jwtToken); } else if (mLoginType == LoginType.PASSWORD) { // Old-style password authentication requestBuilder.addHeader("Authorization", "Basic " + mCredentials); } else { // OAuth2 token (Facebook/G+/etc) requestBuilder.addHeader("Authorization", "Bearer " + mCredentials); } } } try { mResponseErrors = null; Request request = requestBuilder.method(method, requestBody).build(); Response response = client.newCall(request).execute(); Logger.tag(TAG).debug("Response: " + response.code() + ": " + response.message()); mLastStatusCode = response.code(); if (response.isSuccessful()) { String content = response.body().string(); Logger.tag(TAG).debug(String.format(Locale.ENGLISH, "(for URL: %s - %s (params: %s / %s))", method, url, (params != null ? params.toString() : "null"), (jsonContent != null ? jsonContent.toString() : "null"))); Logger.tag(TAG).debug(content); JSONArray json = null; try { json = new JSONArray(content); } catch (JSONException e) { try { JSONObject jo = new JSONObject(content); json = new JSONArray(); json.put(jo); } catch (JSONException e2) { } } mResponseHeaders = response.headers(); response.close(); try { if ((json != null) && (json.length() > 0)) { JSONObject result = json.getJSONObject(0); if (result.has("errors")) { // Error response Logger.tag(TAG).error("Got an error response: " + result.get("errors").toString()); mResponseErrors = result.getJSONArray("errors"); return null; } } } catch (JSONException e) { Logger.tag(TAG).error(e); } if ((content != null) && (content.length() == 0)) { // In case it's just non content (but OK HTTP status code) - so there's no error json = new JSONArray(); } return json; } else { response.close(); // HTTP error of some kind - Check for response code switch (mLastStatusCode) { case HTTP_UNAUTHORIZED: // Authentication error throw new AuthenticationException(); case HTTP_UNAVAILABLE: Logger.tag(TAG).error("503 server unavailable"); mServiceUnavailable = true; // Find out if there's a "Retry-After" header List<String> headers = response.headers("Retry-After"); if (headers.size() > 0) { for (String timestampString : headers) { Logger.tag(TAG).error("Retry after raw string: " + timestampString); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); try { mRetryAfterDate = format.parse(timestampString); Logger.tag(TAG).error("Retry after: " + mRetryAfterDate); break; } catch (ParseException e) { Logger.tag(TAG).error(e); try { // Try parsing it as a seconds-delay value int secondsDelay = Integer.valueOf(timestampString); Logger.tag(TAG).error("Retry after: " + secondsDelay); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, secondsDelay); mRetryAfterDate = calendar.getTime(); break; } catch (NumberFormatException exc) { Logger.tag(TAG).error(exc); } } } } // Show service not available message to user mHandler.post(() -> { String errorMessage; if (mRetryAfterDate == null) { // No specific retry time errorMessage = getString(R.string.please_try_again_in_a_few_hours); } else { // Specific retry time Date currentTime = Calendar.getInstance().getTime(); long differenceSeconds = (mRetryAfterDate.getTime() - currentTime.getTime()) / 1000; long delay; String delayType; if (differenceSeconds < 60) { delayType = getString(R.string.seconds_value); delay = differenceSeconds; } else if (differenceSeconds < 60 * 60) { delayType = getString(R.string.minutes); delay = (differenceSeconds / 60); } else { delayType = getString(R.string.hours); delay = (differenceSeconds / (60 * 60)); } errorMessage = String.format(getString(R.string.please_try_again_in_x), delay, delayType); } if (System.currentTimeMillis() - mLastServiceUnavailableNotification > 30000) { // Make sure we won't notify the user about this too often mLastServiceUnavailableNotification = System.currentTimeMillis(); Toast.makeText(getApplicationContext(), getString(R.string.service_temporarily_unavailable) + " " + errorMessage, Toast.LENGTH_LONG).show(); } }); break; case HTTP_GONE: // TODO create notification that informs user some observations have been deleted on the server, // click should take them to an activity that lets them decide whether to delete them locally // or post them as new observations break; default: } return null; } } catch (IOException e) { Logger.tag(TAG).error("Error for URL " + url + ":" + e); Logger.tag(TAG).error(e); // Test out the Internet connection in multiple ways (helps pin-pointing issue) performConnectivityTest(); } return null; } private void performConnectivityTest() { long currentTime = System.currentTimeMillis(); // Perform connectivity test once every 5 minutes at most if (currentTime - mLastConnectionTest < 5 * 60 * 1000) { return; } mLastConnectionTest = currentTime; Logger.tag(TAG).info("Performing connectivity test"); contactUrl("https://api.inaturalist.org/v1/taxa/1"); contactUrl("http://api.inaturalist.org/v1/taxa/1"); contactUrl("https://www.inaturalist.org/taxa/1.json"); contactUrl("http://www.inaturalist.org/taxa/1.json"); contactUrl("https://www.naturalista.mx/taxa/1.json"); contactUrl("http://www.naturalista.mx/taxa/1.json"); contactUrl("https://www.google.com"); contactUrl("http://www.example.com"); } private void contactUrl(String url) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); try { Logger.tag(TAG).info("Contacting " + url); Response response = client.newCall(request).execute(); Logger.tag(TAG).info("isSuccessful: " + response.isSuccessful() + "; response code = " + response.code()); response.close(); } catch (IOException e) { Logger.tag(TAG).error("Failed contacting " + url); Logger.tag(TAG).error(e); } } private boolean ensureCredentials() throws AuthenticationException { if (mCredentials != null) { return true; } // request login unless passive if (!mPassive) { throw new AuthenticationException(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { stopForeground(true); } else { stopSelf(); } return false; } private void requestCredentials() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { stopForeground(true); } else { stopSelf(); } mApp.sweepingNotify(AUTH_NOTIFICATION, getString(R.string.please_sign_in), getString(R.string.please_sign_in_description), null); } // Returns an array of two strings: access token + iNat username public static String[] verifyCredentials(Context context, String username, String oauth2Token, LoginType authType, boolean askForScopeDeletion) { String grantType = null; String url = HOST + (authType == LoginType.OAUTH_PASSWORD ? "/oauth/token" : "/oauth/assertion_token"); OkHttpClient client = new OkHttpClient().newBuilder() .followRedirects(true) .followSslRedirects(true) .connectTimeout(HTTP_CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS) .writeTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .readTimeout(HTTP_READ_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS) .build(); FormBody.Builder requestBodyBuilder = new FormBody.Builder() .add("format", "json") .add("client_id", INaturalistApp.getAppContext().getString(R.string.oauth_client_id)); if (authType == LoginType.FACEBOOK) { grantType = "facebook"; } else if (authType == LoginType.GOOGLE) { grantType = "google"; } else if (authType == LoginType.OAUTH_PASSWORD) { grantType = "password"; } requestBodyBuilder.add("grant_type", grantType); if (authType == LoginType.OAUTH_PASSWORD) { requestBodyBuilder.add("password", oauth2Token); requestBodyBuilder.add("username", username); requestBodyBuilder.add("client_secret", INaturalistApp.getAppContext().getString(R.string.oauth_client_secret)); } else { requestBodyBuilder.add("assertion", oauth2Token); } if (askForScopeDeletion) { requestBodyBuilder.add("scope", "login write account_delete"); } RequestBody requestBody = requestBodyBuilder.build(); Request request = new Request.Builder() .addHeader("User-Agent", getUserAgent(context)) .url(url) .post(requestBody) .build(); try { Response response = client.newCall(request).execute(); if (!response.isSuccessful()) { Logger.tag(TAG).error("Authentication failed: " + response.code() + ": " + response.message()); return null; } String content = response.body().string(); response.close(); // Upgrade to an access token JSONObject json = new JSONObject(content); String accessToken = json.getString("access_token"); // Next, find the iNat username (since we currently only have the FB/Google email) request = new Request.Builder() .addHeader("User-Agent", getUserAgent(context)) .addHeader("Authorization", "Bearer " + accessToken) .url(HOST + "/users/edit.json") .build(); response = client.newCall(request).execute(); if (!response.isSuccessful()) { Logger.tag(TAG).error("Authentication failed (edit.json): " + response.code() + ": " + response.message()); return null; } content = response.body().string(); response.close(); Logger.tag(TAG).debug(String.format("RESP2: %s", content)); json = new JSONObject(content); if (!json.has("login")) { return null; } String returnedUsername = json.getString("login"); return new String[]{accessToken, returnedUsername}; } catch (IOException e) { Logger.tag(TAG).warn("Error for URL " + url, e); } catch (JSONException e) { Logger.tag(TAG).error(e); } return null; } /** Create a file Uri for saving an image or video */ private Uri getOutputMediaFileUri(Observation observation) { ContentValues values = new ContentValues(); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String name = "observation_" + observation.created_at.getTime() + "_" + timeStamp; values.put(android.provider.MediaStore.Images.Media.TITLE, name); return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } public void syncJson(JSONArray json, boolean isUser) { ArrayList<Integer> ids = new ArrayList<Integer>(); ArrayList<Integer> existingIds = new ArrayList<Integer>(); ArrayList<Integer> newIds = new ArrayList<Integer>(); HashMap<Integer, Observation> jsonObservationsById = new HashMap<Integer, Observation>(); Observation observation; Observation jsonObservation; BetterJSONObject o; Logger.tag(TAG).debug("syncJson: " + isUser); Logger.tag(TAG).debug(json.toString()); for (int i = 0; i < json.length(); i++) { try { o = new BetterJSONObject(json.getJSONObject(i)); ids.add(o.getInt("id")); Observation obs = new Observation(o); jsonObservationsById.put(o.getInt("id"), obs); if (isUser) { // Save the project observations aside (will be later used in the syncing of project observations) mProjectObservations.add(o.getJSONArray("project_observations")); // Save project field values Hashtable<Integer, ProjectFieldValue> fields = new Hashtable<Integer, ProjectFieldValue>(); JSONArray jsonFields = o.getJSONArray(o.has("ofvs") ? "ofvs" : "observation_field_values").getJSONArray(); for (int j = 0; j < jsonFields.length(); j++) { BetterJSONObject field = new BetterJSONObject(jsonFields.getJSONObject(j)); int fieldId; if (field.has("observation_field")) { fieldId = field.getJSONObject("observation_field").getInt("id"); } else { fieldId = field.getInt("field_id"); } fields.put(fieldId, new ProjectFieldValue(field)); } mProjectFieldValues.put(o.getInt("id"), fields); } } catch (JSONException e) { Logger.tag(TAG).error("syncJson: JSONException: " + e.toString()); } } // find obs with existing ids String joinedIds = StringUtils.join(ids, ","); // TODO why doesn't selectionArgs work for id IN (?) Cursor c = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id IN (" + joinedIds + ")", null, Observation.DEFAULT_SORT_ORDER); // update existing c.moveToFirst(); ContentValues cv; while (c.isAfterLast() == false) { observation = new Observation(c); jsonObservation = jsonObservationsById.get(observation.id); boolean isModified = observation.merge(jsonObservation); Logger.tag(TAG).debug("syncJson - updating existing: " + observation.id + ":" + observation._id + ":" + observation.preferred_common_name + ":" + observation.taxon_id); Logger.tag(TAG).debug("syncJson - remote obs: " + jsonObservation.id + ":" + jsonObservation.preferred_common_name + ":" + jsonObservation.taxon_id); cv = observation.getContentValues(); if (observation._updated_at.before(jsonObservation.updated_at)) { // Remote observation is newer (and thus has overwritten the local one) - update its // sync at time so we won't update the remote servers later on (since we won't // accidentally consider this an updated record) cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); } // Add any new photos that were added remotely ArrayList<Integer> observationPhotoIds = new ArrayList<Integer>(); ArrayList<Integer> existingObservationPhotoIds = new ArrayList<Integer>(); Cursor pc = getContentResolver().query( ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "(observation_id = " + observation.id + ")", null, null); pc.moveToFirst(); while (pc.isAfterLast() == false) { int photoId = pc.getInt(pc.getColumnIndexOrThrow(ObservationPhoto.ID)); if (photoId != 0) { existingObservationPhotoIds.add(photoId); } pc.moveToNext(); } pc.close(); Logger.tag(TAG).debug("syncJson: Adding photos for obs " + observation.id + ":" + existingObservationPhotoIds.toString()); Logger.tag(TAG).debug("syncJson: JsonObservation: " + jsonObservation + ":" + jsonObservation.photos); for (int j = 0; j < jsonObservation.photos.size(); j++) { ObservationPhoto photo = jsonObservation.photos.get(j); photo._observation_id = jsonObservation._id; if (photo.id == null) { Logger.tag(TAG).warn("syncJson: Null photo ID! " + photo); continue; } observationPhotoIds.add(photo.id); if (existingObservationPhotoIds.contains(photo.id)) { Logger.tag(TAG).debug("syncJson: photo " + photo.id + " has already been added, skipping..."); continue; } ContentValues opcv = photo.getContentValues(); // So we won't re-add this photo as though it was a local photo Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo.id + ":" + photo._id + ":" + photo._observation_id + ":" + photo.observation_id); opcv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); opcv.put(ObservationPhoto._OBSERVATION_ID, photo.observation_id); opcv.put(ObservationPhoto._PHOTO_ID, photo._photo_id); opcv.put(ObservationPhoto.ID, photo.id); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + photo.observation_id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); Observation obs = new Observation(obsc); opcv.put(ObservationPhoto.OBSERVATION_UUID, obs.uuid); } obsc.close(); try { getContentResolver().insert(ObservationPhoto.CONTENT_URI, opcv); } catch (SQLException ex) { // Happens when the photo already exists - ignore Logger.tag(TAG).error(ex); } } // Delete photos that were synced but weren't present in the remote response, // indicating they were deleted elsewhere String joinedPhotoIds = StringUtils.join(observationPhotoIds, ","); String where = "observation_id = " + observation.id + " AND id IS NOT NULL"; if (observationPhotoIds.size() > 0) { where += " AND id NOT in (" + joinedPhotoIds + ")"; } Logger.tag(TAG).debug("syncJson: Deleting local photos: " + where); Logger.tag(TAG).debug("syncJson: Deleting local photos, IDs: " + observationPhotoIds); int deleteCount = getContentResolver().delete( ObservationPhoto.CONTENT_URI, where, null); Logger.tag(TAG).debug("syncJson: Deleting local photos: " + deleteCount); if (deleteCount > 0) { Crashlytics.log(1, TAG, String.format(Locale.ENGLISH, "Warning: Deleted %d photos locally after sever did not contain those IDs - observation id: %s, photo ids: %s", deleteCount, observation.id, joinedPhotoIds)); } // Add any new sounds that were added remotely ArrayList<Integer> observationSoundIds = new ArrayList<Integer>(); ArrayList<Integer> existingObservationSoundIds = new ArrayList<Integer>(); Cursor sc = getContentResolver().query( ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "(observation_id = " + observation.id + ")", null, null); sc.moveToFirst(); while (sc.isAfterLast() == false) { int soundId = sc.getInt(sc.getColumnIndexOrThrow(ObservationSound.ID)); if (soundId != 0) { existingObservationSoundIds.add(soundId); } sc.moveToNext(); } sc.close(); Logger.tag(TAG).debug("syncJson: Adding sounds for obs " + observation.id + ":" + existingObservationSoundIds.toString()); Logger.tag(TAG).debug("syncJson: JsonObservation: " + jsonObservation + ":" + jsonObservation.sounds); for (int j = 0; j < jsonObservation.sounds.size(); j++) { ObservationSound sound = jsonObservation.sounds.get(j); sound._observation_id = jsonObservation._id; if (sound.id == null) { Logger.tag(TAG).warn("syncJson: Null sound ID! " + sound); continue; } observationSoundIds.add(sound.id); if (existingObservationSoundIds.contains(sound.id)) { Logger.tag(TAG).debug("syncJson: sound " + sound.id + " has already been added, skipping..."); continue; } ContentValues oscv = sound.getContentValues(); oscv.put(ObservationSound._OBSERVATION_ID, sound.observation_id); oscv.put(ObservationSound.ID, sound.id); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + sound.observation_id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); Observation obs = new Observation(obsc); oscv.put(ObservationSound.OBSERVATION_UUID, obs.uuid); } obsc.close(); try { getContentResolver().insert(ObservationSound.CONTENT_URI, oscv); } catch (SQLException ex) { // Happens when the sound already exists - ignore Logger.tag(TAG).error(ex); } } // Delete sounds that were synced but weren't present in the remote response, // indicating they were deleted elsewhere String joinedSoundIds = StringUtils.join(observationSoundIds, ","); where = "observation_id = " + observation.id + " AND id IS NOT NULL"; if (observationSoundIds.size() > 0) { where += " AND id NOT in (" + joinedSoundIds + ")"; } Logger.tag(TAG).debug("syncJson: Deleting local sounds: " + where); Logger.tag(TAG).debug("syncJson: Deleting local sounds, IDs: " + observationSoundIds); deleteCount = getContentResolver().delete( ObservationSound.CONTENT_URI, where, null); Logger.tag(TAG).debug("syncJson: Deleting local sounds: " + deleteCount); if (deleteCount > 0) { Crashlytics.log(1, TAG, String.format(Locale.ENGLISH, "Warning: Deleted %d sounds locally after server did not contain those IDs - observation id: %s, sound ids: %s", deleteCount, observation.id, joinedSoundIds)); } if (isModified) { // Only update the DB if needed Logger.tag(TAG).debug("syncJson: Updating observation: " + observation.id + ":" + observation._id); getContentResolver().update(observation.getUri(), cv, null, null); } existingIds.add(observation.id); c.moveToNext(); } c.close(); // insert new List<Observation> newObservations = new ArrayList<Observation>(); newIds = (ArrayList<Integer>) CollectionUtils.subtract(ids, existingIds); Collections.sort(newIds); Logger.tag(TAG).debug("syncJson: Adding new observations: " + newIds); for (int i = 0; i < newIds.size(); i++) { jsonObservation = jsonObservationsById.get(newIds.get(i)); Cursor c2 = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = ?", new String[]{String.valueOf(jsonObservation.id)}, Observation.DEFAULT_SORT_ORDER); int count = c2.getCount(); c2.close(); if (count > 0) { Logger.tag(TAG).debug("syncJson: Observation " + jsonObservation.id + " already exists locally - not adding"); continue; } cv = jsonObservation.getContentValues(); cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); cv.put(Observation.LAST_COMMENTS_COUNT, jsonObservation.comments_count); cv.put(Observation.LAST_IDENTIFICATIONS_COUNT, jsonObservation.identifications_count); Uri newObs = getContentResolver().insert(Observation.CONTENT_URI, cv); Long newObsId = ContentUris.parseId(newObs); jsonObservation._id = Integer.valueOf(newObsId.toString()); Logger.tag(TAG).debug("syncJson: Adding new obs: " + jsonObservation); newObservations.add(jsonObservation); } if (isUser) { for (int i = 0; i < newObservations.size(); i++) { jsonObservation = newObservations.get(i); // Save new observation's sounds Logger.tag(TAG).debug("syncJson: Saving new obs' sounds: " + jsonObservation + ":" + jsonObservation.sounds); for (int j = 0; j < jsonObservation.sounds.size(); j++) { ObservationSound sound = jsonObservation.sounds.get(j); c = getContentResolver().query(ObservationSound.CONTENT_URI, ObservationSound.PROJECTION, "id = ?", new String[]{String.valueOf(sound.id)}, ObservationSound.DEFAULT_SORT_ORDER); if (c.getCount() > 0) { // Sound already exists - don't save Logger.tag(TAG).debug("syncJson: Sound already exists - skipping: " + sound.id); c.close(); continue; } c.close(); sound._observation_id = jsonObservation._id; ContentValues opcv = sound.getContentValues(); Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + sound.id + ":" + sound._id + ":" + sound._observation_id + ":" + sound.observation_id); Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + sound); opcv.put(ObservationSound._OBSERVATION_ID, sound._observation_id); opcv.put(ObservationSound._ID, sound.id); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + sound.observation_id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); Observation obs = new Observation(obsc); opcv.put(ObservationSound.OBSERVATION_UUID, obs.uuid); } obsc.close(); try { getContentResolver().insert(ObservationSound.CONTENT_URI, opcv); } catch (SQLException ex) { // Happens when the sound already exists - ignore Logger.tag(TAG).error(ex); } } // Save the new observation's photos Logger.tag(TAG).debug("syncJson: Saving new obs' photos: " + jsonObservation + ":" + jsonObservation.photos); for (int j = 0; j < jsonObservation.photos.size(); j++) { ObservationPhoto photo = jsonObservation.photos.get(j); if (photo.uuid == null) { c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "_id = ?", new String[]{String.valueOf(photo.id)}, ObservationPhoto.DEFAULT_SORT_ORDER); } else { c = getContentResolver().query(ObservationPhoto.CONTENT_URI, ObservationPhoto.PROJECTION, "uuid = ?", new String[]{String.valueOf(photo.uuid)}, ObservationPhoto.DEFAULT_SORT_ORDER); } if (c.getCount() > 0) { // Photo already exists - don't save Logger.tag(TAG).debug("syncJson: Photo already exists - skipping: " + photo.id); c.close(); continue; } c.close(); photo._observation_id = jsonObservation._id; ContentValues opcv = photo.getContentValues(); Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo.id + ":" + photo._id + ":" + photo._observation_id + ":" + photo.observation_id); Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo); opcv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); // So we won't re-add this photo as though it was a local photo opcv.put(ObservationPhoto._OBSERVATION_ID, photo._observation_id); opcv.put(ObservationPhoto._PHOTO_ID, photo._photo_id); opcv.put(ObservationPhoto._ID, photo.id); Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION, "id = " + photo.observation_id, null, Observation.DEFAULT_SORT_ORDER); if (obsc.getCount() > 0) { obsc.moveToFirst(); Observation obs = new Observation(obsc); opcv.put(ObservationPhoto.OBSERVATION_UUID, obs.uuid); } obsc.close(); try { getContentResolver().insert(ObservationPhoto.CONTENT_URI, opcv); } catch (SQLException ex) { // Happens when the photo already exists - ignore Logger.tag(TAG).error(ex); } } } } if (isUser) { storeProjectObservations(); } } private JSONObject observationToJsonObject(Observation observation, boolean isPOST) { JSONObject obs = observation.toJSONObject(true); try { if (isPOST) { String inatNetwork = mApp.getInaturalistNetworkMember(); obs.put("site_id", mApp.getStringResourceByName("inat_site_id_" + inatNetwork)); } if (obs.has("longitude") && !obs.isNull("longitude")) { if (obs.getString("longitude").equals("0.0")) { // Handle edge cases where long/lat was saved as 0.0 - just don't send a location obs.remove("longitude"); } } if (obs.has("latitude") && !obs.isNull("latitude")) { if (obs.getString("latitude").equals("0.0")) { // Handle edge cases where long/lat was saved as 0.0 - just don't send a location obs.remove("latitude"); } } JSONObject obsContainer = new JSONObject(); obsContainer.put("observation", obs); obsContainer.put("ignore_photos", true); return obsContainer; } catch (JSONException exc) { Logger.tag(TAG).error(exc); return null; } } private ArrayList<NameValuePair> paramsForObservation(Observation observation, boolean isPOST) { ArrayList<NameValuePair> params = observation.getParams(); params.add(new BasicNameValuePair("ignore_photos", "true")); if (isPOST) { String inatNetwork = mApp.getInaturalistNetworkMember(); params.add(new BasicNameValuePair("site_id", mApp.getStringResourceByName("inat_site_id_" + inatNetwork))); } return params; } private boolean handleObservationResponse(Observation observation, JSONArray response) { try { if (response == null || response.length() != 1) { return false; } JSONObject json = response.getJSONObject(0); BetterJSONObject o = new BetterJSONObject(json); Logger.tag(TAG).debug("handleObservationResponse: Observation: " + observation); Logger.tag(TAG).debug("handleObservationResponse: JSON: "); Logger.tag(TAG).debug(json.toString()); if ((json.has("error") && !json.isNull("error")) || ((mLastStatusCode >= 400) && (mLastStatusCode < 500))) { // Error Logger.tag(TAG).debug("handleObservationResponse - error response (probably validation error)"); JSONObject original = json.optJSONObject("error").optJSONObject("original"); if ((original != null) && (original.has("error")) && (!original.isNull("error"))) { JSONArray errors = new JSONArray(); errors.put(original.optString("error").trim()); mApp.setErrorsForObservation(observation.id != null ? observation.id : observation._id, 0, errors); } return false; } else if (mLastStatusCode == HTTP_UNAVAILABLE) { // Server not available Logger.tag(TAG).error("503 - server not available"); return false; } Observation jsonObservation = new Observation(o); Logger.tag(TAG).debug("handleObservationResponse: jsonObservation: " + jsonObservation); observation.merge(jsonObservation); Logger.tag(TAG).debug("handleObservationResponse: merged obs: " + observation); ContentValues cv = observation.getContentValues(); cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); getContentResolver().update(observation.getUri(), cv, null, null); } catch (JSONException e) { Logger.tag(TAG).error(e); return false; } return true; } private class AuthenticationException extends Exception { private static final long serialVersionUID = 1L; } public interface IOnLocation { void onLocation(Location location); } private Location getLocationFromGPS() { LocationManager locationManager = (LocationManager) mApp.getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = locationManager.getBestProvider(criteria, false); if (provider == null) return null; Location location = locationManager.getLastKnownLocation(provider); Logger.tag(TAG).error("getLocationFromGPS: " + location); mLastLocation = location; return location; } private Location getLastKnownLocationFromClient() { Location location = null; try { location = LocationServices.FusedLocationApi.getLastLocation(mLocationClient); } catch (IllegalStateException ex) { Logger.tag(TAG).error(ex); } Logger.tag(TAG).error("getLastKnownLocationFromClient: " + location); if (location == null) { // Failed - try and return last place using GPS return getLocationFromGPS(); } else { mLastLocation = location; return location; } } private void getLocation(final IOnLocation callback) { if (!mApp.isLocationEnabled(null)) { Logger.tag(TAG).error("getLocation: Location not enabled"); // Location not enabled new Thread(new Runnable() { @Override public void run() { callback.onLocation(null); } }).start(); return; } int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); Logger.tag(TAG).error("getLocation: resultCode = " + resultCode); if (ConnectionResult.SUCCESS == resultCode) { // User Google Play services if available if ((mLocationClient != null) && (mLocationClient.isConnected())) { // Location client already initialized and connected - use it new Thread(new Runnable() { @Override public void run() { callback.onLocation(getLastKnownLocationFromClient()); } }).start(); } else { // Connect to the place services mLocationClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(new ConnectionCallbacks() { @Override public void onConnected(Bundle bundle) { // Connected successfully new Thread(new Runnable() { @Override public void run() { callback.onLocation(getLastKnownLocationFromClient()); mLocationClient.disconnect(); } }).start(); } @Override public void onConnectionSuspended(int i) { } }) .addOnConnectionFailedListener(new OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult connectionResult) { // Couldn't connect new Thread(new Runnable() { @Override public void run() { callback.onLocation(null); mLocationClient.disconnect(); } }).start(); } }) .build(); mLocationClient.connect(); } } else { // Use GPS alone for place new Thread(new Runnable() { @Override public void run() { callback.onLocation(getLocationFromGPS()); } }).start(); } } @Override public void onDestroy() { mIsStopped = true; super.onDestroy(); } public static String getUserAgent(Context context) { PackageInfo info = null; try { info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); } catch (PackageManager.NameNotFoundException e) { Logger.tag(TAG).error(e); } String userAgent = USER_AGENT.replace("%BUILD%", info != null ? String.valueOf(info.versionCode) : String.valueOf(INaturalistApp.VERSION)); userAgent = userAgent.replace("%VERSION%", info != null ? info.versionName : String.valueOf(INaturalistApp.VERSION)); return userAgent; } private int modulo(int x, int y) { int result = x % y; if (result < 0) { result += y; } return result; } private boolean downloadToFile(String uri, String outputFilename) { HttpURLConnection conn = null; StringBuilder jsonResults = new StringBuilder(); try { URL url = new URL(uri); conn = (HttpURLConnection) url.openConnection(); InputStream in = conn.getInputStream(); FileOutputStream output = new FileOutputStream(outputFilename); int read; byte[] buff = new byte[1024]; while ((read = in.read(buff)) != -1) { output.write(buff, 0, read); } output.close(); conn.disconnect(); } catch (MalformedURLException e) { return false; } catch (IOException e) { return false; } return true; } }
syncJson - mechanism to not run in parallel (duplicate obs phenomenon)
iNaturalist/src/main/java/org/inaturalist/android/INaturalistService.java
syncJson - mechanism to not run in parallel (duplicate obs phenomenon)
<ide><path>Naturalist/src/main/java/org/inaturalist/android/INaturalistService.java <ide> private String mNearByObservationsUrl; <ide> private int mLastStatusCode = 0; <ide> private Object mObservationLock = new Object(); <add> private Object mSyncJsonLock = new Object(); <add> private List<String> mSyncedJSONs = new ArrayList<>(); <ide> <ide> private Location mLastLocation = null; <ide> <ide> <ide> <ide> public void syncJson(JSONArray json, boolean isUser) { <del> ArrayList<Integer> ids = new ArrayList<Integer>(); <del> ArrayList<Integer> existingIds = new ArrayList<Integer>(); <del> ArrayList<Integer> newIds = new ArrayList<Integer>(); <del> HashMap<Integer, Observation> jsonObservationsById = new HashMap<Integer, Observation>(); <del> Observation observation; <del> Observation jsonObservation; <del> <del> BetterJSONObject o; <del> <del> Logger.tag(TAG).debug("syncJson: " + isUser); <del> Logger.tag(TAG).debug(json.toString()); <del> <del> for (int i = 0; i < json.length(); i++) { <del> try { <del> o = new BetterJSONObject(json.getJSONObject(i)); <del> ids.add(o.getInt("id")); <del> <del> Observation obs = new Observation(o); <del> jsonObservationsById.put(o.getInt("id"), obs); <del> <del> if (isUser) { <del> // Save the project observations aside (will be later used in the syncing of project observations) <del> mProjectObservations.add(o.getJSONArray("project_observations")); <del> <del> // Save project field values <del> Hashtable<Integer, ProjectFieldValue> fields = new Hashtable<Integer, ProjectFieldValue>(); <del> JSONArray jsonFields = o.getJSONArray(o.has("ofvs") ? "ofvs" : "observation_field_values").getJSONArray(); <del> <del> for (int j = 0; j < jsonFields.length(); j++) { <del> BetterJSONObject field = new BetterJSONObject(jsonFields.getJSONObject(j)); <del> int fieldId; <del> if (field.has("observation_field")) { <del> fieldId = field.getJSONObject("observation_field").getInt("id"); <del> } else { <del> fieldId = field.getInt("field_id"); <add> synchronized (mSyncJsonLock) { <add> ArrayList<Integer> ids = new ArrayList<Integer>(); <add> ArrayList<Integer> existingIds = new ArrayList<Integer>(); <add> ArrayList<Integer> newIds = new ArrayList<Integer>(); <add> HashMap<Integer, Observation> jsonObservationsById = new HashMap<Integer, Observation>(); <add> Observation observation; <add> Observation jsonObservation; <add> <add> if (mSyncedJSONs.contains(json.toString())) { <add> // Already synced this exact JSON recently <add> Logger.tag(TAG).info("Skipping syncJSON - already synced same JSON"); <add> return; <add> } <add> <add> mSyncedJSONs.add(json.toString()); <add> <add> BetterJSONObject o; <add> <add> Logger.tag(TAG).debug("syncJson: " + isUser); <add> Logger.tag(TAG).debug(json.toString()); <add> <add> for (int i = 0; i < json.length(); i++) { <add> try { <add> o = new BetterJSONObject(json.getJSONObject(i)); <add> ids.add(o.getInt("id")); <add> <add> Observation obs = new Observation(o); <add> jsonObservationsById.put(o.getInt("id"), obs); <add> <add> if (isUser) { <add> // Save the project observations aside (will be later used in the syncing of project observations) <add> mProjectObservations.add(o.getJSONArray("project_observations")); <add> <add> // Save project field values <add> Hashtable<Integer, ProjectFieldValue> fields = new Hashtable<Integer, ProjectFieldValue>(); <add> JSONArray jsonFields = o.getJSONArray(o.has("ofvs") ? "ofvs" : "observation_field_values").getJSONArray(); <add> <add> for (int j = 0; j < jsonFields.length(); j++) { <add> BetterJSONObject field = new BetterJSONObject(jsonFields.getJSONObject(j)); <add> int fieldId; <add> if (field.has("observation_field")) { <add> fieldId = field.getJSONObject("observation_field").getInt("id"); <add> } else { <add> fieldId = field.getInt("field_id"); <add> } <add> fields.put(fieldId, new ProjectFieldValue(field)); <ide> } <del> fields.put(fieldId, new ProjectFieldValue(field)); <add> <add> mProjectFieldValues.put(o.getInt("id"), fields); <ide> } <del> <del> mProjectFieldValues.put(o.getInt("id"), fields); <del> } <del> } catch (JSONException e) { <del> Logger.tag(TAG).error("syncJson: JSONException: " + e.toString()); <del> } <del> } <del> // find obs with existing ids <del> String joinedIds = StringUtils.join(ids, ","); <del> // TODO why doesn't selectionArgs work for id IN (?) <del> Cursor c = getContentResolver().query(Observation.CONTENT_URI, <del> Observation.PROJECTION, <del> "id IN (" + joinedIds + ")", null, Observation.DEFAULT_SORT_ORDER); <del> <del> // update existing <del> c.moveToFirst(); <del> ContentValues cv; <del> while (c.isAfterLast() == false) { <del> observation = new Observation(c); <del> jsonObservation = jsonObservationsById.get(observation.id); <del> boolean isModified = observation.merge(jsonObservation); <del> <del> Logger.tag(TAG).debug("syncJson - updating existing: " + observation.id + ":" + observation._id + ":" + observation.preferred_common_name + ":" + observation.taxon_id); <del> Logger.tag(TAG).debug("syncJson - remote obs: " + jsonObservation.id + ":" + jsonObservation.preferred_common_name + ":" + jsonObservation.taxon_id); <del> <del> cv = observation.getContentValues(); <del> if (observation._updated_at.before(jsonObservation.updated_at)) { <del> // Remote observation is newer (and thus has overwritten the local one) - update its <del> // sync at time so we won't update the remote servers later on (since we won't <del> // accidentally consider this an updated record) <del> cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); <del> } <del> <del> // Add any new photos that were added remotely <del> ArrayList<Integer> observationPhotoIds = new ArrayList<Integer>(); <del> ArrayList<Integer> existingObservationPhotoIds = new ArrayList<Integer>(); <del> Cursor pc = getContentResolver().query( <del> ObservationPhoto.CONTENT_URI, <del> ObservationPhoto.PROJECTION, <del> "(observation_id = " + observation.id + ")", <del> null, null); <del> pc.moveToFirst(); <del> while (pc.isAfterLast() == false) { <del> int photoId = pc.getInt(pc.getColumnIndexOrThrow(ObservationPhoto.ID)); <del> if (photoId != 0) { <del> existingObservationPhotoIds.add(photoId); <del> } <del> pc.moveToNext(); <del> } <del> pc.close(); <del> Logger.tag(TAG).debug("syncJson: Adding photos for obs " + observation.id + ":" + existingObservationPhotoIds.toString()); <del> Logger.tag(TAG).debug("syncJson: JsonObservation: " + jsonObservation + ":" + jsonObservation.photos); <del> for (int j = 0; j < jsonObservation.photos.size(); j++) { <del> ObservationPhoto photo = jsonObservation.photos.get(j); <del> photo._observation_id = jsonObservation._id; <del> <del> if (photo.id == null) { <del> Logger.tag(TAG).warn("syncJson: Null photo ID! " + photo); <del> continue; <del> } <del> <del> observationPhotoIds.add(photo.id); <del> if (existingObservationPhotoIds.contains(photo.id)) { <del> Logger.tag(TAG).debug("syncJson: photo " + photo.id + " has already been added, skipping..."); <del> continue; <del> } <del> ContentValues opcv = photo.getContentValues(); <del> // So we won't re-add this photo as though it was a local photo <del> Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo.id + ":" + photo._id + ":" + photo._observation_id + ":" + photo.observation_id); <del> opcv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); <del> opcv.put(ObservationPhoto._OBSERVATION_ID, photo.observation_id); <del> opcv.put(ObservationPhoto._PHOTO_ID, photo._photo_id); <del> opcv.put(ObservationPhoto.ID, photo.id); <del> <del> Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, <del> Observation.PROJECTION, <del> "id = " + photo.observation_id, null, Observation.DEFAULT_SORT_ORDER); <del> if (obsc.getCount() > 0) { <del> obsc.moveToFirst(); <del> Observation obs = new Observation(obsc); <del> opcv.put(ObservationPhoto.OBSERVATION_UUID, obs.uuid); <del> } <del> obsc.close(); <del> try { <del> getContentResolver().insert(ObservationPhoto.CONTENT_URI, opcv); <del> } catch (SQLException ex) { <del> // Happens when the photo already exists - ignore <del> Logger.tag(TAG).error(ex); <del> } <del> } <del> <del> // Delete photos that were synced but weren't present in the remote response, <del> // indicating they were deleted elsewhere <del> String joinedPhotoIds = StringUtils.join(observationPhotoIds, ","); <del> String where = "observation_id = " + observation.id + " AND id IS NOT NULL"; <del> if (observationPhotoIds.size() > 0) { <del> where += " AND id NOT in (" + joinedPhotoIds + ")"; <del> } <del> Logger.tag(TAG).debug("syncJson: Deleting local photos: " + where); <del> Logger.tag(TAG).debug("syncJson: Deleting local photos, IDs: " + observationPhotoIds); <del> int deleteCount = getContentResolver().delete( <del> ObservationPhoto.CONTENT_URI, <del> where, <del> null); <del> Logger.tag(TAG).debug("syncJson: Deleting local photos: " + deleteCount); <del> <del> if (deleteCount > 0) { <del> Crashlytics.log(1, TAG, String.format(Locale.ENGLISH, "Warning: Deleted %d photos locally after sever did not contain those IDs - observation id: %s, photo ids: %s", <del> deleteCount, observation.id, joinedPhotoIds)); <del> } <del> <del> // Add any new sounds that were added remotely <del> ArrayList<Integer> observationSoundIds = new ArrayList<Integer>(); <del> ArrayList<Integer> existingObservationSoundIds = new ArrayList<Integer>(); <del> Cursor sc = getContentResolver().query( <del> ObservationSound.CONTENT_URI, <del> ObservationSound.PROJECTION, <del> "(observation_id = " + observation.id + ")", <del> null, null); <del> sc.moveToFirst(); <del> while (sc.isAfterLast() == false) { <del> int soundId = sc.getInt(sc.getColumnIndexOrThrow(ObservationSound.ID)); <del> if (soundId != 0) { <del> existingObservationSoundIds.add(soundId); <del> } <del> sc.moveToNext(); <del> } <del> sc.close(); <del> Logger.tag(TAG).debug("syncJson: Adding sounds for obs " + observation.id + ":" + existingObservationSoundIds.toString()); <del> Logger.tag(TAG).debug("syncJson: JsonObservation: " + jsonObservation + ":" + jsonObservation.sounds); <del> for (int j = 0; j < jsonObservation.sounds.size(); j++) { <del> ObservationSound sound = jsonObservation.sounds.get(j); <del> sound._observation_id = jsonObservation._id; <del> <del> if (sound.id == null) { <del> Logger.tag(TAG).warn("syncJson: Null sound ID! " + sound); <del> continue; <del> } <del> <del> observationSoundIds.add(sound.id); <del> if (existingObservationSoundIds.contains(sound.id)) { <del> Logger.tag(TAG).debug("syncJson: sound " + sound.id + " has already been added, skipping..."); <del> continue; <del> } <del> ContentValues oscv = sound.getContentValues(); <del> oscv.put(ObservationSound._OBSERVATION_ID, sound.observation_id); <del> oscv.put(ObservationSound.ID, sound.id); <del> <del> Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, <del> Observation.PROJECTION, <del> "id = " + sound.observation_id, null, Observation.DEFAULT_SORT_ORDER); <del> if (obsc.getCount() > 0) { <del> obsc.moveToFirst(); <del> Observation obs = new Observation(obsc); <del> oscv.put(ObservationSound.OBSERVATION_UUID, obs.uuid); <del> } <del> obsc.close(); <del> try { <del> getContentResolver().insert(ObservationSound.CONTENT_URI, oscv); <del> } catch (SQLException ex) { <del> // Happens when the sound already exists - ignore <del> Logger.tag(TAG).error(ex); <del> } <del> } <del> <del> // Delete sounds that were synced but weren't present in the remote response, <del> // indicating they were deleted elsewhere <del> String joinedSoundIds = StringUtils.join(observationSoundIds, ","); <del> where = "observation_id = " + observation.id + " AND id IS NOT NULL"; <del> if (observationSoundIds.size() > 0) { <del> where += " AND id NOT in (" + joinedSoundIds + ")"; <del> } <del> Logger.tag(TAG).debug("syncJson: Deleting local sounds: " + where); <del> Logger.tag(TAG).debug("syncJson: Deleting local sounds, IDs: " + observationSoundIds); <del> deleteCount = getContentResolver().delete( <del> ObservationSound.CONTENT_URI, <del> where, <del> null); <del> Logger.tag(TAG).debug("syncJson: Deleting local sounds: " + deleteCount); <del> <del> if (deleteCount > 0) { <del> Crashlytics.log(1, TAG, String.format(Locale.ENGLISH, "Warning: Deleted %d sounds locally after server did not contain those IDs - observation id: %s, sound ids: %s", <del> deleteCount, observation.id, joinedSoundIds)); <del> } <del> <del> <del> if (isModified) { <del> // Only update the DB if needed <del> Logger.tag(TAG).debug("syncJson: Updating observation: " + observation.id + ":" + observation._id); <del> getContentResolver().update(observation.getUri(), cv, null, null); <del> } <del> existingIds.add(observation.id); <del> c.moveToNext(); <del> } <del> c.close(); <del> <del> // insert new <del> List<Observation> newObservations = new ArrayList<Observation>(); <del> newIds = (ArrayList<Integer>) CollectionUtils.subtract(ids, existingIds); <del> Collections.sort(newIds); <del> Logger.tag(TAG).debug("syncJson: Adding new observations: " + newIds); <del> for (int i = 0; i < newIds.size(); i++) { <del> jsonObservation = jsonObservationsById.get(newIds.get(i)); <del> <del> Cursor c2 = getContentResolver().query(Observation.CONTENT_URI, <add> } catch (JSONException e) { <add> Logger.tag(TAG).error("syncJson: JSONException: " + e.toString()); <add> } <add> } <add> // find obs with existing ids <add> String joinedIds = StringUtils.join(ids, ","); <add> // TODO why doesn't selectionArgs work for id IN (?) <add> Cursor c = getContentResolver().query(Observation.CONTENT_URI, <ide> Observation.PROJECTION, <del> "id = ?", new String[]{String.valueOf(jsonObservation.id)}, Observation.DEFAULT_SORT_ORDER); <del> int count = c2.getCount(); <del> c2.close(); <del> <del> if (count > 0) { <del> Logger.tag(TAG).debug("syncJson: Observation " + jsonObservation.id + " already exists locally - not adding"); <del> continue; <del> } <del> <del> cv = jsonObservation.getContentValues(); <del> cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); <del> cv.put(Observation.LAST_COMMENTS_COUNT, jsonObservation.comments_count); <del> cv.put(Observation.LAST_IDENTIFICATIONS_COUNT, jsonObservation.identifications_count); <del> Uri newObs = getContentResolver().insert(Observation.CONTENT_URI, cv); <del> Long newObsId = ContentUris.parseId(newObs); <del> jsonObservation._id = Integer.valueOf(newObsId.toString()); <del> Logger.tag(TAG).debug("syncJson: Adding new obs: " + jsonObservation); <del> newObservations.add(jsonObservation); <del> } <del> <del> if (isUser) { <del> for (int i = 0; i < newObservations.size(); i++) { <del> jsonObservation = newObservations.get(i); <del> <del> // Save new observation's sounds <del> Logger.tag(TAG).debug("syncJson: Saving new obs' sounds: " + jsonObservation + ":" + jsonObservation.sounds); <del> for (int j = 0; j < jsonObservation.sounds.size(); j++) { <del> ObservationSound sound = jsonObservation.sounds.get(j); <del> <del> c = getContentResolver().query(ObservationSound.CONTENT_URI, <del> ObservationSound.PROJECTION, <del> "id = ?", new String[]{String.valueOf(sound.id)}, ObservationSound.DEFAULT_SORT_ORDER); <del> <del> if (c.getCount() > 0) { <del> // Sound already exists - don't save <del> Logger.tag(TAG).debug("syncJson: Sound already exists - skipping: " + sound.id); <del> c.close(); <add> "id IN (" + joinedIds + ")", null, Observation.DEFAULT_SORT_ORDER); <add> <add> // update existing <add> c.moveToFirst(); <add> ContentValues cv; <add> while (c.isAfterLast() == false) { <add> observation = new Observation(c); <add> jsonObservation = jsonObservationsById.get(observation.id); <add> boolean isModified = observation.merge(jsonObservation); <add> <add> Logger.tag(TAG).debug("syncJson - updating existing: " + observation.id + ":" + observation._id + ":" + observation.preferred_common_name + ":" + observation.taxon_id); <add> Logger.tag(TAG).debug("syncJson - remote obs: " + jsonObservation.id + ":" + jsonObservation.preferred_common_name + ":" + jsonObservation.taxon_id); <add> <add> cv = observation.getContentValues(); <add> if (observation._updated_at.before(jsonObservation.updated_at)) { <add> // Remote observation is newer (and thus has overwritten the local one) - update its <add> // sync at time so we won't update the remote servers later on (since we won't <add> // accidentally consider this an updated record) <add> cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); <add> } <add> <add> // Add any new photos that were added remotely <add> ArrayList<Integer> observationPhotoIds = new ArrayList<Integer>(); <add> ArrayList<Integer> existingObservationPhotoIds = new ArrayList<Integer>(); <add> Cursor pc = getContentResolver().query( <add> ObservationPhoto.CONTENT_URI, <add> ObservationPhoto.PROJECTION, <add> "(observation_id = " + observation.id + ")", <add> null, null); <add> pc.moveToFirst(); <add> while (pc.isAfterLast() == false) { <add> int photoId = pc.getInt(pc.getColumnIndexOrThrow(ObservationPhoto.ID)); <add> if (photoId != 0) { <add> existingObservationPhotoIds.add(photoId); <add> } <add> pc.moveToNext(); <add> } <add> pc.close(); <add> Logger.tag(TAG).debug("syncJson: Adding photos for obs " + observation.id + ":" + existingObservationPhotoIds.toString()); <add> Logger.tag(TAG).debug("syncJson: JsonObservation: " + jsonObservation + ":" + jsonObservation.photos); <add> for (int j = 0; j < jsonObservation.photos.size(); j++) { <add> ObservationPhoto photo = jsonObservation.photos.get(j); <add> photo._observation_id = jsonObservation._id; <add> <add> if (photo.id == null) { <add> Logger.tag(TAG).warn("syncJson: Null photo ID! " + photo); <ide> continue; <ide> } <ide> <del> c.close(); <del> <del> sound._observation_id = jsonObservation._id; <del> <del> ContentValues opcv = sound.getContentValues(); <del> Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + sound.id + ":" + sound._id + ":" + sound._observation_id + ":" + sound.observation_id); <del> Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + sound); <del> opcv.put(ObservationSound._OBSERVATION_ID, sound._observation_id); <del> opcv.put(ObservationSound._ID, sound.id); <del> Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, <del> Observation.PROJECTION, <del> "id = " + sound.observation_id, null, Observation.DEFAULT_SORT_ORDER); <del> if (obsc.getCount() > 0) { <del> obsc.moveToFirst(); <del> Observation obs = new Observation(obsc); <del> opcv.put(ObservationSound.OBSERVATION_UUID, obs.uuid); <del> } <del> obsc.close(); <del> try { <del> getContentResolver().insert(ObservationSound.CONTENT_URI, opcv); <del> } catch (SQLException ex) { <del> // Happens when the sound already exists - ignore <del> Logger.tag(TAG).error(ex); <del> } <del> } <del> <del> // Save the new observation's photos <del> Logger.tag(TAG).debug("syncJson: Saving new obs' photos: " + jsonObservation + ":" + jsonObservation.photos); <del> for (int j = 0; j < jsonObservation.photos.size(); j++) { <del> ObservationPhoto photo = jsonObservation.photos.get(j); <del> <del> if (photo.uuid == null) { <del> c = getContentResolver().query(ObservationPhoto.CONTENT_URI, <del> ObservationPhoto.PROJECTION, <del> "_id = ?", new String[]{String.valueOf(photo.id)}, ObservationPhoto.DEFAULT_SORT_ORDER); <del> } else { <del> c = getContentResolver().query(ObservationPhoto.CONTENT_URI, <del> ObservationPhoto.PROJECTION, <del> "uuid = ?", new String[]{String.valueOf(photo.uuid)}, ObservationPhoto.DEFAULT_SORT_ORDER); <del> } <del> <del> if (c.getCount() > 0) { <del> // Photo already exists - don't save <del> Logger.tag(TAG).debug("syncJson: Photo already exists - skipping: " + photo.id); <del> c.close(); <add> observationPhotoIds.add(photo.id); <add> if (existingObservationPhotoIds.contains(photo.id)) { <add> Logger.tag(TAG).debug("syncJson: photo " + photo.id + " has already been added, skipping..."); <ide> continue; <ide> } <del> <del> c.close(); <del> <del> photo._observation_id = jsonObservation._id; <del> <ide> ContentValues opcv = photo.getContentValues(); <add> // So we won't re-add this photo as though it was a local photo <ide> Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo.id + ":" + photo._id + ":" + photo._observation_id + ":" + photo.observation_id); <del> Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo); <del> opcv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); // So we won't re-add this photo as though it was a local photo <del> opcv.put(ObservationPhoto._OBSERVATION_ID, photo._observation_id); <add> opcv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); <add> opcv.put(ObservationPhoto._OBSERVATION_ID, photo.observation_id); <ide> opcv.put(ObservationPhoto._PHOTO_ID, photo._photo_id); <del> opcv.put(ObservationPhoto._ID, photo.id); <add> opcv.put(ObservationPhoto.ID, photo.id); <add> <ide> Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, <ide> Observation.PROJECTION, <ide> "id = " + photo.observation_id, null, Observation.DEFAULT_SORT_ORDER); <ide> Logger.tag(TAG).error(ex); <ide> } <ide> } <del> } <del> } <del> <del> if (isUser) { <del> storeProjectObservations(); <add> <add> // Delete photos that were synced but weren't present in the remote response, <add> // indicating they were deleted elsewhere <add> String joinedPhotoIds = StringUtils.join(observationPhotoIds, ","); <add> String where = "observation_id = " + observation.id + " AND id IS NOT NULL"; <add> if (observationPhotoIds.size() > 0) { <add> where += " AND id NOT in (" + joinedPhotoIds + ")"; <add> } <add> Logger.tag(TAG).debug("syncJson: Deleting local photos: " + where); <add> Logger.tag(TAG).debug("syncJson: Deleting local photos, IDs: " + observationPhotoIds); <add> int deleteCount = getContentResolver().delete( <add> ObservationPhoto.CONTENT_URI, <add> where, <add> null); <add> Logger.tag(TAG).debug("syncJson: Deleting local photos: " + deleteCount); <add> <add> if (deleteCount > 0) { <add> Crashlytics.log(1, TAG, String.format(Locale.ENGLISH, "Warning: Deleted %d photos locally after sever did not contain those IDs - observation id: %s, photo ids: %s", <add> deleteCount, observation.id, joinedPhotoIds)); <add> } <add> <add> // Add any new sounds that were added remotely <add> ArrayList<Integer> observationSoundIds = new ArrayList<Integer>(); <add> ArrayList<Integer> existingObservationSoundIds = new ArrayList<Integer>(); <add> Cursor sc = getContentResolver().query( <add> ObservationSound.CONTENT_URI, <add> ObservationSound.PROJECTION, <add> "(observation_id = " + observation.id + ")", <add> null, null); <add> sc.moveToFirst(); <add> while (sc.isAfterLast() == false) { <add> int soundId = sc.getInt(sc.getColumnIndexOrThrow(ObservationSound.ID)); <add> if (soundId != 0) { <add> existingObservationSoundIds.add(soundId); <add> } <add> sc.moveToNext(); <add> } <add> sc.close(); <add> Logger.tag(TAG).debug("syncJson: Adding sounds for obs " + observation.id + ":" + existingObservationSoundIds.toString()); <add> Logger.tag(TAG).debug("syncJson: JsonObservation: " + jsonObservation + ":" + jsonObservation.sounds); <add> for (int j = 0; j < jsonObservation.sounds.size(); j++) { <add> ObservationSound sound = jsonObservation.sounds.get(j); <add> sound._observation_id = jsonObservation._id; <add> <add> if (sound.id == null) { <add> Logger.tag(TAG).warn("syncJson: Null sound ID! " + sound); <add> continue; <add> } <add> <add> observationSoundIds.add(sound.id); <add> if (existingObservationSoundIds.contains(sound.id)) { <add> Logger.tag(TAG).debug("syncJson: sound " + sound.id + " has already been added, skipping..."); <add> continue; <add> } <add> ContentValues oscv = sound.getContentValues(); <add> oscv.put(ObservationSound._OBSERVATION_ID, sound.observation_id); <add> oscv.put(ObservationSound.ID, sound.id); <add> <add> Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, <add> Observation.PROJECTION, <add> "id = " + sound.observation_id, null, Observation.DEFAULT_SORT_ORDER); <add> if (obsc.getCount() > 0) { <add> obsc.moveToFirst(); <add> Observation obs = new Observation(obsc); <add> oscv.put(ObservationSound.OBSERVATION_UUID, obs.uuid); <add> } <add> obsc.close(); <add> try { <add> getContentResolver().insert(ObservationSound.CONTENT_URI, oscv); <add> } catch (SQLException ex) { <add> // Happens when the sound already exists - ignore <add> Logger.tag(TAG).error(ex); <add> } <add> } <add> <add> // Delete sounds that were synced but weren't present in the remote response, <add> // indicating they were deleted elsewhere <add> String joinedSoundIds = StringUtils.join(observationSoundIds, ","); <add> where = "observation_id = " + observation.id + " AND id IS NOT NULL"; <add> if (observationSoundIds.size() > 0) { <add> where += " AND id NOT in (" + joinedSoundIds + ")"; <add> } <add> Logger.tag(TAG).debug("syncJson: Deleting local sounds: " + where); <add> Logger.tag(TAG).debug("syncJson: Deleting local sounds, IDs: " + observationSoundIds); <add> deleteCount = getContentResolver().delete( <add> ObservationSound.CONTENT_URI, <add> where, <add> null); <add> Logger.tag(TAG).debug("syncJson: Deleting local sounds: " + deleteCount); <add> <add> if (deleteCount > 0) { <add> Crashlytics.log(1, TAG, String.format(Locale.ENGLISH, "Warning: Deleted %d sounds locally after server did not contain those IDs - observation id: %s, sound ids: %s", <add> deleteCount, observation.id, joinedSoundIds)); <add> } <add> <add> <add> if (isModified) { <add> // Only update the DB if needed <add> Logger.tag(TAG).debug("syncJson: Updating observation: " + observation.id + ":" + observation._id); <add> getContentResolver().update(observation.getUri(), cv, null, null); <add> } <add> existingIds.add(observation.id); <add> c.moveToNext(); <add> } <add> c.close(); <add> <add> // insert new <add> List<Observation> newObservations = new ArrayList<Observation>(); <add> newIds = (ArrayList<Integer>) CollectionUtils.subtract(ids, existingIds); <add> Collections.sort(newIds); <add> Logger.tag(TAG).debug("syncJson: Adding new observations: " + newIds); <add> for (int i = 0; i < newIds.size(); i++) { <add> jsonObservation = jsonObservationsById.get(newIds.get(i)); <add> <add> Cursor c2 = getContentResolver().query(Observation.CONTENT_URI, <add> Observation.PROJECTION, <add> "id = ?", new String[]{String.valueOf(jsonObservation.id)}, Observation.DEFAULT_SORT_ORDER); <add> int count = c2.getCount(); <add> c2.close(); <add> <add> if (count > 0) { <add> Logger.tag(TAG).debug("syncJson: Observation " + jsonObservation.id + " already exists locally - not adding"); <add> continue; <add> } <add> <add> cv = jsonObservation.getContentValues(); <add> cv.put(Observation._SYNCED_AT, System.currentTimeMillis()); <add> cv.put(Observation.LAST_COMMENTS_COUNT, jsonObservation.comments_count); <add> cv.put(Observation.LAST_IDENTIFICATIONS_COUNT, jsonObservation.identifications_count); <add> Uri newObs = getContentResolver().insert(Observation.CONTENT_URI, cv); <add> Long newObsId = ContentUris.parseId(newObs); <add> jsonObservation._id = Integer.valueOf(newObsId.toString()); <add> Logger.tag(TAG).debug("syncJson: Adding new obs: " + jsonObservation); <add> newObservations.add(jsonObservation); <add> } <add> <add> if (isUser) { <add> for (int i = 0; i < newObservations.size(); i++) { <add> jsonObservation = newObservations.get(i); <add> <add> // Save new observation's sounds <add> Logger.tag(TAG).debug("syncJson: Saving new obs' sounds: " + jsonObservation + ":" + jsonObservation.sounds); <add> for (int j = 0; j < jsonObservation.sounds.size(); j++) { <add> ObservationSound sound = jsonObservation.sounds.get(j); <add> <add> c = getContentResolver().query(ObservationSound.CONTENT_URI, <add> ObservationSound.PROJECTION, <add> "id = ?", new String[]{String.valueOf(sound.id)}, ObservationSound.DEFAULT_SORT_ORDER); <add> <add> if (c.getCount() > 0) { <add> // Sound already exists - don't save <add> Logger.tag(TAG).debug("syncJson: Sound already exists - skipping: " + sound.id); <add> c.close(); <add> continue; <add> } <add> <add> c.close(); <add> <add> sound._observation_id = jsonObservation._id; <add> <add> ContentValues opcv = sound.getContentValues(); <add> Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + sound.id + ":" + sound._id + ":" + sound._observation_id + ":" + sound.observation_id); <add> Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + sound); <add> opcv.put(ObservationSound._OBSERVATION_ID, sound._observation_id); <add> opcv.put(ObservationSound._ID, sound.id); <add> Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, <add> Observation.PROJECTION, <add> "id = " + sound.observation_id, null, Observation.DEFAULT_SORT_ORDER); <add> if (obsc.getCount() > 0) { <add> obsc.moveToFirst(); <add> Observation obs = new Observation(obsc); <add> opcv.put(ObservationSound.OBSERVATION_UUID, obs.uuid); <add> } <add> obsc.close(); <add> try { <add> getContentResolver().insert(ObservationSound.CONTENT_URI, opcv); <add> } catch (SQLException ex) { <add> // Happens when the sound already exists - ignore <add> Logger.tag(TAG).error(ex); <add> } <add> } <add> <add> // Save the new observation's photos <add> Logger.tag(TAG).debug("syncJson: Saving new obs' photos: " + jsonObservation + ":" + jsonObservation.photos); <add> for (int j = 0; j < jsonObservation.photos.size(); j++) { <add> ObservationPhoto photo = jsonObservation.photos.get(j); <add> <add> if (photo.uuid == null) { <add> c = getContentResolver().query(ObservationPhoto.CONTENT_URI, <add> ObservationPhoto.PROJECTION, <add> "_id = ?", new String[]{String.valueOf(photo.id)}, ObservationPhoto.DEFAULT_SORT_ORDER); <add> } else { <add> c = getContentResolver().query(ObservationPhoto.CONTENT_URI, <add> ObservationPhoto.PROJECTION, <add> "uuid = ?", new String[]{String.valueOf(photo.uuid)}, ObservationPhoto.DEFAULT_SORT_ORDER); <add> } <add> <add> if (c.getCount() > 0) { <add> // Photo already exists - don't save <add> Logger.tag(TAG).debug("syncJson: Photo already exists - skipping: " + photo.id); <add> c.close(); <add> continue; <add> } <add> <add> c.close(); <add> <add> photo._observation_id = jsonObservation._id; <add> <add> ContentValues opcv = photo.getContentValues(); <add> Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo.id + ":" + photo._id + ":" + photo._observation_id + ":" + photo.observation_id); <add> Logger.tag(TAG).debug("syncJson: Setting _SYNCED_AT - " + photo); <add> opcv.put(ObservationPhoto._SYNCED_AT, System.currentTimeMillis()); // So we won't re-add this photo as though it was a local photo <add> opcv.put(ObservationPhoto._OBSERVATION_ID, photo._observation_id); <add> opcv.put(ObservationPhoto._PHOTO_ID, photo._photo_id); <add> opcv.put(ObservationPhoto._ID, photo.id); <add> Cursor obsc = getContentResolver().query(Observation.CONTENT_URI, <add> Observation.PROJECTION, <add> "id = " + photo.observation_id, null, Observation.DEFAULT_SORT_ORDER); <add> if (obsc.getCount() > 0) { <add> obsc.moveToFirst(); <add> Observation obs = new Observation(obsc); <add> opcv.put(ObservationPhoto.OBSERVATION_UUID, obs.uuid); <add> } <add> obsc.close(); <add> try { <add> getContentResolver().insert(ObservationPhoto.CONTENT_URI, opcv); <add> } catch (SQLException ex) { <add> // Happens when the photo already exists - ignore <add> Logger.tag(TAG).error(ex); <add> } <add> } <add> } <add> } <add> <add> if (isUser) { <add> storeProjectObservations(); <add> } <add> <add> if (mSyncedJSONs.size() > 5) { <add> mSyncedJSONs.remove(0); <add> } <ide> } <ide> } <ide>
Java
mit
58d49b62325429ca4aa0100870d4d9c7e26d6feb
0
pbakondy/cordova-plugin-speechrecognition,pbakondy/cordova-plugin-speechrecognition
// https://developer.android.com/reference/android/speech/SpeechRecognizer.html package com.pbakondy; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.Manifest; import android.os.Build; import android.os.Bundle; import android.speech.RecognitionListener; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.util.Log; import android.view.View; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class SpeechRecognition extends CordovaPlugin { private static final String LOG_TAG = "SpeechRecognition"; private static final int REQUEST_CODE_PERMISSION = 2001; private static final int REQUEST_CODE_SPEECH = 2002; private static final String IS_RECOGNITION_AVAILABLE = "isRecognitionAvailable"; private static final String START_LISTENING = "startListening"; private static final String STOP_LISTENING = "stopListening"; private static final String GET_SUPPORTED_LANGUAGES = "getSupportedLanguages"; private static final String HAS_PERMISSION = "hasPermission"; private static final String REQUEST_PERMISSION = "requestPermission"; // android.speech.extra.MAX_RESULTS private static final int MAX_RESULTS = 5; private static final String NOT_AVAILABLE = "Speech recognition service is not available on the system."; private static final String MISSING_PERMISSION = "Missing permission"; private static final String RECORD_AUDIO_PERMISSION = Manifest.permission.RECORD_AUDIO; private CallbackContext callbackContext; private LanguageDetailsChecker languageDetailsChecker; private Activity activity; private Context context; private View view; private SpeechRecognizer recognizer; @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); activity = cordova.getActivity(); context = webView.getContext(); view = webView.getView(); view.post(new Runnable() { @Override public void run() { recognizer = SpeechRecognizer.createSpeechRecognizer(activity); SpeechRecognitionListener listener = new SpeechRecognitionListener(); recognizer.setRecognitionListener(listener); } }); } @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { this.callbackContext = callbackContext; Log.d(LOG_TAG, "execute() action " + action); try { if (IS_RECOGNITION_AVAILABLE.equals(action)) { boolean available = isRecognitionAvailable(); PluginResult result = new PluginResult(PluginResult.Status.OK, available); callbackContext.sendPluginResult(result); return true; } if (START_LISTENING.equals(action)) { if (!isRecognitionAvailable()) { callbackContext.error(NOT_AVAILABLE); return true; } if (!audioPermissionGranted(RECORD_AUDIO_PERMISSION)) { callbackContext.error(MISSING_PERMISSION); return true; } String lang = args.optString(0); if (lang == null || lang.isEmpty() || lang.equals("null")) { lang = Locale.getDefault().toString(); } int matches = args.optInt(1, MAX_RESULTS); String prompt = args.optString(2); if (prompt == null || prompt.isEmpty() || prompt.equals("null")) { prompt = null; } Boolean showPopup = args.optBoolean(4, true); startListening(lang, matches, prompt, showPopup); return true; } if (STOP_LISTENING.equals(action)) { final CallbackContext callbackContextStop = this.callbackContext; view.post(new Runnable() { @Override public void run() { if(recognizer != null) { recognizer.stopListening(); } callbackContextStop.success(); } }); return true; } if (GET_SUPPORTED_LANGUAGES.equals(action)) { getSupportedLanguages(); return true; } if (HAS_PERMISSION.equals(action)) { hasAudioPermission(); return true; } if (REQUEST_PERMISSION.equals(action)) { requestAudioPermission(); return true; } } catch (Exception e) { e.printStackTrace(); callbackContext.error(e.getMessage()); } return false; } private boolean isRecognitionAvailable() { return SpeechRecognizer.isRecognitionAvailable(context); } private void startListening(String language, int matches, String prompt, Boolean showPopup) { Log.d(LOG_TAG, "startListening() language: " + language + ", matches: " + matches + ", prompt: " + prompt + ", showPopup: " + showPopup); final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, matches); intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, activity.getPackageName()); if (prompt != null) { intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt); } if (showPopup) { cordova.startActivityForResult(this, intent, REQUEST_CODE_SPEECH); } else { view.post(new Runnable() { @Override public void run() { recognizer.startListening(intent); } }); } } private void getSupportedLanguages() { if (languageDetailsChecker == null) { languageDetailsChecker = new LanguageDetailsChecker(callbackContext); } List<String> supportedLanguages = languageDetailsChecker.getSupportedLanguages(); if (supportedLanguages != null) { JSONArray languages = new JSONArray(supportedLanguages); callbackContext.success(languages); return; } Intent detailsIntent = new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS); activity.sendOrderedBroadcast(detailsIntent, null, languageDetailsChecker, null, Activity.RESULT_OK, null, null); } private void hasAudioPermission() { PluginResult result = new PluginResult(PluginResult.Status.OK, audioPermissionGranted(RECORD_AUDIO_PERMISSION)); this.callbackContext.sendPluginResult(result); } private void requestAudioPermission() { requestPermission(RECORD_AUDIO_PERMISSION); } private boolean audioPermissionGranted(String type) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } return cordova.hasPermission(type); } private void requestPermission(String type) { if (!audioPermissionGranted(type)) { cordova.requestPermission(this, 23456, type); } else { this.callbackContext.success(); } } @Override public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { this.callbackContext.success(); } else { this.callbackContext.error("Permission denied"); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(LOG_TAG, "onActivityResult() requestCode: " + requestCode + ", resultCode: " + resultCode); if (requestCode == REQUEST_CODE_SPEECH) { if (resultCode == Activity.RESULT_OK) { try { ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); JSONArray jsonMatches = new JSONArray(matches); this.callbackContext.success(jsonMatches); } catch (Exception e) { e.printStackTrace(); this.callbackContext.error(e.getMessage()); } } else { this.callbackContext.error(Integer.toString(resultCode)); } return; } super.onActivityResult(requestCode, resultCode, data); } private class SpeechRecognitionListener implements RecognitionListener { @Override public void onBeginningOfSpeech() { } @Override public void onBufferReceived(byte[] buffer) { } @Override public void onEndOfSpeech() { } @Override public void onError(int errorCode) { String errorMessage = getErrorText(errorCode); Log.d(LOG_TAG, "Error: " + errorMessage); callbackContext.error(errorMessage); } @Override public void onEvent(int eventType, Bundle params) { } @Override public void onPartialResults(Bundle partialResults) { } @Override public void onReadyForSpeech(Bundle params) { Log.d(LOG_TAG, "onReadyForSpeech"); } @Override public void onResults(Bundle results) { ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); Log.d(LOG_TAG, "SpeechRecognitionListener results: " + matches); try { JSONArray jsonMatches = new JSONArray(matches); callbackContext.success(jsonMatches); } catch (Exception e) { e.printStackTrace(); callbackContext.error(e.getMessage()); } } @Override public void onRmsChanged(float rmsdB) { } private String getErrorText(int errorCode) { String message; switch (errorCode) { case SpeechRecognizer.ERROR_AUDIO: message = "Audio recording error"; break; case SpeechRecognizer.ERROR_CLIENT: message = "Client side error"; break; case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS: message = "Insufficient permissions"; break; case SpeechRecognizer.ERROR_NETWORK: message = "Network error"; break; case SpeechRecognizer.ERROR_NETWORK_TIMEOUT: message = "Network timeout"; break; case SpeechRecognizer.ERROR_NO_MATCH: message = "No match"; break; case SpeechRecognizer.ERROR_RECOGNIZER_BUSY: message = "RecognitionService busy"; break; case SpeechRecognizer.ERROR_SERVER: message = "error from server"; break; case SpeechRecognizer.ERROR_SPEECH_TIMEOUT: message = "No speech input"; break; default: message = "Didn't understand, please try again."; break; } return message; } } }
src/android/com/pbakondy/SpeechRecognition.java
// https://developer.android.com/reference/android/speech/SpeechRecognizer.html package com.pbakondy; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.Manifest; import android.os.Build; import android.os.Bundle; import android.speech.RecognitionListener; import android.speech.RecognizerIntent; import android.speech.SpeechRecognizer; import android.util.Log; import android.view.View; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class SpeechRecognition extends CordovaPlugin { private static final String LOG_TAG = "SpeechRecognition"; private static final int REQUEST_CODE_PERMISSION = 2001; private static final int REQUEST_CODE_SPEECH = 2002; private static final String IS_RECOGNITION_AVAILABLE = "isRecognitionAvailable"; private static final String START_LISTENING = "startListening"; private static final String STOP_LISTENING = "stopListening"; private static final String GET_SUPPORTED_LANGUAGES = "getSupportedLanguages"; private static final String HAS_PERMISSION = "hasPermission"; private static final String REQUEST_PERMISSION = "requestPermission"; // android.speech.extra.MAX_RESULTS private static final int MAX_RESULTS = 5; private static final String NOT_AVAILABLE = "Speech recognition service is not available on the system."; private static final String MISSING_PERMISSION = "Missing permission"; private static final String RECORD_AUDIO_PERMISSION = Manifest.permission.RECORD_AUDIO; private CallbackContext callbackContext; private LanguageDetailsChecker languageDetailsChecker; private Activity activity; private Context context; private View view; private SpeechRecognizer recognizer; @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); activity = cordova.getActivity(); context = webView.getContext(); view = webView.getView(); view.post(new Runnable() { @Override public void run() { recognizer = SpeechRecognizer.createSpeechRecognizer(activity); SpeechRecognitionListener listener = new SpeechRecognitionListener(); recognizer.setRecognitionListener(listener); } }); } @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { this.callbackContext = callbackContext; Log.d(LOG_TAG, "execute() action " + action); try { if (IS_RECOGNITION_AVAILABLE.equals(action)) { boolean available = isRecognitionAvailable(); PluginResult result = new PluginResult(PluginResult.Status.OK, available); callbackContext.sendPluginResult(result); return true; } if (START_LISTENING.equals(action)) { if (!isRecognitionAvailable()) { callbackContext.error(NOT_AVAILABLE); return true; } if (!audioPermissionGranted(RECORD_AUDIO_PERMISSION)) { callbackContext.error(MISSING_PERMISSION); return true; } String lang = args.optString(0); if (lang == null || lang.isEmpty() || lang.equals("null")) { lang = Locale.getDefault().toString(); } int matches = args.optInt(1, MAX_RESULTS); String prompt = args.optString(2); if (prompt == null || prompt.isEmpty() || prompt.equals("null")) { prompt = null; } Boolean showPopup = args.optBoolean(4, true); startListening(lang, matches, prompt, showPopup); return true; } if (STOP_LISTENING.equals(action)) { this.callbackContext.success(); return true; } if (GET_SUPPORTED_LANGUAGES.equals(action)) { getSupportedLanguages(); return true; } if (HAS_PERMISSION.equals(action)) { hasAudioPermission(); return true; } if (REQUEST_PERMISSION.equals(action)) { requestAudioPermission(); return true; } } catch (Exception e) { e.printStackTrace(); callbackContext.error(e.getMessage()); } return false; } private boolean isRecognitionAvailable() { return SpeechRecognizer.isRecognitionAvailable(context); } private void startListening(String language, int matches, String prompt, Boolean showPopup) { Log.d(LOG_TAG, "startListening() language: " + language + ", matches: " + matches + ", prompt: " + prompt + ", showPopup: " + showPopup); final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, matches); intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, activity.getPackageName()); if (prompt != null) { intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt); } if (showPopup) { cordova.startActivityForResult(this, intent, REQUEST_CODE_SPEECH); } else { view.post(new Runnable() { @Override public void run() { recognizer.startListening(intent); } }); } } private void getSupportedLanguages() { if (languageDetailsChecker == null) { languageDetailsChecker = new LanguageDetailsChecker(callbackContext); } List<String> supportedLanguages = languageDetailsChecker.getSupportedLanguages(); if (supportedLanguages != null) { JSONArray languages = new JSONArray(supportedLanguages); callbackContext.success(languages); return; } Intent detailsIntent = new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS); activity.sendOrderedBroadcast(detailsIntent, null, languageDetailsChecker, null, Activity.RESULT_OK, null, null); } private void hasAudioPermission() { PluginResult result = new PluginResult(PluginResult.Status.OK, audioPermissionGranted(RECORD_AUDIO_PERMISSION)); this.callbackContext.sendPluginResult(result); } private void requestAudioPermission() { requestPermission(RECORD_AUDIO_PERMISSION); } private boolean audioPermissionGranted(String type) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } return cordova.hasPermission(type); } private void requestPermission(String type) { if (!audioPermissionGranted(type)) { cordova.requestPermission(this, 23456, type); } else { this.callbackContext.success(); } } @Override public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { this.callbackContext.success(); } else { this.callbackContext.error("Permission denied"); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(LOG_TAG, "onActivityResult() requestCode: " + requestCode + ", resultCode: " + resultCode); if (requestCode == REQUEST_CODE_SPEECH) { if (resultCode == Activity.RESULT_OK) { try { ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); JSONArray jsonMatches = new JSONArray(matches); this.callbackContext.success(jsonMatches); } catch (Exception e) { e.printStackTrace(); this.callbackContext.error(e.getMessage()); } } else { this.callbackContext.error(Integer.toString(resultCode)); } return; } super.onActivityResult(requestCode, resultCode, data); } private class SpeechRecognitionListener implements RecognitionListener { @Override public void onBeginningOfSpeech() { } @Override public void onBufferReceived(byte[] buffer) { } @Override public void onEndOfSpeech() { } @Override public void onError(int errorCode) { String errorMessage = getErrorText(errorCode); Log.d(LOG_TAG, "Error: " + errorMessage); callbackContext.error(errorMessage); } @Override public void onEvent(int eventType, Bundle params) { } @Override public void onPartialResults(Bundle partialResults) { } @Override public void onReadyForSpeech(Bundle params) { Log.d(LOG_TAG, "onReadyForSpeech"); } @Override public void onResults(Bundle results) { ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); Log.d(LOG_TAG, "SpeechRecognitionListener results: " + matches); try { JSONArray jsonMatches = new JSONArray(matches); callbackContext.success(jsonMatches); } catch (Exception e) { e.printStackTrace(); callbackContext.error(e.getMessage()); } } @Override public void onRmsChanged(float rmsdB) { } private String getErrorText(int errorCode) { String message; switch (errorCode) { case SpeechRecognizer.ERROR_AUDIO: message = "Audio recording error"; break; case SpeechRecognizer.ERROR_CLIENT: message = "Client side error"; break; case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS: message = "Insufficient permissions"; break; case SpeechRecognizer.ERROR_NETWORK: message = "Network error"; break; case SpeechRecognizer.ERROR_NETWORK_TIMEOUT: message = "Network timeout"; break; case SpeechRecognizer.ERROR_NO_MATCH: message = "No match"; break; case SpeechRecognizer.ERROR_RECOGNIZER_BUSY: message = "RecognitionService busy"; break; case SpeechRecognizer.ERROR_SERVER: message = "error from server"; break; case SpeechRecognizer.ERROR_SPEECH_TIMEOUT: message = "No speech input"; break; default: message = "Didn't understand, please try again."; break; } return message; } } }
Add STOP_LISTENING for android Add the STOP_LISTENING method for Android. The user can force to stop the speech recognition.
src/android/com/pbakondy/SpeechRecognition.java
Add STOP_LISTENING for android
<ide><path>rc/android/com/pbakondy/SpeechRecognition.java <ide> } <ide> <ide> if (STOP_LISTENING.equals(action)) { <del> this.callbackContext.success(); <add> final CallbackContext callbackContextStop = this.callbackContext; <add> view.post(new Runnable() { <add> @Override <add> public void run() { <add> if(recognizer != null) { <add> recognizer.stopListening(); <add> } <add> callbackContextStop.success(); <add> } <add> }); <ide> return true; <ide> } <ide>
Java
apache-2.0
b4ad8299fcb615cf7bad3f5fc6db8ecd1eb6fa93
0
vadimmanaev/JavaDataBaseConnector,vadimmanaev/LightWeightSQLWrapper,vadimmanaev/LightWeightMySQLWrapper
/******************************************************************************* * Copyright 2013 * * 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.lightweight.mysql; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import com.lightweight.mysql.exceptions.IllegalSQLQueryException; import com.lightweight.mysql.model.DataBaseColumn; import com.lightweight.mysql.model.DataBaseRow; import com.lightweight.mysql.model.MySQLQuery; import com.lightweight.mysql.model.Result; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.ResultSetMetaData; /** * This class should serve as adapter to MySQL database * @version 2.0 * @author Vladi - 8:09 PM 9/12/2013 */ public class MySQLConnector { private Connection connection = null; private String url; private String user; private String password; public MySQLConnector(String url, String user, String password) { this.url = url; this.user = user; this.password = password; } /** * Opens connection to MySQL database */ public void open() throws SQLException, ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); connection = (Connection) DriverManager.getConnection(url, user, password); } /** * Closing connection to MySQL database */ public void close() throws SQLException { if (connection != null) { connection.close(); } } /** * Checks if connection to Database is open */ public boolean isConnected() throws SQLException { boolean isConnected = false; if (connection != null) { isConnected = !connection.isClosed(); } return isConnected; } /** * Insert, Update, Drop, Delete, Create, Alter query to MySQL database. */ public void executeUpdateQuery(MySQLQuery mySQLQuery) throws SQLException, IllegalSQLQueryException, ClassNotFoundException { PreparedStatement preparedStatement = null; try { if (!isConnected()) { open(); } preparedStatement = (PreparedStatement) connection.prepareStatement(mySQLQuery.toString()); updatePreparedStatementWithParameters(preparedStatement, mySQLQuery); preparedStatement.executeUpdate(); } finally { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } } /** * Select query to MySQL database. */ public Result executeSelectQuery(MySQLQuery mySQLQuery) throws SQLException, IllegalSQLQueryException, ClassNotFoundException { Result mySQLResult = new Result(); PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { if (!isConnected()) { open(); } preparedStatement = (PreparedStatement) connection.prepareStatement(mySQLQuery.toString()); updatePreparedStatementWithParameters(preparedStatement, mySQLQuery); resultSet = preparedStatement.executeQuery(); ResultSetMetaData resultMetaData = (ResultSetMetaData) resultSet.getMetaData(); int maxNumberOfColums = resultMetaData.getColumnCount(); while (resultSet.next()) { DataBaseRow row = new DataBaseRow(); for (int columnNumber = 1; columnNumber <= maxNumberOfColums; columnNumber++) { DataBaseColumn column = new DataBaseColumn(); column.setColumnName(resultMetaData.getColumnName(columnNumber)); column.setColumnValue(resultSet.getString(columnNumber)); row.addColumn(column); } mySQLResult.addRow(row); } } finally { if (resultSet != null) { resultSet.close(); } if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } return mySQLResult; } /** * Creating prepared statement in order to avoid SQL injections */ private void updatePreparedStatementWithParameters(PreparedStatement preparedStatement, MySQLQuery mySQLQuery) throws SQLException, IllegalSQLQueryException { // Databases counts from 1 and not 0 thats why there is (i + 1). for (int i = 0; i < mySQLQuery.getNumberOfParameters(); i++) { if (mySQLQuery.getParameterType(i) == MySQLQuery.ParameterType.STRING) { preparedStatement.setString(i + 1, mySQLQuery.getParameterValue(i)); } else if (mySQLQuery.getParameterType(i) == MySQLQuery.ParameterType.INTEGER) { preparedStatement.setInt(i + 1, Integer.parseInt(mySQLQuery.getParameterValue(i))); } else if (mySQLQuery.getParameterType(i) == MySQLQuery.ParameterType.DOUBLE) { preparedStatement.setDouble(i + 1, Double.parseDouble(mySQLQuery.getParameterValue(i))); } else if (mySQLQuery.getParameterType(i) == MySQLQuery.ParameterType.FLOAT) { preparedStatement.setFloat(i + 1, Float.parseFloat(mySQLQuery.getParameterValue(i))); } else { throw new IllegalSQLQueryException("Invalid type of ParameterType!"); } } } }
src/main/java/com/lightweight/mysql/MySQLConnector.java
/******************************************************************************* * Copyright 2013 * * 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.lightweight.mysql; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import com.lightweight.mysql.exceptions.IllegalSQLQueryException; import com.lightweight.mysql.model.DataBaseColumn; import com.lightweight.mysql.model.DataBaseRow; import com.lightweight.mysql.model.MySQLQuery; import com.lightweight.mysql.model.Result; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.ResultSetMetaData; /** * This class should serve as adapter to MySQL database * @version 2.0 * @author Vladi - 8:09 PM 9/12/2013 */ public class MySQLConnector { private Connection connection = null; private PreparedStatement preparedStatement = null; private ResultSet result = null; private String url; private String user; private String password; public MySQLConnector(String url, String user, String password) { this.url = url; this.user = user; this.password = password; } /** * Opens connection to MySQL database */ public void open() throws SQLException, ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); connection = (Connection) DriverManager.getConnection(url, user, password); } /** * Closing connection to MySQL database */ public void close() throws SQLException { if (connection != null) { connection.close(); } } /** * Checks if connection to Database is open */ public boolean isConnected() throws SQLException { boolean isConnected = false; if (connection != null) { isConnected = !connection.isClosed(); } return isConnected; } /** * Insert, Update, Drop, Delete, Create, Alter query to MySQL database. */ public void executeUpdateQuery(MySQLQuery mySQLQuery) throws SQLException, IllegalSQLQueryException, ClassNotFoundException { try { if (!isConnected()) { open(); } preparedStatement = (PreparedStatement) connection.prepareStatement(mySQLQuery.toString()); updatePreparedStatementWithParameters(preparedStatement, mySQLQuery); preparedStatement.executeUpdate(); } finally { if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } } /** * Select query to MySQL database. */ public Result executeSelectQuery(MySQLQuery mySQLQuery) throws SQLException, IllegalSQLQueryException, ClassNotFoundException { Result mySQLResult = new Result(); try { if (!isConnected()) { open(); } preparedStatement = (PreparedStatement) connection.prepareStatement(mySQLQuery.toString()); updatePreparedStatementWithParameters(preparedStatement, mySQLQuery); result = preparedStatement.executeQuery(); ResultSetMetaData resultMetaData = (ResultSetMetaData) result.getMetaData(); int maxNumberOfColums = resultMetaData.getColumnCount(); while (result.next()) { DataBaseRow row = new DataBaseRow(); for (int columnNumber = 1; columnNumber <= maxNumberOfColums; columnNumber++) { DataBaseColumn column = new DataBaseColumn(); column.setColumnName(resultMetaData.getColumnName(columnNumber)); column.setColumnValue(result.getString(columnNumber)); row.addColumn(column); } mySQLResult.addRow(row); } } finally { if (result != null) { result.close(); } if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { connection.close(); } } return mySQLResult; } /** * Creating prepared statement in order to avoid SQL injections */ private void updatePreparedStatementWithParameters(PreparedStatement preparedStatement, MySQLQuery mySQLQuery) throws SQLException, IllegalSQLQueryException { // Databases counts from 1 and not 0 thats why there is (i + 1). for (int i = 0; i < mySQLQuery.getNumberOfParameters(); i++) { if (mySQLQuery.getParameterType(i) == MySQLQuery.ParameterType.STRING) { preparedStatement.setString(i + 1, mySQLQuery.getParameterValue(i)); } else if (mySQLQuery.getParameterType(i) == MySQLQuery.ParameterType.INTEGER) { preparedStatement.setInt(i + 1, Integer.parseInt(mySQLQuery.getParameterValue(i))); } else if (mySQLQuery.getParameterType(i) == MySQLQuery.ParameterType.DOUBLE) { preparedStatement.setDouble(i + 1, Double.parseDouble(mySQLQuery.getParameterValue(i))); } else if (mySQLQuery.getParameterType(i) == MySQLQuery.ParameterType.FLOAT) { preparedStatement.setFloat(i + 1, Float.parseFloat(mySQLQuery.getParameterValue(i))); } else { throw new IllegalSQLQueryException("Invalid type of ParameterType!"); } } } }
Small refactor
src/main/java/com/lightweight/mysql/MySQLConnector.java
Small refactor
<ide><path>rc/main/java/com/lightweight/mysql/MySQLConnector.java <ide> */ <ide> public class MySQLConnector { <ide> private Connection connection = null; <del> private PreparedStatement preparedStatement = null; <del> private ResultSet result = null; <ide> <ide> private String url; <ide> private String user; <ide> * Insert, Update, Drop, Delete, Create, Alter query to MySQL database. <ide> */ <ide> public void executeUpdateQuery(MySQLQuery mySQLQuery) throws SQLException, IllegalSQLQueryException, ClassNotFoundException { <add> PreparedStatement preparedStatement = null; <ide> try { <ide> if (!isConnected()) { <ide> open(); <ide> */ <ide> public Result executeSelectQuery(MySQLQuery mySQLQuery) throws SQLException, IllegalSQLQueryException, ClassNotFoundException { <ide> Result mySQLResult = new Result(); <del> <add> PreparedStatement preparedStatement = null; <add> ResultSet resultSet = null; <ide> try { <ide> if (!isConnected()) { <ide> open(); <ide> <ide> preparedStatement = (PreparedStatement) connection.prepareStatement(mySQLQuery.toString()); <ide> updatePreparedStatementWithParameters(preparedStatement, mySQLQuery); <del> result = preparedStatement.executeQuery(); <del> ResultSetMetaData resultMetaData = (ResultSetMetaData) result.getMetaData(); <add> resultSet = preparedStatement.executeQuery(); <add> ResultSetMetaData resultMetaData = (ResultSetMetaData) resultSet.getMetaData(); <ide> <ide> int maxNumberOfColums = resultMetaData.getColumnCount(); <ide> <del> while (result.next()) { <add> while (resultSet.next()) { <ide> DataBaseRow row = new DataBaseRow(); <ide> for (int columnNumber = 1; columnNumber <= maxNumberOfColums; columnNumber++) { <ide> DataBaseColumn column = new DataBaseColumn(); <ide> <ide> column.setColumnName(resultMetaData.getColumnName(columnNumber)); <del> column.setColumnValue(result.getString(columnNumber)); <add> column.setColumnValue(resultSet.getString(columnNumber)); <ide> <ide> row.addColumn(column); <ide> } <ide> } <ide> <ide> } finally { <del> if (result != null) { <del> result.close(); <add> if (resultSet != null) { <add> resultSet.close(); <ide> } <ide> if (preparedStatement != null) { <ide> preparedStatement.close();
JavaScript
unlicense
ac127398c1032b1826916a2cf5f1215c55414ae9
0
chadfurman/tumblr-template-sass,chadfurman/tumblr-template-sass,shadesoflight/tumblr-template-sass,ShadeLotus/tumblr-template-sass,shadesoflight/tumblr-template-sass,ShadeLotus/tumblr-template-sass
$(document).foundation(); $(document).ready(function() { console.log($('.photo-slideshow').tumblrPhotoset({ 'ligthbox' : true, // uses the default Tumblr lightbox, change to false to use your own 'highRes' : true, // will use high res images 'rounded' : 'corners', // corners, all or false 'exif' : true, // display EXIF data if available (tooltip) 'captions' : true, // display individual captions on photos (tooltip) 'gutter' : '10px', // spacing between the images 'photoset' : '.photo-slideshow', // photoset wrapper 'photoWrap' : '.photo-data', // photo data wrapper (includes photo, icons + exif) 'photo' : '.pxu-photo' // photo wrap (includes photo only) })); })
theme/js/theme.js
$(document).foundation(); $(document).ready(function() { console.log($('.photo-slideshow').pxuPhotoset({ 'ligthbox' : true, // uses the default Tumblr lightbox, change to false to use your own 'highRes' : true, // will use high res images 'rounded' : 'corners', // corners, all or false 'exif' : true, // display EXIF data if available (tooltip) 'captions' : true, // display individual captions on photos (tooltip) 'gutter' : '10px', // spacing between the images 'photoset' : '.photo-slideshow', // photoset wrapper 'photoWrap' : '.photo-data', // photo data wrapper (includes photo, icons + exif) 'photo' : '.pxu-photo' // photo wrap (includes photo only) })); })
calling the renamed photoset plugin
theme/js/theme.js
calling the renamed photoset plugin
<ide><path>heme/js/theme.js <ide> $(document).foundation(); <ide> <ide> $(document).ready(function() { <del> console.log($('.photo-slideshow').pxuPhotoset({ <add> console.log($('.photo-slideshow').tumblrPhotoset({ <ide> 'ligthbox' : true, // uses the default Tumblr lightbox, change to false to use your own <ide> 'highRes' : true, // will use high res images <ide> 'rounded' : 'corners', // corners, all or false
Java
mit
9a8e4956e4045a422a5cbe5bac45330ae1e85e27
0
JJ-Atkinson/Connect-n
package connectn.game; import connectn.players.Player; import connectn.util.ListUtil; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.summingInt; /** * Created by Jarrett on 12/07/15. */ public class Runner { private static final boolean SHOW_STATISTICS = true; private final static int PLAYERS_PER_GAME = 3; public static int MINIMUM_NUMBER_OF_GAMES = 100000; public void runGames() { int actNumberOfRounds = Math.max(MINIMUM_NUMBER_OF_GAMES * PlayerFactory.playerCreator.size() / PLAYERS_PER_GAME + 1, MINIMUM_NUMBER_OF_GAMES); List<List<Player>> games = IntStream .range(0, actNumberOfRounds - 1) .mapToObj(value -> generateNextPlayers()).collect(Collectors.toList()); List<Class<? extends Player>> winners = games.stream() .parallel() .map(this::runGame) .collect(Collectors.toList()); Map<Class<? extends Player>, Integer> totalScore = winningCounts(winners); System.out.println(prettyPrintScore(totalScore)); if (SHOW_STATISTICS) printStatistics(games, winners); } private Class<? extends Player> runGame(List<Player> players) { Game game = new Game(players); game.runGame(); return game.getWinner(); } private Map<Class<? extends Player>, Integer> winningCounts (List<Class<? extends Player>> gameResults) { HashSet<Class<? extends Player>> losers = new HashSet<>(PlayerFactory.getPlayerTypes()); losers.removeAll(gameResults); Map<Class<? extends Player>, Integer> winners = gameResults .stream() .collect( groupingBy( Function.identity(), summingInt(e -> 1))); for (Class<? extends Player> loser : losers) winners.put(loser, 0); return winners; } private String prettyPrintScore(Map<Class<? extends Player>, Integer> scores) { StringBuilder ret = new StringBuilder(); ArrayList<Map.Entry<Class<? extends Player>, Integer>> scorePairsAsList = new ArrayList<>(scores.entrySet()); Collections.sort(scorePairsAsList, (o1, o2) -> -Integer.compare( (int) ((Map.Entry) (o1)).getValue(), (int) ((Map.Entry) (o2)).getValue())); for (Map.Entry<Class<? extends Player>, Integer> scorePair : scorePairsAsList) ret.append(scorePair.getKey().getSimpleName()) .append(" -> ") .append(scorePair.getValue()) .append('\n'); return ret.toString(); } private List<List<Class<? extends Player>>> playerCombinations = ListUtil.combinations(new ArrayList<Iterable<Class<? extends Player>>>() {{ List<Class<? extends Player>> allPlayers = PlayerFactory.getPlayerTypes(); add(allPlayers); add(allPlayers); add(allPlayers); }}).stream().filter(lst -> new HashSet<>(lst).size() == lst.size()).collect(Collectors.toList()); private int playerPosition = 0; public List<Player> generateNextPlayers() { playerPosition = ++playerPosition % (playerCombinations.size() - 1); List<Player> players = PlayerFactory.create(playerCombinations.get(playerPosition)); Collections.shuffle(players, ThreadLocalRandom.current()); int nextId = 1; for (Player player : players) player.setID(nextId++); return players; } private void printStatistics (List<List<Player>> gameSets, List<Class<? extends Player>> winners) { HashMap<List<Class<? extends Player>>, List<Class<? extends Player>>> lineupWinnerPairs = new HashMap<>(); for (int i = 0; i < gameSets.size(); i++) { List<Class<? extends Player>> gameSet = new ArrayList<>(); List<Player> gameSetAsPlayer = gameSets.get(i); for (Player player : gameSetAsPlayer) gameSet.add(player.getClass()); Class<? extends Player> winner = winners.get(i); lineupWinnerPairs.putIfAbsent(gameSet, new ArrayList<>()); lineupWinnerPairs.get(gameSet).add(winner); } HashMap<List<Class<? extends Player>>, Map<Class<? extends Player>, Integer>> lineupScorePairs = new HashMap<>(); lineupWinnerPairs.forEach((classes, classes2) -> { Map<Class<? extends Player>, Integer> winningCount = winningCounts(classes2); Iterator<Map.Entry<Class<? extends Player>, Integer>> iterator = winningCount.entrySet().iterator(); while (iterator.hasNext()) if (iterator.next().getValue() == 0) iterator.remove(); lineupScorePairs.put(classes, winningCount); }); lineupScorePairs.forEach((key, wins) -> { System.out.println(key); System.out.println( prettyPrintScore(wins)); }); } }
src/main/java/connectn/game/Runner.java
package connectn.game; import connectn.players.Player; import connectn.util.ListUtil; import java.util.*; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.summingInt; /** * Created by Jarrett on 12/07/15. */ public class Runner { private static final boolean SHOW_STATISTICS = true; private final static int PLAYERS_PER_GAME = 3; public static int MINIMUM_NUMBER_OF_GAMES = 100000; private static int actNumberOfRounds = -1; private Set<Class<? extends Player>> allPlayers; static { actNumberOfRounds = Math.max(MINIMUM_NUMBER_OF_GAMES * PlayerFactory.playerCreator.size() / PLAYERS_PER_GAME + 1, MINIMUM_NUMBER_OF_GAMES); } { allPlayers = new HashSet<>(PlayerFactory.getPlayerTypes()); } public void runGames() { List<List<Player>> games = IntStream .range(0, actNumberOfRounds - 1) .mapToObj(value -> generateNextPlayers()).collect(Collectors.toList()); List<Class<? extends Player>> winners = games.stream() .parallel() .unordered() .map(this::runGame) .collect(Collectors.toList()); Map<Class<? extends Player>, Integer> totalScore = winningCounts(winners); System.out.println(prettyPrintScore(totalScore)); if (SHOW_STATISTICS) printStatistics(games, winners); } private Class<? extends Player> runGame(List<Player> players) { Game game = new Game(players); game.runGame(); return game.getWinner(); } private Map<Class<? extends Player>, Integer> winningCounts (List<Class<? extends Player>> gameResults) { HashSet<Class<? extends Player>> losers = new HashSet<>(PlayerFactory.getPlayerTypes()); losers.removeAll(gameResults); Map<Class<? extends Player>, Integer> winners = gameResults .stream() .collect( groupingBy( Function.identity(), summingInt(e -> 1))); for (Class<? extends Player> loser : losers) winners.put(loser, 0); return winners; } private String prettyPrintScore(Map<Class<? extends Player>, Integer> scores) { StringBuilder ret = new StringBuilder(); ArrayList<Map.Entry<Class<? extends Player>, Integer>> scorePairsAsList = new ArrayList<>(scores.entrySet()); Collections.sort(scorePairsAsList, (o1, o2) -> -Integer.compare( (int) ((Map.Entry) (o1)).getValue(), (int) ((Map.Entry) (o2)).getValue())); for (Map.Entry<Class<? extends Player>, Integer> scorePair : scorePairsAsList) ret.append(scorePair.getKey().getSimpleName()) .append(" -> ") .append(scorePair.getValue()) .append('\n'); return ret.toString(); } private List<List<Class<? extends Player>>> playerCombinations = ListUtil.combinations(new ArrayList<Iterable<Class<? extends Player>>>() {{ add(allPlayers); add(allPlayers); add(allPlayers); }}).stream().filter(lst -> new HashSet<>(lst).size() == lst.size()).collect(Collectors.toList()); private int playerPosition = 0; public List<Player> generateNextPlayers() { playerPosition = ++playerPosition % (playerCombinations.size() - 1); List<Player> players = PlayerFactory.create(playerCombinations.get(playerPosition)); Collections.shuffle(players, ThreadLocalRandom.current()); int nextId = 1; for (Player player : players) player.setID(nextId++); return players; } private void printStatistics (List<List<Player>> gameSets, List<Class<? extends Player>> winners) { HashMap<List<Class<? extends Player>>, List<Class<? extends Player>>> lineupWinnerPairs = new HashMap<>(); for (int i = 0; i < gameSets.size(); i++) { List<Class<? extends Player>> gameSet = new ArrayList<>(); List<Player> gameSetAsPlayer = gameSets.get(i); for (Player player : gameSetAsPlayer) gameSet.add(player.getClass()); Class<? extends Player> winner = winners.get(i); lineupWinnerPairs.putIfAbsent(gameSet, new ArrayList<>()); lineupWinnerPairs.get(gameSet).add(winner); } HashMap<List<Class<? extends Player>>, Map<Class<? extends Player>, Integer>> lineupScorePairs = new HashMap<>(); lineupWinnerPairs.forEach((classes, classes2) -> { Map<Class<? extends Player>, Integer> winningCount = winningCounts(classes2); Iterator<Map.Entry<Class<? extends Player>, Integer>> iterator = winningCount.entrySet().iterator(); while (iterator.hasNext()) if (iterator.next().getValue() == 0) iterator.remove(); lineupScorePairs.put(classes, winningCount); }); lineupScorePairs.forEach((key, wins) -> { System.out.println(key); System.out.println( prettyPrintScore(wins)); }); } }
Cleanup code, small refactoring
src/main/java/connectn/game/Runner.java
Cleanup code, small refactoring
<ide><path>rc/main/java/connectn/game/Runner.java <ide> private static final boolean SHOW_STATISTICS = true; <ide> private final static int PLAYERS_PER_GAME = 3; <ide> public static int MINIMUM_NUMBER_OF_GAMES = 100000; <del> private static int actNumberOfRounds = -1; <del> <del> private Set<Class<? extends Player>> allPlayers; <del> <del> static { <del> actNumberOfRounds = Math.max(MINIMUM_NUMBER_OF_GAMES * PlayerFactory.playerCreator.size() / PLAYERS_PER_GAME + 1, <del> MINIMUM_NUMBER_OF_GAMES); <del> } <del> <del> <del> { <del> allPlayers = new HashSet<>(PlayerFactory.getPlayerTypes()); <del> } <ide> <ide> <ide> public void runGames() { <add> int actNumberOfRounds = Math.max(MINIMUM_NUMBER_OF_GAMES * PlayerFactory.playerCreator.size() / PLAYERS_PER_GAME + 1, <add> MINIMUM_NUMBER_OF_GAMES); <add> <ide> List<List<Player>> games = IntStream <ide> .range(0, actNumberOfRounds - 1) <ide> .mapToObj(value -> generateNextPlayers()).collect(Collectors.toList()); <ide> List<Class<? extends Player>> winners = games.stream() <ide> .parallel() <del> .unordered() <ide> .map(this::runGame) <ide> .collect(Collectors.toList()); <ide> <ide> <ide> <ide> private List<List<Class<? extends Player>>> playerCombinations = ListUtil.combinations(new ArrayList<Iterable<Class<? extends Player>>>() {{ <add> List<Class<? extends Player>> allPlayers = PlayerFactory.getPlayerTypes(); <ide> add(allPlayers); <ide> add(allPlayers); <ide> add(allPlayers);
JavaScript
mit
9839dcea8259e79166547e33f5cc18f563f5a051
0
yefremov/algorithms-with-javascript
var test = require('tape'); var linear = require('../linear'); test('linear(array, value)', function (t) { t.equal(linear([1, 2, 3, 4, 5], 3), 3, 'should return 3'); t.equal(linear(['c', 'a', 'b'], 'a'), 'a', 'should return a'); t.equal(linear(['foo', 'bar', 'baz'], 'foo'), 'foo', 'should return foo'); t.end(); });
lib/search/test/linear-test.js
var test = require('tape'); var linear = require('../linear'); test('linear(array, value)', function (t) { t.deepEqual(linear(['c', 'a', 'b'], 'a'), 'a', 'should be equal a'); t.deepEqual(linear([0xa, null, 'foo', 'false'], 'foo'), 'foo', 'should be equal foo'); t.end(); });
Fix typos in tests
lib/search/test/linear-test.js
Fix typos in tests
<ide><path>ib/search/test/linear-test.js <ide> var linear = require('../linear'); <ide> <ide> test('linear(array, value)', function (t) { <del> t.deepEqual(linear(['c', 'a', 'b'], 'a'), 'a', 'should be equal a'); <del> t.deepEqual(linear([0xa, null, 'foo', 'false'], 'foo'), 'foo', 'should be equal foo'); <add> t.equal(linear([1, 2, 3, 4, 5], 3), 3, 'should return 3'); <add> t.equal(linear(['c', 'a', 'b'], 'a'), 'a', 'should return a'); <add> t.equal(linear(['foo', 'bar', 'baz'], 'foo'), 'foo', 'should return foo'); <ide> t.end(); <ide> });
Java
unlicense
8c8ca33fb2380ebd651a9df60fbe84f0f19d1547
0
ferreusveritas/Growing-Trees
package com.ferreusveritas.dynamictrees.client; import java.util.ArrayList; import java.util.Arrays; import net.minecraft.client.renderer.texture.TextureAtlasSprite; public class TextureUtils { public static class PixelBuffer { public final int[] pixels; public final int w; public final int h; public PixelBuffer(int w, int h) { this.w = w; this.h = h; pixels = new int[w * h]; } public PixelBuffer(TextureAtlasSprite sprite) { this.w = sprite.getIconWidth(); this.h = sprite.getIconHeight(); int data[][] = sprite.getFrameTextureData(0); pixels = data[0]; } public PixelBuffer(TextureAtlasSprite sprite, boolean copy) { this.w = sprite.getIconWidth(); this.h = sprite.getIconHeight(); int[][] original = sprite.getFrameTextureData(0); pixels = Arrays.copyOf(original[0], original[0].length); } public PixelBuffer(PixelBuffer other) { this.w = other.w; this.h = other.h; this.pixels = Arrays.copyOf(other.pixels, other.pixels.length); } public void apply(TextureAtlasSprite sprite) { if(w == sprite.getIconWidth() && h == sprite.getIconHeight()) { int[][] original = sprite.getFrameTextureData(0); int[][] data = new int[original.length][]; data[0] = pixels; ArrayList<int[][]> ftd = new ArrayList<>(); ftd.add(data); sprite.setFramesTextureData(ftd); } } public int calcPos(int offX, int offY) { return offY * w + offX; } public int getPixel(int offX, int offY) { if(offX >= 0 && offX < w && offY >= 0 && offY < h) { return pixels[calcPos(offX, offY)]; } return 0; } public void setPixel(int offX, int offY, int pixel) { if(offX >= 0 && offX < w && offY >= 0 && offY < h) { pixels[calcPos(offX, offY)] = pixel; } } public void blit(PixelBuffer dst, int offX, int offY) { blit(dst, offX, offY, 0); } //A very very inefficient and simple blitter. public void blit(PixelBuffer dst, int offX, int offY, int rotCW90) { switch(rotCW90 & 3) { case 0: for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { dst.setPixel(x + offX, y + offY, getPixel(x, y)); } }; return; case 1: for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { int destX = h - y - 1; int destY = x; dst.setPixel(destX + offX, destY + offY, getPixel(x, y)); } } return; case 2: for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { int destX = w - x - 1; int destY = h - y - 1; dst.setPixel(destX + offX, destY + offY, getPixel(x, y)); } } return; case 3: for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { int destX = y; int destY = w - x - 1; dst.setPixel(destX + offX, destY + offY, getPixel(x, y)); } } return; } } public int averageColor() { return avgColors(pixels); } public void grayScale() { for(int i = 0; i < pixels.length; i++) { int a = alpha(pixels[i]); int r = red(pixels[i]); int g = green(pixels[i]); int b = blue(pixels[i]); int gray = ((r * 30) + (g * 59) + (b * 11)) / 100; pixels[i] = compose(gray, gray, gray, a); } } public void fill(int color) { for(int i = 0; i < pixels.length; i++) { pixels[i] = color; } } } public static int compose(int r, int g, int b, int a) { int rgb = a; rgb = (rgb << 8) + r; rgb = (rgb << 8) + g; rgb = (rgb << 8) + b; return rgb; } public static int compose(int c[]) { return c.length >= 4 ? compose(c[0], c[1], c[2], c[3]) : 0; } /** * @param c input color * @return an array ordered r, g, b, a */ public static int[] decompose(int c) { return new int[] { red(c), green(c), blue(c), alpha(c) }; } public static int alpha(int c) { return (c >> 24) & 0xFF; } public static int red(int c) { return (c >> 16) & 0xFF; } public static int green(int c) { return (c >> 8) & 0xFF; } public static int blue(int c) { return (c) & 0xFF; } public static int avgColors(int pixels[]) { long rAccum = 0; long gAccum = 0; long bAccum = 0; int count = 0; for(int i = 0; i < pixels.length; i++) { int alpha = alpha(pixels[i]); if(alpha >= 128) { rAccum += red(pixels[i]); gAccum += green(pixels[i]); bAccum += blue(pixels[i]); count++; } } int r = (int) (rAccum / count); int g = (int) (gAccum / count); int b = (int) (bAccum / count); return compose(r, g, b, 255); } }
src/main/java/com/ferreusveritas/dynamictrees/client/TextureUtils.java
package com.ferreusveritas.dynamictrees.client; import java.util.ArrayList; import java.util.Arrays; import net.minecraft.client.renderer.texture.TextureAtlasSprite; public class TextureUtils { public static class PixelBuffer { public final int[] pixels; public final int w; public final int h; public PixelBuffer(int w, int h) { this.w = w; this.h = h; pixels = new int[w * h]; } public PixelBuffer(TextureAtlasSprite sprite) { this.w = sprite.getIconWidth(); this.h = sprite.getIconHeight(); int data[][] = sprite.getFrameTextureData(0); pixels = data[0]; } public PixelBuffer(TextureAtlasSprite sprite, boolean copy) { this.w = sprite.getIconWidth(); this.h = sprite.getIconHeight(); int[][] original = sprite.getFrameTextureData(0); pixels = Arrays.copyOf(original[0], original[0].length); } public PixelBuffer(PixelBuffer other) { this.w = other.w; this.h = other.h; this.pixels = Arrays.copyOf(other.pixels, other.pixels.length); } public void apply(TextureAtlasSprite sprite) { if(w == sprite.getIconWidth() && h == sprite.getIconHeight()) { int[][] original = sprite.getFrameTextureData(0); int[][] data = new int[original.length][]; data[0] = pixels; ArrayList<int[][]> ftd = new ArrayList<>(); ftd.add(data); sprite.setFramesTextureData(ftd); } } public int calcPos(int offX, int offY) { return offY * w + offX; } public int getPixel(int offX, int offY) { if(offX >= 0 && offX < w && offY >= 0 && offY < h) { return pixels[calcPos(offX, offY)]; } return 0; } public void setPixel(int offX, int offY, int pixel) { if(offX >= 0 && offX < w && offY >= 0 && offY < h) { pixels[calcPos(offX, offY)] = pixel; } } public void blit(PixelBuffer dst, int offX, int offY) { blit(dst, offX, offY, 0); } //A very very inefficient and simple blitter. public void blit(PixelBuffer dst, int offX, int offY, int rotCW90) { switch(rotCW90 & 3) { case 0: for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { dst.setPixel(x + offX, y + offY, getPixel(x, y)); } }; return; case 1: for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { int destX = h - y - 1; int destY = x; dst.setPixel(destX + offX, destY + offY, getPixel(x, y)); } } return; case 2: for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { int destX = w - x - 1; int destY = h - y - 1; dst.setPixel(destX + offX, destY + offY, getPixel(x, y)); } } return; case 3: for(int y = 0; y < h; y++) { for(int x = 0; x < w; x++) { int destX = y; int destY = w - x - 1; dst.setPixel(destX + offX, destY + offY, getPixel(x, y)); } } return; } } public int averageColor() { return avgColors(pixels); } public void grayScale() { for(int i = 0; i < pixels.length; i++) { int a = alpha(pixels[i]); int r = red(pixels[i]); int g = green(pixels[i]); int b = blue(pixels[i]); int gray = ((r * 30) + (g * 59) + (b * 11)) / 100; pixels[i] = compose(gray, gray, gray, a); } } public void fill(int color) { for(int i = 0; i < pixels.length; i++) { pixels[i] = color; } } } public static int compose(int r, int g, int b, int a) { int rgb = a; rgb = (rgb << 8) + r; rgb = (rgb << 8) + g; rgb = (rgb << 8) + b; return rgb; } public static int compose(int c[]) { return c.length >= 4 ? compose(c[0], c[1], c[2], c[3]) : 0; } /** * @param c input color * @return an array ordered r, g, b, a */ public static int[] decompose(int c) { return new int[] { red(c), green(c), blue(c), alpha(c) }; } public static int alpha(int c) { return (c >> 24) & 0xFF; } public static int red(int c) { return (c >> 16) & 0xFF; } public static int green(int c) { return (c >> 8) & 0xFF; } public static int blue(int c) { return (c) & 0xFF; } public static int avgColors(int pixels[]) { long rAccum = 0; long gAccum = 0; long bAccum = 0; for(int i = 0; i < pixels.length; i++) { rAccum += red(pixels[i]); gAccum += green(pixels[i]); bAccum += blue(pixels[i]); } int r = (int) (rAccum / pixels.length); int g = (int) (gAccum / pixels.length); int b = (int) (bAccum / pixels.length); return compose(r, g, b, 255); } }
account for alpha channel when averaging colors
src/main/java/com/ferreusveritas/dynamictrees/client/TextureUtils.java
account for alpha channel when averaging colors
<ide><path>rc/main/java/com/ferreusveritas/dynamictrees/client/TextureUtils.java <ide> long gAccum = 0; <ide> long bAccum = 0; <ide> <add> int count = 0; <add> <ide> for(int i = 0; i < pixels.length; i++) { <del> rAccum += red(pixels[i]); <del> gAccum += green(pixels[i]); <del> bAccum += blue(pixels[i]); <add> int alpha = alpha(pixels[i]); <add> if(alpha >= 128) { <add> rAccum += red(pixels[i]); <add> gAccum += green(pixels[i]); <add> bAccum += blue(pixels[i]); <add> count++; <add> } <ide> } <ide> <del> int r = (int) (rAccum / pixels.length); <del> int g = (int) (gAccum / pixels.length); <del> int b = (int) (bAccum / pixels.length); <add> int r = (int) (rAccum / count); <add> int g = (int) (gAccum / count); <add> int b = (int) (bAccum / count); <ide> <ide> return compose(r, g, b, 255); <ide> }
JavaScript
mit
daea1e7a922c4088fdebb20cdb7a181b577071d1
0
cujojs/wire,designeng/wire,wilson7287/wire,designeng/wire,cujojs/wire
/** * @license Copyright (c) 2010-2011 Brian Cavalier * LICENSE: see the LICENSE.txt file. If file is missing, this file is subject * to the MIT License at: http://www.opensource.org/licenses/mit-license.php. */ /* File: wire.js */ //noinspection ThisExpressionReferencesGlobalObjectJS (function(global, define){ define(['require', 'when', 'wire/base'], function(require, when, basePlugin) { "use strict"; var VERSION, tos, arrayProto, apIndexOf, apSlice, rootSpec, rootContext, delegate, emptyObject, defer, chain, whenAll, isPromise, isArray, indexOf, undef; wire.version = VERSION = "0.7.2"; rootSpec = global['wire'] || {}; tos = Object.prototype.toString; arrayProto = Array.prototype; apSlice = arrayProto.slice; apIndexOf = arrayProto.indexOf; // Polyfills /** * Object.create */ delegate = Object.create || createObject; /** * Array.isArray */ isArray = Array.isArray || function (it) { return tos.call(it) == '[object Array]'; }; /** * Array.prototype.indexOf */ indexOf = apIndexOf ? function(array, item) { return apIndexOf.call(array, item); } : function (array, item) { for (var i = 0, len = array.length; i < len; i++) { if(array[i] === item) return i; } return -1; }; emptyObject = {}; // Local refs to when.js defer = when.defer; chain = when.chain; whenAll = when.all; isPromise = when.isPromise; // Helper to reject a deferred when another is rejected function chainReject(resolver) { return function(err) { resolver.reject(err); }; } function rejected(err) { var d = defer(); d.reject(err); return d; } // // AMD Module API // function wire(spec) { // If the root context is not yet wired, wire it first if (!rootContext) { rootContext = wireContext(rootSpec); } // Use the rootContext to wire all new contexts. // TODO: Remove .then() for when.js 0.9.4 return when(rootContext, function(root) { return root.wire(spec); } ); } // // AMD loader plugin API // //noinspection JSUnusedLocalSymbols function amdLoad(name, require, callback, config) { var promise = callback.resolve ? callback : { resolve: callback, reject: function(err) { throw err; } }; chain(wire(name), promise); } wire.load = amdLoad; // // AMD Analyze/Build plugin API // // Separate builder plugin as per CommonJS LoaderPlugin spec: // http://wiki.commonjs.org/wiki/Modules/LoaderPlugin // plugin-builder: wire/cram/builder // cram v 0.2+ supports plugin-builder property wire['plugin-builder'] = 'wire/cram/builder'; // // Private functions // function wireContext(specs, parent, mixin) { var deferred = defer(); // Function to do the actual wiring. Capture the // parent so it can be called after an async load // if spec is an AMD module Id string. function doWireContexts(specs) { if(mixin) specs.push(mixin); var spec = mergeSpecs(specs); when(createScope(spec, parent), function(scope) { deferred.resolve(scope.objects); }, chainReject(deferred) ); } // If spec is a module Id, or list of module Ids, load it/them, then wire. // If it's a spec object or array of objects, wire it now. if(isString(specs)) { var specIds = specs.split(','); require(specIds, function() { doWireContexts(apSlice.call(arguments)); }); } else { doWireContexts(isArray(specs) ? specs : [specs]); } return deferred; } // Merge multiple specs together before wiring. function mergeSpecs(specs) { var i = 0, merged = {}, s; while(s = specs[i++]) { mixinSpec(merged, s); } return merged; } // Add components in from to those in to. If duplicates are found, it // is an error. function mixinSpec(to, from) { for (var name in from) { if (from.hasOwnProperty(name) && !(name in emptyObject)) { if (to.hasOwnProperty(name)) { throw new Error("Duplicate component name in sibling specs: " + name); } else { to[name] = from[name]; } } } } function createScope(scopeDef, parent, scopeName) { var scope, scopeParent, local, proxied, objects, pluginApi, resolvers, factories, facets, listeners, proxies, modulesToLoad, moduleLoadPromises, wireApi, modulesReady, scopeReady, scopeDestroyed, contextPromise, doDestroy; // Empty parent scope if none provided parent = parent || {}; initFromParent(parent); initPluginApi(); // TODO: Find a better way to load and scan the base plugin scanPlugin(basePlugin); contextPromise = initContextPromise(scopeDef, scopeReady); initWireApi(contextPromise, objects); createComponents(local, scopeDef); // Once all modules are loaded, all the components can finish ensureAllModulesLoaded(); // Setup overwritable doDestroy so that this context // can only be destroyed once doDestroy = function() { // Retain a do-nothing doDestroy() func, in case // it is called again for some reason. doDestroy = function() {}; return destroyContext(); }; // Return promise // Context will be ready when this promise resolves return scopeReady.promise; // // Initialization // function initFromParent(parent) { local = {}; // Descend scope and plugins from parent so that this scope can // use them directly via the prototype chain objects = delegate(parent.objects ||{}); resolvers = delegate(parent.resolvers||{}); factories = delegate(parent.factories||{}); facets = delegate(parent.facets ||{}); listeners = parent.listeners ? [].concat(parent.listeners) : []; // Proxies is an array, have to concat proxies = parent.proxies ? [].concat(parent.proxies) : []; proxied = []; modulesToLoad = []; moduleLoadPromises = {}; modulesReady = defer(); scopeReady = defer(); scopeDestroyed = defer(); // A proxy of this scope that can be used as a parent to // any child scopes that may be created. scopeParent = { name: scopeName, objects: objects, destroyed: scopeDestroyed }; // Full scope definition. This will be given to sub-scopes, // but should never be given to child contexts scope = delegate(scopeParent); scope.local = local; scope.resolvers = resolvers; scope.factories = factories; scope.facets = facets; scope.listeners = listeners; scope.proxies = proxies; scope.resolveRef = doResolveRef; scope.destroy = destroy; scope.path = createPath(scopeName, parent.path); // When the parent begins its destroy phase, this child must // begin its destroy phase and complete it before the parent. // The context hierarchy will be destroyed from child to parent. if (parent.destroyed) { when(parent.destroyed, destroy); } } function initWireApi(contextPromise, objects) { // DEPRECATED // Access to objects will be removed after 0.7.0, so it // won't need to be decorated anymore. May provide access // to contextPromise instead, if there are valid use cases // wireApi is be the preferred way to inject access to // wire in 0.7.0+ wireApi = objects.wire = wireChild; wireApi.destroy = objects.destroy = apiDestroy; // Consider deprecating resolve // Any reference you could resolve using this should simply be // injected instead. wireApi.resolve = objects.resolve = apiResolveRef; // DEPRECATED objects.then // To be removed after 0.7.0 - See notes above about objects, // contextPromise, and wireApi objects.then = contextPromise.then; } function initPluginApi() { // Plugin API // wire() API that is passed to plugins. pluginApi = function(spec, name, path) { // FIXME: Why does returning when(item) here cause // the resulting, returned promise never to resolve // in wire-factory1.html? var item = createItem(spec, createPath(name, path)); return when.isPromise(item) ? item : when(item); }; pluginApi.resolveRef = apiResolveRef; // DEPRECATED // To be removed after 0.7.0 // These will be removed from the plugin API after v0.7.0 in favor // of using when.js (or any other CommonJS Promises/A compliant // deferred/when) directly in plugins pluginApi.deferred = defer; pluginApi.when = when; pluginApi.whenAll = whenAll; // DEPRECATED // To be removed after 0.7.0 // Should not be used pluginApi.ready = scopeReady.promise; } function initContextPromise(scopeDef, scopeReady) { var promises = []; // Setup a promise for each item in this scope for (var name in scopeDef) { if (scopeDef.hasOwnProperty(name)) { promises.push(local[name] = objects[name] = defer()); } } // When all scope item promises are resolved, the scope // is resolved. // When this scope is ready, resolve the contextPromise // with the objects that were created return whenAll(promises, function() { scopeReady.resolve(scope); return objects; }, chainReject(scopeReady) ); } // // Context Startup // function createComponents(names, scopeDef) { // Process/create each item in scope and resolve its // promise when completed. for (var name in names) { // No need to check hasOwnProperty since we know names // only contains scopeDef's own prop names. createScopeItem(name, scopeDef[name], objects[name]); } } function ensureAllModulesLoaded() { // Once all modules have been loaded, resolve modulesReady require(modulesToLoad, function(modules) { modulesReady.resolve(modules); moduleLoadPromises = modulesToLoad = null; }); } // // Context Destroy // function destroyContext() { var p, promises, pDeferred, i; scopeDestroyed.resolve(); // TODO: Clear out the context prototypes? promises = []; for (i = 0; (p = proxied[i++]);) { pDeferred = defer(); promises.push(pDeferred); processListeners(pDeferred, 'destroy', p); } // *After* listeners are processed, whenAll(promises, function() { var p, i; for (p in local) delete local[p]; for (p in objects) delete objects[p]; for (p in scope) delete scope[p]; for (i = 0; (p = proxied[i++]);) { p.destroy(); } // Free Objects local = objects = scope = proxied = proxies = parent = resolvers = factories = facets = wireApi = undef; // Free Arrays listeners = undef; }); return scopeDestroyed; } // // Context API // // API of a wired context that is returned, via promise, to // the caller. It will also have properties for all the // objects that were created in this scope. function apiResolveRef(ref) { return when(doResolveRef(ref)); } function apiDestroy() { return destroy(); } /** * Wires a child spec with this context as its parent * @param spec * @param [mixin] {Object} */ function wireChild(spec, /* {Object}? */ mixin) { return wireContext(spec, scopeParent, mixin); } // // Scope functions // function createPath(name, basePath) { var path = basePath || scope.path; return (path && name) ? (path + '.' + name) : name; } function createScopeItem(name, val, itemPromise) { // NOTE: Order is important here. // The object & local property assignment MUST happen before // the chain resolves so that the concrete item is in place. // Otherwise, the whole scope can be marked as resolved before // the final item has been resolved. var p = createItem(val, name); return when(p, function(resolved) { objects[name] = local[name] = resolved; itemPromise.resolve(resolved); }, chainReject(itemPromise)); } function createItem(val, name) { var created; if (isRef(val)) { // Reference created = resolveRef(val, name); } else if (isArray(val)) { // Array created = createArray(val, name); } else if (isStrictlyObject(val)) { // Module or nested scope created = createModule(val, name); } else { // Plain value created = val; } return created; } function getModule(moduleId, spec) { var module; if (isString(moduleId)) { var m = moduleLoadPromises[moduleId]; if (!m) { modulesToLoad.push(moduleId); m = moduleLoadPromises[moduleId] = { id: moduleId, deferred: defer() }; moduleLoadPromises[moduleId] = m; require([moduleId], function(module) { scanPlugin(module, spec); m.module = module; chain(modulesReady, m.deferred, m.module); }); } module = m.deferred; } else { module = moduleId; scanPlugin(module); } return module; } function scanPlugin(module, spec) { if (module && isFunction(module.wire$plugin)) { var plugin = module.wire$plugin(contextPromise, scopeDestroyed.promise, spec); if (plugin) { addPlugin(plugin.resolvers, resolvers); addPlugin(plugin.factories, factories); addPlugin(plugin.facets, facets); listeners.push(plugin); addProxies(plugin.proxies); } } } function addProxies(proxiesToAdd) { if(!proxiesToAdd) return; var newProxies, p, i = 0; newProxies = []; while(p = proxiesToAdd[i++]) { if(indexOf(proxies, p) < 0) { newProxies.push(p) } } scope.proxies = proxies = newProxies.concat(proxies); } function addPlugin(src, registry) { for (var name in src) { if (registry.hasOwnProperty(name)) { throw new Error("Two plugins for same type in scope: " + name); } registry[name] = src[name]; } } function createArray(arrayDef, name) { var result, id; result = []; if (arrayDef.length) { result = when.map(arrayDef, function(item) { return createItem(item, id); }); } return result; } function createModule(spec, name) { // Look for a factory, then use it to create the object return when(findFactory(spec), function(factory) { if(!spec.id) spec.id = name; var factoryPromise = defer(); factory(factoryPromise.resolver, spec, pluginApi); return processObject(factoryPromise, spec); }, function() { // No factory found, treat object spec as a nested scope return when(createScope(spec, scope, name), function(created) { return created.local; }, rejected ); } ); } function findFactory(spec) { var promise; // FIXME: Should not have to wait for all modules to load, // but rather only the module containing the particular // factory we need. But how to know which factory before // they are all loaded? // Maybe need a special syntax for factories, something like: // create: "factory!whatever-arg-the-factory-takes" // args: [factory args here] if (spec.module) { promise = moduleFactory; } else if (spec.create) { promise = instanceFactory; } else if (spec.wire) { promise = wireFactory; } else { // TODO: Switch to when() without then() for when.js 0.9.4+ promise = when(modulesReady, function() { for (var f in factories) { if (spec.hasOwnProperty(f)) { return factories[f]; } } return rejected(spec); }); } return promise; } function processObject(target, spec) { var created, configured, initialized, destroyed; created = defer(); configured = defer(); initialized = defer(); destroyed = defer(); // After the object has been created, update progress for // the entire scope, then process the post-created facets return when(target, function(object) { chain(scopeDestroyed, destroyed, object); var proxy = createProxy(object, spec); proxied.push(proxy); return when.reduce(['create', 'configure', 'initialize', 'ready'], function(object, step) { return processFacets(step, proxy); }, proxy); }, rejected); } function createProxy(object, spec) { var proxier, proxy, id, i; i = 0; id = spec.id; while((proxier = proxies[i++]) && !(proxy = proxier(object, spec))) {} proxy.target = object; proxy.spec = spec; proxy.id = id; proxy.path = createPath(id); return proxy; } function processFacets(step, proxy) { var promises, options, name, spec; promises = []; spec = proxy.spec; for(name in facets) { options = spec[name]; if(options) { processStep(promises, facets[name], step, proxy, options); } } var d = defer(); whenAll(promises, function() { processListeners(d, step, proxy); }, chainReject(d) ); return d; } function processListeners(promise, step, proxy) { var listenerPromises = []; for(var i=0; i<listeners.length; i++) { processStep(listenerPromises, listeners[i], step, proxy); } // FIXME: Use only proxy here, caller should resolve target return chain(whenAll(listenerPromises), promise, proxy.target); } function processStep(promises, processor, step, proxy, options) { var facet, facetPromise; if(processor && processor[step]) { facetPromise = defer(); promises.push(facetPromise); facet = delegate(proxy); facet.options = options; processor[step](facetPromise.resolver, facet, pluginApi); } } // // Built-in Factories // function moduleFactory(resolver, spec /*, wire, name*/) { chain(getModule(spec.module, spec), resolver); } /* Function: instanceFactory Factory that uses an AMD module either directly, or as a constructor or plain function to create the resulting item. */ //noinspection JSUnusedLocalSymbols function instanceFactory(resolver, spec, wire) { var fail, create, module, args, isConstructor, name; fail = chainReject(resolver); name = spec.id; create = spec.create; if (isStrictlyObject(create)) { module = create.module; args = create.args; isConstructor = create.isConstructor; } else { module = create; } // Load the module, and use it to create the object function handleModule(module) { function resolve(resolvedArgs) { try { var instantiated = instantiate(module, resolvedArgs, isConstructor); resolver.resolve(instantiated); } catch(e) { resolver.reject(e); } } try { // We'll either use the module directly, or we need // to instantiate/invoke it. if (isFunction(module)) { // Instantiate or invoke it and use the result if (args) { args = isArray(args) ? args : [args]; when(createArray(args, name), resolve, fail); } else { // No args, don't need to process them, so can directly // insantiate the module and resolve resolve([]); } } else { // Simply use the module as is resolver.resolve(module); } } catch(e) { fail(e); } } when(getModule(module, spec), handleModule, fail); } function wireFactory(resolver, spec/*, wire, name*/) { var options, module, defer; options = spec.wire; // Get child spec and options if(isString(options)) { module = options; } else { module = options.spec; defer = options.defer; } function createChild(/** {Object}? */ mixin) { return wireChild(module, mixin); } if(defer) { // Resolve with the createChild function itself // which can be used later to wire the spec resolver.resolve(createChild); } else { // Start wiring the child var context = createChild(); // Resolve immediately with the child promise resolver.resolve(context.promise); } } // // Reference resolution // function resolveRef(ref, name) { var refName = ref.$ref; return doResolveRef(refName, ref, name == refName); } function doResolveRef(refName, refObj, excludeSelf) { var promise, registry; registry = excludeSelf ? parent.objects : objects; if (refName in registry) { promise = registry[refName]; } else { var split; promise = defer(); split = refName.indexOf('!'); if (split > 0) { var name = refName.substring(0, split); refName = refName.substring(split + 1); if (name == 'wire') { wireResolver(promise, refName /*, refObj, pluginApi*/); } else { // Wait for modules, since the reference may need to be // resolved by a resolver plugin when(modulesReady, function() { var resolver = resolvers[name]; if (resolver) { resolver(promise, refName, refObj, pluginApi); } else { promise.reject("No resolver found for ref: " + refObj); } }); } } else { promise.reject("Cannot resolve ref: " + refName); } } return promise; } function wireResolver(promise /*, name, refObj, wire*/) { // DEPRECATED access to objects // Providing access to objects here is dangerous since not all // the components in objects have been initialized--that is, they // may still be promises, and it's possible to deadlock by waiting // on one of those promises (via when() or promise.then()) promise.resolve(wireApi); } // // Destroy // function destroy() { return when(scopeReady, doDestroy, doDestroy); } } // createScope function isRef(it) { return it && it.$ref; } function isString(it) { return typeof it == 'string'; } function isStrictlyObject(it) { return tos.call(it) == '[object Object]'; } /* Function: isFunction Standard function test Parameters: it - anything Returns: true iff it is a Function */ function isFunction(it) { return typeof it == 'function'; } // In case Object.create isn't available function T() {} function createObject(prototype) { T.prototype = prototype; return new T(); } /* Constructor: Begetter Constructor used to beget objects that wire needs to create using new. Parameters: ctor - real constructor to be invoked args - arguments to be supplied to ctor */ function Begetter(ctor, args) { return ctor.apply(this, args); } /* Function: instantiate Creates an object by either invoking ctor as a function and returning the result, or by calling new ctor(). It uses a simple heuristic to try to guess which approach is the "right" one. Parameters: ctor - function or constructor to invoke args - array of arguments to pass to ctor in either case Returns: The result of invoking ctor with args, with or without new, depending on the strategy selected. */ function instantiate(ctor, args, forceConstructor) { if (forceConstructor || isConstructor(ctor)) { Begetter.prototype = ctor.prototype; Begetter.prototype.constructor = ctor; return new Begetter(ctor, args); } else { return ctor.apply(null, args); } } /* Function: isConstructor Determines with the supplied function should be invoked directly or should be invoked using new in order to create the object to be wired. Parameters: func - determine whether this should be called using new or not Returns: true iff func should be invoked using new, false otherwise. */ function isConstructor(func) { var is = false, p; for (p in func.prototype) { if (p !== undef) { is = true; break; } } return is; } return wire; }); })(this, typeof define != 'undefined' // use define for AMD if available ? define // Browser // If no define or module, attach to current context. : function(deps, factory) { this.wire = factory( // Fake require() function(modules, callback) { callback(modules); }, // dependencies this.when, this.wire_base ); } // NOTE: Node not supported yet, coming soon );
wire.js
/** * @license Copyright (c) 2010-2011 Brian Cavalier * LICENSE: see the LICENSE.txt file. If file is missing, this file is subject * to the MIT License at: http://www.opensource.org/licenses/mit-license.php. */ /* File: wire.js */ //noinspection ThisExpressionReferencesGlobalObjectJS (function(global, define){ define(['require', 'when', 'wire/base'], function(require, when, basePlugin) { "use strict"; var VERSION, tos, arrayProto, apIndexOf, apSlice, rootSpec, rootContext, delegate, emptyObject, defer, chain, whenAll, isPromise, isArray, indexOf, undef; wire.version = VERSION = "0.7.2"; rootSpec = global['wire'] || {}; tos = Object.prototype.toString; arrayProto = Array.prototype; apSlice = arrayProto.slice; apIndexOf = arrayProto.indexOf; // Polyfills /** * Object.create */ delegate = Object.create || createObject; /** * Array.isArray */ isArray = Array.isArray || function (it) { return tos.call(it) == '[object Array]'; }; /** * Array.prototype.indexOf */ indexOf = apIndexOf ? function(array, item) { return apIndexOf.call(array, item); } : function (array, item) { for (var i = 0, len = array.length; i < len; i++) { if(array[i] === item) return i; } return -1; }; emptyObject = {}; // Local refs to when.js defer = when.defer; chain = when.chain; whenAll = when.all; isPromise = when.isPromise; // Helper to reject a deferred when another is rejected function chainReject(resolver) { return function(err) { resolver.reject(err); }; } function rejected(err) { var d = defer(); d.reject(err); return d; } // // AMD Module API // function wire(spec) { // If the root context is not yet wired, wire it first if (!rootContext) { rootContext = wireContext(rootSpec); } // Use the rootContext to wire all new contexts. // TODO: Remove .then() for when.js 0.9.4 return when(rootContext, function(root) { return root.wire(spec); } ); } // // AMD loader plugin API // //noinspection JSUnusedLocalSymbols function amdLoad(name, require, callback, config) { var promise = callback.resolve ? callback : { resolve: callback, reject: function(err) { throw err; } }; chain(wire(name), promise); } wire.load = amdLoad; // // AMD Analyze/Build plugin API // // Separate builder plugin as per CommonJS LoaderPlugin spec: // http://wiki.commonjs.org/wiki/Modules/LoaderPlugin // plugin-builder: wire/cram/builder // cram v 0.2+ supports plugin-builder property wire['plugin-builder'] = 'wire/cram/builder'; // // Private functions // function wireContext(specs, parent, mixin) { var deferred = defer(); // Function to do the actual wiring. Capture the // parent so it can be called after an async load // if spec is an AMD module Id string. function doWireContexts(specs) { if(mixin) specs.push(mixin); var spec = mergeSpecs(specs); when(createScope(spec, parent), function(scope) { deferred.resolve(scope.objects); }, chainReject(deferred) ); } // If spec is a module Id, or list of module Ids, load it/them, then wire. // If it's a spec object or array of objects, wire it now. if(isString(specs)) { var specIds = specs.split(','); require(specIds, function() { doWireContexts(apSlice.call(arguments)); }); } else { doWireContexts(isArray(specs) ? specs : [specs]); } return deferred; } // Merge multiple specs together before wiring. function mergeSpecs(specs) { var i = 0, merged = {}, s; while(s = specs[i++]) { mixinSpec(merged, s); } return merged; } // Add components in from to those in to. If duplicates are found, it // is an error. function mixinSpec(to, from) { for (var name in from) { if (from.hasOwnProperty(name) && !(name in emptyObject)) { if (to.hasOwnProperty(name)) { throw new Error("Duplicate component name in sibling specs: " + name); } else { to[name] = from[name]; } } } } function createScope(scopeDef, parent, scopeName) { var scope, scopeParent, local, proxied, objects, pluginApi, resolvers, factories, facets, listeners, proxies, modulesToLoad, moduleLoadPromises, wireApi, modulesReady, scopeReady, scopeDestroyed, contextPromise, doDestroy; // Empty parent scope if none provided parent = parent || {}; initFromParent(parent); initPluginApi(); // TODO: Find a better way to load and scan the base plugin scanPlugin(basePlugin); contextPromise = initContextPromise(scopeDef, scopeReady); initWireApi(contextPromise, objects); createComponents(local, scopeDef); // Once all modules are loaded, all the components can finish ensureAllModulesLoaded(); // Setup overwritable doDestroy so that this context // can only be destroyed once doDestroy = function() { // Retain a do-nothing doDestroy() func, in case // it is called again for some reason. doDestroy = function() {}; return destroyContext(); }; // Return promise // Context will be ready when this promise resolves return scopeReady.promise; // // Initialization // function initFromParent(parent) { local = {}; // Descend scope and plugins from parent so that this scope can // use them directly via the prototype chain objects = delegate(parent.objects ||{}); resolvers = delegate(parent.resolvers||{}); factories = delegate(parent.factories||{}); facets = delegate(parent.facets ||{}); listeners = parent.listeners ? [].concat(parent.listeners) : []; // Proxies is an array, have to concat proxies = parent.proxies ? [].concat(parent.proxies) : []; proxied = []; modulesToLoad = []; moduleLoadPromises = {}; modulesReady = defer(); scopeReady = defer(); scopeDestroyed = defer(); // A proxy of this scope that can be used as a parent to // any child scopes that may be created. scopeParent = { name: scopeName, objects: objects, destroyed: scopeDestroyed }; // Full scope definition. This will be given to sub-scopes, // but should never be given to child contexts scope = delegate(scopeParent); scope.local = local; scope.resolvers = resolvers; scope.factories = factories; scope.facets = facets; scope.listeners = listeners; scope.proxies = proxies; scope.resolveRef = doResolveRef; scope.destroy = destroy; scope.path = createPath(scopeName, parent.path); // When the parent begins its destroy phase, this child must // begin its destroy phase and complete it before the parent. // The context hierarchy will be destroyed from child to parent. if (parent.destroyed) { when(parent.destroyed, destroy); } } function initWireApi(contextPromise, objects) { // DEPRECATED // Access to objects will be removed after 0.7.0, so it // won't need to be decorated anymore. May provide access // to contextPromise instead, if there are valid use cases // wireApi is be the preferred way to inject access to // wire in 0.7.0+ wireApi = objects.wire = wireChild; wireApi.destroy = objects.destroy = apiDestroy; // Consider deprecating resolve // Any reference you could resolve using this should simply be // injected instead. wireApi.resolve = objects.resolve = apiResolveRef; // DEPRECATED objects.then // To be removed after 0.7.0 - See notes above about objects, // contextPromise, and wireApi objects.then = contextPromise.then; } function initPluginApi() { // Plugin API // wire() API that is passed to plugins. pluginApi = function(spec, name, path) { // FIXME: Why does returning when(item) here cause // the resulting, returned promise never to resolve // in wire-factory1.html? var item = createItem(spec, createPath(name, path)); return when.isPromise(item) ? item : when(item); }; pluginApi.resolveRef = apiResolveRef; // DEPRECATED // To be removed after 0.7.0 // These will be removed from the plugin API after v0.7.0 in favor // of using when.js (or any other CommonJS Promises/A compliant // deferred/when) directly in plugins pluginApi.deferred = defer; pluginApi.when = when; pluginApi.whenAll = whenAll; // DEPRECATED // To be removed after 0.7.0 // Should not be used pluginApi.ready = scopeReady.promise; } function initContextPromise(scopeDef, scopeReady) { var promises = []; // Setup a promise for each item in this scope for (var name in scopeDef) { if (scopeDef.hasOwnProperty(name)) { promises.push(local[name] = objects[name] = defer()); } } // When all scope item promises are resolved, the scope // is resolved. // When this scope is ready, resolve the contextPromise // with the objects that were created return whenAll(promises, function() { scopeReady.resolve(scope); return objects; }, chainReject(scopeReady) ); } // // Context Startup // function createComponents(names, scopeDef) { // Process/create each item in scope and resolve its // promise when completed. for (var name in names) { // No need to check hasOwnProperty since we know names // only contains scopeDef's own prop names. createScopeItem(name, scopeDef[name], objects[name]); } } function ensureAllModulesLoaded() { // Once all modules have been loaded, resolve modulesReady require(modulesToLoad, function(modules) { modulesReady.resolve(modules); moduleLoadPromises = modulesToLoad = null; }); } // // Context Destroy // function destroyContext() { var p, promises, pDeferred, i; scopeDestroyed.resolve(); // TODO: Clear out the context prototypes? promises = []; for (i = 0; (p = proxied[i++]);) { pDeferred = defer(); promises.push(pDeferred); processListeners(pDeferred, 'destroy', p); } // *After* listeners are processed, whenAll(promises, function() { var p, i; for (p in local) delete local[p]; for (p in objects) delete objects[p]; for (p in scope) delete scope[p]; for (i = 0; (p = proxied[i++]);) { p.destroy(); } // Free Objects local = objects = scope = proxied = proxies = parent = resolvers = factories = facets = wireApi = undef; // Free Arrays listeners = undef; }); return scopeDestroyed; } // // Context API // // API of a wired context that is returned, via promise, to // the caller. It will also have properties for all the // objects that were created in this scope. function apiResolveRef(ref) { return when(doResolveRef(ref)); } function apiDestroy() { return destroy(); } /** * Wires a child spec with this context as its parent * @param spec * @param [mixin] {Object} */ function wireChild(spec, /* {Object}? */ mixin) { return wireContext(spec, scopeParent, mixin); } // // Scope functions // function createPath(name, basePath) { var path = basePath || scope.path; return (path && name) ? (path + '.' + name) : name; } function createScopeItem(name, val, itemPromise) { // NOTE: Order is important here. // The object & local property assignment MUST happen before // the chain resolves so that the concrete item is in place. // Otherwise, the whole scope can be marked as resolved before // the final item has been resolved. var p = createItem(val, name); return when(p, function(resolved) { objects[name] = local[name] = resolved; itemPromise.resolve(resolved); }, chainReject(itemPromise)); } function createItem(val, name) { var created; if (isRef(val)) { // Reference created = resolveRef(val, name); } else if (isArray(val)) { // Array created = createArray(val, name); } else if (isStrictlyObject(val)) { // Module or nested scope created = createModule(val, name); } else { // Plain value created = val; } return created; } function getModule(moduleId, spec) { var module; if (isString(moduleId)) { var m = moduleLoadPromises[moduleId]; if (!m) { modulesToLoad.push(moduleId); m = moduleLoadPromises[moduleId] = { id: moduleId, deferred: defer() }; moduleLoadPromises[moduleId] = m; require([moduleId], function(module) { scanPlugin(module, spec); m.module = module; chain(modulesReady, m.deferred, m.module); }); } module = m.deferred; } else { module = moduleId; scanPlugin(module); } return module; } function scanPlugin(module, spec) { if (module && isFunction(module.wire$plugin)) { var plugin = module.wire$plugin(contextPromise, scopeDestroyed.promise, spec); if (plugin) { addPlugin(plugin.resolvers, resolvers); addPlugin(plugin.factories, factories); addPlugin(plugin.facets, facets); listeners.push(plugin); addProxies(plugin.proxies); } } } function addProxies(proxiesToAdd) { if(!proxiesToAdd) return; var newProxies, p, i = 0; newProxies = []; while(p = proxiesToAdd[i++]) { if(indexOf(proxies, p) < 0) { newProxies.push(p) } } scope.proxies = proxies = newProxies.concat(proxies); } function addPlugin(src, registry) { for (var name in src) { if (registry.hasOwnProperty(name)) { throw new Error("Two plugins for same type in scope: " + name); } registry[name] = src[name]; } } function createArray(arrayDef, name) { var result, promises, itemPromise, item, id, i; result = []; if (arrayDef.length) { promises = []; for (i = 0; (item = arrayDef[i]); i++) { id = item.id || name + '[' + i + ']'; itemPromise = result[i] = createItem(arrayDef[i], id); promises.push(itemPromise); resolveArrayValue(itemPromise, result, i); } result = chain(whenAll(promises), defer(), result); } return result; } function resolveArrayValue(promise, array, i) { when(promise, function(value) { array[i] = value; }); } function createModule(spec, name) { // Look for a factory, then use it to create the object return when(findFactory(spec), function(factory) { if(!spec.id) spec.id = name; var factoryPromise = defer(); factory(factoryPromise.resolver, spec, pluginApi); return processObject(factoryPromise, spec); }, function() { // No factory found, treat object spec as a nested scope return when(createScope(spec, scope, name), function(created) { return created.local; }, rejected ); } ); } function findFactory(spec) { var promise; // FIXME: Should not have to wait for all modules to load, // but rather only the module containing the particular // factory we need. But how to know which factory before // they are all loaded? // Maybe need a special syntax for factories, something like: // create: "factory!whatever-arg-the-factory-takes" // args: [factory args here] if (spec.module) { promise = moduleFactory; } else if (spec.create) { promise = instanceFactory; } else if (spec.wire) { promise = wireFactory; } else { // TODO: Switch to when() without then() for when.js 0.9.4+ promise = when(modulesReady, function() { for (var f in factories) { if (spec.hasOwnProperty(f)) { return factories[f]; } } return rejected(spec); }); } return promise; } function processObject(target, spec) { var created, configured, initialized, destroyed; created = defer(); configured = defer(); initialized = defer(); destroyed = defer(); // After the object has been created, update progress for // the entire scope, then process the post-created facets return when(target, function(object) { chain(scopeDestroyed, destroyed, object); var proxy = createProxy(object, spec); proxied.push(proxy); return when.reduce(['create', 'configure', 'initialize', 'ready'], function(object, step) { return processFacets(step, proxy); }, proxy); }, rejected); } function createProxy(object, spec) { var proxier, proxy, id, i; i = 0; id = spec.id; while((proxier = proxies[i++]) && !(proxy = proxier(object, spec))) {} proxy.target = object; proxy.spec = spec; proxy.id = id; proxy.path = createPath(id); return proxy; } function processFacets(step, proxy) { var promises, options, name, spec; promises = []; spec = proxy.spec; for(name in facets) { options = spec[name]; if(options) { processStep(promises, facets[name], step, proxy, options); } } var d = defer(); whenAll(promises, function() { processListeners(d, step, proxy); }, chainReject(d) ); return d; } function processListeners(promise, step, proxy) { var listenerPromises = []; for(var i=0; i<listeners.length; i++) { processStep(listenerPromises, listeners[i], step, proxy); } // FIXME: Use only proxy here, caller should resolve target return chain(whenAll(listenerPromises), promise, proxy.target); } function processStep(promises, processor, step, proxy, options) { var facet, facetPromise; if(processor && processor[step]) { facetPromise = defer(); promises.push(facetPromise); facet = delegate(proxy); facet.options = options; processor[step](facetPromise.resolver, facet, pluginApi); } } // // Built-in Factories // function moduleFactory(resolver, spec /*, wire, name*/) { chain(getModule(spec.module, spec), resolver); } /* Function: instanceFactory Factory that uses an AMD module either directly, or as a constructor or plain function to create the resulting item. */ //noinspection JSUnusedLocalSymbols function instanceFactory(resolver, spec, wire) { var fail, create, module, args, isConstructor, name; fail = chainReject(resolver); name = spec.id; create = spec.create; if (isStrictlyObject(create)) { module = create.module; args = create.args; isConstructor = create.isConstructor; } else { module = create; } // Load the module, and use it to create the object function handleModule(module) { function resolve(resolvedArgs) { try { var instantiated = instantiate(module, resolvedArgs, isConstructor); resolver.resolve(instantiated); } catch(e) { resolver.reject(e); } } try { // We'll either use the module directly, or we need // to instantiate/invoke it. if (isFunction(module)) { // Instantiate or invoke it and use the result if (args) { args = isArray(args) ? args : [args]; when(createArray(args, name), resolve, fail); } else { // No args, don't need to process them, so can directly // insantiate the module and resolve resolve([]); } } else { // Simply use the module as is resolver.resolve(module); } } catch(e) { fail(e); } } when(getModule(module, spec), handleModule, fail); } function wireFactory(resolver, spec/*, wire, name*/) { var options, module, defer; options = spec.wire; // Get child spec and options if(isString(options)) { module = options; } else { module = options.spec; defer = options.defer; } function createChild(/** {Object}? */ mixin) { return wireChild(module, mixin); } if(defer) { // Resolve with the createChild function itself // which can be used later to wire the spec resolver.resolve(createChild); } else { // Start wiring the child var context = createChild(); // Resolve immediately with the child promise resolver.resolve(context.promise); } } // // Reference resolution // function resolveRef(ref, name) { var refName = ref.$ref; return doResolveRef(refName, ref, name == refName); } function doResolveRef(refName, refObj, excludeSelf) { var promise, registry; registry = excludeSelf ? parent.objects : objects; if (refName in registry) { promise = registry[refName]; } else { var split; promise = defer(); split = refName.indexOf('!'); if (split > 0) { var name = refName.substring(0, split); refName = refName.substring(split + 1); if (name == 'wire') { wireResolver(promise, refName /*, refObj, pluginApi*/); } else { // Wait for modules, since the reference may need to be // resolved by a resolver plugin when(modulesReady, function() { var resolver = resolvers[name]; if (resolver) { resolver(promise, refName, refObj, pluginApi); } else { promise.reject("No resolver found for ref: " + refObj); } }); } } else { promise.reject("Cannot resolve ref: " + refName); } } return promise; } function wireResolver(promise /*, name, refObj, wire*/) { // DEPRECATED access to objects // Providing access to objects here is dangerous since not all // the components in objects have been initialized--that is, they // may still be promises, and it's possible to deadlock by waiting // on one of those promises (via when() or promise.then()) promise.resolve(wireApi); } // // Destroy // function destroy() { return when(scopeReady, doDestroy, doDestroy); } } // createScope function isRef(it) { return it && it.$ref; } function isString(it) { return typeof it == 'string'; } function isStrictlyObject(it) { return tos.call(it) == '[object Object]'; } /* Function: isFunction Standard function test Parameters: it - anything Returns: true iff it is a Function */ function isFunction(it) { return typeof it == 'function'; } // In case Object.create isn't available function T() {} function createObject(prototype) { T.prototype = prototype; return new T(); } /* Constructor: Begetter Constructor used to beget objects that wire needs to create using new. Parameters: ctor - real constructor to be invoked args - arguments to be supplied to ctor */ function Begetter(ctor, args) { return ctor.apply(this, args); } /* Function: instantiate Creates an object by either invoking ctor as a function and returning the result, or by calling new ctor(). It uses a simple heuristic to try to guess which approach is the "right" one. Parameters: ctor - function or constructor to invoke args - array of arguments to pass to ctor in either case Returns: The result of invoking ctor with args, with or without new, depending on the strategy selected. */ function instantiate(ctor, args, forceConstructor) { if (forceConstructor || isConstructor(ctor)) { Begetter.prototype = ctor.prototype; Begetter.prototype.constructor = ctor; return new Begetter(ctor, args); } else { return ctor.apply(null, args); } } /* Function: isConstructor Determines with the supplied function should be invoked directly or should be invoked using new in order to create the object to be wired. Parameters: func - determine whether this should be called using new or not Returns: true iff func should be invoked using new, false otherwise. */ function isConstructor(func) { var is = false, p; for (p in func.prototype) { if (p !== undef) { is = true; break; } } return is; } return wire; }); })(this, typeof define != 'undefined' // use define for AMD if available ? define // Browser // If no define or module, attach to current context. : function(deps, factory) { this.wire = factory( // Fake require() function(modules, callback) { callback(modules); }, // dependencies this.when, this.wire_base ); } // NOTE: Node not supported yet, coming soon );
Using when.map where possible
wire.js
Using when.map where possible
<ide><path>ire.js <ide> } <ide> <ide> function createArray(arrayDef, name) { <del> var result, promises, itemPromise, item, id, i; <del> <add> var result, id; <ide> result = []; <ide> <ide> if (arrayDef.length) { <del> promises = []; <del> <del> for (i = 0; (item = arrayDef[i]); i++) { <del> id = item.id || name + '[' + i + ']'; <del> itemPromise = result[i] = createItem(arrayDef[i], id); <del> promises.push(itemPromise); <del> <del> resolveArrayValue(itemPromise, result, i); <del> } <del> <del> result = chain(whenAll(promises), defer(), result); <add> <add> result = when.map(arrayDef, function(item) { <add> return createItem(item, id); <add> }); <ide> <ide> } <ide> <ide> return result; <del> } <del> <del> function resolveArrayValue(promise, array, i) { <del> when(promise, function(value) { <del> array[i] = value; <del> }); <ide> } <ide> <ide> function createModule(spec, name) {
Java
mit
b709abe906f5f873e102fbfa67338a6ebc31bb53
0
MrCreosote/jgi_kbase_integration_tests,MrCreosote/jgi_kbase_integration_tests,MrCreosote/jgi_kbase_integration_tests,MrCreosote/jgi_kbase_integration_tests,MrCreosote/jgi_kbase_integration_tests
package us.kbase.jgiintegration.test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.BeforeClass; import org.junit.Test; import com.gargoylesoftware.htmlunit.AlertHandler; import com.gargoylesoftware.htmlunit.ElementNotFoundException; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.DomNode; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlDivision; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; public class JGIIntegrationTest { //TODO add more data types other than reads //TODO add a list of reads (in another suite? - factor out the common test code) //TODO test with nothing selected: use code like: /* * List<String> alerts = new LinkedList<String>(); * cli.setAlertHandler(new CollectingAlertHandler(alerts)); */ private static String JGI_USER; private static String JGI_PWD; private static String KB_USER_1; private static String KB_PWD_1; @BeforeClass public static void setUpClass() throws Exception { JGI_USER = System.getProperty("test.jgi.user"); JGI_PWD = System.getProperty("test.jgi.pwd"); KB_USER_1 = System.getProperty("test.kbase.user1"); KB_PWD_1 = System.getProperty("test.kbase.pwd1"); } private class JGIOrganismPage { private final static String JGI_SIGN_ON = "https://signon.jgi.doe.gov/signon"; private final static String JGI_ORGANISM_PAGE = "http://genomeportal.jgi.doe.gov/pages/dynamicOrganismDownload.jsf?organism="; private final String organismCode; private HtmlPage page; private final WebClient client; private final Set<JGIFileLocation> selected = new HashSet<JGIFileLocation>(); public JGIOrganismPage( WebClient client, String organismCode, String JGIuser, String JGIpwd) throws Exception { super(); this.client = client; signOnToJGI(client, JGIuser, JGIpwd); this.organismCode = organismCode; this.page = this.client.getPage(JGI_ORGANISM_PAGE + organismCode); Thread.sleep(3000); // wait for page & file table to load //TODO find a better way to check page is loaded } private void signOnToJGI(WebClient cli, String user, String password) throws IOException, MalformedURLException { HtmlPage hp = cli.getPage(JGI_SIGN_ON); assertThat("Signon title ok", hp.getTitleText(), is("JGI Single Sign On")); try { hp.getHtmlElementById("highlight-me"); fail("logged in already"); } catch (ElementNotFoundException enfe) { //we're all good } //login form has no name, which is the only way to get a specific form List<HtmlForm> forms = hp.getForms(); assertThat("2 forms on login page", forms.size(), is(2)); HtmlForm form = forms.get(1); form.getInputByName("login").setValueAttribute(user); form.getInputByName("password").setValueAttribute(password); HtmlPage loggedIn = form.getInputByName("commit").click(); HtmlDivision div = loggedIn.getHtmlElementById("highlight-me"); assertThat("signed in correctly", div.getTextContent(), is("You have signed in successfully.")); } public void selectFile(JGIFileLocation file) throws IOException, InterruptedException { //text element with the file group name DomElement fileGroupText = findFileGroup(file); HtmlAnchor fileSetToggle = (HtmlAnchor) fileGroupText .getParentNode() //td .getPreviousSibling() //td folder icon .getPreviousSibling() //td toggle icon .getChildNodes().get(0) //div .getChildNodes().get(0); //a this.page = fileSetToggle.click(); Thread.sleep(2000); //load file names, etc. //TODO check that file names are loaded //TODO is this toggling the files off if run twice DomElement fileText = findFile(file); HtmlInput filetoggle = (HtmlInput) ((DomElement) fileText .getParentNode() //i .getParentNode() //a .getParentNode() //span .getParentNode()) //td .getElementsByTagName("input").get(0); if (filetoggle.getCheckedAttribute().equals("checked")) { return; } this.page = filetoggle.click(); selected.add(file); Thread.sleep(1000); //every click gets sent to the server } public String pushToKBase(String user, String pwd) throws IOException, InterruptedException { HtmlInput push = (HtmlInput) page.getElementById( "downloadForm:fileTreePanel") .getChildNodes().get(2) //div .getFirstChild() //div .getFirstChild() //table .getFirstChild() //tbody .getFirstChild() //tr .getChildNodes().get(1) //td .getFirstChild(); //input this.page = push.click(); Thread.sleep(1000); // just in case, should be fast to create modal HtmlForm kbLogin = page.getFormByName("form"); //interesting id there kbLogin.getInputByName("user_id").setValueAttribute(KB_USER_1); kbLogin.getInputByName("password").setValueAttribute(KB_PWD_1); HtmlAnchor loginButton = (HtmlAnchor) kbLogin .getParentNode() //p .getParentNode() //div .getNextSibling() //div .getFirstChild() //div .getChildNodes().get(1) //div .getChildNodes().get(1); //a this.page = loginButton.click(); //TODO test periodically with a timeout, needs to be long for tape Thread.sleep(5000); checkPushedFiles(); //TODO click ok and check results return getWorkspaceName(user); } private String getWorkspaceName(String user) { DomNode foldable = page.getElementById("foldable"); DomNode projName = foldable .getFirstChild() .getFirstChild() .getChildNodes().get(1); return projName.getTextContent().replace(' ', '_') + '_' + user; } private void checkPushedFiles() { HtmlElement resDialogDiv = (HtmlElement) page.getElementById("filesPushedToKbase"); String[] splDialog = resDialogDiv.getTextContent().split("\n"); Set<String> filesFound = new HashSet<String>(); //skip first row for (int i = 1; i < splDialog.length; i++) { String[] filespl = splDialog[i].split("/"); if (filespl.length > 1) { filesFound.add(filespl[filespl.length - 1]); } } Set<String> filesExpected = new HashSet<String>(); for (JGIFileLocation file: selected) { filesExpected.add(file.getFile()); } assertThat("correct files in dialog", filesFound, is(filesExpected)); } private DomElement getFilesDivFromFilesGroup(DomElement selGroup) { return (DomElement) selGroup .getParentNode() //td .getParentNode() //tr .getParentNode() //tbody .getParentNode() //table .getNextSibling(); //div below table } private DomElement findFileGroup(JGIFileLocation file) { //this is ugly but it doesn't seem like there's another way //to get the node DomElement selGroup = null; List<DomElement> bold = page.getElementsByTagName("b"); for (DomElement de: bold) { if (file.getGroup().equals(de.getTextContent())) { selGroup = de; break; } } if (selGroup == null) { throw new TestException(String.format( "There is no file group %s for the organism %s", file.getGroup(), organismCode)); } return selGroup; } //file must be visible prior to calling this method private DomElement findFile(JGIFileLocation file) { DomElement fileGroupText = findFileGroup(file); DomElement fileGroup = getFilesDivFromFilesGroup(fileGroupText); //this is ugly but it doesn't seem like there's another way //to get the node DomElement selGroup = null; List<HtmlElement> bold = fileGroup.getElementsByTagName("b"); for (HtmlElement de: bold) { if (file.getFile().equals(de.getTextContent())) { selGroup = de; break; } } if (selGroup == null) { throw new TestException(String.format( "There is no file %s in file group %s for the organism %s", file.getFile(), file.getGroup(), organismCode)); } return selGroup; } } private class JGIFileLocation { private final String group; private final String file; public JGIFileLocation(String group, String file) { super(); this.group = group; this.file = file; } public String getGroup() { return group; } public String getFile() { return file; } } @SuppressWarnings("serial") public class TestException extends RuntimeException { public TestException(String msg) { super(msg); } } @Test public void fullIntegration() throws Exception { WebClient cli = new WebClient(); //TODO ZZ: if JGI fixes login page remove next line cli.getOptions().setThrowExceptionOnScriptError(false); cli.setAlertHandler(new AlertHandler() { @Override public void handleAlert(Page arg0, String arg1) { throw new TestException(arg1); } }); JGIOrganismPage org = new JGIOrganismPage(cli, "BlaspURHD0036", JGI_USER, JGI_PWD); JGIFileLocation qcReads = new JGIFileLocation("QC Filtered Raw Data", "7625.2.79179.AGTTCC.adnq.fastq.gz"); org.selectFile(qcReads); String wsName = org.pushToKBase(KB_USER_1, KB_PWD_1); System.out.println(wsName); cli.closeAllWindows(); } }
src/us/kbase/jgiintegration/test/JGIIntegrationTest.java
package us.kbase.jgiintegration.test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.BeforeClass; import org.junit.Test; import com.gargoylesoftware.htmlunit.AlertHandler; import com.gargoylesoftware.htmlunit.ElementNotFoundException; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.DomElement; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlDivision; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; public class JGIIntegrationTest { //TODO add more data types other than reads //TODO add a list of reads (in another suite? - factor out the common test code) //TODO test with nothing selected: use code like: /* * List<String> alerts = new LinkedList<String>(); * cli.setAlertHandler(new CollectingAlertHandler(alerts)); */ private static String JGI_USER; private static String JGI_PWD; private static String KB_USER_1; private static String KB_PWD_1; @BeforeClass public static void setUpClass() throws Exception { JGI_USER = System.getProperty("test.jgi.user"); JGI_PWD = System.getProperty("test.jgi.pwd"); KB_USER_1 = System.getProperty("test.kbase.user1"); KB_PWD_1 = System.getProperty("test.kbase.pwd1"); } private class JGIOrganismPage { private final static String JGI_SIGN_ON = "https://signon.jgi.doe.gov/signon"; private final static String JGI_ORGANISM_PAGE = "http://genomeportal.jgi.doe.gov/pages/dynamicOrganismDownload.jsf?organism="; private final String organismCode; private HtmlPage page; private final WebClient client; private final Set<JGIFileLocation> selected = new HashSet<JGIFileLocation>(); public JGIOrganismPage( WebClient client, String organismCode, String JGIuser, String JGIpwd) throws Exception { super(); this.client = client; signOnToJGI(client, JGIuser, JGIpwd); this.organismCode = organismCode; this.page = this.client.getPage(JGI_ORGANISM_PAGE + organismCode); Thread.sleep(3000); // wait for page & file table to load //TODO find a better way to check page is loaded } private void signOnToJGI(WebClient cli, String user, String password) throws IOException, MalformedURLException { HtmlPage hp = cli.getPage(JGI_SIGN_ON); assertThat("Signon title ok", hp.getTitleText(), is("JGI Single Sign On")); try { hp.getHtmlElementById("highlight-me"); fail("logged in already"); } catch (ElementNotFoundException enfe) { //we're all good } //login form has no name, which is the only way to get a specific form List<HtmlForm> forms = hp.getForms(); assertThat("2 forms on login page", forms.size(), is(2)); HtmlForm form = forms.get(1); form.getInputByName("login").setValueAttribute(user); form.getInputByName("password").setValueAttribute(password); HtmlPage loggedIn = form.getInputByName("commit").click(); HtmlDivision div = loggedIn.getHtmlElementById("highlight-me"); assertThat("signed in correctly", div.getTextContent(), is("You have signed in successfully.")); } public void selectFile(JGIFileLocation file) throws IOException, InterruptedException { //text element with the file group name DomElement fileGroupText = findFileGroup(file); HtmlAnchor fileSetToggle = (HtmlAnchor) fileGroupText .getParentNode() //td .getPreviousSibling() //td folder icon .getPreviousSibling() //td toggle icon .getChildNodes().get(0) //div .getChildNodes().get(0); //a this.page = fileSetToggle.click(); Thread.sleep(2000); //load file names, etc. //TODO check that file names are loaded //TODO is this toggling the files off if run twice DomElement fileText = findFile(file); HtmlInput filetoggle = (HtmlInput) ((DomElement) fileText .getParentNode() //i .getParentNode() //a .getParentNode() //span .getParentNode()) //td .getElementsByTagName("input").get(0); if (filetoggle.getCheckedAttribute().equals("checked")) { return; } this.page = filetoggle.click(); selected.add(file); Thread.sleep(1000); //every click gets sent to the server } public void pushToKBase(String user, String pwd) throws IOException, InterruptedException { HtmlInput push = (HtmlInput) page.getElementById( "downloadForm:fileTreePanel") .getChildNodes().get(2) //div .getFirstChild() //div .getFirstChild() //table .getFirstChild() //tbody .getFirstChild() //tr .getChildNodes().get(1) //td .getFirstChild(); //input this.page = push.click(); Thread.sleep(1000); // just in case, should be fast to create modal HtmlForm kbLogin = page.getFormByName("form"); //interesting id there kbLogin.getInputByName("user_id").setValueAttribute(KB_USER_1); kbLogin.getInputByName("password").setValueAttribute(KB_PWD_1); HtmlAnchor loginButton = (HtmlAnchor) kbLogin .getParentNode() //p .getParentNode() //div .getNextSibling() //div .getFirstChild() //div .getChildNodes().get(1) //div .getChildNodes().get(1); //a this.page = loginButton.click(); //TODO test periodically with a timeout, needs to be long for tape Thread.sleep(5000); checkPushedFiles(); //TODO click ok and check results } private void checkPushedFiles() { HtmlElement resDialogDiv = (HtmlElement) page.getElementById("filesPushedToKbase"); String[] splDialog = resDialogDiv.getTextContent().split("\n"); Set<String> filesFound = new HashSet<String>(); //skip first row for (int i = 1; i < splDialog.length; i++) { String[] filespl = splDialog[i].split("/"); if (filespl.length > 1) { filesFound.add(filespl[filespl.length - 1]); } } Set<String> filesExpected = new HashSet<String>(); for (JGIFileLocation file: selected) { filesExpected.add(file.getFile()); } assertThat("correct files in dialog", filesFound, is(filesExpected)); } private DomElement getFilesDivFromFilesGroup(DomElement selGroup) { return (DomElement) selGroup .getParentNode() //td .getParentNode() //tr .getParentNode() //tbody .getParentNode() //table .getNextSibling(); //div below table } private DomElement findFileGroup(JGIFileLocation file) { //this is ugly but it doesn't seem like there's another way //to get the node DomElement selGroup = null; List<DomElement> bold = page.getElementsByTagName("b"); for (DomElement de: bold) { if (file.getGroup().equals(de.getTextContent())) { selGroup = de; break; } } if (selGroup == null) { throw new TestException(String.format( "There is no file group %s for the organism %s", file.getGroup(), organismCode)); } return selGroup; } //file must be visible prior to calling this method private DomElement findFile(JGIFileLocation file) { DomElement fileGroupText = findFileGroup(file); DomElement fileGroup = getFilesDivFromFilesGroup(fileGroupText); //this is ugly but it doesn't seem like there's another way //to get the node DomElement selGroup = null; List<HtmlElement> bold = fileGroup.getElementsByTagName("b"); for (HtmlElement de: bold) { if (file.getFile().equals(de.getTextContent())) { selGroup = de; break; } } if (selGroup == null) { throw new TestException(String.format( "There is no file %s in file group %s for the organism %s", file.getFile(), file.getGroup(), organismCode)); } return selGroup; } } private class JGIFileLocation { private final String group; private final String file; public JGIFileLocation(String group, String file) { super(); this.group = group; this.file = file; } public String getGroup() { return group; } public String getFile() { return file; } } @SuppressWarnings("serial") public class TestException extends RuntimeException { public TestException(String msg) { super(msg); } } @Test public void fullIntegration() throws Exception { WebClient cli = new WebClient(); //TODO ZZ: if JGI fixes their login page remove next line cli.getOptions().setThrowExceptionOnScriptError(false); cli.setAlertHandler(new AlertHandler() { @Override public void handleAlert(Page arg0, String arg1) { throw new TestException(arg1); } }); JGIOrganismPage org = new JGIOrganismPage(cli, "BlaspURHD0036", JGI_USER, JGI_PWD); JGIFileLocation qcReads = new JGIFileLocation("QC Filtered Raw Data", "7625.2.79179.AGTTCC.adnq.fastq.gz"); org.selectFile(qcReads); org.pushToKBase(KB_USER_1, KB_PWD_1); cli.closeAllWindows(); } }
Get workspace name for organism
src/us/kbase/jgiintegration/test/JGIIntegrationTest.java
Get workspace name for organism
<ide><path>rc/us/kbase/jgiintegration/test/JGIIntegrationTest.java <ide> import com.gargoylesoftware.htmlunit.Page; <ide> import com.gargoylesoftware.htmlunit.WebClient; <ide> import com.gargoylesoftware.htmlunit.html.DomElement; <add>import com.gargoylesoftware.htmlunit.html.DomNode; <ide> import com.gargoylesoftware.htmlunit.html.HtmlAnchor; <ide> import com.gargoylesoftware.htmlunit.html.HtmlDivision; <ide> import com.gargoylesoftware.htmlunit.html.HtmlElement; <ide> Thread.sleep(1000); //every click gets sent to the server <ide> } <ide> <del> public void pushToKBase(String user, String pwd) <add> public String pushToKBase(String user, String pwd) <ide> throws IOException, InterruptedException { <ide> HtmlInput push = (HtmlInput) page.getElementById( <ide> "downloadForm:fileTreePanel") <ide> checkPushedFiles(); <ide> <ide> //TODO click ok and check results <add> <add> return getWorkspaceName(user); <add> } <add> <add> private String getWorkspaceName(String user) { <add> DomNode foldable = page.getElementById("foldable"); <add> DomNode projName = foldable <add> .getFirstChild() <add> .getFirstChild() <add> .getChildNodes().get(1); <add> return projName.getTextContent().replace(' ', '_') + '_' + user; <ide> } <ide> <ide> private void checkPushedFiles() { <ide> @Test <ide> public void fullIntegration() throws Exception { <ide> WebClient cli = new WebClient(); <del> //TODO ZZ: if JGI fixes their login page remove next line <add> //TODO ZZ: if JGI fixes login page remove next line <ide> cli.getOptions().setThrowExceptionOnScriptError(false); <ide> cli.setAlertHandler(new AlertHandler() { <ide> <ide> "7625.2.79179.AGTTCC.adnq.fastq.gz"); <ide> org.selectFile(qcReads); <ide> <del> org.pushToKBase(KB_USER_1, KB_PWD_1); <add> String wsName = org.pushToKBase(KB_USER_1, KB_PWD_1); <add> System.out.println(wsName); <ide> <ide> cli.closeAllWindows(); <ide> }
Java
apache-2.0
2a54feabb2d1245d80f061c5c796f0663dd2a689
0
steveloughran/hadoop,apurtell/hadoop,apache/hadoop,plusplusjiajia/hadoop,mapr/hadoop-common,steveloughran/hadoop,JingchengDu/hadoop,mapr/hadoop-common,lukmajercak/hadoop,steveloughran/hadoop,JingchengDu/hadoop,apurtell/hadoop,steveloughran/hadoop,mapr/hadoop-common,apurtell/hadoop,JingchengDu/hadoop,JingchengDu/hadoop,nandakumar131/hadoop,nandakumar131/hadoop,lukmajercak/hadoop,lukmajercak/hadoop,steveloughran/hadoop,wwjiang007/hadoop,nandakumar131/hadoop,nandakumar131/hadoop,lukmajercak/hadoop,nandakumar131/hadoop,wwjiang007/hadoop,mapr/hadoop-common,lukmajercak/hadoop,apurtell/hadoop,steveloughran/hadoop,plusplusjiajia/hadoop,nandakumar131/hadoop,apache/hadoop,plusplusjiajia/hadoop,apurtell/hadoop,wwjiang007/hadoop,mapr/hadoop-common,wwjiang007/hadoop,apache/hadoop,wwjiang007/hadoop,apache/hadoop,plusplusjiajia/hadoop,mapr/hadoop-common,nandakumar131/hadoop,plusplusjiajia/hadoop,plusplusjiajia/hadoop,lukmajercak/hadoop,mapr/hadoop-common,JingchengDu/hadoop,wwjiang007/hadoop,apurtell/hadoop,lukmajercak/hadoop,steveloughran/hadoop,wwjiang007/hadoop,plusplusjiajia/hadoop,JingchengDu/hadoop,apache/hadoop,apache/hadoop,apache/hadoop,apurtell/hadoop,JingchengDu/hadoop
/** * 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.ipc; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.*; import com.google.protobuf.Descriptors.MethodDescriptor; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.retry.RetryPolicy; import org.apache.hadoop.ipc.Client.ConnectionId; import org.apache.hadoop.ipc.RPC.RpcInvoker; import org.apache.hadoop.ipc.protobuf.ProtobufRpcEngineProtos.RequestHeaderProto; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.SecretManager; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.util.Time; import org.apache.hadoop.util.concurrent.AsyncGet; import org.apache.htrace.core.TraceScope; import org.apache.htrace.core.Tracer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.SocketFactory; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * RPC Engine for for protobuf based RPCs. */ @InterfaceStability.Evolving public class ProtobufRpcEngine implements RpcEngine { public static final Logger LOG = LoggerFactory.getLogger(ProtobufRpcEngine.class); private static final ThreadLocal<AsyncGet<Message, Exception>> ASYNC_RETURN_MESSAGE = new ThreadLocal<>(); static { // Register the rpcRequest deserializer for ProtobufRpcEngine org.apache.hadoop.ipc.Server.registerProtocolEngine( RPC.RpcKind.RPC_PROTOCOL_BUFFER, RpcProtobufRequest.class, new Server.ProtoBufRpcInvoker()); } private static final ClientCache CLIENTS = new ClientCache(); @Unstable public static AsyncGet<Message, Exception> getAsyncReturnMessage() { return ASYNC_RETURN_MESSAGE.get(); } public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout) throws IOException { return getProxy(protocol, clientVersion, addr, ticket, conf, factory, rpcTimeout, null); } @Override public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy ) throws IOException { return getProxy(protocol, clientVersion, addr, ticket, conf, factory, rpcTimeout, connectionRetryPolicy, null, null); } @Override @SuppressWarnings("unchecked") public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy, AtomicBoolean fallbackToSimpleAuth, AlignmentContext alignmentContext) throws IOException { final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout, connectionRetryPolicy, fallbackToSimpleAuth, alignmentContext); return new ProtocolProxy<T>(protocol, (T) Proxy.newProxyInstance( protocol.getClassLoader(), new Class[]{protocol}, invoker), false); } @Override public ProtocolProxy<ProtocolMetaInfoPB> getProtocolMetaInfoProxy( ConnectionId connId, Configuration conf, SocketFactory factory) throws IOException { Class<ProtocolMetaInfoPB> protocol = ProtocolMetaInfoPB.class; return new ProtocolProxy<ProtocolMetaInfoPB>(protocol, (ProtocolMetaInfoPB) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(protocol, connId, conf, factory)), false); } private static class Invoker implements RpcInvocationHandler { private final Map<String, Message> returnTypes = new ConcurrentHashMap<String, Message>(); private boolean isClosed = false; private final Client.ConnectionId remoteId; private final Client client; private final long clientProtocolVersion; private final String protocolName; private AtomicBoolean fallbackToSimpleAuth; private AlignmentContext alignmentContext; private Invoker(Class<?> protocol, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy, AtomicBoolean fallbackToSimpleAuth, AlignmentContext alignmentContext) throws IOException { this(protocol, Client.ConnectionId.getConnectionId( addr, protocol, ticket, rpcTimeout, connectionRetryPolicy, conf), conf, factory); this.fallbackToSimpleAuth = fallbackToSimpleAuth; this.alignmentContext = alignmentContext; } /** * This constructor takes a connectionId, instead of creating a new one. */ private Invoker(Class<?> protocol, Client.ConnectionId connId, Configuration conf, SocketFactory factory) { this.remoteId = connId; this.client = CLIENTS.getClient(conf, factory, RpcWritable.Buffer.class); this.protocolName = RPC.getProtocolName(protocol); this.clientProtocolVersion = RPC .getProtocolVersion(protocol); } private RequestHeaderProto constructRpcRequestHeader(Method method) { RequestHeaderProto.Builder builder = RequestHeaderProto .newBuilder(); builder.setMethodName(method.getName()); // For protobuf, {@code protocol} used when creating client side proxy is // the interface extending BlockingInterface, which has the annotations // such as ProtocolName etc. // // Using Method.getDeclaringClass(), as in WritableEngine to get at // the protocol interface will return BlockingInterface, from where // the annotation ProtocolName and Version cannot be // obtained. // // Hence we simply use the protocol class used to create the proxy. // For PB this may limit the use of mixins on client side. builder.setDeclaringClassProtocolName(protocolName); builder.setClientProtocolVersion(clientProtocolVersion); return builder.build(); } /** * This is the client side invoker of RPC method. It only throws * ServiceException, since the invocation proxy expects only * ServiceException to be thrown by the method in case protobuf service. * * ServiceException has the following causes: * <ol> * <li>Exceptions encountered on the client side in this method are * set as cause in ServiceException as is.</li> * <li>Exceptions from the server are wrapped in RemoteException and are * set as cause in ServiceException</li> * </ol> * * Note that the client calling protobuf RPC methods, must handle * ServiceException by getting the cause from the ServiceException. If the * cause is RemoteException, then unwrap it to get the exception thrown by * the server. */ @Override public Message invoke(Object proxy, final Method method, Object[] args) throws ServiceException { long startTime = 0; if (LOG.isDebugEnabled()) { startTime = Time.now(); } if (args.length != 2) { // RpcController + Message throw new ServiceException( "Too many or few parameters for request. Method: [" + method.getName() + "]" + ", Expected: 2, Actual: " + args.length); } if (args[1] == null) { throw new ServiceException("null param while calling Method: [" + method.getName() + "]"); } // if Tracing is on then start a new span for this rpc. // guard it in the if statement to make sure there isn't // any extra string manipulation. Tracer tracer = Tracer.curThreadTracer(); TraceScope traceScope = null; if (tracer != null) { traceScope = tracer.newScope(RpcClientUtil.methodToTraceString(method)); } RequestHeaderProto rpcRequestHeader = constructRpcRequestHeader(method); if (LOG.isTraceEnabled()) { LOG.trace(Thread.currentThread().getId() + ": Call -> " + remoteId + ": " + method.getName() + " {" + TextFormat.shortDebugString((Message) args[1]) + "}"); } final Message theRequest = (Message) args[1]; final RpcWritable.Buffer val; try { val = (RpcWritable.Buffer) client.call(RPC.RpcKind.RPC_PROTOCOL_BUFFER, new RpcProtobufRequest(rpcRequestHeader, theRequest), remoteId, fallbackToSimpleAuth, alignmentContext); } catch (Throwable e) { if (LOG.isTraceEnabled()) { LOG.trace(Thread.currentThread().getId() + ": Exception <- " + remoteId + ": " + method.getName() + " {" + e + "}"); } if (traceScope != null) { traceScope.addTimelineAnnotation("Call got exception: " + e.toString()); } throw new ServiceException(e); } finally { if (traceScope != null) traceScope.close(); } if (LOG.isDebugEnabled()) { long callTime = Time.now() - startTime; LOG.debug("Call: " + method.getName() + " took " + callTime + "ms"); } if (Client.isAsynchronousMode()) { final AsyncGet<RpcWritable.Buffer, IOException> arr = Client.getAsyncRpcResponse(); final AsyncGet<Message, Exception> asyncGet = new AsyncGet<Message, Exception>() { @Override public Message get(long timeout, TimeUnit unit) throws Exception { return getReturnMessage(method, arr.get(timeout, unit)); } @Override public boolean isDone() { return arr.isDone(); } }; ASYNC_RETURN_MESSAGE.set(asyncGet); return null; } else { return getReturnMessage(method, val); } } private Message getReturnMessage(final Method method, final RpcWritable.Buffer buf) throws ServiceException { Message prototype = null; try { prototype = getReturnProtoType(method); } catch (Exception e) { throw new ServiceException(e); } Message returnMessage; try { returnMessage = buf.getValue(prototype.getDefaultInstanceForType()); if (LOG.isTraceEnabled()) { LOG.trace(Thread.currentThread().getId() + ": Response <- " + remoteId + ": " + method.getName() + " {" + TextFormat.shortDebugString(returnMessage) + "}"); } } catch (Throwable e) { throw new ServiceException(e); } return returnMessage; } @Override public void close() throws IOException { if (!isClosed) { isClosed = true; CLIENTS.stopClient(client); } } private Message getReturnProtoType(Method method) throws Exception { if (returnTypes.containsKey(method.getName())) { return returnTypes.get(method.getName()); } Class<?> returnType = method.getReturnType(); Method newInstMethod = returnType.getMethod("getDefaultInstance"); newInstMethod.setAccessible(true); Message prototype = (Message) newInstMethod.invoke(null, (Object[]) null); returnTypes.put(method.getName(), prototype); return prototype; } @Override //RpcInvocationHandler public ConnectionId getConnectionId() { return remoteId; } } @VisibleForTesting @InterfaceAudience.Private @InterfaceStability.Unstable static Client getClient(Configuration conf) { return CLIENTS.getClient(conf, SocketFactory.getDefault(), RpcWritable.Buffer.class); } @Override public RPC.Server getServer(Class<?> protocol, Object protocolImpl, String bindAddress, int port, int numHandlers, int numReaders, int queueSizePerHandler, boolean verbose, Configuration conf, SecretManager<? extends TokenIdentifier> secretManager, String portRangeConfig, AlignmentContext alignmentContext) throws IOException { return new Server(protocol, protocolImpl, conf, bindAddress, port, numHandlers, numReaders, queueSizePerHandler, verbose, secretManager, portRangeConfig, alignmentContext); } public static class Server extends RPC.Server { static final ThreadLocal<ProtobufRpcEngineCallback> currentCallback = new ThreadLocal<>(); static final ThreadLocal<CallInfo> currentCallInfo = new ThreadLocal<>(); static class CallInfo { private final RPC.Server server; private final String methodName; public CallInfo(RPC.Server server, String methodName) { this.server = server; this.methodName = methodName; } } static class ProtobufRpcEngineCallbackImpl implements ProtobufRpcEngineCallback { private final RPC.Server server; private final Call call; private final String methodName; private final long setupTime; public ProtobufRpcEngineCallbackImpl() { this.server = currentCallInfo.get().server; this.call = Server.getCurCall().get(); this.methodName = currentCallInfo.get().methodName; this.setupTime = Time.now(); } @Override public void setResponse(Message message) { long processingTime = Time.now() - setupTime; call.setDeferredResponse(RpcWritable.wrap(message)); server.updateDeferredMetrics(methodName, processingTime); } @Override public void error(Throwable t) { long processingTime = Time.now() - setupTime; String detailedMetricsName = t.getClass().getSimpleName(); server.updateDeferredMetrics(detailedMetricsName, processingTime); call.setDeferredError(t); } } @InterfaceStability.Unstable public static ProtobufRpcEngineCallback registerForDeferredResponse() { ProtobufRpcEngineCallback callback = new ProtobufRpcEngineCallbackImpl(); currentCallback.set(callback); return callback; } /** * Construct an RPC server. * * @param protocolClass the class of protocol * @param protocolImpl the protocolImpl whose methods will be called * @param conf the configuration to use * @param bindAddress the address to bind on to listen for connection * @param port the port to listen for connections on * @param numHandlers the number of method handler threads to run * @param verbose whether each call should be logged * @param portRangeConfig A config parameter that can be used to restrict * the range of ports used when port is 0 (an ephemeral port) * @param alignmentContext provides server state info on client responses */ public Server(Class<?> protocolClass, Object protocolImpl, Configuration conf, String bindAddress, int port, int numHandlers, int numReaders, int queueSizePerHandler, boolean verbose, SecretManager<? extends TokenIdentifier> secretManager, String portRangeConfig, AlignmentContext alignmentContext) throws IOException { super(bindAddress, port, null, numHandlers, numReaders, queueSizePerHandler, conf, serverNameFromClass(protocolImpl.getClass()), secretManager, portRangeConfig); setAlignmentContext(alignmentContext); this.verbose = verbose; registerProtocolAndImpl(RPC.RpcKind.RPC_PROTOCOL_BUFFER, protocolClass, protocolImpl); } /** * Protobuf invoker for {@link RpcInvoker} */ static class ProtoBufRpcInvoker implements RpcInvoker { private static ProtoClassProtoImpl getProtocolImpl(RPC.Server server, String protoName, long clientVersion) throws RpcServerException { ProtoNameVer pv = new ProtoNameVer(protoName, clientVersion); ProtoClassProtoImpl impl = server.getProtocolImplMap(RPC.RpcKind.RPC_PROTOCOL_BUFFER).get(pv); if (impl == null) { // no match for Protocol AND Version VerProtocolImpl highest = server.getHighestSupportedProtocol(RPC.RpcKind.RPC_PROTOCOL_BUFFER, protoName); if (highest == null) { throw new RpcNoSuchProtocolException( "Unknown protocol: " + protoName); } // protocol supported but not the version that client wants throw new RPC.VersionMismatch(protoName, clientVersion, highest.version); } return impl; } @Override /** * This is a server side method, which is invoked over RPC. On success * the return response has protobuf response payload. On failure, the * exception name and the stack trace are returned in the response. * See {@link HadoopRpcResponseProto} * * In this method there three types of exceptions possible and they are * returned in response as follows. * <ol> * <li> Exceptions encountered in this method that are returned * as {@link RpcServerException} </li> * <li> Exceptions thrown by the service is wrapped in ServiceException. * In that this method returns in response the exception thrown by the * service.</li> * <li> Other exceptions thrown by the service. They are returned as * it is.</li> * </ol> */ public Writable call(RPC.Server server, String connectionProtocolName, Writable writableRequest, long receiveTime) throws Exception { RpcProtobufRequest request = (RpcProtobufRequest) writableRequest; RequestHeaderProto rpcRequest = request.getRequestHeader(); String methodName = rpcRequest.getMethodName(); /** * RPCs for a particular interface (ie protocol) are done using a * IPC connection that is setup using rpcProxy. * The rpcProxy's has a declared protocol name that is * sent form client to server at connection time. * * Each Rpc call also sends a protocol name * (called declaringClassprotocolName). This name is usually the same * as the connection protocol name except in some cases. * For example metaProtocols such ProtocolInfoProto which get info * about the protocol reuse the connection but need to indicate that * the actual protocol is different (i.e. the protocol is * ProtocolInfoProto) since they reuse the connection; in this case * the declaringClassProtocolName field is set to the ProtocolInfoProto. */ String declaringClassProtoName = rpcRequest.getDeclaringClassProtocolName(); long clientVersion = rpcRequest.getClientProtocolVersion(); if (server.verbose) LOG.info("Call: connectionProtocolName=" + connectionProtocolName + ", method=" + methodName); ProtoClassProtoImpl protocolImpl = getProtocolImpl(server, declaringClassProtoName, clientVersion); BlockingService service = (BlockingService) protocolImpl.protocolImpl; MethodDescriptor methodDescriptor = service.getDescriptorForType() .findMethodByName(methodName); if (methodDescriptor == null) { String msg = "Unknown method " + methodName + " called on " + connectionProtocolName + " protocol."; LOG.warn(msg); throw new RpcNoSuchMethodException(msg); } Message prototype = service.getRequestPrototype(methodDescriptor); Message param = request.getValue(prototype); Message result; long startTime = Time.now(); int qTime = (int) (startTime - receiveTime); Exception exception = null; boolean isDeferred = false; try { server.rpcDetailedMetrics.init(protocolImpl.protocolClass); currentCallInfo.set(new CallInfo(server, methodName)); result = service.callBlockingMethod(methodDescriptor, null, param); // Check if this needs to be a deferred response, // by checking the ThreadLocal callback being set if (currentCallback.get() != null) { Server.getCurCall().get().deferResponse(); isDeferred = true; currentCallback.set(null); return null; } } catch (ServiceException e) { exception = (Exception) e.getCause(); throw (Exception) e.getCause(); } catch (Exception e) { exception = e; throw e; } finally { currentCallInfo.set(null); int processingTime = (int) (Time.now() - startTime); if (LOG.isDebugEnabled()) { String msg = "Served: " + methodName + (isDeferred ? ", deferred" : "") + ", queueTime= " + qTime + " procesingTime= " + processingTime; if (exception != null) { msg += " exception= " + exception.getClass().getSimpleName(); } LOG.debug(msg); } String detailedMetricsName = (exception == null) ? methodName : exception.getClass().getSimpleName(); server.updateMetrics(detailedMetricsName, qTime, processingTime, isDeferred); } return RpcWritable.wrap(result); } } } // htrace in the ipc layer creates the span name based on toString() // which uses the rpc header. in the normal case we want to defer decoding // the rpc header until needed by the rpc engine. static class RpcProtobufRequest extends RpcWritable.Buffer { private volatile RequestHeaderProto requestHeader; private Message payload; public RpcProtobufRequest() { } RpcProtobufRequest(RequestHeaderProto header, Message payload) { this.requestHeader = header; this.payload = payload; } RequestHeaderProto getRequestHeader() throws IOException { if (getByteBuffer() != null && requestHeader == null) { requestHeader = getValue(RequestHeaderProto.getDefaultInstance()); } return requestHeader; } @Override public void writeTo(ResponseBuffer out) throws IOException { requestHeader.writeDelimitedTo(out); if (payload != null) { payload.writeDelimitedTo(out); } } // this is used by htrace to name the span. @Override public String toString() { try { RequestHeaderProto header = getRequestHeader(); return header.getDeclaringClassProtocolName() + "." + header.getMethodName(); } catch (IOException e) { throw new IllegalArgumentException(e); } } } }
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine.java
/** * 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.ipc; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.*; import com.google.protobuf.Descriptors.MethodDescriptor; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.retry.RetryPolicy; import org.apache.hadoop.ipc.Client.ConnectionId; import org.apache.hadoop.ipc.RPC.RpcInvoker; import org.apache.hadoop.ipc.protobuf.ProtobufRpcEngineProtos.RequestHeaderProto; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.SecretManager; import org.apache.hadoop.security.token.TokenIdentifier; import org.apache.hadoop.util.Time; import org.apache.hadoop.util.concurrent.AsyncGet; import org.apache.htrace.core.TraceScope; import org.apache.htrace.core.Tracer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.SocketFactory; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * RPC Engine for for protobuf based RPCs. */ @InterfaceStability.Evolving public class ProtobufRpcEngine implements RpcEngine { public static final Logger LOG = LoggerFactory.getLogger(ProtobufRpcEngine.class); private static final ThreadLocal<AsyncGet<Message, Exception>> ASYNC_RETURN_MESSAGE = new ThreadLocal<>(); static { // Register the rpcRequest deserializer for ProtobufRpcEngine org.apache.hadoop.ipc.Server.registerProtocolEngine( RPC.RpcKind.RPC_PROTOCOL_BUFFER, RpcProtobufRequest.class, new Server.ProtoBufRpcInvoker()); } private static final ClientCache CLIENTS = new ClientCache(); @Unstable public static AsyncGet<Message, Exception> getAsyncReturnMessage() { return ASYNC_RETURN_MESSAGE.get(); } public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout) throws IOException { return getProxy(protocol, clientVersion, addr, ticket, conf, factory, rpcTimeout, null); } @Override public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy ) throws IOException { return getProxy(protocol, clientVersion, addr, ticket, conf, factory, rpcTimeout, connectionRetryPolicy, null, null); } @Override @SuppressWarnings("unchecked") public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy, AtomicBoolean fallbackToSimpleAuth, AlignmentContext alignmentContext) throws IOException { final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout, connectionRetryPolicy, fallbackToSimpleAuth, alignmentContext); return new ProtocolProxy<T>(protocol, (T) Proxy.newProxyInstance( protocol.getClassLoader(), new Class[]{protocol}, invoker), false); } @Override public ProtocolProxy<ProtocolMetaInfoPB> getProtocolMetaInfoProxy( ConnectionId connId, Configuration conf, SocketFactory factory) throws IOException { Class<ProtocolMetaInfoPB> protocol = ProtocolMetaInfoPB.class; return new ProtocolProxy<ProtocolMetaInfoPB>(protocol, (ProtocolMetaInfoPB) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, new Invoker(protocol, connId, conf, factory)), false); } private static class Invoker implements RpcInvocationHandler { private final Map<String, Message> returnTypes = new ConcurrentHashMap<String, Message>(); private boolean isClosed = false; private final Client.ConnectionId remoteId; private final Client client; private final long clientProtocolVersion; private final String protocolName; private AtomicBoolean fallbackToSimpleAuth; private AlignmentContext alignmentContext; private Invoker(Class<?> protocol, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy, AtomicBoolean fallbackToSimpleAuth, AlignmentContext alignmentContext) throws IOException { this(protocol, Client.ConnectionId.getConnectionId( addr, protocol, ticket, rpcTimeout, connectionRetryPolicy, conf), conf, factory); this.fallbackToSimpleAuth = fallbackToSimpleAuth; this.alignmentContext = alignmentContext; } /** * This constructor takes a connectionId, instead of creating a new one. */ private Invoker(Class<?> protocol, Client.ConnectionId connId, Configuration conf, SocketFactory factory) { this.remoteId = connId; this.client = CLIENTS.getClient(conf, factory, RpcWritable.Buffer.class); this.protocolName = RPC.getProtocolName(protocol); this.clientProtocolVersion = RPC .getProtocolVersion(protocol); } private RequestHeaderProto constructRpcRequestHeader(Method method) { RequestHeaderProto.Builder builder = RequestHeaderProto .newBuilder(); builder.setMethodName(method.getName()); // For protobuf, {@code protocol} used when creating client side proxy is // the interface extending BlockingInterface, which has the annotations // such as ProtocolName etc. // // Using Method.getDeclaringClass(), as in WritableEngine to get at // the protocol interface will return BlockingInterface, from where // the annotation ProtocolName and Version cannot be // obtained. // // Hence we simply use the protocol class used to create the proxy. // For PB this may limit the use of mixins on client side. builder.setDeclaringClassProtocolName(protocolName); builder.setClientProtocolVersion(clientProtocolVersion); return builder.build(); } /** * This is the client side invoker of RPC method. It only throws * ServiceException, since the invocation proxy expects only * ServiceException to be thrown by the method in case protobuf service. * * ServiceException has the following causes: * <ol> * <li>Exceptions encountered on the client side in this method are * set as cause in ServiceException as is.</li> * <li>Exceptions from the server are wrapped in RemoteException and are * set as cause in ServiceException</li> * </ol> * * Note that the client calling protobuf RPC methods, must handle * ServiceException by getting the cause from the ServiceException. If the * cause is RemoteException, then unwrap it to get the exception thrown by * the server. */ @Override public Message invoke(Object proxy, final Method method, Object[] args) throws ServiceException { long startTime = 0; if (LOG.isDebugEnabled()) { startTime = Time.now(); } if (args.length != 2) { // RpcController + Message throw new ServiceException( "Too many or few parameters for request. Method: [" + method.getName() + "]" + ", Expected: 2, Actual: " + args.length); } if (args[1] == null) { throw new ServiceException("null param while calling Method: [" + method.getName() + "]"); } // if Tracing is on then start a new span for this rpc. // guard it in the if statement to make sure there isn't // any extra string manipulation. Tracer tracer = Tracer.curThreadTracer(); TraceScope traceScope = null; if (tracer != null) { traceScope = tracer.newScope(RpcClientUtil.methodToTraceString(method)); } RequestHeaderProto rpcRequestHeader = constructRpcRequestHeader(method); if (LOG.isTraceEnabled()) { LOG.trace(Thread.currentThread().getId() + ": Call -> " + remoteId + ": " + method.getName() + " {" + TextFormat.shortDebugString((Message) args[1]) + "}"); } final Message theRequest = (Message) args[1]; final RpcWritable.Buffer val; try { val = (RpcWritable.Buffer) client.call(RPC.RpcKind.RPC_PROTOCOL_BUFFER, new RpcProtobufRequest(rpcRequestHeader, theRequest), remoteId, fallbackToSimpleAuth, alignmentContext); } catch (Throwable e) { if (LOG.isTraceEnabled()) { LOG.trace(Thread.currentThread().getId() + ": Exception <- " + remoteId + ": " + method.getName() + " {" + e + "}"); } if (traceScope != null) { traceScope.addTimelineAnnotation("Call got exception: " + e.toString()); } throw new ServiceException(e); } finally { if (traceScope != null) traceScope.close(); } if (LOG.isDebugEnabled()) { long callTime = Time.now() - startTime; LOG.debug("Call: " + method.getName() + " took " + callTime + "ms"); } if (Client.isAsynchronousMode()) { final AsyncGet<RpcWritable.Buffer, IOException> arr = Client.getAsyncRpcResponse(); final AsyncGet<Message, Exception> asyncGet = new AsyncGet<Message, Exception>() { @Override public Message get(long timeout, TimeUnit unit) throws Exception { return getReturnMessage(method, arr.get(timeout, unit)); } @Override public boolean isDone() { return arr.isDone(); } }; ASYNC_RETURN_MESSAGE.set(asyncGet); return null; } else { return getReturnMessage(method, val); } } private Message getReturnMessage(final Method method, final RpcWritable.Buffer buf) throws ServiceException { Message prototype = null; try { prototype = getReturnProtoType(method); } catch (Exception e) { throw new ServiceException(e); } Message returnMessage; try { returnMessage = buf.getValue(prototype.getDefaultInstanceForType()); if (LOG.isTraceEnabled()) { LOG.trace(Thread.currentThread().getId() + ": Response <- " + remoteId + ": " + method.getName() + " {" + TextFormat.shortDebugString(returnMessage) + "}"); } } catch (Throwable e) { throw new ServiceException(e); } return returnMessage; } @Override public void close() throws IOException { if (!isClosed) { isClosed = true; CLIENTS.stopClient(client); } } private Message getReturnProtoType(Method method) throws Exception { if (returnTypes.containsKey(method.getName())) { return returnTypes.get(method.getName()); } Class<?> returnType = method.getReturnType(); Method newInstMethod = returnType.getMethod("getDefaultInstance"); newInstMethod.setAccessible(true); Message prototype = (Message) newInstMethod.invoke(null, (Object[]) null); returnTypes.put(method.getName(), prototype); return prototype; } @Override //RpcInvocationHandler public ConnectionId getConnectionId() { return remoteId; } } @VisibleForTesting @InterfaceAudience.Private @InterfaceStability.Unstable static Client getClient(Configuration conf) { return CLIENTS.getClient(conf, SocketFactory.getDefault(), RpcWritable.Buffer.class); } @Override public RPC.Server getServer(Class<?> protocol, Object protocolImpl, String bindAddress, int port, int numHandlers, int numReaders, int queueSizePerHandler, boolean verbose, Configuration conf, SecretManager<? extends TokenIdentifier> secretManager, String portRangeConfig, AlignmentContext alignmentContext) throws IOException { return new Server(protocol, protocolImpl, conf, bindAddress, port, numHandlers, numReaders, queueSizePerHandler, verbose, secretManager, portRangeConfig, alignmentContext); } public static class Server extends RPC.Server { static final ThreadLocal<ProtobufRpcEngineCallback> currentCallback = new ThreadLocal<>(); static final ThreadLocal<CallInfo> currentCallInfo = new ThreadLocal<>(); static class CallInfo { private final RPC.Server server; private final String methodName; public CallInfo(RPC.Server server, String methodName) { this.server = server; this.methodName = methodName; } } static class ProtobufRpcEngineCallbackImpl implements ProtobufRpcEngineCallback { private final RPC.Server server; private final Call call; private final String methodName; private final long setupTime; public ProtobufRpcEngineCallbackImpl() { this.server = currentCallInfo.get().server; this.call = Server.getCurCall().get(); this.methodName = currentCallInfo.get().methodName; this.setupTime = Time.now(); } @Override public void setResponse(Message message) { long processingTime = Time.now() - setupTime; call.setDeferredResponse(RpcWritable.wrap(message)); server.updateDeferredMetrics(methodName, processingTime); } @Override public void error(Throwable t) { long processingTime = Time.now() - setupTime; String detailedMetricsName = t.getClass().getSimpleName(); server.updateDeferredMetrics(detailedMetricsName, processingTime); call.setDeferredError(t); } } @InterfaceStability.Unstable public static ProtobufRpcEngineCallback registerForDeferredResponse() { ProtobufRpcEngineCallback callback = new ProtobufRpcEngineCallbackImpl(); currentCallback.set(callback); return callback; } /** * Construct an RPC server. * * @param protocolClass the class of protocol * @param protocolImpl the protocolImpl whose methods will be called * @param conf the configuration to use * @param bindAddress the address to bind on to listen for connection * @param port the port to listen for connections on * @param numHandlers the number of method handler threads to run * @param verbose whether each call should be logged * @param portRangeConfig A config parameter that can be used to restrict * @param alignmentContext provides server state info on client responses */ public Server(Class<?> protocolClass, Object protocolImpl, Configuration conf, String bindAddress, int port, int numHandlers, int numReaders, int queueSizePerHandler, boolean verbose, SecretManager<? extends TokenIdentifier> secretManager, String portRangeConfig, AlignmentContext alignmentContext) throws IOException { super(bindAddress, port, null, numHandlers, numReaders, queueSizePerHandler, conf, serverNameFromClass(protocolImpl.getClass()), secretManager, portRangeConfig); setAlignmentContext(alignmentContext); this.verbose = verbose; registerProtocolAndImpl(RPC.RpcKind.RPC_PROTOCOL_BUFFER, protocolClass, protocolImpl); } /** * Protobuf invoker for {@link RpcInvoker} */ static class ProtoBufRpcInvoker implements RpcInvoker { private static ProtoClassProtoImpl getProtocolImpl(RPC.Server server, String protoName, long clientVersion) throws RpcServerException { ProtoNameVer pv = new ProtoNameVer(protoName, clientVersion); ProtoClassProtoImpl impl = server.getProtocolImplMap(RPC.RpcKind.RPC_PROTOCOL_BUFFER).get(pv); if (impl == null) { // no match for Protocol AND Version VerProtocolImpl highest = server.getHighestSupportedProtocol(RPC.RpcKind.RPC_PROTOCOL_BUFFER, protoName); if (highest == null) { throw new RpcNoSuchProtocolException( "Unknown protocol: " + protoName); } // protocol supported but not the version that client wants throw new RPC.VersionMismatch(protoName, clientVersion, highest.version); } return impl; } @Override /** * This is a server side method, which is invoked over RPC. On success * the return response has protobuf response payload. On failure, the * exception name and the stack trace are returned in the response. * See {@link HadoopRpcResponseProto} * * In this method there three types of exceptions possible and they are * returned in response as follows. * <ol> * <li> Exceptions encountered in this method that are returned * as {@link RpcServerException} </li> * <li> Exceptions thrown by the service is wrapped in ServiceException. * In that this method returns in response the exception thrown by the * service.</li> * <li> Other exceptions thrown by the service. They are returned as * it is.</li> * </ol> */ public Writable call(RPC.Server server, String connectionProtocolName, Writable writableRequest, long receiveTime) throws Exception { RpcProtobufRequest request = (RpcProtobufRequest) writableRequest; RequestHeaderProto rpcRequest = request.getRequestHeader(); String methodName = rpcRequest.getMethodName(); /** * RPCs for a particular interface (ie protocol) are done using a * IPC connection that is setup using rpcProxy. * The rpcProxy's has a declared protocol name that is * sent form client to server at connection time. * * Each Rpc call also sends a protocol name * (called declaringClassprotocolName). This name is usually the same * as the connection protocol name except in some cases. * For example metaProtocols such ProtocolInfoProto which get info * about the protocol reuse the connection but need to indicate that * the actual protocol is different (i.e. the protocol is * ProtocolInfoProto) since they reuse the connection; in this case * the declaringClassProtocolName field is set to the ProtocolInfoProto. */ String declaringClassProtoName = rpcRequest.getDeclaringClassProtocolName(); long clientVersion = rpcRequest.getClientProtocolVersion(); if (server.verbose) LOG.info("Call: connectionProtocolName=" + connectionProtocolName + ", method=" + methodName); ProtoClassProtoImpl protocolImpl = getProtocolImpl(server, declaringClassProtoName, clientVersion); BlockingService service = (BlockingService) protocolImpl.protocolImpl; MethodDescriptor methodDescriptor = service.getDescriptorForType() .findMethodByName(methodName); if (methodDescriptor == null) { String msg = "Unknown method " + methodName + " called on " + connectionProtocolName + " protocol."; LOG.warn(msg); throw new RpcNoSuchMethodException(msg); } Message prototype = service.getRequestPrototype(methodDescriptor); Message param = request.getValue(prototype); Message result; long startTime = Time.now(); int qTime = (int) (startTime - receiveTime); Exception exception = null; boolean isDeferred = false; try { server.rpcDetailedMetrics.init(protocolImpl.protocolClass); currentCallInfo.set(new CallInfo(server, methodName)); result = service.callBlockingMethod(methodDescriptor, null, param); // Check if this needs to be a deferred response, // by checking the ThreadLocal callback being set if (currentCallback.get() != null) { Server.getCurCall().get().deferResponse(); isDeferred = true; currentCallback.set(null); return null; } } catch (ServiceException e) { exception = (Exception) e.getCause(); throw (Exception) e.getCause(); } catch (Exception e) { exception = e; throw e; } finally { currentCallInfo.set(null); int processingTime = (int) (Time.now() - startTime); if (LOG.isDebugEnabled()) { String msg = "Served: " + methodName + (isDeferred ? ", deferred" : "") + ", queueTime= " + qTime + " procesingTime= " + processingTime; if (exception != null) { msg += " exception= " + exception.getClass().getSimpleName(); } LOG.debug(msg); } String detailedMetricsName = (exception == null) ? methodName : exception.getClass().getSimpleName(); server.updateMetrics(detailedMetricsName, qTime, processingTime, isDeferred); } return RpcWritable.wrap(result); } } } // htrace in the ipc layer creates the span name based on toString() // which uses the rpc header. in the normal case we want to defer decoding // the rpc header until needed by the rpc engine. static class RpcProtobufRequest extends RpcWritable.Buffer { private volatile RequestHeaderProto requestHeader; private Message payload; public RpcProtobufRequest() { } RpcProtobufRequest(RequestHeaderProto header, Message payload) { this.requestHeader = header; this.payload = payload; } RequestHeaderProto getRequestHeader() throws IOException { if (getByteBuffer() != null && requestHeader == null) { requestHeader = getValue(RequestHeaderProto.getDefaultInstance()); } return requestHeader; } @Override public void writeTo(ResponseBuffer out) throws IOException { requestHeader.writeDelimitedTo(out); if (payload != null) { payload.writeDelimitedTo(out); } } // this is used by htrace to name the span. @Override public String toString() { try { RequestHeaderProto header = getRequestHeader(); return header.getDeclaringClassProtocolName() + "." + header.getMethodName(); } catch (IOException e) { throw new IllegalArgumentException(e); } } } }
HDFS-14347. [SBN Read] Restore a comment line mistakenly removed in ProtobufRpcEngine. Contributed by Fengnan Li.
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine.java
HDFS-14347. [SBN Read] Restore a comment line mistakenly removed in ProtobufRpcEngine. Contributed by Fengnan Li.
<ide><path>adoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufRpcEngine.java <ide> * @param numHandlers the number of method handler threads to run <ide> * @param verbose whether each call should be logged <ide> * @param portRangeConfig A config parameter that can be used to restrict <add> * the range of ports used when port is 0 (an ephemeral port) <ide> * @param alignmentContext provides server state info on client responses <ide> */ <ide> public Server(Class<?> protocolClass, Object protocolImpl,
Java
agpl-3.0
d92501138028fa50bfb3f15e34d7a6c05d26687d
0
winni67/AndroidAPS,PoweRGbg/AndroidAPS,PoweRGbg/AndroidAPS,Heiner1/AndroidAPS,MilosKozak/AndroidAPS,jotomo/AndroidAPS,Heiner1/AndroidAPS,winni67/AndroidAPS,Heiner1/AndroidAPS,Heiner1/AndroidAPS,MilosKozak/AndroidAPS,PoweRGbg/AndroidAPS,jotomo/AndroidAPS,MilosKozak/AndroidAPS,jotomo/AndroidAPS
package info.nightscout.androidaps.plugins.NSClientInternal.services; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Binder; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import com.j256.ormlite.dao.CloseableIterator; import com.squareup.otto.Subscribe; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URISyntaxException; import java.sql.SQLException; import java.util.ArrayList; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAddAck; import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAuthAck; import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSUpdateAck; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAlarm; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAnnouncement; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastCals; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastClearAlarm; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastDeviceStatus; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastFood; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastMbgs; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastProfile; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastSgvs; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastStatus; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastUrgentAlarm; import info.nightscout.androidaps.plugins.NSClientInternal.data.AlarmAck; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.utils.DateUtil; import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.JsonHelper; import info.nightscout.utils.SP; import info.nightscout.utils.T; import io.socket.client.IO; import io.socket.client.Socket; import io.socket.emitter.Emitter; public class NSClientService extends Service { private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); static public PowerManager.WakeLock mWakeLock; private IBinder mBinder = new NSClientService.LocalBinder(); static ProfileStore profileStore; static public Handler handler; public static Socket mSocket; public static boolean isConnected = false; public static boolean hasWriteAuth = false; private static Integer dataCounter = 0; private static Integer connectCounter = 0; public static String nightscoutVersionName = ""; public static Integer nightscoutVersionCode = 0; private boolean nsEnabled = false; static public String nsURL = ""; private String nsAPISecret = ""; private String nsDevice = ""; private Integer nsHours = 48; public long lastResendTime = 0; public long latestDateInReceivedData = 0; private String nsAPIhashCode = ""; public static UploadQueue uploadQueue = new UploadQueue(); private ArrayList<Long> reconnections = new ArrayList<>(); private int WATCHDOG_INTERVAL_MINUTES = 2; private int WATCHDOG_RECONNECT_IN = 15; private int WATCHDOG_MAXCONNECTIONS = 5; public NSClientService() { registerBus(); if (handler == null) { HandlerThread handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); } PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NSClientService"); initialize(); } @Override public void onCreate() { super.onCreate(); mWakeLock.acquire(); } @Override public void onDestroy() { super.onDestroy(); if (mWakeLock.isHeld()) mWakeLock.release(); } public class LocalBinder extends Binder { public NSClientService getServiceInstance() { return NSClientService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } private void registerBus() { try { MainApp.bus().unregister(this); } catch (RuntimeException x) { // Ignore } MainApp.bus().register(this); } @Subscribe public void onStatusEvent(EventAppExit event) { if (L.isEnabled(L.NSCLIENT)) log.debug("EventAppExit received"); destroy(); stopSelf(); } @Subscribe public void onStatusEvent(EventPreferenceChange ev) { if (ev.isChanged(R.string.key_nsclientinternal_url) || ev.isChanged(R.string.key_nsclientinternal_api_secret) || ev.isChanged(R.string.key_nsclientinternal_paused) ) { latestDateInReceivedData = 0; destroy(); initialize(); } } @Subscribe public void onStatusEvent(EventConfigBuilderChange ev) { if (nsEnabled != MainApp.getSpecificPlugin(NSClientPlugin.class).isEnabled(PluginType.GENERAL)) { latestDateInReceivedData = 0; destroy(); initialize(); } } @Subscribe public void onStatusEvent(final EventNSClientRestart ev) { latestDateInReceivedData = 0; restart(); } public void initialize() { dataCounter = 0; readPreferences(); if (!nsAPISecret.equals("")) nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString(); MainApp.bus().post(new EventNSClientStatus("Initializing")); if (!MainApp.getSpecificPlugin(NSClientPlugin.class).isAllowed()) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "not allowed")); MainApp.bus().post(new EventNSClientStatus("Not allowed")); } else if (MainApp.getSpecificPlugin(NSClientPlugin.class).paused) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "paused")); MainApp.bus().post(new EventNSClientStatus("Paused")); } else if (!nsEnabled) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disabled")); MainApp.bus().post(new EventNSClientStatus("Disabled")); } else if (!nsURL.equals("")) { try { MainApp.bus().post(new EventNSClientStatus("Connecting ...")); IO.Options opt = new IO.Options(); opt.forceNew = true; opt.reconnection = true; mSocket = IO.socket(nsURL, opt); mSocket.on(Socket.EVENT_CONNECT, onConnect); mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect); mSocket.on(Socket.EVENT_PING, onPing); MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "do connect")); mSocket.connect(); mSocket.on("dataUpdate", onDataUpdate); mSocket.on("announcement", onAnnouncement); mSocket.on("alarm", onAlarm); mSocket.on("urgent_alarm", onUrgentAlarm); mSocket.on("clear_alarm", onClearAlarm); } catch (URISyntaxException | RuntimeException e) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax")); MainApp.bus().post(new EventNSClientStatus("Wrong URL syntax")); } } else { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "No NS URL specified")); MainApp.bus().post(new EventNSClientStatus("Not configured")); } } private Emitter.Listener onConnect = new Emitter.Listener() { @Override public void call(Object... args) { connectCounter++; String socketId = mSocket != null ? mSocket.id() : "NULL"; MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId)); if (mSocket != null) sendAuthMessage(new NSAuthAck()); watchdog(); } }; void watchdog() { synchronized (reconnections) { long now = DateUtil.now(); reconnections.add(now); for (int i = 0; i < reconnections.size(); i++) { Long r = reconnections.get(i); if (r < now - T.mins(WATCHDOG_INTERVAL_MINUTES).msecs()) { reconnections.remove(r); } } MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAXCONNECTIONS)); if (reconnections.size() >= WATCHDOG_MAXCONNECTIONS) { Notification n = new Notification(Notification.NSMALFUNCTION, MainApp.gs(R.string.nsmalfunction), Notification.URGENT); MainApp.bus().post(new EventNewNotification(n)); MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins")); NSClientPlugin.getPlugin().pause(true); MainApp.bus().post(new EventNSClientUpdateGUI()); new Thread(() -> { SystemClock.sleep(T.mins(WATCHDOG_RECONNECT_IN).msecs()); MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "reenabling NSClient")); NSClientPlugin.getPlugin().pause(false); }).start(); } } } private Emitter.Listener onDisconnect = new Emitter.Listener() { @Override public void call(Object... args) { if (L.isEnabled(L.NSCLIENT)) log.debug("disconnect reason: {}", args); MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disconnect event")); } }; public synchronized void destroy() { if (mSocket != null) { mSocket.off(Socket.EVENT_CONNECT); mSocket.off(Socket.EVENT_DISCONNECT); mSocket.off(Socket.EVENT_PING); mSocket.off("dataUpdate"); mSocket.off("announcement"); mSocket.off("alarm"); mSocket.off("urgent_alarm"); mSocket.off("clear_alarm"); MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "destroy")); isConnected = false; hasWriteAuth = false; mSocket.disconnect(); mSocket = null; } } public void sendAuthMessage(NSAuthAck ack) { JSONObject authMessage = new JSONObject(); try { authMessage.put("client", "Android_" + nsDevice); authMessage.put("history", nsHours); authMessage.put("status", true); // receive status authMessage.put("from", latestDateInReceivedData); // send data newer than authMessage.put("secret", nsAPIhashCode); } catch (JSONException e) { log.error("Unhandled exception", e); return; } MainApp.bus().post(new EventNSClientNewLog("AUTH", "requesting auth")); mSocket.emit("authorize", authMessage, ack); } @Subscribe public void onStatusEvent(NSAuthAck ack) { String connectionStatus = "Authenticated ("; if (ack.read) connectionStatus += "R"; if (ack.write) connectionStatus += "W"; if (ack.write_treatment) connectionStatus += "T"; connectionStatus += ')'; isConnected = true; hasWriteAuth = ack.write && ack.write_treatment; MainApp.bus().post(new EventNSClientStatus(connectionStatus)); MainApp.bus().post(new EventNSClientNewLog("AUTH", connectionStatus)); if (!ack.write) { MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!")); } if (!ack.write_treatment) { MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!")); } if (!hasWriteAuth) { Notification noperm = new Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, MainApp.gs(R.string.nowritepermission), Notification.URGENT); MainApp.bus().post(new EventNewNotification(noperm)); } else { MainApp.bus().post(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION)); } } public void readPreferences() { nsEnabled = MainApp.getSpecificPlugin(NSClientPlugin.class).isEnabled(PluginType.GENERAL); nsURL = SP.getString(R.string.key_nsclientinternal_url, ""); nsAPISecret = SP.getString(R.string.key_nsclientinternal_api_secret, ""); nsDevice = SP.getString("careportal_enteredby", ""); } private Emitter.Listener onPing = new Emitter.Listener() { @Override public void call(final Object... args) { MainApp.bus().post(new EventNSClientNewLog("PING", "received")); // send data if there is something waiting resend("Ping received"); } }; private Emitter.Listener onAnnouncement = new Emitter.Listener() { /* { "level":0, "title":"Announcement", "message":"test", "plugin":{"name":"treatmentnotify","label":"Treatment Notifications","pluginType":"notification","enabled":true}, "group":"Announcement", "isAnnouncement":true, "key":"9ac46ad9a1dcda79dd87dae418fce0e7955c68da" } */ @Override public void call(final Object... args) { JSONObject data; try { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong Announcement from NS: " + args[0]); log.error("Unhandled exception", e); return; } try { MainApp.bus().post(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received"))); } catch (Exception e) { FabricPrivacy.logException(e); log.error("Unhandled exception", e); } BroadcastAnnouncement.handleAnnouncement(data, getApplicationContext()); if (L.isEnabled(L.NSCLIENT)) log.debug(data.toString()); } }; private Emitter.Listener onAlarm = new Emitter.Listener() { /* { "level":1, "title":"Warning HIGH", "message":"BG Now: 5 -0.2 → mmol\/L\nRaw BG: 4.8 mmol\/L Čistý\nBG 15m: 4.8 mmol\/L\nIOB: -0.02U\nCOB: 0g", "eventName":"high", "plugin":{"name":"simplealarms","label":"Simple Alarms","pluginType":"notification","enabled":true}, "pushoverSound":"climb", "debug":{"lastSGV":5,"thresholds":{"bgHigh":180,"bgTargetTop":75,"bgTargetBottom":72,"bgLow":70}}, "group":"default", "key":"simplealarms_1" } */ @Override public void call(final Object... args) { MainApp.bus().post(new EventNSClientNewLog("ALARM", "received")); JSONObject data; try { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong alarm from NS: " + args[0]); log.error("Unhandled exception", e); return; } BroadcastAlarm.handleAlarm(data, getApplicationContext()); if (L.isEnabled(L.NSCLIENT)) log.debug(data.toString()); } }; private Emitter.Listener onUrgentAlarm = new Emitter.Listener() { /* { "level":2, "title":"Urgent HIGH", "message":"BG Now: 5.2 -0.1 → mmol\/L\nRaw BG: 5 mmol\/L Čistý\nBG 15m: 5 mmol\/L\nIOB: 0.00U\nCOB: 0g", "eventName":"high", "plugin":{"name":"simplealarms","label":"Simple Alarms","pluginType":"notification","enabled":true}, "pushoverSound":"persistent", "debug":{"lastSGV":5.2,"thresholds":{"bgHigh":80,"bgTargetTop":75,"bgTargetBottom":72,"bgLow":70}}, "group":"default", "key":"simplealarms_2" } */ @Override public void call(final Object... args) { JSONObject data; try { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong Urgent alarm from NS: " + args[0]); log.error("Unhandled exception", e); return; } MainApp.bus().post(new EventNSClientNewLog("URGENTALARM", "received")); BroadcastUrgentAlarm.handleUrgentAlarm(data, getApplicationContext()); if (L.isEnabled(L.NSCLIENT)) log.debug(data.toString()); } }; private Emitter.Listener onClearAlarm = new Emitter.Listener() { /* { "clear":true, "title":"All Clear", "message":"default - Urgent was ack'd", "group":"default" } */ @Override public void call(final Object... args) { JSONObject data; try { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong Urgent alarm from NS: " + args[0]); log.error("Unhandled exception", e); return; } MainApp.bus().post(new EventNSClientNewLog("CLEARALARM", "received")); BroadcastClearAlarm.handleClearAlarm(data, getApplicationContext()); if (L.isEnabled(L.NSCLIENT)) log.debug(data.toString()); } }; private Emitter.Listener onDataUpdate = new Emitter.Listener() { @Override public void call(final Object... args) { NSClientService.handler.post(new Runnable() { @Override public void run() { PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "onDataUpdate"); wakeLock.acquire(); try { JSONObject data = (JSONObject) args[0]; boolean broadcastProfile = false; try { // delta means only increment/changes are comming boolean isDelta = data.has("delta"); boolean isFull = !isDelta; MainApp.bus().post(new EventNSClientNewLog("DATA", "Data packet #" + dataCounter++ + (isDelta ? " delta" : " full"))); if (data.has("profiles")) { JSONArray profiles = data.getJSONArray("profiles"); if (profiles.length() > 0) { JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1); profileStore = new ProfileStore(profile); broadcastProfile = true; MainApp.bus().post(new EventNSClientNewLog("PROFILE", "profile received")); } } if (data.has("status")) { JSONObject status = data.getJSONObject("status"); NSSettingsStatus nsSettingsStatus = NSSettingsStatus.getInstance().setData(status); if (!status.has("versionNum")) { if (status.getInt("versionNum") < Config.SUPPORTEDNSVERSION) { MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); } } else { nightscoutVersionName = nsSettingsStatus.getVersion(); nightscoutVersionCode = nsSettingsStatus.getVersionNum(); } BroadcastStatus.handleNewStatus(nsSettingsStatus, MainApp.instance().getApplicationContext(), isDelta); /* Other received data to 2016/02/10 { status: 'ok' , name: env.name , version: env.version , versionNum: versionNum (for ver 1.2.3 contains 10203) , serverTime: new Date().toISOString() , apiEnabled: apiEnabled , careportalEnabled: apiEnabled && env.settings.enable.indexOf('careportal') > -1 , boluscalcEnabled: apiEnabled && env.settings.enable.indexOf('boluscalc') > -1 , head: env.head , settings: env.settings , extendedSettings: ctx.plugins && ctx.plugins.extendedClientSettings ? ctx.plugins.extendedClientSettings(env.extendedSettings) : {} , activeProfile ..... calculated from treatments or missing } */ } else if (!isDelta) { MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); } // If new profile received or change detected broadcast it if (broadcastProfile && profileStore != null) { BroadcastProfile.handleNewTreatment(profileStore, MainApp.instance().getApplicationContext(), isDelta); MainApp.bus().post(new EventNSClientNewLog("PROFILE", "broadcasting")); } if (data.has("treatments")) { JSONArray treatments = data.getJSONArray("treatments"); JSONArray removedTreatments = new JSONArray(); JSONArray updatedTreatments = new JSONArray(); JSONArray addedTreatments = new JSONArray(); if (treatments.length() > 0) MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + treatments.length() + " treatments")); for (Integer index = 0; index < treatments.length(); index++) { JSONObject jsonTreatment = treatments.getJSONObject(index); NSTreatment treatment = new NSTreatment(jsonTreatment); // remove from upload queue if Ack is failing UploadQueue.removeID(jsonTreatment); //Find latest date in treatment if (treatment.getMills() != null && treatment.getMills() < System.currentTimeMillis()) if (treatment.getMills() > latestDateInReceivedData) latestDateInReceivedData = treatment.getMills(); if (treatment.getAction() == null) { addedTreatments.put(jsonTreatment); } else if (treatment.getAction().equals("update")) { updatedTreatments.put(jsonTreatment); } else if (treatment.getAction().equals("remove")) { if (treatment.getMills() != null && treatment.getMills() > System.currentTimeMillis() - 24 * 60 * 60 * 1000L) // handle 1 day old deletions only removedTreatments.put(jsonTreatment); } } if (removedTreatments.length() > 0) { BroadcastTreatment.handleRemovedTreatment(removedTreatments, isDelta); } if (updatedTreatments.length() > 0) { BroadcastTreatment.handleChangedTreatment(updatedTreatments, isDelta); } if (addedTreatments.length() > 0) { BroadcastTreatment.handleNewTreatment(addedTreatments, isDelta); } } if (data.has("devicestatus")) { JSONArray devicestatuses = data.getJSONArray("devicestatus"); if (devicestatuses.length() > 0) { MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses")); for (Integer index = 0; index < devicestatuses.length(); index++) { JSONObject jsonStatus = devicestatuses.getJSONObject(index); // remove from upload queue if Ack is failing UploadQueue.removeID(jsonStatus); } BroadcastDeviceStatus.handleNewDeviceStatus(devicestatuses, MainApp.instance().getApplicationContext(), isDelta); } } if (data.has("food")) { JSONArray foods = data.getJSONArray("food"); JSONArray removedFoods = new JSONArray(); JSONArray updatedFoods = new JSONArray(); JSONArray addedFoods = new JSONArray(); if (foods.length() > 0) MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + foods.length() + " foods")); for (Integer index = 0; index < foods.length(); index++) { JSONObject jsonFood = foods.getJSONObject(index); // remove from upload queue if Ack is failing UploadQueue.removeID(jsonFood); String action = JsonHelper.safeGetString(jsonFood, "action"); if (action == null) { addedFoods.put(jsonFood); } else if (action.equals("update")) { updatedFoods.put(jsonFood); } else if (action.equals("remove")) { removedFoods.put(jsonFood); } } if (removedFoods.length() > 0) { BroadcastFood.handleRemovedFood(removedFoods, MainApp.instance().getApplicationContext(), isDelta); } if (updatedFoods.length() > 0) { BroadcastFood.handleChangedFood(updatedFoods, MainApp.instance().getApplicationContext(), isDelta); } if (addedFoods.length() > 0) { BroadcastFood.handleNewFood(addedFoods, MainApp.instance().getApplicationContext(), isDelta); } } if (data.has("mbgs")) { JSONArray mbgs = data.getJSONArray("mbgs"); if (mbgs.length() > 0) MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs")); for (Integer index = 0; index < mbgs.length(); index++) { JSONObject jsonMbg = mbgs.getJSONObject(index); // remove from upload queue if Ack is failing UploadQueue.removeID(jsonMbg); } BroadcastMbgs.handleNewMbg(mbgs, MainApp.instance().getApplicationContext(), isDelta); } if (data.has("cals")) { JSONArray cals = data.getJSONArray("cals"); if (cals.length() > 0) MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals")); // Retreive actual calibration for (Integer index = 0; index < cals.length(); index++) { // remove from upload queue if Ack is failing UploadQueue.removeID(cals.optJSONObject(index)); } BroadcastCals.handleNewCal(cals, MainApp.instance().getApplicationContext(), isDelta); } if (data.has("sgvs")) { JSONArray sgvs = data.getJSONArray("sgvs"); if (sgvs.length() > 0) MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs")); for (Integer index = 0; index < sgvs.length(); index++) { JSONObject jsonSgv = sgvs.getJSONObject(index); // MainApp.bus().post(new EventNSClientNewLog("DATA", "svg " + sgvs.getJSONObject(index).toString()); NSSgv sgv = new NSSgv(jsonSgv); // Handle new sgv here // remove from upload queue if Ack is failing UploadQueue.removeID(jsonSgv); //Find latest date in sgv if (sgv.getMills() != null && sgv.getMills() < System.currentTimeMillis()) if (sgv.getMills() > latestDateInReceivedData) latestDateInReceivedData = sgv.getMills(); } // Was that sgv more less 15 mins ago ? boolean lessThan15MinAgo = false; if ((System.currentTimeMillis() - latestDateInReceivedData) / (60 * 1000L) < 15L) lessThan15MinAgo = true; if (Notification.isAlarmForStaleData() && lessThan15MinAgo) { MainApp.bus().post(new EventDismissNotification(Notification.NSALARM)); } BroadcastSgvs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta); } MainApp.bus().post(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData))); } catch (JSONException e) { log.error("Unhandled exception", e); } //MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end"); } finally { if (wakeLock.isHeld()) wakeLock.release(); } } }); } }; public void dbUpdate(DbRequest dbr, NSUpdateAck ack) { try { if (!isConnected || !hasWriteAuth) return; JSONObject message = new JSONObject(); message.put("collection", dbr.collection); message.put("_id", dbr._id); message.put("data", new JSONObject(dbr.data)); mSocket.emit("dbUpdate", message, ack); MainApp.bus().post(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { log.error("Unhandled exception", e); } } public void dbUpdateUnset(DbRequest dbr, NSUpdateAck ack) { try { if (!isConnected || !hasWriteAuth) return; JSONObject message = new JSONObject(); message.put("collection", dbr.collection); message.put("_id", dbr._id); message.put("data", new JSONObject(dbr.data)); mSocket.emit("dbUpdateUnset", message, ack); MainApp.bus().post(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { log.error("Unhandled exception", e); } } public void dbRemove(DbRequest dbr, NSUpdateAck ack) { try { if (!isConnected || !hasWriteAuth) return; JSONObject message = new JSONObject(); message.put("collection", dbr.collection); message.put("_id", dbr._id); mSocket.emit("dbRemove", message, ack); MainApp.bus().post(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { log.error("Unhandled exception", e); } } @Subscribe public void onStatusEvent(NSUpdateAck ack) { if (ack.result) { uploadQueue.removeID(ack.action, ack._id); MainApp.bus().post(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id)); } else { MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response")); } } public void dbAdd(DbRequest dbr, NSAddAck ack) { try { if (!isConnected || !hasWriteAuth) return; JSONObject message = new JSONObject(); message.put("collection", dbr.collection); message.put("data", new JSONObject(dbr.data)); mSocket.emit("dbAdd", message, ack); MainApp.bus().post(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID)); } catch (JSONException e) { log.error("Unhandled exception", e); } } public void sendAlarmAck(AlarmAck alarmAck) { if (!isConnected || !hasWriteAuth) return; mSocket.emit("ack", alarmAck.level, alarmAck.group, alarmAck.silenceTime); MainApp.bus().post(new EventNSClientNewLog("ALARMACK ", alarmAck.level + " " + alarmAck.group + " " + alarmAck.silenceTime)); } @Subscribe public void onStatusEvent(NSAddAck ack) { if (ack.nsClientID != null) { uploadQueue.removeID(ack.json); MainApp.bus().post(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID)); } else { MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBADD Unknown response")); } } public void resend(final String reason) { if (UploadQueue.size() == 0) return; if (!isConnected || !hasWriteAuth) return; handler.post(new Runnable() { @Override public void run() { if (mSocket == null || !mSocket.connected()) return; if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) { if (L.isEnabled(L.NSCLIENT)) log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); return; } lastResendTime = System.currentTimeMillis(); MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend started: " + reason)); CloseableIterator<DbRequest> iterator = null; int maxcount = 30; try { iterator = MainApp.getDbHelper().getDbRequestInterator(); try { while (iterator.hasNext() && maxcount > 0) { DbRequest dbr = iterator.next(); if (dbr.action.equals("dbAdd")) { NSAddAck addAck = new NSAddAck(); dbAdd(dbr, addAck); } else if (dbr.action.equals("dbRemove")) { NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id); dbRemove(dbr, removeAck); } else if (dbr.action.equals("dbUpdate")) { NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id); dbUpdate(dbr, updateAck); } else if (dbr.action.equals("dbUpdateUnset")) { NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id); dbUpdateUnset(dbr, updateUnsetAck); } maxcount--; } } finally { iterator.close(); } } catch (SQLException e) { log.error("Unhandled exception", e); } MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason)); } }); } public void restart() { destroy(); initialize(); } }
app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java
package info.nightscout.androidaps.plugins.NSClientInternal.services; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Binder; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import com.j256.ormlite.dao.CloseableIterator; import com.squareup.otto.Subscribe; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URISyntaxException; import java.sql.SQLException; import java.util.ArrayList; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAddAck; import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAuthAck; import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSUpdateAck; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAlarm; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAnnouncement; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastCals; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastClearAlarm; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastDeviceStatus; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastFood; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastMbgs; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastProfile; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastSgvs; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastStatus; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastUrgentAlarm; import info.nightscout.androidaps.plugins.NSClientInternal.data.AlarmAck; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.utils.DateUtil; import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.JsonHelper; import info.nightscout.utils.SP; import info.nightscout.utils.T; import io.socket.client.IO; import io.socket.client.Socket; import io.socket.emitter.Emitter; public class NSClientService extends Service { private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); static public PowerManager.WakeLock mWakeLock; private IBinder mBinder = new NSClientService.LocalBinder(); static ProfileStore profileStore; static public Handler handler; public static Socket mSocket; public static boolean isConnected = false; public static boolean hasWriteAuth = false; private static Integer dataCounter = 0; private static Integer connectCounter = 0; public static String nightscoutVersionName = ""; public static Integer nightscoutVersionCode = 0; private boolean nsEnabled = false; static public String nsURL = ""; private String nsAPISecret = ""; private String nsDevice = ""; private Integer nsHours = 48; public long lastResendTime = 0; public long latestDateInReceivedData = 0; private String nsAPIhashCode = ""; public static UploadQueue uploadQueue = new UploadQueue(); private ArrayList<Long> reconnections = new ArrayList<>(); private int WATCHDOG_INTERVAL_MINUTES = 2; private int WATCHDOG_RECONNECT_IN = 1; private int WATCHDOG_MAXCONNECTIONS = 5; public NSClientService() { registerBus(); if (handler == null) { HandlerThread handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler"); handlerThread.start(); handler = new Handler(handlerThread.getLooper()); } PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NSClientService"); initialize(); } @Override public void onCreate() { super.onCreate(); mWakeLock.acquire(); } @Override public void onDestroy() { super.onDestroy(); if (mWakeLock.isHeld()) mWakeLock.release(); } public class LocalBinder extends Binder { public NSClientService getServiceInstance() { return NSClientService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } private void registerBus() { try { MainApp.bus().unregister(this); } catch (RuntimeException x) { // Ignore } MainApp.bus().register(this); } @Subscribe public void onStatusEvent(EventAppExit event) { if (L.isEnabled(L.NSCLIENT)) log.debug("EventAppExit received"); destroy(); stopSelf(); } @Subscribe public void onStatusEvent(EventPreferenceChange ev) { if (ev.isChanged(R.string.key_nsclientinternal_url) || ev.isChanged(R.string.key_nsclientinternal_api_secret) || ev.isChanged(R.string.key_nsclientinternal_paused) ) { latestDateInReceivedData = 0; destroy(); initialize(); } } @Subscribe public void onStatusEvent(EventConfigBuilderChange ev) { if (nsEnabled != MainApp.getSpecificPlugin(NSClientPlugin.class).isEnabled(PluginType.GENERAL)) { latestDateInReceivedData = 0; destroy(); initialize(); } } @Subscribe public void onStatusEvent(final EventNSClientRestart ev) { latestDateInReceivedData = 0; restart(); } public void initialize() { dataCounter = 0; readPreferences(); if (!nsAPISecret.equals("")) nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString(); MainApp.bus().post(new EventNSClientStatus("Initializing")); if (!MainApp.getSpecificPlugin(NSClientPlugin.class).isAllowed()) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "not allowed")); MainApp.bus().post(new EventNSClientStatus("Not allowed")); } else if (MainApp.getSpecificPlugin(NSClientPlugin.class).paused) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "paused")); MainApp.bus().post(new EventNSClientStatus("Paused")); } else if (!nsEnabled) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disabled")); MainApp.bus().post(new EventNSClientStatus("Disabled")); } else if (!nsURL.equals("")) { try { MainApp.bus().post(new EventNSClientStatus("Connecting ...")); IO.Options opt = new IO.Options(); opt.forceNew = true; opt.reconnection = true; mSocket = IO.socket(nsURL, opt); mSocket.on(Socket.EVENT_CONNECT, onConnect); mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect); mSocket.on(Socket.EVENT_PING, onPing); MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "do connect")); mSocket.connect(); mSocket.on("dataUpdate", onDataUpdate); mSocket.on("announcement", onAnnouncement); mSocket.on("alarm", onAlarm); mSocket.on("urgent_alarm", onUrgentAlarm); mSocket.on("clear_alarm", onClearAlarm); } catch (URISyntaxException | RuntimeException e) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax")); MainApp.bus().post(new EventNSClientStatus("Wrong URL syntax")); } } else { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "No NS URL specified")); MainApp.bus().post(new EventNSClientStatus("Not configured")); } } private Emitter.Listener onConnect = new Emitter.Listener() { @Override public void call(Object... args) { connectCounter++; String socketId = mSocket != null ? mSocket.id() : "NULL"; MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId)); if (mSocket != null) sendAuthMessage(new NSAuthAck()); watchdog(); } }; void watchdog() { synchronized (reconnections) { long now = DateUtil.now(); reconnections.add(now); for (int i = 0; i < reconnections.size(); i++) { Long r = reconnections.get(i); if (r < now - T.mins(WATCHDOG_INTERVAL_MINUTES).msecs()) { reconnections.remove(r); } } MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAXCONNECTIONS)); if (reconnections.size() >= WATCHDOG_MAXCONNECTIONS) { Notification n = new Notification(Notification.NSMALFUNCTION, MainApp.gs(R.string.nsmalfunction), Notification.URGENT); MainApp.bus().post(new EventNewNotification(n)); MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins")); NSClientPlugin.getPlugin().pause(true); MainApp.bus().post(new EventNSClientUpdateGUI()); new Thread(() -> { SystemClock.sleep(T.mins(WATCHDOG_RECONNECT_IN).msecs()); MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "reenabling NSClient")); NSClientPlugin.getPlugin().pause(false); }).start(); } } } private Emitter.Listener onDisconnect = new Emitter.Listener() { @Override public void call(Object... args) { if (L.isEnabled(L.NSCLIENT)) log.debug("disconnect reason: {}", args); MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disconnect event")); } }; public synchronized void destroy() { if (mSocket != null) { mSocket.off(Socket.EVENT_CONNECT); mSocket.off(Socket.EVENT_DISCONNECT); mSocket.off(Socket.EVENT_PING); mSocket.off("dataUpdate"); mSocket.off("announcement"); mSocket.off("alarm"); mSocket.off("urgent_alarm"); mSocket.off("clear_alarm"); MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "destroy")); isConnected = false; hasWriteAuth = false; mSocket.disconnect(); mSocket = null; } } public void sendAuthMessage(NSAuthAck ack) { JSONObject authMessage = new JSONObject(); try { authMessage.put("client", "Android_" + nsDevice); authMessage.put("history", nsHours); authMessage.put("status", true); // receive status authMessage.put("from", latestDateInReceivedData); // send data newer than authMessage.put("secret", nsAPIhashCode); } catch (JSONException e) { log.error("Unhandled exception", e); return; } MainApp.bus().post(new EventNSClientNewLog("AUTH", "requesting auth")); mSocket.emit("authorize", authMessage, ack); } @Subscribe public void onStatusEvent(NSAuthAck ack) { String connectionStatus = "Authenticated ("; if (ack.read) connectionStatus += "R"; if (ack.write) connectionStatus += "W"; if (ack.write_treatment) connectionStatus += "T"; connectionStatus += ')'; isConnected = true; hasWriteAuth = ack.write && ack.write_treatment; MainApp.bus().post(new EventNSClientStatus(connectionStatus)); MainApp.bus().post(new EventNSClientNewLog("AUTH", connectionStatus)); if (!ack.write) { MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!")); } if (!ack.write_treatment) { MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!")); } if (!hasWriteAuth) { Notification noperm = new Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, MainApp.gs(R.string.nowritepermission), Notification.URGENT); MainApp.bus().post(new EventNewNotification(noperm)); } else { MainApp.bus().post(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION)); } } public void readPreferences() { nsEnabled = MainApp.getSpecificPlugin(NSClientPlugin.class).isEnabled(PluginType.GENERAL); nsURL = SP.getString(R.string.key_nsclientinternal_url, ""); nsAPISecret = SP.getString(R.string.key_nsclientinternal_api_secret, ""); nsDevice = SP.getString("careportal_enteredby", ""); } private Emitter.Listener onPing = new Emitter.Listener() { @Override public void call(final Object... args) { MainApp.bus().post(new EventNSClientNewLog("PING", "received")); // send data if there is something waiting resend("Ping received"); } }; private Emitter.Listener onAnnouncement = new Emitter.Listener() { /* { "level":0, "title":"Announcement", "message":"test", "plugin":{"name":"treatmentnotify","label":"Treatment Notifications","pluginType":"notification","enabled":true}, "group":"Announcement", "isAnnouncement":true, "key":"9ac46ad9a1dcda79dd87dae418fce0e7955c68da" } */ @Override public void call(final Object... args) { JSONObject data; try { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong Announcement from NS: " + args[0]); log.error("Unhandled exception", e); return; } try { MainApp.bus().post(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received"))); } catch (Exception e) { FabricPrivacy.logException(e); log.error("Unhandled exception", e); } BroadcastAnnouncement.handleAnnouncement(data, getApplicationContext()); if (L.isEnabled(L.NSCLIENT)) log.debug(data.toString()); } }; private Emitter.Listener onAlarm = new Emitter.Listener() { /* { "level":1, "title":"Warning HIGH", "message":"BG Now: 5 -0.2 → mmol\/L\nRaw BG: 4.8 mmol\/L Čistý\nBG 15m: 4.8 mmol\/L\nIOB: -0.02U\nCOB: 0g", "eventName":"high", "plugin":{"name":"simplealarms","label":"Simple Alarms","pluginType":"notification","enabled":true}, "pushoverSound":"climb", "debug":{"lastSGV":5,"thresholds":{"bgHigh":180,"bgTargetTop":75,"bgTargetBottom":72,"bgLow":70}}, "group":"default", "key":"simplealarms_1" } */ @Override public void call(final Object... args) { MainApp.bus().post(new EventNSClientNewLog("ALARM", "received")); JSONObject data; try { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong alarm from NS: " + args[0]); log.error("Unhandled exception", e); return; } BroadcastAlarm.handleAlarm(data, getApplicationContext()); if (L.isEnabled(L.NSCLIENT)) log.debug(data.toString()); } }; private Emitter.Listener onUrgentAlarm = new Emitter.Listener() { /* { "level":2, "title":"Urgent HIGH", "message":"BG Now: 5.2 -0.1 → mmol\/L\nRaw BG: 5 mmol\/L Čistý\nBG 15m: 5 mmol\/L\nIOB: 0.00U\nCOB: 0g", "eventName":"high", "plugin":{"name":"simplealarms","label":"Simple Alarms","pluginType":"notification","enabled":true}, "pushoverSound":"persistent", "debug":{"lastSGV":5.2,"thresholds":{"bgHigh":80,"bgTargetTop":75,"bgTargetBottom":72,"bgLow":70}}, "group":"default", "key":"simplealarms_2" } */ @Override public void call(final Object... args) { JSONObject data; try { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong Urgent alarm from NS: " + args[0]); log.error("Unhandled exception", e); return; } MainApp.bus().post(new EventNSClientNewLog("URGENTALARM", "received")); BroadcastUrgentAlarm.handleUrgentAlarm(data, getApplicationContext()); if (L.isEnabled(L.NSCLIENT)) log.debug(data.toString()); } }; private Emitter.Listener onClearAlarm = new Emitter.Listener() { /* { "clear":true, "title":"All Clear", "message":"default - Urgent was ack'd", "group":"default" } */ @Override public void call(final Object... args) { JSONObject data; try { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong Urgent alarm from NS: " + args[0]); log.error("Unhandled exception", e); return; } MainApp.bus().post(new EventNSClientNewLog("CLEARALARM", "received")); BroadcastClearAlarm.handleClearAlarm(data, getApplicationContext()); if (L.isEnabled(L.NSCLIENT)) log.debug(data.toString()); } }; private Emitter.Listener onDataUpdate = new Emitter.Listener() { @Override public void call(final Object... args) { NSClientService.handler.post(new Runnable() { @Override public void run() { PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "onDataUpdate"); wakeLock.acquire(); try { JSONObject data = (JSONObject) args[0]; boolean broadcastProfile = false; try { // delta means only increment/changes are comming boolean isDelta = data.has("delta"); boolean isFull = !isDelta; MainApp.bus().post(new EventNSClientNewLog("DATA", "Data packet #" + dataCounter++ + (isDelta ? " delta" : " full"))); if (data.has("profiles")) { JSONArray profiles = data.getJSONArray("profiles"); if (profiles.length() > 0) { JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1); profileStore = new ProfileStore(profile); broadcastProfile = true; MainApp.bus().post(new EventNSClientNewLog("PROFILE", "profile received")); } } if (data.has("status")) { JSONObject status = data.getJSONObject("status"); NSSettingsStatus nsSettingsStatus = NSSettingsStatus.getInstance().setData(status); if (!status.has("versionNum")) { if (status.getInt("versionNum") < Config.SUPPORTEDNSVERSION) { MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); } } else { nightscoutVersionName = nsSettingsStatus.getVersion(); nightscoutVersionCode = nsSettingsStatus.getVersionNum(); } BroadcastStatus.handleNewStatus(nsSettingsStatus, MainApp.instance().getApplicationContext(), isDelta); /* Other received data to 2016/02/10 { status: 'ok' , name: env.name , version: env.version , versionNum: versionNum (for ver 1.2.3 contains 10203) , serverTime: new Date().toISOString() , apiEnabled: apiEnabled , careportalEnabled: apiEnabled && env.settings.enable.indexOf('careportal') > -1 , boluscalcEnabled: apiEnabled && env.settings.enable.indexOf('boluscalc') > -1 , head: env.head , settings: env.settings , extendedSettings: ctx.plugins && ctx.plugins.extendedClientSettings ? ctx.plugins.extendedClientSettings(env.extendedSettings) : {} , activeProfile ..... calculated from treatments or missing } */ } else if (!isDelta) { MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); } // If new profile received or change detected broadcast it if (broadcastProfile && profileStore != null) { BroadcastProfile.handleNewTreatment(profileStore, MainApp.instance().getApplicationContext(), isDelta); MainApp.bus().post(new EventNSClientNewLog("PROFILE", "broadcasting")); } if (data.has("treatments")) { JSONArray treatments = data.getJSONArray("treatments"); JSONArray removedTreatments = new JSONArray(); JSONArray updatedTreatments = new JSONArray(); JSONArray addedTreatments = new JSONArray(); if (treatments.length() > 0) MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + treatments.length() + " treatments")); for (Integer index = 0; index < treatments.length(); index++) { JSONObject jsonTreatment = treatments.getJSONObject(index); NSTreatment treatment = new NSTreatment(jsonTreatment); // remove from upload queue if Ack is failing UploadQueue.removeID(jsonTreatment); //Find latest date in treatment if (treatment.getMills() != null && treatment.getMills() < System.currentTimeMillis()) if (treatment.getMills() > latestDateInReceivedData) latestDateInReceivedData = treatment.getMills(); if (treatment.getAction() == null) { addedTreatments.put(jsonTreatment); } else if (treatment.getAction().equals("update")) { updatedTreatments.put(jsonTreatment); } else if (treatment.getAction().equals("remove")) { if (treatment.getMills() != null && treatment.getMills() > System.currentTimeMillis() - 24 * 60 * 60 * 1000L) // handle 1 day old deletions only removedTreatments.put(jsonTreatment); } } if (removedTreatments.length() > 0) { BroadcastTreatment.handleRemovedTreatment(removedTreatments, isDelta); } if (updatedTreatments.length() > 0) { BroadcastTreatment.handleChangedTreatment(updatedTreatments, isDelta); } if (addedTreatments.length() > 0) { BroadcastTreatment.handleNewTreatment(addedTreatments, isDelta); } } if (data.has("devicestatus")) { JSONArray devicestatuses = data.getJSONArray("devicestatus"); if (devicestatuses.length() > 0) { MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses")); for (Integer index = 0; index < devicestatuses.length(); index++) { JSONObject jsonStatus = devicestatuses.getJSONObject(index); // remove from upload queue if Ack is failing UploadQueue.removeID(jsonStatus); } BroadcastDeviceStatus.handleNewDeviceStatus(devicestatuses, MainApp.instance().getApplicationContext(), isDelta); } } if (data.has("food")) { JSONArray foods = data.getJSONArray("food"); JSONArray removedFoods = new JSONArray(); JSONArray updatedFoods = new JSONArray(); JSONArray addedFoods = new JSONArray(); if (foods.length() > 0) MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + foods.length() + " foods")); for (Integer index = 0; index < foods.length(); index++) { JSONObject jsonFood = foods.getJSONObject(index); // remove from upload queue if Ack is failing UploadQueue.removeID(jsonFood); String action = JsonHelper.safeGetString(jsonFood, "action"); if (action == null) { addedFoods.put(jsonFood); } else if (action.equals("update")) { updatedFoods.put(jsonFood); } else if (action.equals("remove")) { removedFoods.put(jsonFood); } } if (removedFoods.length() > 0) { BroadcastFood.handleRemovedFood(removedFoods, MainApp.instance().getApplicationContext(), isDelta); } if (updatedFoods.length() > 0) { BroadcastFood.handleChangedFood(updatedFoods, MainApp.instance().getApplicationContext(), isDelta); } if (addedFoods.length() > 0) { BroadcastFood.handleNewFood(addedFoods, MainApp.instance().getApplicationContext(), isDelta); } } if (data.has("mbgs")) { JSONArray mbgs = data.getJSONArray("mbgs"); if (mbgs.length() > 0) MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs")); for (Integer index = 0; index < mbgs.length(); index++) { JSONObject jsonMbg = mbgs.getJSONObject(index); // remove from upload queue if Ack is failing UploadQueue.removeID(jsonMbg); } BroadcastMbgs.handleNewMbg(mbgs, MainApp.instance().getApplicationContext(), isDelta); } if (data.has("cals")) { JSONArray cals = data.getJSONArray("cals"); if (cals.length() > 0) MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals")); // Retreive actual calibration for (Integer index = 0; index < cals.length(); index++) { // remove from upload queue if Ack is failing UploadQueue.removeID(cals.optJSONObject(index)); } BroadcastCals.handleNewCal(cals, MainApp.instance().getApplicationContext(), isDelta); } if (data.has("sgvs")) { JSONArray sgvs = data.getJSONArray("sgvs"); if (sgvs.length() > 0) MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs")); for (Integer index = 0; index < sgvs.length(); index++) { JSONObject jsonSgv = sgvs.getJSONObject(index); // MainApp.bus().post(new EventNSClientNewLog("DATA", "svg " + sgvs.getJSONObject(index).toString()); NSSgv sgv = new NSSgv(jsonSgv); // Handle new sgv here // remove from upload queue if Ack is failing UploadQueue.removeID(jsonSgv); //Find latest date in sgv if (sgv.getMills() != null && sgv.getMills() < System.currentTimeMillis()) if (sgv.getMills() > latestDateInReceivedData) latestDateInReceivedData = sgv.getMills(); } // Was that sgv more less 15 mins ago ? boolean lessThan15MinAgo = false; if ((System.currentTimeMillis() - latestDateInReceivedData) / (60 * 1000L) < 15L) lessThan15MinAgo = true; if (Notification.isAlarmForStaleData() && lessThan15MinAgo) { MainApp.bus().post(new EventDismissNotification(Notification.NSALARM)); } BroadcastSgvs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta); } MainApp.bus().post(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData))); } catch (JSONException e) { log.error("Unhandled exception", e); } //MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end"); } finally { if (wakeLock.isHeld()) wakeLock.release(); } } }); } }; public void dbUpdate(DbRequest dbr, NSUpdateAck ack) { try { if (!isConnected || !hasWriteAuth) return; JSONObject message = new JSONObject(); message.put("collection", dbr.collection); message.put("_id", dbr._id); message.put("data", new JSONObject(dbr.data)); mSocket.emit("dbUpdate", message, ack); MainApp.bus().post(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { log.error("Unhandled exception", e); } } public void dbUpdateUnset(DbRequest dbr, NSUpdateAck ack) { try { if (!isConnected || !hasWriteAuth) return; JSONObject message = new JSONObject(); message.put("collection", dbr.collection); message.put("_id", dbr._id); message.put("data", new JSONObject(dbr.data)); mSocket.emit("dbUpdateUnset", message, ack); MainApp.bus().post(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { log.error("Unhandled exception", e); } } public void dbRemove(DbRequest dbr, NSUpdateAck ack) { try { if (!isConnected || !hasWriteAuth) return; JSONObject message = new JSONObject(); message.put("collection", dbr.collection); message.put("_id", dbr._id); mSocket.emit("dbRemove", message, ack); MainApp.bus().post(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { log.error("Unhandled exception", e); } } @Subscribe public void onStatusEvent(NSUpdateAck ack) { if (ack.result) { uploadQueue.removeID(ack.action, ack._id); MainApp.bus().post(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id)); } else { MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response")); } } public void dbAdd(DbRequest dbr, NSAddAck ack) { try { if (!isConnected || !hasWriteAuth) return; JSONObject message = new JSONObject(); message.put("collection", dbr.collection); message.put("data", new JSONObject(dbr.data)); mSocket.emit("dbAdd", message, ack); MainApp.bus().post(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID)); } catch (JSONException e) { log.error("Unhandled exception", e); } } public void sendAlarmAck(AlarmAck alarmAck) { if (!isConnected || !hasWriteAuth) return; mSocket.emit("ack", alarmAck.level, alarmAck.group, alarmAck.silenceTime); MainApp.bus().post(new EventNSClientNewLog("ALARMACK ", alarmAck.level + " " + alarmAck.group + " " + alarmAck.silenceTime)); } @Subscribe public void onStatusEvent(NSAddAck ack) { if (ack.nsClientID != null) { uploadQueue.removeID(ack.json); MainApp.bus().post(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID)); } else { MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBADD Unknown response")); } } public void resend(final String reason) { if (UploadQueue.size() == 0) return; if (!isConnected || !hasWriteAuth) return; handler.post(new Runnable() { @Override public void run() { if (mSocket == null || !mSocket.connected()) return; if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) { if (L.isEnabled(L.NSCLIENT)) log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); return; } lastResendTime = System.currentTimeMillis(); MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend started: " + reason)); CloseableIterator<DbRequest> iterator = null; int maxcount = 30; try { iterator = MainApp.getDbHelper().getDbRequestInterator(); try { while (iterator.hasNext() && maxcount > 0) { DbRequest dbr = iterator.next(); if (dbr.action.equals("dbAdd")) { NSAddAck addAck = new NSAddAck(); dbAdd(dbr, addAck); } else if (dbr.action.equals("dbRemove")) { NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id); dbRemove(dbr, removeAck); } else if (dbr.action.equals("dbUpdate")) { NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id); dbUpdate(dbr, updateAck); } else if (dbr.action.equals("dbUpdateUnset")) { NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id); dbUpdateUnset(dbr, updateUnsetAck); } maxcount--; } } finally { iterator.close(); } } catch (SQLException e) { log.error("Unhandled exception", e); } MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason)); } }); } public void restart() { destroy(); initialize(); } }
WATCHDOG_RECONNECT_IN = 15
app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java
WATCHDOG_RECONNECT_IN = 15
<ide><path>pp/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java <ide> <ide> private ArrayList<Long> reconnections = new ArrayList<>(); <ide> private int WATCHDOG_INTERVAL_MINUTES = 2; <del> private int WATCHDOG_RECONNECT_IN = 1; <add> private int WATCHDOG_RECONNECT_IN = 15; <ide> private int WATCHDOG_MAXCONNECTIONS = 5; <ide> <ide> public NSClientService() {
Java
apache-2.0
error: pathspec 'src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java' did not match any file(s) known to git
ca23acfcc44ba9e2a1a2a7c5c580e1218b727e9f
1
StrategyObject/fop,StrategyObject/fop,argv-minus-one/fop,argv-minus-one/fop,spepping/fop-cs,Distrotech/fop,StrategyObject/fop,StrategyObject/fop,Distrotech/fop,argv-minus-one/fop,Distrotech/fop,argv-minus-one/fop,argv-minus-one/fop,spepping/fop-cs,StrategyObject/fop,Distrotech/fop,spepping/fop-cs,spepping/fop-cs
/* * $Id: PDFToUnicodeCMap.java,v 1.3.2.1 2005/12/01 12:00:00 ono Exp $ * ============================================================================ * The Apache Software License, Version 1.1 * ============================================================================ * * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: "This product includes software * developed by the Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * * 4. The names "FOP" and "Apache Software Foundation" must not be used to * endorse or promote products derived from this software without prior * written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "Apache", nor may * "Apache" appear in their name, without prior written permission of the * Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ============================================================================ * * This software consists of voluntary contributions made by many individuals * on behalf of the Apache Software Foundation and was originally created by * James Tauber <[email protected]>. For more information on the Apache * Software Foundation, please see <http://www.apache.org/>. */ package org.apache.fop.pdf; /** * Class representing ToUnicode CMaps. * Here are some documentation resources: * <ul> * <li>PDF Reference, Second Edition, Section 5.6.4, for general information * about CMaps in PDF Files.</li> * <li>PDF Reference, Second Edition, Section 5.9, for specific information * about ToUnicodeCMaps in PDF Files.</li> * <li> * <a href="http://partners.adobe.com/asn/developer/pdfs/tn/5411.ToUnicode.pdf"> * Adobe Technical Note #5411, "ToUnicode Mapping File Tutorial"</a>. * </ul> */ import org.apache.fop.fonts.CIDFont; public class PDFToUnicodeCMap extends PDFCMap { /** * handle to read font */ protected CIDFont cidFont; /** * Constructor. * * @param name One of the registered names found in Table 5.14 in PDF * Reference, Second Edition. * @param sysInfo The attributes of the character collection of the CIDFont. */ public PDFToUnicodeCMap(CIDFont cidMetrics, String name, PDFCIDSystemInfo sysInfo) { super(name, sysInfo); cidFont = cidMetrics; } public void fillInPDF(StringBuffer p) { writeCIDInit(p); writeCIDSystemInfo(p); writeVersionTypeName(p); writeCodeSpaceRange(p); writeBFEntries(p); writeWrapUp(p); add(p.toString()); } protected void writeCIDSystemInfo(StringBuffer p) { p.append("/CIDSystemInfo\n"); p.append("<< /Registry (Adobe)\n"); p.append("/Ordering (UCS)\n"); p.append("/Supplement 0\n"); p.append(">> def\n"); } protected void writeVersionTypeName(StringBuffer p) { p.append("/CMapName /Adobe-Identity-UCS def\n"); p.append("/CMapType 2 def\n"); } /** * Writes the character mappings for this font. */ protected void writeBFEntries(StringBuffer p) { if(cidFont == null) return; char[] charArray = cidFont.getCharsUsed(); if(charArray != null) { writeBFCharEntries(p, charArray); writeBFRangeEntries(p, charArray); } } protected void writeBFCharEntries(StringBuffer p, char[] charArray) { int completedEntries = 0; int totalEntries = 0; for (int i = 0; i < charArray.length; i++) { if (! partOfRange(charArray, i)) { totalEntries ++; } } if (totalEntries < 1) { return; } int remainingEntries = totalEntries; /* Limited to 100 entries in each section */ int entriesThisSection = Math.min(remainingEntries, 100); int remainingEntriesThisSection = entriesThisSection; p.append(entriesThisSection + " beginbfchar\n"); for (int i = 0; i < charArray.length; i++) { if (partOfRange(charArray, i)) { continue; } p.append("<" + padHexString(Integer.toHexString(i), 4) + "> "); p.append("<" + padHexString(Integer.toHexString(charArray[i]), 4) + ">\n"); /* Compute the statistics. */ completedEntries ++; remainingEntries = totalEntries - completedEntries; remainingEntriesThisSection --; if (remainingEntriesThisSection < 1) { if (remainingEntries > 0) { p.append("endbfchar\n"); entriesThisSection = Math.min(remainingEntries, 100); remainingEntriesThisSection = entriesThisSection; p.append(entriesThisSection + " beginbfchar\n"); } } } p.append("endbfchar\n"); } protected void writeBFRangeEntries(StringBuffer p, char[] charArray) { int completedEntries = 0; int totalEntries = 0; for (int i = 0; i < charArray.length; i++) { if (startOfRange(charArray, i)) { totalEntries ++; } } if (totalEntries < 1) { return; } int remainingEntries = totalEntries; int entriesThisSection = Math.min(remainingEntries, 100); int remainingEntriesThisSection = entriesThisSection; p.append(entriesThisSection + " beginbfrange\n"); for (int i = 0; i < charArray.length; i++) { if (! startOfRange(charArray, i)) { continue; } p.append("<" + padHexString(Integer.toHexString(i), 4) + "> "); p.append("<" + padHexString(Integer.toHexString (endOfRange(charArray, i)), 4) + "> "); p.append("<" + padHexString(Integer.toHexString(charArray[i]), 4) + ">\n"); /* Compute the statistics. */ completedEntries ++; remainingEntries = totalEntries - completedEntries; if (remainingEntriesThisSection < 1) { if (remainingEntries > 0) { p.append("endbfrange\n"); entriesThisSection = Math.min(remainingEntries, 100); remainingEntriesThisSection = entriesThisSection; p.append(entriesThisSection + " beginbfrange\n"); } } } p.append("endbfrange\n"); } /** * Find the end of the current range. * @param charArray The array which is being tested. * @param startOfRange The index to the array element that is the start of * the range. * @return The index to the element that is the end of the range. */ private int endOfRange(char[] charArray, int startOfRange) { int endOfRange = -1; for (int i = startOfRange; i < charArray.length - 1 && endOfRange < 0; i++) { if (! sameRangeEntryAsNext(charArray, i)) { endOfRange = i; } } return endOfRange; } /** * Determine whether this array element should be part of a bfchar entry or * a bfrange entry. * @param charArray The array to be tested. * @param arrayIndex The index to the array element to be tested. * @return True if this array element should be included in a range. */ private boolean partOfRange(char[] charArray, int arrayIndex) { if (charArray.length < 2) { return false; } if (arrayIndex == 0) { return sameRangeEntryAsNext(charArray, 0); } if (arrayIndex == charArray.length - 1) { return sameRangeEntryAsNext(charArray, arrayIndex - 1); } if (sameRangeEntryAsNext(charArray, arrayIndex - 1)) { return true; } if (sameRangeEntryAsNext(charArray, arrayIndex)) { return true; } return false; } /** * Determine whether two bytes can be written in the same bfrange entry. * @param charArray The array to be tested. * @param firstItem The first of the two items in the array to be tested. * The second item is firstItem + 1. * @return True if both 1) the next item in the array is sequential with * this one, and 2) the first byte of the character in the first position * is equal to the first byte of the character in the second position. */ private boolean sameRangeEntryAsNext(char[] charArray, int firstItem) { if (charArray[firstItem] + 1 != charArray[firstItem + 1]) { return false; } if (firstItem / 256 != (firstItem + 1) / 256) { return false; } return true; } /** * Determine whether this array element should be the start of a bfrange * entry. * @param charArray The array to be tested. * @param arrayIndex The index to the array element to be tested. * @return True if this array element is the beginning of a range. */ private boolean startOfRange(char[] charArray, int arrayIndex) { // Can't be the start of a range if not part of a range. if (! partOfRange(charArray, arrayIndex)) { return false; } // If first element in the array, must be start of a range if (arrayIndex == 0) { return true; } // If last element in the array, cannot be start of a range if (arrayIndex == charArray.length - 1) { return false; } /* * If part of same range as the previous element is, cannot be start * of range. */ if (sameRangeEntryAsNext(charArray, arrayIndex - 1)) { return false; } // Otherwise, this is start of a range. return true; } /** * Prepends the input string with a sufficient number of "0" characters to * get the returned string to be numChars length. * @param input The input string. * @param numChars The minimum characters in the output string. * @return The padded string. */ public static String padHexString(String input, int numChars) { int length = input.length(); if (length >= numChars) { return input; } StringBuffer returnString = new StringBuffer(); for (int i = 1; i <= numChars - length; i++) { returnString.append("0"); } returnString.append(input); return returnString.toString(); } }
src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java
(this file was missing in previous commit) Applied patch from bugzilla 5335, comment 10. Generates a ToUnicode table for embedded CID fonts. Patch provided by Adam Strzelecki, [email protected]. The patch contains code for the FOray project, used with permission (bugzilla 5335 comment #13). git-svn-id: 102839466c3b40dd9c7e25c0a1a6d26afc40150a@454731 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java
(this file was missing in previous commit) Applied patch from bugzilla 5335, comment 10. Generates a ToUnicode table for embedded CID fonts. Patch provided by Adam Strzelecki, [email protected]. The patch contains code for the FOray project, used with permission (bugzilla 5335 comment #13).
<ide><path>rc/java/org/apache/fop/pdf/PDFToUnicodeCMap.java <add>/* <add> * $Id: PDFToUnicodeCMap.java,v 1.3.2.1 2005/12/01 12:00:00 ono Exp $ <add> * ============================================================================ <add> * The Apache Software License, Version 1.1 <add> * ============================================================================ <add> * <add> * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved. <add> * <add> * Redistribution and use in source and binary forms, with or without modifica- <add> * tion, are permitted provided that the following conditions are met: <add> * <add> * 1. Redistributions of source code must retain the above copyright notice, <add> * this list of conditions and the following disclaimer. <add> * <add> * 2. Redistributions in binary form must reproduce the above copyright notice, <add> * this list of conditions and the following disclaimer in the documentation <add> * and/or other materials provided with the distribution. <add> * <add> * 3. The end-user documentation included with the redistribution, if any, must <add> * include the following acknowledgment: "This product includes software <add> * developed by the Apache Software Foundation (http://www.apache.org/)." <add> * Alternately, this acknowledgment may appear in the software itself, if <add> * and wherever such third-party acknowledgments normally appear. <add> * <add> * 4. The names "FOP" and "Apache Software Foundation" must not be used to <add> * endorse or promote products derived from this software without prior <add> * written permission. For written permission, please contact <add> * [email protected]. <add> * <add> * 5. Products derived from this software may not be called "Apache", nor may <add> * "Apache" appear in their name, without prior written permission of the <add> * Apache Software Foundation. <add> * <add> * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, <add> * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND <add> * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE <add> * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, <add> * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- <add> * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS <add> * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON <add> * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT <add> * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF <add> * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <add> * ============================================================================ <add> * <add> * This software consists of voluntary contributions made by many individuals <add> * on behalf of the Apache Software Foundation and was originally created by <add> * James Tauber <[email protected]>. For more information on the Apache <add> * Software Foundation, please see <http://www.apache.org/>. <add> */ <add>package org.apache.fop.pdf; <add> <add>/** <add> * Class representing ToUnicode CMaps. <add> * Here are some documentation resources: <add> * <ul> <add> * <li>PDF Reference, Second Edition, Section 5.6.4, for general information <add> * about CMaps in PDF Files.</li> <add> * <li>PDF Reference, Second Edition, Section 5.9, for specific information <add> * about ToUnicodeCMaps in PDF Files.</li> <add> * <li> <add> * <a href="http://partners.adobe.com/asn/developer/pdfs/tn/5411.ToUnicode.pdf"> <add> * Adobe Technical Note #5411, "ToUnicode Mapping File Tutorial"</a>. <add> * </ul> <add> */ <add>import org.apache.fop.fonts.CIDFont; <add> <add>public class PDFToUnicodeCMap extends PDFCMap { <add> <add> /** <add> * handle to read font <add> */ <add> protected CIDFont cidFont; <add> <add> /** <add> * Constructor. <add> * <add> * @param name One of the registered names found in Table 5.14 in PDF <add> * Reference, Second Edition. <add> * @param sysInfo The attributes of the character collection of the CIDFont. <add> */ <add> public PDFToUnicodeCMap(CIDFont cidMetrics, String name, PDFCIDSystemInfo sysInfo) { <add> super(name, sysInfo); <add> cidFont = cidMetrics; <add> } <add> <add> public void fillInPDF(StringBuffer p) { <add> writeCIDInit(p); <add> writeCIDSystemInfo(p); <add> writeVersionTypeName(p); <add> writeCodeSpaceRange(p); <add> writeBFEntries(p); <add> writeWrapUp(p); <add> add(p.toString()); <add> } <add> <add> protected void writeCIDSystemInfo(StringBuffer p) { <add> p.append("/CIDSystemInfo\n"); <add> p.append("<< /Registry (Adobe)\n"); <add> p.append("/Ordering (UCS)\n"); <add> p.append("/Supplement 0\n"); <add> p.append(">> def\n"); <add> } <add> <add> protected void writeVersionTypeName(StringBuffer p) { <add> p.append("/CMapName /Adobe-Identity-UCS def\n"); <add> p.append("/CMapType 2 def\n"); <add> } <add> <add> /** <add> * Writes the character mappings for this font. <add> */ <add> protected void writeBFEntries(StringBuffer p) { <add> if(cidFont == null) return; <add> <add> char[] charArray = cidFont.getCharsUsed(); <add> <add> if(charArray != null) { <add> writeBFCharEntries(p, charArray); <add> writeBFRangeEntries(p, charArray); <add> } <add> } <add> <add> protected void writeBFCharEntries(StringBuffer p, char[] charArray) { <add> int completedEntries = 0; <add> int totalEntries = 0; <add> for (int i = 0; i < charArray.length; i++) { <add> if (! partOfRange(charArray, i)) { <add> totalEntries ++; <add> } <add> } <add> if (totalEntries < 1) { <add> return; <add> } <add> int remainingEntries = totalEntries; <add> /* Limited to 100 entries in each section */ <add> int entriesThisSection = Math.min(remainingEntries, 100); <add> int remainingEntriesThisSection = entriesThisSection; <add> p.append(entriesThisSection + " beginbfchar\n"); <add> for (int i = 0; i < charArray.length; i++) { <add> if (partOfRange(charArray, i)) { <add> continue; <add> } <add> p.append("<" + padHexString(Integer.toHexString(i), 4) <add> + "> "); <add> p.append("<" + padHexString(Integer.toHexString(charArray[i]), 4) <add> + ">\n"); <add> /* Compute the statistics. */ <add> completedEntries ++; <add> remainingEntries = totalEntries - completedEntries; <add> remainingEntriesThisSection --; <add> if (remainingEntriesThisSection < 1) { <add> if (remainingEntries > 0) { <add> p.append("endbfchar\n"); <add> entriesThisSection = Math.min(remainingEntries, 100); <add> remainingEntriesThisSection = entriesThisSection; <add> p.append(entriesThisSection + " beginbfchar\n"); <add> } <add> } <add> } <add> p.append("endbfchar\n"); <add> } <add> <add> protected void writeBFRangeEntries(StringBuffer p, char[] charArray) { <add> int completedEntries = 0; <add> int totalEntries = 0; <add> for (int i = 0; i < charArray.length; i++) { <add> if (startOfRange(charArray, i)) { <add> totalEntries ++; <add> } <add> } <add> if (totalEntries < 1) { <add> return; <add> } <add> int remainingEntries = totalEntries; <add> int entriesThisSection = Math.min(remainingEntries, 100); <add> int remainingEntriesThisSection = entriesThisSection; <add> p.append(entriesThisSection + " beginbfrange\n"); <add> for (int i = 0; i < charArray.length; i++) { <add> if (! startOfRange(charArray, i)) { <add> continue; <add> } <add> p.append("<" <add> + padHexString(Integer.toHexString(i), 4) <add> + "> "); <add> p.append("<" <add> + padHexString(Integer.toHexString <add> (endOfRange(charArray, i)), 4) <add> + "> "); <add> p.append("<" <add> + padHexString(Integer.toHexString(charArray[i]), 4) <add> + ">\n"); <add> /* Compute the statistics. */ <add> completedEntries ++; <add> remainingEntries = totalEntries - completedEntries; <add> if (remainingEntriesThisSection < 1) { <add> if (remainingEntries > 0) { <add> p.append("endbfrange\n"); <add> entriesThisSection = Math.min(remainingEntries, 100); <add> remainingEntriesThisSection = entriesThisSection; <add> p.append(entriesThisSection + " beginbfrange\n"); <add> } <add> } <add> } <add> p.append("endbfrange\n"); <add> } <add> <add> /** <add> * Find the end of the current range. <add> * @param charArray The array which is being tested. <add> * @param startOfRange The index to the array element that is the start of <add> * the range. <add> * @return The index to the element that is the end of the range. <add> */ <add> private int endOfRange(char[] charArray, int startOfRange) { <add> int endOfRange = -1; <add> for (int i = startOfRange; i < charArray.length - 1 && endOfRange < 0; <add> i++) { <add> if (! sameRangeEntryAsNext(charArray, i)) { <add> endOfRange = i; <add> } <add> } <add> return endOfRange; <add> } <add> <add> /** <add> * Determine whether this array element should be part of a bfchar entry or <add> * a bfrange entry. <add> * @param charArray The array to be tested. <add> * @param arrayIndex The index to the array element to be tested. <add> * @return True if this array element should be included in a range. <add> */ <add> private boolean partOfRange(char[] charArray, int arrayIndex) { <add> if (charArray.length < 2) { <add> return false; <add> } <add> if (arrayIndex == 0) { <add> return sameRangeEntryAsNext(charArray, 0); <add> } <add> if (arrayIndex == charArray.length - 1) { <add> return sameRangeEntryAsNext(charArray, arrayIndex - 1); <add> } <add> if (sameRangeEntryAsNext(charArray, arrayIndex - 1)) { <add> return true; <add> } <add> if (sameRangeEntryAsNext(charArray, arrayIndex)) { <add> return true; <add> } <add> return false; <add> } <add> <add> /** <add> * Determine whether two bytes can be written in the same bfrange entry. <add> * @param charArray The array to be tested. <add> * @param firstItem The first of the two items in the array to be tested. <add> * The second item is firstItem + 1. <add> * @return True if both 1) the next item in the array is sequential with <add> * this one, and 2) the first byte of the character in the first position <add> * is equal to the first byte of the character in the second position. <add> */ <add> private boolean sameRangeEntryAsNext(char[] charArray, int firstItem) { <add> if (charArray[firstItem] + 1 != charArray[firstItem + 1]) { <add> return false; <add> } <add> if (firstItem / 256 != (firstItem + 1) / 256) { <add> return false; <add> } <add> return true; <add> } <add> <add> /** <add> * Determine whether this array element should be the start of a bfrange <add> * entry. <add> * @param charArray The array to be tested. <add> * @param arrayIndex The index to the array element to be tested. <add> * @return True if this array element is the beginning of a range. <add> */ <add> private boolean startOfRange(char[] charArray, int arrayIndex) { <add> // Can't be the start of a range if not part of a range. <add> if (! partOfRange(charArray, arrayIndex)) { <add> return false; <add> } <add> // If first element in the array, must be start of a range <add> if (arrayIndex == 0) { <add> return true; <add> } <add> // If last element in the array, cannot be start of a range <add> if (arrayIndex == charArray.length - 1) { <add> return false; <add> } <add> /* <add> * If part of same range as the previous element is, cannot be start <add> * of range. <add> */ <add> if (sameRangeEntryAsNext(charArray, arrayIndex - 1)) { <add> return false; <add> } <add> // Otherwise, this is start of a range. <add> return true; <add> } <add> <add> /** <add> * Prepends the input string with a sufficient number of "0" characters to <add> * get the returned string to be numChars length. <add> * @param input The input string. <add> * @param numChars The minimum characters in the output string. <add> * @return The padded string. <add> */ <add> public static String padHexString(String input, int numChars) { <add> int length = input.length(); <add> if (length >= numChars) { <add> return input; <add> } <add> StringBuffer returnString = new StringBuffer(); <add> for (int i = 1; i <= numChars - length; i++) { <add> returnString.append("0"); <add> } <add> returnString.append(input); <add> return returnString.toString(); <add> } <add> <add>}
Java
apache-2.0
ba2df2a9957b8eb6dbada7fa4fea08c6ba8f34a3
0
ishan1604/Smack,magnetsystems/message-smack,mar-v-in/Smack,annovanvliet/Smack,lovely3x/Smack,vanitasvitae/smack-omemo,annovanvliet/Smack,unisontech/Smack,ishan1604/Smack,chuangWu/Smack,vito-c/Smack,igniterealtime/Smack,xuIcream/Smack,andrey42/Smack,cjpx00008/Smack,Flowdalic/Smack,TTalkIM/Smack,ishan1604/Smack,igorexax3mal/Smack,opg7371/Smack,Tibo-lg/Smack,ayne/Smack,kkroid/OnechatSmack,xuIcream/Smack,vito-c/Smack,magnetsystems/message-smack,TTalkIM/Smack,igniterealtime/Smack,igorexax3mal/Smack,lovely3x/Smack,opg7371/Smack,igniterealtime/Smack,Tibo-lg/Smack,xuIcream/Smack,hy9902/Smack,u20024804/Smack,Tibo-lg/Smack,vanitasvitae/Smack,esl/Smack,unisontech/Smack,hy9902/Smack,qingsong-xu/Smack,andrey42/Smack,igorexax3mal/Smack,dpr-odoo/Smack,TTalkIM/Smack,mar-v-in/Smack,deeringc/Smack,dpr-odoo/Smack,deeringc/Smack,Flowdalic/Smack,vanitasvitae/Smack,ayne/Smack,andrey42/Smack,opg7371/Smack,dpr-odoo/Smack,vanitasvitae/smack-omemo,ayne/Smack,mar-v-in/Smack,esl/Smack,chuangWu/Smack,cjpx00008/Smack,deeringc/Smack,chuangWu/Smack,esl/Smack,qingsong-xu/Smack,hy9902/Smack,annovanvliet/Smack,u20024804/Smack,Flowdalic/Smack,magnetsystems/message-smack,kkroid/OnechatSmack,vanitasvitae/smack-omemo,cjpx00008/Smack,kkroid/OnechatSmack,vanitasvitae/Smack,u20024804/Smack,qingsong-xu/Smack,lovely3x/Smack,unisontech/Smack
/** * * Copyright 2003-2007 Jive Software. * * 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.jivesoftware.smack.packet; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import org.jivesoftware.smack.util.XmlStringBuilder; /** * Represents XMPP message packets. A message can be one of several types: * * <ul> * <li>Message.Type.NORMAL -- (Default) a normal text message used in email like interface. * <li>Message.Type.CHAT -- a typically short text message used in line-by-line chat interfaces. * <li>Message.Type.GROUP_CHAT -- a chat message sent to a groupchat server for group chats. * <li>Message.Type.HEADLINE -- a text message to be displayed in scrolling marquee displays. * <li>Message.Type.ERROR -- indicates a messaging error. * </ul> * * For each message type, different message fields are typically used as follows: * <p> * <table border="1"> * <tr><td>&nbsp;</td><td colspan="5"><b>Message type</b></td></tr> * <tr><td><i>Field</i></td><td><b>Normal</b></td><td><b>Chat</b></td><td><b>Group Chat</b></td><td><b>Headline</b></td><td><b>XMPPError</b></td></tr> * <tr><td><i>subject</i></td> <td>SHOULD</td><td>SHOULD NOT</td><td>SHOULD NOT</td><td>SHOULD NOT</td><td>SHOULD NOT</td></tr> * <tr><td><i>thread</i></td> <td>OPTIONAL</td><td>SHOULD</td><td>OPTIONAL</td><td>OPTIONAL</td><td>SHOULD NOT</td></tr> * <tr><td><i>body</i></td> <td>SHOULD</td><td>SHOULD</td><td>SHOULD</td><td>SHOULD</td><td>SHOULD NOT</td></tr> * <tr><td><i>error</i></td> <td>MUST NOT</td><td>MUST NOT</td><td>MUST NOT</td><td>MUST NOT</td><td>MUST</td></tr> * </table> * * @author Matt Tucker */ public final class Message extends Packet { public static final String ELEMENT = "message"; public static final String BODY = "body"; private Type type = Type.normal; private String thread = null; private final Set<Subject> subjects = new HashSet<Subject>(); private final Set<Body> bodies = new HashSet<Body>(); /** * Creates a new, "normal" message. */ public Message() { } /** * Creates a new "normal" message to the specified recipient. * * @param to the recipient of the message. */ public Message(String to) { setTo(to); } /** * Creates a new message of the specified type to a recipient. * * @param to the user to send the message to. * @param type the message type. */ public Message(String to, Type type) { this(to); setType(type); } /** * Creates a new message to the specified recipient and with the specified body. * * @param to the user to send the message to. * @param body the body of the message. */ public Message(String to, String body) { this(to); setBody(body); } /** * Returns the type of the message. If no type has been set this method will return {@link * org.jivesoftware.smack.packet.Message.Type#normal}. * * @return the type of the message. */ public Type getType() { return type; } /** * Sets the type of the message. * * @param type the type of the message. * @throws IllegalArgumentException if null is passed in as the type */ public void setType(Type type) { if (type == null) { throw new IllegalArgumentException("Type cannot be null."); } this.type = type; } /** * Returns the default subject of the message, or null if the subject has not been set. * The subject is a short description of message contents. * <p> * The default subject of a message is the subject that corresponds to the message's language. * (see {@link #getLanguage()}) or if no language is set to the applications default * language (see {@link Packet#getDefaultLanguage()}). * * @return the subject of the message. */ public String getSubject() { return getSubject(null); } /** * Returns the subject corresponding to the language. If the language is null, the method result * will be the same as {@link #getSubject()}. Null will be returned if the language does not have * a corresponding subject. * * @param language the language of the subject to return. * @return the subject related to the passed in language. */ public String getSubject(String language) { Subject subject = getMessageSubject(language); return subject == null ? null : subject.subject; } private Subject getMessageSubject(String language) { language = determineLanguage(language); for (Subject subject : subjects) { if (language.equals(subject.language)) { return subject; } } return null; } /** * Returns a set of all subjects in this Message, including the default message subject accessible * from {@link #getSubject()}. * * @return a collection of all subjects in this message. */ public Set<Subject> getSubjects() { return Collections.unmodifiableSet(subjects); } /** * Sets the subject of the message. The subject is a short description of * message contents. * * @param subject the subject of the message. */ public void setSubject(String subject) { if (subject == null) { removeSubject(""); // use empty string because #removeSubject(null) is ambiguous return; } addSubject(null, subject); } /** * Adds a subject with a corresponding language. * * @param language the language of the subject being added. * @param subject the subject being added to the message. * @return the new {@link org.jivesoftware.smack.packet.Message.Subject} * @throws NullPointerException if the subject is null, a null pointer exception is thrown */ public Subject addSubject(String language, String subject) { language = determineLanguage(language); Subject messageSubject = new Subject(language, subject); subjects.add(messageSubject); return messageSubject; } /** * Removes the subject with the given language from the message. * * @param language the language of the subject which is to be removed * @return true if a subject was removed and false if it was not. */ public boolean removeSubject(String language) { language = determineLanguage(language); for (Subject subject : subjects) { if (language.equals(subject.language)) { return subjects.remove(subject); } } return false; } /** * Removes the subject from the message and returns true if the subject was removed. * * @param subject the subject being removed from the message. * @return true if the subject was successfully removed and false if it was not. */ public boolean removeSubject(Subject subject) { return subjects.remove(subject); } /** * Returns all the languages being used for the subjects, not including the default subject. * * @return the languages being used for the subjects. */ public List<String> getSubjectLanguages() { Subject defaultSubject = getMessageSubject(null); List<String> languages = new ArrayList<String>(); for (Subject subject : subjects) { if (!subject.equals(defaultSubject)) { languages.add(subject.language); } } return Collections.unmodifiableList(languages); } /** * Returns the default body of the message, or null if the body has not been set. The body * is the main message contents. * <p> * The default body of a message is the body that corresponds to the message's language. * (see {@link #getLanguage()}) or if no language is set to the applications default * language (see {@link Packet#getDefaultLanguage()}). * * @return the body of the message. */ public String getBody() { return getBody(null); } /** * Returns the body corresponding to the language. If the language is null, the method result * will be the same as {@link #getBody()}. Null will be returned if the language does not have * a corresponding body. * * @param language the language of the body to return. * @return the body related to the passed in language. * @since 3.0.2 */ public String getBody(String language) { Body body = getMessageBody(language); return body == null ? null : body.message; } private Body getMessageBody(String language) { language = determineLanguage(language); for (Body body : bodies) { if (language.equals(body.language)) { return body; } } return null; } /** * Returns a set of all bodies in this Message, including the default message body accessible * from {@link #getBody()}. * * @return a collection of all bodies in this Message. * @since 3.0.2 */ public Set<Body> getBodies() { return Collections.unmodifiableSet(bodies); } /** * Sets the body of the message. The body is the main message contents. * * @param body the body of the message. */ public void setBody(String body) { if (body == null) { removeBody(""); // use empty string because #removeBody(null) is ambiguous return; } addBody(null, body); } /** * Adds a body with a corresponding language. * * @param language the language of the body being added. * @param body the body being added to the message. * @return the new {@link org.jivesoftware.smack.packet.Message.Body} * @throws NullPointerException if the body is null, a null pointer exception is thrown * @since 3.0.2 */ public Body addBody(String language, String body) { language = determineLanguage(language); Body messageBody = new Body(language, body); bodies.add(messageBody); return messageBody; } /** * Removes the body with the given language from the message. * * @param language the language of the body which is to be removed * @return true if a body was removed and false if it was not. */ public boolean removeBody(String language) { language = determineLanguage(language); for (Body body : bodies) { if (language.equals(body.language)) { return bodies.remove(body); } } return false; } /** * Removes the body from the message and returns true if the body was removed. * * @param body the body being removed from the message. * @return true if the body was successfully removed and false if it was not. * @since 3.0.2 */ public boolean removeBody(Body body) { return bodies.remove(body); } /** * Returns all the languages being used for the bodies, not including the default body. * * @return the languages being used for the bodies. * @since 3.0.2 */ public List<String> getBodyLanguages() { Body defaultBody = getMessageBody(null); List<String> languages = new ArrayList<String>(); for (Body body : bodies) { if (!body.equals(defaultBody)) { languages.add(body.language); } } return Collections.unmodifiableList(languages); } /** * Returns the thread id of the message, which is a unique identifier for a sequence * of "chat" messages. If no thread id is set, <tt>null</tt> will be returned. * * @return the thread id of the message, or <tt>null</tt> if it doesn't exist. */ public String getThread() { return thread; } /** * Sets the thread id of the message, which is a unique identifier for a sequence * of "chat" messages. * * @param thread the thread id of the message. */ public void setThread(String thread) { this.thread = thread; } private String determineLanguage(String language) { // empty string is passed by #setSubject() and #setBody() and is the same as null language = "".equals(language) ? null : language; // if given language is null check if message language is set if (language == null && this.language != null) { return this.language; } else if (language == null) { return getDefaultLanguage(); } else { return language; } } @Override public XmlStringBuilder toXML() { XmlStringBuilder buf = new XmlStringBuilder(); buf.halfOpenElement(ELEMENT); addCommonAttributes(buf); if (type != Type.normal) { buf.attribute("type", type); } buf.rightAngleBracket(); // Add the subject in the default language Subject defaultSubject = getMessageSubject(null); if (defaultSubject != null) { buf.element("subject", defaultSubject.subject); } // Add the subject in other languages for (Subject subject : getSubjects()) { // Skip the default language if(subject.equals(defaultSubject)) continue; buf.halfOpenElement("subject").xmllangAttribute(subject.language).rightAngleBracket(); buf.escape(subject.subject); buf.closeElement("subject"); } // Add the body in the default language Body defaultBody = getMessageBody(null); if (defaultBody != null) { buf.element("body", defaultBody.message); } // Add the bodies in other languages for (Body body : getBodies()) { // Skip the default language if(body.equals(defaultBody)) continue; buf.halfOpenElement(BODY).xmllangAttribute(body.getLanguage()).rightAngleBracket(); buf.escape(body.getMessage()); buf.closeElement(BODY); } buf.optElement("thread", thread); // Append the error subpacket if the message type is an error. if (type == Type.error) { appendErrorIfExists(buf); } // Add packet extensions, if any are defined. buf.append(getExtensionsXML()); buf.closeElement(ELEMENT); return buf; } /** * Represents a message subject, its language and the content of the subject. */ public static class Subject { private final String subject; private final String language; private Subject(String language, String subject) { if (language == null) { throw new NullPointerException("Language cannot be null."); } if (subject == null) { throw new NullPointerException("Subject cannot be null."); } this.language = language; this.subject = subject; } /** * Returns the language of this message subject. * * @return the language of this message subject. */ public String getLanguage() { return language; } /** * Returns the subject content. * * @return the content of the subject. */ public String getSubject() { return subject; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.language.hashCode(); result = prime * result + this.subject.hashCode(); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Subject other = (Subject) obj; // simplified comparison because language and subject are always set return this.language.equals(other.language) && this.subject.equals(other.subject); } } /** * Represents a message body, its language and the content of the message. */ public static class Body { private final String message; private final String language; private Body(String language, String message) { if (language == null) { throw new NullPointerException("Language cannot be null."); } if (message == null) { throw new NullPointerException("Message cannot be null."); } this.language = language; this.message = message; } /** * Returns the language of this message body. * * @return the language of this message body. */ public String getLanguage() { return language; } /** * Returns the message content. * * @return the content of the message. */ public String getMessage() { return message; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.language.hashCode(); result = prime * result + this.message.hashCode(); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Body other = (Body) obj; // simplified comparison because language and message are always set return this.language.equals(other.language) && this.message.equals(other.message); } } /** * Represents the type of a message. */ public enum Type { /** * (Default) a normal text message used in email like interface. */ normal, /** * Typically short text message used in line-by-line chat interfaces. */ chat, /** * Chat message sent to a groupchat server for group chats. */ groupchat, /** * Text message to be displayed in scrolling marquee displays. */ headline, /** * indicates a messaging error. */ error; /** * Converts a String into the corresponding types. Valid String values that can be converted * to types are: "normal", "chat", "groupchat", "headline" and "error". * * @param string the String value to covert. * @return the corresponding Type. * @throws IllegalArgumentException when not able to parse the string parameter * @throws NullPointerException if the string is null */ public static Type fromString(String string) { return Type.valueOf(string.toLowerCase(Locale.US)); } } }
smack-core/src/main/java/org/jivesoftware/smack/packet/Message.java
/** * * Copyright 2003-2007 Jive Software. * * 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.jivesoftware.smack.packet; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import org.jivesoftware.smack.util.XmlStringBuilder; /** * Represents XMPP message packets. A message can be one of several types: * * <ul> * <li>Message.Type.NORMAL -- (Default) a normal text message used in email like interface. * <li>Message.Type.CHAT -- a typically short text message used in line-by-line chat interfaces. * <li>Message.Type.GROUP_CHAT -- a chat message sent to a groupchat server for group chats. * <li>Message.Type.HEADLINE -- a text message to be displayed in scrolling marquee displays. * <li>Message.Type.ERROR -- indicates a messaging error. * </ul> * * For each message type, different message fields are typically used as follows: * <p> * <table border="1"> * <tr><td>&nbsp;</td><td colspan="5"><b>Message type</b></td></tr> * <tr><td><i>Field</i></td><td><b>Normal</b></td><td><b>Chat</b></td><td><b>Group Chat</b></td><td><b>Headline</b></td><td><b>XMPPError</b></td></tr> * <tr><td><i>subject</i></td> <td>SHOULD</td><td>SHOULD NOT</td><td>SHOULD NOT</td><td>SHOULD NOT</td><td>SHOULD NOT</td></tr> * <tr><td><i>thread</i></td> <td>OPTIONAL</td><td>SHOULD</td><td>OPTIONAL</td><td>OPTIONAL</td><td>SHOULD NOT</td></tr> * <tr><td><i>body</i></td> <td>SHOULD</td><td>SHOULD</td><td>SHOULD</td><td>SHOULD</td><td>SHOULD NOT</td></tr> * <tr><td><i>error</i></td> <td>MUST NOT</td><td>MUST NOT</td><td>MUST NOT</td><td>MUST NOT</td><td>MUST</td></tr> * </table> * * @author Matt Tucker */ public final class Message extends Packet { public static final String ELEMENT = "message"; public static final String BODY = "body"; private Type type = Type.normal; private String thread = null; private final Set<Subject> subjects = new HashSet<Subject>(); private final Set<Body> bodies = new HashSet<Body>(); /** * Creates a new, "normal" message. */ public Message() { } /** * Creates a new "normal" message to the specified recipient. * * @param to the recipient of the message. */ public Message(String to) { setTo(to); } /** * Creates a new message of the specified type to a recipient. * * @param to the user to send the message to. * @param type the message type. */ public Message(String to, Type type) { this(to); setType(type); } /** * Returns the type of the message. If no type has been set this method will return {@link * org.jivesoftware.smack.packet.Message.Type#normal}. * * @return the type of the message. */ public Type getType() { return type; } /** * Sets the type of the message. * * @param type the type of the message. * @throws IllegalArgumentException if null is passed in as the type */ public void setType(Type type) { if (type == null) { throw new IllegalArgumentException("Type cannot be null."); } this.type = type; } /** * Returns the default subject of the message, or null if the subject has not been set. * The subject is a short description of message contents. * <p> * The default subject of a message is the subject that corresponds to the message's language. * (see {@link #getLanguage()}) or if no language is set to the applications default * language (see {@link Packet#getDefaultLanguage()}). * * @return the subject of the message. */ public String getSubject() { return getSubject(null); } /** * Returns the subject corresponding to the language. If the language is null, the method result * will be the same as {@link #getSubject()}. Null will be returned if the language does not have * a corresponding subject. * * @param language the language of the subject to return. * @return the subject related to the passed in language. */ public String getSubject(String language) { Subject subject = getMessageSubject(language); return subject == null ? null : subject.subject; } private Subject getMessageSubject(String language) { language = determineLanguage(language); for (Subject subject : subjects) { if (language.equals(subject.language)) { return subject; } } return null; } /** * Returns a set of all subjects in this Message, including the default message subject accessible * from {@link #getSubject()}. * * @return a collection of all subjects in this message. */ public Set<Subject> getSubjects() { return Collections.unmodifiableSet(subjects); } /** * Sets the subject of the message. The subject is a short description of * message contents. * * @param subject the subject of the message. */ public void setSubject(String subject) { if (subject == null) { removeSubject(""); // use empty string because #removeSubject(null) is ambiguous return; } addSubject(null, subject); } /** * Adds a subject with a corresponding language. * * @param language the language of the subject being added. * @param subject the subject being added to the message. * @return the new {@link org.jivesoftware.smack.packet.Message.Subject} * @throws NullPointerException if the subject is null, a null pointer exception is thrown */ public Subject addSubject(String language, String subject) { language = determineLanguage(language); Subject messageSubject = new Subject(language, subject); subjects.add(messageSubject); return messageSubject; } /** * Removes the subject with the given language from the message. * * @param language the language of the subject which is to be removed * @return true if a subject was removed and false if it was not. */ public boolean removeSubject(String language) { language = determineLanguage(language); for (Subject subject : subjects) { if (language.equals(subject.language)) { return subjects.remove(subject); } } return false; } /** * Removes the subject from the message and returns true if the subject was removed. * * @param subject the subject being removed from the message. * @return true if the subject was successfully removed and false if it was not. */ public boolean removeSubject(Subject subject) { return subjects.remove(subject); } /** * Returns all the languages being used for the subjects, not including the default subject. * * @return the languages being used for the subjects. */ public List<String> getSubjectLanguages() { Subject defaultSubject = getMessageSubject(null); List<String> languages = new ArrayList<String>(); for (Subject subject : subjects) { if (!subject.equals(defaultSubject)) { languages.add(subject.language); } } return Collections.unmodifiableList(languages); } /** * Returns the default body of the message, or null if the body has not been set. The body * is the main message contents. * <p> * The default body of a message is the body that corresponds to the message's language. * (see {@link #getLanguage()}) or if no language is set to the applications default * language (see {@link Packet#getDefaultLanguage()}). * * @return the body of the message. */ public String getBody() { return getBody(null); } /** * Returns the body corresponding to the language. If the language is null, the method result * will be the same as {@link #getBody()}. Null will be returned if the language does not have * a corresponding body. * * @param language the language of the body to return. * @return the body related to the passed in language. * @since 3.0.2 */ public String getBody(String language) { Body body = getMessageBody(language); return body == null ? null : body.message; } private Body getMessageBody(String language) { language = determineLanguage(language); for (Body body : bodies) { if (language.equals(body.language)) { return body; } } return null; } /** * Returns a set of all bodies in this Message, including the default message body accessible * from {@link #getBody()}. * * @return a collection of all bodies in this Message. * @since 3.0.2 */ public Set<Body> getBodies() { return Collections.unmodifiableSet(bodies); } /** * Sets the body of the message. The body is the main message contents. * * @param body the body of the message. */ public void setBody(String body) { if (body == null) { removeBody(""); // use empty string because #removeBody(null) is ambiguous return; } addBody(null, body); } /** * Adds a body with a corresponding language. * * @param language the language of the body being added. * @param body the body being added to the message. * @return the new {@link org.jivesoftware.smack.packet.Message.Body} * @throws NullPointerException if the body is null, a null pointer exception is thrown * @since 3.0.2 */ public Body addBody(String language, String body) { language = determineLanguage(language); Body messageBody = new Body(language, body); bodies.add(messageBody); return messageBody; } /** * Removes the body with the given language from the message. * * @param language the language of the body which is to be removed * @return true if a body was removed and false if it was not. */ public boolean removeBody(String language) { language = determineLanguage(language); for (Body body : bodies) { if (language.equals(body.language)) { return bodies.remove(body); } } return false; } /** * Removes the body from the message and returns true if the body was removed. * * @param body the body being removed from the message. * @return true if the body was successfully removed and false if it was not. * @since 3.0.2 */ public boolean removeBody(Body body) { return bodies.remove(body); } /** * Returns all the languages being used for the bodies, not including the default body. * * @return the languages being used for the bodies. * @since 3.0.2 */ public List<String> getBodyLanguages() { Body defaultBody = getMessageBody(null); List<String> languages = new ArrayList<String>(); for (Body body : bodies) { if (!body.equals(defaultBody)) { languages.add(body.language); } } return Collections.unmodifiableList(languages); } /** * Returns the thread id of the message, which is a unique identifier for a sequence * of "chat" messages. If no thread id is set, <tt>null</tt> will be returned. * * @return the thread id of the message, or <tt>null</tt> if it doesn't exist. */ public String getThread() { return thread; } /** * Sets the thread id of the message, which is a unique identifier for a sequence * of "chat" messages. * * @param thread the thread id of the message. */ public void setThread(String thread) { this.thread = thread; } private String determineLanguage(String language) { // empty string is passed by #setSubject() and #setBody() and is the same as null language = "".equals(language) ? null : language; // if given language is null check if message language is set if (language == null && this.language != null) { return this.language; } else if (language == null) { return getDefaultLanguage(); } else { return language; } } @Override public XmlStringBuilder toXML() { XmlStringBuilder buf = new XmlStringBuilder(); buf.halfOpenElement(ELEMENT); addCommonAttributes(buf); if (type != Type.normal) { buf.attribute("type", type); } buf.rightAngleBracket(); // Add the subject in the default language Subject defaultSubject = getMessageSubject(null); if (defaultSubject != null) { buf.element("subject", defaultSubject.subject); } // Add the subject in other languages for (Subject subject : getSubjects()) { // Skip the default language if(subject.equals(defaultSubject)) continue; buf.halfOpenElement("subject").xmllangAttribute(subject.language).rightAngleBracket(); buf.escape(subject.subject); buf.closeElement("subject"); } // Add the body in the default language Body defaultBody = getMessageBody(null); if (defaultBody != null) { buf.element("body", defaultBody.message); } // Add the bodies in other languages for (Body body : getBodies()) { // Skip the default language if(body.equals(defaultBody)) continue; buf.halfOpenElement(BODY).xmllangAttribute(body.getLanguage()).rightAngleBracket(); buf.escape(body.getMessage()); buf.closeElement(BODY); } buf.optElement("thread", thread); // Append the error subpacket if the message type is an error. if (type == Type.error) { appendErrorIfExists(buf); } // Add packet extensions, if any are defined. buf.append(getExtensionsXML()); buf.closeElement(ELEMENT); return buf; } /** * Represents a message subject, its language and the content of the subject. */ public static class Subject { private final String subject; private final String language; private Subject(String language, String subject) { if (language == null) { throw new NullPointerException("Language cannot be null."); } if (subject == null) { throw new NullPointerException("Subject cannot be null."); } this.language = language; this.subject = subject; } /** * Returns the language of this message subject. * * @return the language of this message subject. */ public String getLanguage() { return language; } /** * Returns the subject content. * * @return the content of the subject. */ public String getSubject() { return subject; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.language.hashCode(); result = prime * result + this.subject.hashCode(); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Subject other = (Subject) obj; // simplified comparison because language and subject are always set return this.language.equals(other.language) && this.subject.equals(other.subject); } } /** * Represents a message body, its language and the content of the message. */ public static class Body { private final String message; private final String language; private Body(String language, String message) { if (language == null) { throw new NullPointerException("Language cannot be null."); } if (message == null) { throw new NullPointerException("Message cannot be null."); } this.language = language; this.message = message; } /** * Returns the language of this message body. * * @return the language of this message body. */ public String getLanguage() { return language; } /** * Returns the message content. * * @return the content of the message. */ public String getMessage() { return message; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + this.language.hashCode(); result = prime * result + this.message.hashCode(); return result; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Body other = (Body) obj; // simplified comparison because language and message are always set return this.language.equals(other.language) && this.message.equals(other.message); } } /** * Represents the type of a message. */ public enum Type { /** * (Default) a normal text message used in email like interface. */ normal, /** * Typically short text message used in line-by-line chat interfaces. */ chat, /** * Chat message sent to a groupchat server for group chats. */ groupchat, /** * Text message to be displayed in scrolling marquee displays. */ headline, /** * indicates a messaging error. */ error; /** * Converts a String into the corresponding types. Valid String values that can be converted * to types are: "normal", "chat", "groupchat", "headline" and "error". * * @param string the String value to covert. * @return the corresponding Type. * @throws IllegalArgumentException when not able to parse the string parameter * @throws NullPointerException if the string is null */ public static Type fromString(String string) { return Type.valueOf(string.toLowerCase(Locale.US)); } } }
Add Message(String,String)
smack-core/src/main/java/org/jivesoftware/smack/packet/Message.java
Add Message(String,String)
<ide><path>mack-core/src/main/java/org/jivesoftware/smack/packet/Message.java <ide> } <ide> <ide> /** <add> * Creates a new message to the specified recipient and with the specified body. <add> * <add> * @param to the user to send the message to. <add> * @param body the body of the message. <add> */ <add> public Message(String to, String body) { <add> this(to); <add> setBody(body); <add> } <add> <add> /** <ide> * Returns the type of the message. If no type has been set this method will return {@link <ide> * org.jivesoftware.smack.packet.Message.Type#normal}. <ide> *
JavaScript
mpl-2.0
301e9955281b97d67e84ffea22b13c8cdb725037
0
ThosRTanner/inforss,ThosRTanner/inforss
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is infoRSS. * * The Initial Developer of the Original Code is * Didier Ernotte <[email protected]>. * Portions created by the Initial Developer are Copyright (C) 2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Didier Ernotte <[email protected]>. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ //---------------------------------------------------------------------------- // inforssXMLRepository // Author : Didier Ernotte 2005 // Inforss extension //---------------------------------------------------------------------------- /* globals inforssDebug, inforssTraceIn, inforssTraceOut */ Components.utils.import("chrome://inforss/content/modules/inforssDebug.jsm"); /* globals inforssGetResourceFile */ Components.utils.import("chrome://inforss/content/modules/inforssVersion.jsm"); //These should be in another module. Or at least not exported */ /* exported LocalFile */ const LocalFile = Components.Constructor("@mozilla.org/file/local;1", "nsILocalFile", "initWithPath"); /* exported FileInputStream */ const FileInputStream = Components.Constructor("@mozilla.org/network/file-input-stream;1", "nsIFileInputStream", "init"); /* exported ScriptableInputStream */ const ScriptableInputStream = Components.Constructor("@mozilla.org/scriptableinputstream;1", "nsIScriptableInputStream", "init"); //FIXME This is a service /* exported UTF8Converter */ const UTF8Converter = Components.Constructor("@mozilla.org/intl/utf8converterservice;1", "nsIUTF8ConverterService"); /* exported FileOutputStream */ const FileOutputStream = Components.Constructor("@mozilla.org/network/file-output-stream;1", "nsIFileOutputStream", "init"); const Properties = Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIProperties); const profile_dir = Properties.get("ProfD", Components.interfaces.nsIFile); const LoginManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager); const LoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Components.interfaces.nsILoginInfo, "init"); //FIXME Turn this into a module, once we have all access to RSSList in here //Note that inforssOption should have its own instance which is then copied //once we do an apply. Jury is out on whether OPML import/export should work on //the global/local instance... /* global inforssFindIcon */ //To make this a module, will need to construct DOMParser //https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIDOMParser /* exported MODE_APPEND */ const MODE_APPEND = 0; /* exported MODE_REPLACE */ const MODE_REPLACE = 1; //FIXME Should be hooked off profile_dir. The main problem is the rename below const INFORSS_REPOSITORY = "inforss.xml"; /* exported INFORSS_DEFAULT_ICO */ const INFORSS_DEFAULT_ICO = "chrome://inforss/skin/default.ico"; /* exported RSSList */ var RSSList = null; //---------------------------------------------------------------------------- const opml_attributes = [ "acknowledgeDate", "activity", "browserHistory", "filter", "filterCaseSensitive", "filterPolicy", "group", "groupAssociated", "htmlDirection", "htmlTest", "icon", "lengthItem", "nbItem", "playPodcast", "refresh", "regexp", "regexpCategory", "regexpDescription", "regexpLink", "regexpPubDate", "regexpStartAfter", "regexpStopBefore", "regexpTitle", "selected", "title", "type", "user" ]; const INFORSS_BACKUP = "inforss_xml.backup"; //use XML_Repository.<name> = xxxx for static properties/functions function XML_Repository() { return this; } XML_Repository.prototype = { //---------------------------------------------------------------------------- //FIXME THis is only used in one place and I'm not sure if it should be used //there at all. is_valid() { return RSSList != null; }, //---------------------------------------------------------------------------- // Get all the feeds / groups we have configured // Returns a dynamic NodeList get_all() { return RSSList.getElementsByTagName("RSS"); }, // Gets the configured groups // Returns a static NodeList get_groups() { return RSSList.querySelectorAll("RSS[type=group]"); }, // Gets the configured feeds // Returns a static NodeList get_feeds() { return RSSList.querySelectorAll("RSS:not([type=group])"); }, //Get the full name of the configuration file. get_filepath() { const path = profile_dir.clone(); path.append(INFORSS_REPOSITORY); return path; }, //---------------------------------------------------------------------------- //Debug settings (warning: also accessed via about:config) //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //Display debug messages in a popup debug_display_popup() { return RSSList.firstChild.getAttribute("debug") == "true"; }, //---------------------------------------------------------------------------- //Display debug messages on the status bar debug_to_status_bar() { return RSSList.firstChild.getAttribute("statusbar") == "true"; }, //---------------------------------------------------------------------------- //Display debug messages in the browser log debug_to_browser_log() { return RSSList.firstChild.getAttribute("log") == "true"; }, //---------------------------------------------------------------------------- //Default values. //Note that these are given to the feed at the time the feed is created. If //you change the default, you'll only change feeds created in the future. //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //Default number of headlines to show //FIXME Using 9999 for 'unconstrained' is dubious style feeds_default_max_num_headlines() { return parseInt(RSSList.firstChild.getAttribute("defaultNbItem"), 10); }, //---------------------------------------------------------------------------- //Default max headline length to show (longer headlines will be truncated) //FIXME Using 9999 for 'unconstrained' is dubious style feeds_default_max_headline_length() { return parseInt(RSSList.firstChild.getAttribute("defaultLenghtItem"), 10); }, //---------------------------------------------------------------------------- //Default refresh time (time between polls) feeds_default_refresh_time() { return parseInt(RSSList.firstChild.getAttribute("refresh"), 10); }, //---------------------------------------------------------------------------- //Default number of days to retain a headline in the RDF file feeds_default_history_purge_days() { return parseInt(RSSList.firstChild.getAttribute("defaultPurgeHistory"), 10); }, //---------------------------------------------------------------------------- //Default state for playing podcast feed_defaults_play_podcast() { return RSSList.firstChild.getAttribute("defaultPlayPodcast") == "true"; }, //---------------------------------------------------------------------------- //Default switch for whether or not to use browser history to determine if //headline has been read feed_defaults_use_browser_history() { return RSSList.firstChild.getAttribute("defaultBrowserHistory") == "true"; }, //---------------------------------------------------------------------------- //Default icon for a group feeds_default_group_icon() { return RSSList.firstChild.getAttribute("defaultGroupIcon"); }, //---------------------------------------------------------------------------- //Default location to which to save podcasts (if empty, they don't get saved) feeds_default_podcast_location() { return RSSList.firstChild.getAttribute("savePodcastLocation"); }, //---------------------------------------------------------------------------- //Main menu should include an 'add' entry for each feed found on the current page menu_includes_page_feeds() { return RSSList.firstChild.getAttribute("currentfeed") == "true"; }, //---------------------------------------------------------------------------- //Main menu should include an 'add' entry for all livemarks menu_includes_livemarks() { return RSSList.firstChild.getAttribute("livemark") == "true"; }, //---------------------------------------------------------------------------- //Main menu should include an 'add' entry for the current clipboard contents //(if it looks something like a feed at any rate) menu_includes_clipboard() { return RSSList.firstChild.getAttribute("clipboard") == "true"; }, //---------------------------------------------------------------------------- //Sorting style for main menu. May be asc, des or off. menu_sorting_style() { return RSSList.firstChild.getAttribute("sortedMenu"); }, //---------------------------------------------------------------------------- //Main menu should show feeds that are part of a group. If this is off, it wont //show feeds that are in a group (or groups). menu_show_feeds_from_groups() { return RSSList.firstChild.getAttribute("includeAssociated") == "true"; }, //---------------------------------------------------------------------------- //If on, each feed will have a submenu showing the "latest" (i.e. first in the //XML) 20 headlines. menu_show_headlines_in_submenu() { return RSSList.firstChild.getAttribute("submenu") == "true"; }, //---------------------------------------------------------------------------- //main icon should show the icon for the current feed (rather than the globe) icon_shows_current_feed() { return RSSList.firstChild.getAttribute("synchronizeIcon") == "true"; }, //---------------------------------------------------------------------------- //main icon should flash when there is activity (i.e. it reads a feed xml). icon_flashes_on_activity() { return RSSList.firstChild.getAttribute("flashingIcon") == "true"; }, //---------------------------------------------------------------------------- //Shows or collapses the ticker display completely. This only really makes //sense if you have the display in the status bar. headline_bar_enabled() { return RSSList.firstChild.getAttribute("switch") == "true"; }, //---------------------------------------------------------------------------- //Hide headlines once they've been viewed hide_viewed_headlines() { return RSSList.firstChild.getAttribute("hideViewed") == "true"; }, //---------------------------------------------------------------------------- //Hide headlines that are considered 'old' (i.e. have been displayed for //a period of time, but not read) hide_old_headlines() { return RSSList.firstChild.getAttribute("hideOld") == "true"; }, //---------------------------------------------------------------------------- //Remember displayed headlines and state remember_headlines() { return RSSList.firstChild.getAttribute("hideHistory") == "true"; }, //---------------------------------------------------------------------------- //Show a toast (on my windows 10 it appears at the bottom right) on a new //headline show_toast_on_new_headline() { return RSSList.firstChild.getAttribute("popupMessage") == "true"; }, //---------------------------------------------------------------------------- //Plays a sound ('beep' on linux, 'Notify' on windows) on a new headline play_sound_on_new_headline() { return RSSList.firstChild.getAttribute("playSound") == "true"; }, //---------------------------------------------------------------------------- //style of tooltip on headline, can be "description", "title", "allInfo" or //"article" (which most of code treats as default) //FIXME Replace this with appropriate properties. (see below) headline_tooltip_style() { return RSSList.firstChild.getAttribute("tooltip"); }, //---------------------------------------------------------------------------- //When clicking on a headline, article loads in get new_default_tab() { return 0; }, get new_background_tab() { return 1; }, get new_foreground_tab() { return 2; }, get new_window() { return 3; }, get current_tab() { return 4; }, headline_action_on_click() { return parseInt(RSSList.firstChild.getAttribute("clickHeadline"), 10); }, //---------------------------------------------------------------------------- //This is pretty much completely the opposite of a timeslice. It returns the //delay between processing individual headlines (in milliseconds) headline_processing_backoff() { return parseInt(RSSList.firstChild.getAttribute("timeslice"), 10); }, //---------------------------------------------------------------------------- //Get the location of the headline bar. get in_status_bar() { return 0; }, get at_top() { return 1; }, get at_bottom() { return 2; }, get headline_bar_location() { return RSSList.firstChild.getAttribute("separateLine") == "false" ? this.in_status_bar : RSSList.firstChild.getAttribute("linePosition") == "top" ? this.at_top: this.at_bottom; }, set headline_bar_location(loc) { switch (loc) { case this.in_status_bar: RSSList.firstChild.setAttribute("separateLine", "false"); break; case this.at_top: RSSList.firstChild.setAttribute("separateLine", "true"); RSSList.firstChild.setAttribute("linePosition", "top"); break; case this.at_bottom: RSSList.firstChild.setAttribute("separateLine", "true"); RSSList.firstChild.setAttribute("linePosition", "bottom"); break; } }, //---------------------------------------------------------------------------- //If the headline bar is collapsed, it only uses enough of the status bar to //display necessary headlines. //FIXME should be grayed out if not using the status bar get headline_bar_collapsed() { return RSSList.firstChild.getAttribute("collapseBar") == "true"; }, set headline_bar_collapsed(state) { RSSList.firstChild.setAttribute("collapseBar", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //How much the mouse wheel will scroll. //'pixel' scrolls by the scrolling increment //'pixels' appears to scroll 10 'pixels' at a time. get by_pixel() { return 0; }, get by_pixels() { return 1; }, get by_headline() { return 2; }, get headline_bar_mousewheel_scroll() { const type = RSSList.firstChild.getAttribute("mouseWheelScroll"); return type == "pixel" ? this.by_pixel : type == "pixels" ? this.by_pixels : this.by_headline; }, set headline_bar_mousewheel_scroll(scroll) { RSSList.firstChild.setAttribute("mouseWheelScroll", (() => { switch (scroll) { case this.by_pixel: return "pixel"; case this.by_pixels: return "pixels"; case this.by_headline: return "headline"; } })()); }, //---------------------------------------------------------------------------- //Indicate how headlines appear/disappear //For fade, instead of scrolling, one headline is displayed, and it fades //into the next one. Useful for status bar. get static_display() { return 0; }, get scrolling_display() { return 1; }, get fade_into_next() { return 2; }, get headline_bar_scroll_style() { return parseInt(RSSList.firstChild.getAttribute("scrolling"), 10); }, set headline_bar_scroll_style(style) { RSSList.firstChild.setAttribute("scrolling", style); }, //---------------------------------------------------------------------------- //Scrolling speed / fade rate from 1 (slow) to 30 (fast) //Not meaningful for static //FIXME Should be disabled on option screen when not appropriate //FIXME Description should change? get headline_bar_scroll_speed() { return parseInt(RSSList.firstChild.getAttribute("scrollingspeed"), 10); }, set headline_bar_scroll_speed(speed) { RSSList.firstChild.setAttribute("scrollingspeed", speed); }, //---------------------------------------------------------------------------- //The number of pixels a headline is scrolled by, from 1 to 3. //Only meaningful for scrolling, not static or fade //FIXME Should be disabled on option screen when not appropriate get headline_bar_scroll_increment() { return parseInt(RSSList.firstChild.getAttribute("scrollingIncrement"), 10); }, set headline_bar_scroll_increment(increment) { RSSList.firstChild.setAttribute("scrollingIncrement", increment); }, //---------------------------------------------------------------------------- //Stop scrolling when mouse is over headline. I presume this stops fading as //well. //FIXME Should be disabled on option screen when not appropriate get headline_bar_stop_on_mouseover() { return RSSList.firstChild.getAttribute("stopscrolling") == "true"; }, set headline_bar_stop_on_mouseover(state) { RSSList.firstChild.setAttribute("stopscrolling", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Get the scrolling direction (rtl/ltr) //FIXME Should be disabled on option screen when not appropriate //FIXME Shouldn't be raw ascii get headline_bar_scrolling_direction() { return RSSList.firstChild.getAttribute("scrollingdirection"); }, set headline_bar_scrolling_direction(dir) { RSSList.firstChild.setAttribute("scrollingdirection", dir); }, //---------------------------------------------------------------------------- //Cycle between feeds on the headline bar //FIXME If not enabled, the left/right icons shouldn't appear in the headline //bar get headline_bar_cycle_feeds() { return RSSList.firstChild.getAttribute("cycling") == "true"; }, set headline_bar_cycle_feeds(state) { RSSList.firstChild.setAttribute("cycling", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Interval between cycling feeds (in minutes) //FIXME Shouldn't be enabled if not cycling get headline_bar_cycle_interval() { return parseInt(RSSList.firstChild.getAttribute("cyclingDelay"), 10); }, set headline_bar_cycle_interval(interval) { RSSList.firstChild.setAttribute("cyclingDelay", interval); }, //---------------------------------------------------------------------------- //Get what to display on the next cycling, either "next" or "random" //FIXME Shouldn't be enabled if not cycling //FIXME Replace this with appropriate properties (or boolean) get headline_bar_cycle_type() { return RSSList.firstChild.getAttribute("nextFeed"); }, set headline_bar_cycle_type(type) { RSSList.firstChild.setAttribute("nextFeed", type); }, //---------------------------------------------------------------------------- //Cycle feeds in group when set //FIXME Shouldn't be enabled if not cycling get headline_bar_cycle_in_group() { return RSSList.firstChild.getAttribute("cycleWithinGroup") == "true"; }, set headline_bar_cycle_in_group(state) { RSSList.firstChild.setAttribute("cycleWithinGroup", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to mark all headlines as read get headline_bar_show_mark_all_as_read_button() { return RSSList.firstChild.getAttribute("readAllIcon") == "true"; }, set headline_bar_show_mark_all_as_read_button(state) { RSSList.firstChild.setAttribute("readAllIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to switch to previous feed //FIXME Does this make sense when not cycling? get headline_bar_show_previous_feed_button() { return RSSList.firstChild.getAttribute("previousIcon") == "true"; }, set headline_bar_show_previous_feed_button(state) { RSSList.firstChild.setAttribute("previousIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle scrolling get headline_bar_show_pause_toggle() { return RSSList.firstChild.getAttribute("pauseIcon") == "true"; }, set headline_bar_show_pause_toggle(state) { RSSList.firstChild.setAttribute("pauseIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to switch to next feed //FIXME Does this make sense when not cycling? get headline_bar_show_next_feed_button() { return RSSList.firstChild.getAttribute("nextIcon") == "true"; }, set headline_bar_show_next_feed_button(state) { RSSList.firstChild.setAttribute("nextIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to view all headlines get headline_bar_show_view_all_button() { return RSSList.firstChild.getAttribute("viewAllIcon") == "true"; }, set headline_bar_show_view_all_button(state) { RSSList.firstChild.setAttribute("viewAllIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to perform manual refresh //FIXME Whatever that is get headline_bar_show_manual_refresh_button() { return RSSList.firstChild.getAttribute("refreshIcon") == "true"; }, set headline_bar_show_manual_refresh_button(state) { RSSList.firstChild.setAttribute("refreshIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle display of old (not clicked for a while) headlines //FIXME How old exactly is old? get headline_bar_show_hide_old_headlines_toggle() { return RSSList.firstChild.getAttribute("hideOldIcon") == "true"; }, set headline_bar_show_hide_old_headlines_toggle(state) { RSSList.firstChild.setAttribute("hideOldIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle display of viewed headlines get headline_bar_show_hide_viewed_headlines_toggle() { return RSSList.firstChild.getAttribute("hideViewedIcon") == "true"; }, set headline_bar_show_hide_viewed_headlines_toggle(state) { RSSList.firstChild.setAttribute("hideViewedIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle shuffling of headlines //FIXME Should this only be enabled when cycling is on? get headline_bar_show_shuffle_toggle() { return RSSList.firstChild.getAttribute("shuffleIcon") == "true"; }, set headline_bar_show_shuffle_toggle(state) { RSSList.firstChild.setAttribute("shuffleIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle scrolling direction //FIXME Only if scrolling enabled? (though not you can enable scrolling from //the headline bar) get headline_bar_show_direction_toggle() { return RSSList.firstChild.getAttribute("directionIcon") == "true"; }, set headline_bar_show_direction_toggle(state) { RSSList.firstChild.setAttribute("directionIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle scrolling on/off (this completely enables/disables) get headline_bar_show_scrolling_toggle() { return RSSList.firstChild.getAttribute("scrollingIcon") == "true"; }, set headline_bar_show_scrolling_toggle(state) { RSSList.firstChild.setAttribute("scrollingIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to perform manual synchronisation //FIXME Which is what? get headline_bar_show_manual_synchronisation_button() { return RSSList.firstChild.getAttribute("synchronizationIcon") == "true"; }, set headline_bar_show_manual_synchronisation_button(state) { RSSList.firstChild.setAttribute("synchronizationIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to configure quick filter get headline_bar_show_quick_filter_button() { return RSSList.firstChild.getAttribute("filterIcon") == "true"; }, set headline_bar_show_quick_filter_button(state) { RSSList.firstChild.setAttribute("filterIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to open feed home page //FIXME Doesn't make sense for certain types of feed get headline_bar_show_home_button() { return RSSList.firstChild.getAttribute("homeIcon") == "true"; }, set headline_bar_show_home_button(state) { RSSList.firstChild.setAttribute("homeIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Display the feeds icon with each headline headline_shows_feed_icon() { return RSSList.firstChild.getAttribute("favicon") == "true"; }, //---------------------------------------------------------------------------- //Display podcast enclosers with each headline headline_shows_enclosure_icon() { return RSSList.firstChild.getAttribute("displayEnclosure") == "true"; }, //---------------------------------------------------------------------------- //Display ban icon (which is probably mark as read) with each headline headline_shows_ban_icon() { return RSSList.firstChild.getAttribute("displayBanned") == "true"; }, //---------------------------------------------------------------------------- //Font family in which to display headlines. //'inherit' or a font/family name. headline_font_family() { return RSSList.firstChild.getAttribute("font"); }, //---------------------------------------------------------------------------- //Font size in which to display headlines //'inherit' or something else that CSS supports headline_font_size() { return RSSList.firstChild.getAttribute("fontSize"); }, //---------------------------------------------------------------------------- //Text colour for headlines //This can be 'default', or an HTML colour value (hex, rgb) //FIXME replace with mode and value. Also should 'default' be 'inherit'? headline_text_colour() { return RSSList.firstChild.getAttribute("defaultForegroundColor"); }, //---------------------------------------------------------------------------- //Returns how many seconds a hedline remains as 'recent' recent_headline_max_age() { return parseInt(RSSList.firstChild.getAttribute("delay"), 10); }, //---------------------------------------------------------------------------- //Text colour for recent headlines //This can be 'auto', 'sameas' or a colour value. Note that the code is //somewhat obscure (and duplicated) if you have this set to auto and have a //non-default background. recent_headline_text_colour() { return RSSList.firstChild.getAttribute("foregroundColor"); }, //---------------------------------------------------------------------------- //Weight of font. This can be 'bolder' or 'normal' recent_headline_font_weight() { return RSSList.firstChild.getAttribute("bold") == "true" ? "bolder" : "normal"; }, //---------------------------------------------------------------------------- //Style of font. This can be 'italic' or 'normal' (i.e. roman) recent_headline_font_style() { return RSSList.firstChild.getAttribute("italic") == "true" ? "italic" : "normal"; }, //---------------------------------------------------------------------------- //Return the background colour for headlines. //This can be 'inherit' or a hex number recent_headline_background_colour() { return RSSList.firstChild.getAttribute("backgroundColour"); }, //---------------------------------------------------------------------------- //The width of the headline area in the status bar get scrolling_area() { return parseInt(RSSList.firstChild.getAttribute("scrollingArea"), 10); }, //---------------------------------------------------------------------------- set scrolling_area(width) { RSSList.firstChild.setAttribute("scrollingArea", width); }, //////////// //---------------------------------------------------------------------------- setHideViewed(value) { RSSList.firstChild.setAttribute("hideViewed", value); }, //---------------------------------------------------------------------------- setHideOld(value) { RSSList.firstChild.setAttribute("hideOld", value); }, //---------------------------------------------------------------------------- getFilterHeadlines(rss) { return rss.getAttribute("filterHeadlines"); }, //---------------------------------------------------------------------------- //FIXME This is broken in so far as it doesn't account for 'fade in' toggleScrolling() { RSSList.firstChild.setAttribute("scrolling", this.headline_bar_scroll_style == this.static_display ? "1" : "0"); this.save(); }, //---------------------------------------------------------------------------- setQuickFilter(active, filter) { RSSList.firstChild.setAttribute("quickFilterActif", active); RSSList.firstChild.setAttribute("quickFilter", filter); this.save(); }, //---------------------------------------------------------------------------- getQuickFilter() { return RSSList.firstChild.getAttribute("quickFilter"); }, //---------------------------------------------------------------------------- isQuickFilterActif() { return RSSList.firstChild.getAttribute("quickFilterActif") == "true"; }, //---------------------------------------------------------------------------- switchShuffle() { if (RSSList.firstChild.getAttribute("nextFeed") == "next") { RSSList.firstChild.setAttribute("nextFeed", "random"); } else { RSSList.firstChild.setAttribute("nextFeed", "next"); } this.save(); }, //---------------------------------------------------------------------------- switchDirection() { if (RSSList.firstChild.getAttribute("scrollingdirection") == "rtl") { RSSList.firstChild.setAttribute("scrollingdirection", "ltr"); } else { RSSList.firstChild.setAttribute("scrollingdirection", "rtl"); } this.save(); }, //---------------------------------------------------------------------------- //FIXME Why does this live in prefs and not in the xml (or why doesn't more live here?) getServerInfo() { var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("inforss."); var serverInfo = null; if (prefs.prefHasUserValue("repository.user") == false) { serverInfo = { protocol: "ftp://", server: "", directory: "", user: "", password: "", autosync: false }; this.setServerInfo(serverInfo.protocol, serverInfo.server, serverInfo.directory, serverInfo.user, serverInfo.password, serverInfo.autosync); } else { var user = prefs.getCharPref("repository.user"); var password = null; var server = prefs.getCharPref("repository.server"); var protocol = prefs.getCharPref("repository.protocol"); var autosync = null; if (prefs.prefHasUserValue("repository.autosync") == false) { autosync = false; } else { autosync = prefs.getBoolPref("repository.autosync"); } if ((user.length > 0) && (server.length > 0)) { password = this.readPassword(protocol + server, user); } serverInfo = { protocol: protocol, server: server, directory: prefs.getCharPref("repository.directory"), user: user, password: (password == null) ? "" : password, autosync: autosync }; } return serverInfo; }, //---------------------------------------------------------------------------- setServerInfo(protocol, server, directory, user, password, autosync) { var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("inforss."); prefs.setCharPref("repository.protocol", protocol); prefs.setCharPref("repository.server", server); prefs.setCharPref("repository.directory", directory); prefs.setCharPref("repository.user", user); prefs.setBoolPref("repository.autosync", autosync); if ((user != "") && (password != "")) { this.storePassword(protocol + server, user, password); } }, //---------------------------------------------------------------------------- //FIXME I don't think any of these password functions have anything to do //with this class storePassword(url, user, password) { var loginInfo = new LoginInfo(url, 'User Registration', null, user, password, "", ""); try { LoginManager.removeLogin(loginInfo); } catch (e) {} LoginManager.addLogin(loginInfo); }, //---------------------------------------------------------------------------- readPassword(url, user) { try { // Find users for the given parameters let logins = LoginManager.findLogins({}, url, 'User Registration', null); // Find user from returned array of nsILoginInfo objects for (let login of logins) { if (login.username == user) { return login.password; } } } catch (ex) {} return ""; }, //---------------------------------------------------------------------------- save() { this._save(RSSList); }, //---------------------------------------------------------------------------- _save(list) { try { //FIXME should make this atomic write to new/delete/rename let file = this.get_filepath(); let outputStream = new FileOutputStream(file, -1, -1, 0); new XMLSerializer().serializeToStream(list, outputStream, "UTF-8"); outputStream.close(); //FIXME also add this to the inforssXML reader let prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("inforss."); prefs.setBoolPref("debug.alert", list.firstChild.getAttribute("debug") == "true"); prefs.setBoolPref("debug.log", list.firstChild.getAttribute("log") == "true"); prefs.setBoolPref("debug.statusbar", list.firstChild.getAttribute("statusbar") == "true"); } catch (e) { inforssDebug(e); } }, //---------------------------------------------------------------------------- add_item(title, description, url, link, user, password, type) { inforssTraceIn(); try { if (RSSList == null) { RSSList = new DOMParser().parseFromString('<LIST-RSS/>', 'text/xml'); /**/console.log("created empty rss", RSSList); } return this._new_item(RSSList, title, description, url, link, user, password, type); } catch (e) { inforssDebug(e); return null; } finally { inforssTraceOut(); } }, //---------------------------------------------------------------------------- //FIXME maybe should pass the icon? _new_item(list, title, description, url, link, user, password, type) { inforssTraceIn(); try { let elem = list.createElement("RSS"); elem.setAttribute("url", url); elem.setAttribute("title", title); elem.setAttribute("link", link == null || link == "" ? url : link); elem.setAttribute("description", description == null || description == "" ? title : description); if (user != null && user != "") { elem.setAttribute("user", user); this.storePassword(url, user, password); } elem.setAttribute("type", type); //FIXME These also need to be updated in feeds_default array for when //updating to new version. elem.setAttribute("selected", "false"); elem.setAttribute("nbItem", this.feeds_default_max_num_headlines()); elem.setAttribute("lengthItem", this.feeds_default_max_headline_length()); elem.setAttribute("playPodcast", this.feed_defaults_play_podcast() ? "true" : "false"); elem.setAttribute("savePodcastLocation", this.feeds_default_podcast_location()); elem.setAttribute("purgeHistory", this.feeds_default_history_purge_days()); elem.setAttribute("browserHistory", this.feed_defaults_use_browser_history() ? "true" : "false"); elem.setAttribute("filterCaseSensitive", "true"); elem.setAttribute("icon", INFORSS_DEFAULT_ICO); elem.setAttribute("refresh", this.feeds_default_refresh_time()); elem.setAttribute("activity", "true"); elem.setAttribute("filter", "all"); elem.setAttribute("groupAssociated", "false"); elem.setAttribute("group", "false"); elem.setAttribute("filterPolicy", "0"); elem.setAttribute("encoding", ""); list.firstChild.appendChild(elem); return elem; } catch (e) { inforssDebug(e); return null; } finally { inforssTraceOut(); } }, //FIXME Move this back to OPML code export_to_OPML(filePath, progress) { //FIXME Should do an atomic write (to a temp file and then rename) //Might be better to just generate a string and let the client resolve where //to put it. let opmlFile = new LocalFile(filePath); let stream = new FileOutputStream(opmlFile, -1, -1, 0); let sequence = Promise.resolve(1); //FIXME Should just create the opml document then stream it, but need an //async stream to get the feedback. let opml = new DOMParser().parseFromString("<opml/>", "text/xml"); let str = '<?xml version="1.0" encoding="UTF-8"?>\n' + '<opml version="1.0">\n' + ' <head>\n' + ' <title>InfoRSS Data</title>\n' + ' </head>\n' + ' <body>\n'; stream.write(str, str.length); let serializer = new XMLSerializer(); let items = RSSList.querySelectorAll("RSS:not([type=group])"); for (let iteml of items) { let item = iteml; //Hack - according to JS6 this is unnecessary sequence = sequence.then(i => { let outline = opml.createElement("outline"); outline.setAttribute("xmlHome", item.getAttribute("link")); outline.setAttribute("xmlUrl", item.getAttribute("url")); for (let attribute of opml_attributes) { outline.setAttribute(attribute, item.getAttribute(attribute)); } serializer.serializeToStream(outline, stream, "UTF-8"); stream.write("\n", "\n".length); progress(i, items.length); //Give the javascript machine a chance to display the progress bar. return new Promise(function(resolve /*, reject*/ ) { setTimeout(i => resolve(i + 1), 0, i); }); }); } sequence = sequence.then(function() { str = ' </body>\n' + '</opml>'; stream.write(str, str.length); stream.close(); }); return sequence; }, //---------------------------------------------------------------------------- backup() { try { let file = this.get_filepath(); if (file.exists()) { let backup = profile_dir.clone(); backup.append(INFORSS_BACKUP); if (backup.exists()) { backup.remove(true); } file.copyTo(null, INFORSS_BACKUP); } } catch (e) { inforssDebug(e); } }, //---------------------------------------------------------------------------- //FIXME Move this back to OPML code? import_from_OPML(text, mode, progress) { let domFile = new DOMParser().parseFromString(text, "text/xml"); if (domFile.documentElement.nodeName != "opml") { return null; } let list = RSSList.cloneNode(mode == MODE_APPEND); let sequence = Promise.resolve( { count: 1, list: list }); let items = domFile.querySelectorAll("outline[type=rss], outline[xmlUrl]"); for (let iteml of items) { let item = iteml; //Hack for non compliant browser sequence = sequence.then(where => { let link = item.hasAttribute("xmlHome") ? item.getAttribute("xmlHome") : item.hasAttribute("htmlUrl") ? item.getAttribute("htmlUrl") : null; let rss = this._new_item(where.list, item.getAttribute("title"), item.getAttribute("text"), item.getAttribute("xmlUrl"), link, //Not entirely clear to me why we //export username to OPML null, null, item.getAttribute("type")); for (let attribute of opml_attributes) { if (item.hasAttribute(attribute)) { rss.setAttribute(attribute, item.getAttribute(attribute)); } } if (!rss.hasAttribute("icon") || rss.getAttribute("icon") == "") { //FIXME - findicon should in fact be async, would need a module for it //The mozilla api is useless. The following works, but only sometimes, //and seems to require having the page visited in the right way: /* const Cc = Components.classes; const Ci = Components.interfaces; const IO = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); let link = rss.getAttribute('link'); console.log(link); let url = IO.newURI(link, null, null); const FaviconService = Cc["@mozilla.org/browser/favicon-service;1"].getService(Ci.nsIFaviconService); const asyncFavicons = FaviconService.QueryInterface(Ci.mozIAsyncFavicons); asyncFavicons.getFaviconDataForPage(url, function(aURI, aDataLen, aData, aMimeType) { console.log(1080, aURI.asciiSpec, aDataLen, aData, aMimeType); }); asyncFavicons.getFaviconURLForPage(url, function(aURI, aDataLen, aData, aMimeType) { console.log(1084, aURI.asciiSpec, aDataLen, aData, aMimeType); }); if (link.startsWith('http:')) { link = link.slice(0, 4) + 's' + link.slice(4); console.log(link); url = IO.newURI(link, null, null); asyncFavicons.getFaviconDataForPage(url, function(aURI, aDataLen, aData, aMimeType) { console.log(1080, aURI.asciiSpec, aDataLen, aData, aMimeType); }); } */ rss.setAttribute("icon", inforssFindIcon(rss)); } //Possibly want to do tsomething like this, though this would lose all //the custom settings above. Also if we did this we wouldn't need to add //them to the list. //var observerService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); //observerService.notifyObservers(null, "addFeed", rss.getAttribute("url")); progress(where.count, items.length); //Give the javascript machine a chance to display the progress bar. return new Promise(function(resolve /*, reject*/ ) { setTimeout(where => { where.count = where.count + 1; resolve(where); }, 0, where); }); }); } sequence = sequence.then(where => { this.backup(); //FIXME. Do not update the list it just causes grief /**/ console.log("suppressed setting to ", where); /**/ inforssDebug(new Error()); //RSSList = where.list; return new Promise(resolve => resolve(where.list.firstChild.childNodes.length)); }); return sequence; }, //---------------------------------------------------------------------------- //FIXME once this is all in its own class, this should be in the "constructor" //need to be a bit careful about alerting the error if it's possible to keep //the error handling outside of here. read_configuration() { let file = this.get_filepath(); if (!file.exists() || file.fileSize == 0) { this.reset_xml_to_default(); } let is = new FileInputStream(file, -1, -1, 0); let sis = new ScriptableInputStream(is); let data = sis.read(-1); sis.close(); is.close(); this.load_from_string(data); }, //load configuration from xml string. //FIXME Should this take a stream instead? //FIXME Why would you convert utf-8 to utf-8? load_from_string(data) { let uConv = new UTF8Converter(); data = uConv.convertStringToUTF8(data, "UTF-8", false); let new_list = new DOMParser().parseFromString(data, "text/xml"); this._adjust_repository(new_list); RSSList = new_list; }, //write configuration to xml string. //FIXME Should this take a stream instead? to_string() { return new XMLSerializer().serializeToString(RSSList); }, //---------------------------------------------------------------------------- _convert_4_to_5(list) { let config = list.firstChild; let rename_attribute = function(old_name, new_name) { if (config.hasAttribute(old_name)) { if (!config.hasAttribute(new_name)) { config.setAttribute(new_name, config.getAttribute(old_name)); } config.removeAttribute(old_name); } }; if (config.getAttribute("switch") == "on") { config.setAttribute("switch", "true"); } if (config.getAttribute("scrolling") == "true") { config.setAttribute("scrolling", "1"); } else if (config.getAttribute("scrolling") == "false") { config.setAttribute("scrolling", "0"); } rename_attribute("purgeHistory", "defaultPurgeHistory"); for (let item of list.getElementsByTagName("RSS")) { if (item.hasAttribute("password")) { if (item.getAttribute("password") != "") { inforssXMLRepository.storePassword(item.getAttribute("url"), item.getAttribute("user"), item.getAttribute("password")); } item.removeAttribute("password"); } } }, //---------------------------------------------------------------------------- _convert_5_to_6(list) { let config = list.firstChild; let rename_attribute = function(old_name, new_name) { if (config.hasAttribute(old_name)) { if (!config.hasAttribute(new_name)) { config.setAttribute(new_name, config.getAttribute(old_name)); } config.removeAttribute(old_name); } }; rename_attribute("DefaultPurgeHistory", "defaultPurgeHistory"); rename_attribute("shuffleicon", "shuffleIcon"); let items = list.getElementsByTagName("RSS"); for (let item of items) { if (item.hasAttribute("user") && (item.getAttribute("user") == "" || item.getAttribute("user") == "null")) { item.removeAttribute("user"); } if (item.getAttribute("type") == "html" && !item.hasAttribute("htmlDirection")) { item.setAttribute("htmlDirection", "asc"); } if (!item.hasAttribute("browserHistory")) { item.setAttribute("browserHistory", "true"); if (item.getAttribute("url").indexOf("https://gmail.google.com/gmail/feed/atom") == 0 || item.getAttribute("url").indexOf(".ebay.") != -1) { item.setAttribute("browserHistory", "false"); } } if (item.getAttribute("type") == "group" && !item.hasAttribute("playlist")) { item.setAttribute("playlist", "false"); } if (item.hasAttribute("icon") && item.getAttribute("icon") == "") { item.setAttribute("icon", INFORSS_DEFAULT_ICO); } } this._set_defaults(list); }, _convert_6_to_7(list) { let config = list.firstChild; config.removeAttribute("mouseEvent"); config.removeAttribute("net"); }, _convert_7_to_8(list) { let config = list.firstChild; config.removeAttribute("groupNbItem"); config.removeAttribute("groupLenghtItem"); config.removeAttribute("groupRefresh"); config.removeAttribute("false"); //Embarassing result of fix to strange code if (config.getAttribute("font") == "auto") { config.setAttribute("font", "inherit"); } { const fontSize = config.getAttribute("fontSize"); if (fontSize == "auto") { config.setAttribute("fontSize", "inherit"); } else if (!isNaN(fontSize)) { config.setAttribute("fontSize", fontSize + "pt"); } } //If defaultForegroundColor is "sameas", we need to swap that and //foregroundColor if (config.getAttribute("defaultForegroundColor") == "sameas") { let colour = config.getAttribute("foregroundColor"); if (colour == "auto") { colour = "default"; } config.setAttribute("defaultForegroundColor", colour); config.setAttribute("foregroundColor", "sameas"); } //Convert the 3 r/g/b to one single background colour. //A note: This is questionable in a sense, but css takes html colours and //html doesn't take css colour specs. if (config.hasAttribute("red")) { const red = Number(config.getAttribute("red")); if (red == "-1") { config.setAttribute("backgroundColour", "inherit"); } else { const green = Number(config.getAttribute("green")); const blue = Number(config.getAttribute("blue")); config.setAttribute( "backgroundColour", '#' + ("000000" + ((red * 256 + green) * 256 + blue).toString(16)).substr(-6)); } config.removeAttribute("red"); config.removeAttribute("green"); config.removeAttribute("blue"); } }, //---------------------------------------------------------------------------- _adjust_repository(list) { let config = list.firstChild; if (config.getAttribute("version") <= "4") { this._convert_4_to_5(list); } if (config.getAttribute("version") <= "5") { this._convert_5_to_6(list); } if (config.getAttribute("version") <= "6") { this._convert_6_to_7(list); } if (config.getAttribute("version") <= "7") { this._convert_7_to_8(list); } //FIXME this should be done properly when saving and then it becomes part of //a normal convert. { let items = list.getElementsByTagName("RSS"); for (let item of items) { item.setAttribute("groupAssociated", "false"); } for (let group of items) { if (group.getAttribute("type") == "group") { for (let feed of group.getElementsByTagName("GROUP")) { let url = feed.getAttribute("url"); for (let item of items) { if (item.getAttribute("type") != "group" && item.getAttribute("url") == url) { item.setAttribute("groupAssociated", "true"); break; } } } } } } //NOTNOTENOTE Check this before release. //It should be set to what is up above if (config.getAttribute("version") != "7") { config.setAttribute("version", 7); this.backup(); this._save(list); } }, //---------------------------------------------------------------------------- _set_defaults(list) { //Add in missing defaults const defaults = { backgroundColour: "#7fc0ff", bold: true, clickHeadline: 0, clipboard: true, collapseBar: false, currentfeed: true, cycleWithinGroup: false, cycling: false, cyclingDelay: 5, debug: false, defaultBrowserHistory: true, defaultForegroundColor: "default", defaultGroupIcon: "chrome://inforss/skin/group.png", defaultLenghtItem: 25, defaultNbItem: 9999, defaultPlayPodcast: true, defaultPurgeHistory: 3, delay: 15, directionIcon: true, displayBanned: true, displayEnclosure: true, favicon: true, filterIcon: true, flashingIcon: true, font: "inherit", fontSize: "inherit", foregroundColor: "auto", group: false, hideHistory: true, hideOld: false, hideOldIcon: false, hideViewed: false, hideViewedIcon: false, homeIcon: true, includeAssociated: true, italic: true, linePosition: "bottom", livemark: true, log: false, mouseWheelScroll: "pixel", nextFeed: "next", nextIcon: true, pauseIcon: true, playSound: true, popupMessage: true, previousIcon: true, quickFilter: "", quickFilterActif: false, readAllIcon: true, refresh: 2, refreshIcon: false, savePodcastLocation: "", scrolling: 1, scrollingArea: 500, scrollingIcon: true, scrollingIncrement: 2, scrollingdirection: "rtl", scrollingspeed: 19, separateLine: false, shuffleIcon: true, sortedMenu: "asc", statusbar: false, stopscrolling: true, submenu: false, "switch": true, synchronizationIcon: false, synchronizeIcon: false, timeslice: 90, tooltip: "description", viewAllIcon: true, }; let config = list.firstChild; for (let attrib in defaults) { if (!defaults.hasOwnProperty(attrib)) { continue; } if (!config.hasAttribute(attrib)) { config.setAttribute(attrib, defaults[attrib]); } } //Now for the rss items //FIXME see also add_item and anywhere that creates a new item. const feed_defaults = { activity: true, browserHistory: config.getAttribute("defaultBrowserHistory"), description: "", encoding: "", filter: "all", filterCaseSensitive: true, filterPolicy: 0, group: false, groupAssociated: false, icon: INFORSS_DEFAULT_ICO, lengthItem: config.getAttribute("defaultLenghtItem"), nbItem: config.getAttribute("defaultNbItem"), playPodcast: config.getAttribute("defaultPlayPodcast"), purgeHistory: config.getAttribute("defaultPurgeHistory"), refresh: config.getAttribute("refresh"), savePodcastLocation: config.getAttribute("savePodcastLocation"), selected: false, type: "rss", }; for (let item of list.getElementsByTagName("RSS")) { for (let attrib in feed_defaults) { if (!feed_defaults.hasOwnProperty(attrib)) { continue; } if (!item.hasAttribute(attrib)) { item.setAttribute(attrib, feed_defaults[attrib]); } } } }, //---------------------------------------------------------------------------- reset_xml_to_default() { //Back up the current file if it exists so recovery may be attempted { let file = this.get_filepath(); if (file.exists()) { const INFORSS_INERROR = "inforss_xml.inerror"; let dest = profile_dir.clone(); dest.append(INFORSS_INERROR); if (dest.exists()) { dest.remove(false); } file.renameTo(profile_dir, INFORSS_INERROR); } } //Copy the default setup. let source = inforssGetResourceFile("inforss.default"); if (source.exists()) { source.copyTo(profile_dir, INFORSS_REPOSITORY); } }, }; //---------------------------------------------------------------------------- /* exported inforssGetItemFromUrl */ //FIXME Should be a method of the above //FIXME replace with document.querySelector(RSS[url=url]) (i think) function inforssGetItemFromUrl(url) { inforssTraceIn(); try { for (let item of inforssXMLRepository.get_all()) { if (item.getAttribute("url") == url) { return item; } } } finally { inforssTraceOut(); } return null; } //---------------------------------------------------------------------------- /* exported getCurrentRSS */ //FIXME Should be a method of the above //FIXME Use document.querySelector function getCurrentRSS() { inforssTraceIn(); try { for (let item of inforssXMLRepository.get_all()) { if (item.getAttribute("selected") == "true") { return item; } } } finally { inforssTraceOut(); } return null; } /* exported inforssXMLRepository */ var inforssXMLRepository = new XML_Repository();
source/content/inforss/inforssXMLRepository.js
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is infoRSS. * * The Initial Developer of the Original Code is * Didier Ernotte <[email protected]>. * Portions created by the Initial Developer are Copyright (C) 2004 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Didier Ernotte <[email protected]>. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ //---------------------------------------------------------------------------- // inforssXMLRepository // Author : Didier Ernotte 2005 // Inforss extension //---------------------------------------------------------------------------- /* globals inforssDebug, inforssTraceIn, inforssTraceOut */ Components.utils.import("chrome://inforss/content/modules/inforssDebug.jsm"); /* globals inforssGetResourceFile */ Components.utils.import("chrome://inforss/content/modules/inforssVersion.jsm"); //These should be in another module. Or at least not exported */ /* exported LocalFile */ const LocalFile = Components.Constructor("@mozilla.org/file/local;1", "nsILocalFile", "initWithPath"); /* exported FileInputStream */ const FileInputStream = Components.Constructor("@mozilla.org/network/file-input-stream;1", "nsIFileInputStream", "init"); /* exported ScriptableInputStream */ const ScriptableInputStream = Components.Constructor("@mozilla.org/scriptableinputstream;1", "nsIScriptableInputStream", "init"); //FIXME This is a service /* exported UTF8Converter */ const UTF8Converter = Components.Constructor("@mozilla.org/intl/utf8converterservice;1", "nsIUTF8ConverterService"); /* exported FileOutputStream */ const FileOutputStream = Components.Constructor("@mozilla.org/network/file-output-stream;1", "nsIFileOutputStream", "init"); const Properties = Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIProperties); const profile_dir = Properties.get("ProfD", Components.interfaces.nsIFile); const LoginManager = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager); const LoginInfo = Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Components.interfaces.nsILoginInfo, "init"); //FIXME Turn this into a module, once we have all access to RSSList in here //Note that inforssOption should have its own instance which is then copied //once we do an apply. Jury is out on whether OPML import/export should work on //the global/local instance... /* global inforssFindIcon */ //To make this a module, will need to construct DOMParser //https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsIDOMParser /* exported MODE_APPEND */ const MODE_APPEND = 0; /* exported MODE_REPLACE */ const MODE_REPLACE = 1; //FIXME Should be hooked off profile_dir. The main problem is the rename below const INFORSS_REPOSITORY = "inforss.xml"; /* exported INFORSS_DEFAULT_ICO */ const INFORSS_DEFAULT_ICO = "chrome://inforss/skin/default.ico"; /* exported RSSList */ var RSSList = null; //---------------------------------------------------------------------------- const opml_attributes = [ "acknowledgeDate", "activity", "browserHistory", "filter", "filterCaseSensitive", "filterPolicy", "group", "groupAssociated", "htmlDirection", "htmlTest", "icon", "lengthItem", "nbItem", "playPodcast", "refresh", "regexp", "regexpCategory", "regexpDescription", "regexpLink", "regexpPubDate", "regexpStartAfter", "regexpStopBefore", "regexpTitle", "selected", "title", "type", "user" ]; const INFORSS_BACKUP = "inforss_xml.backup"; //use XML_Repository.<name> = xxxx for static properties/functions function XML_Repository() { return this; } XML_Repository.prototype = { //---------------------------------------------------------------------------- //FIXME THis is only used in one place and I'm not sure if it should be used //there at all. is_valid() { return RSSList != null; }, //---------------------------------------------------------------------------- // Get all the feeds / groups we have configured // Returns a dynamic NodeList get_all() { return RSSList.getElementsByTagName("RSS"); }, // Gets the configured groups // Returns a static NodeList get_groups() { return RSSList.querySelectorAll("RSS[type=group]"); }, // Gets the configured feeds // Returns a static NodeList get_feeds() { return RSSList.querySelectorAll("RSS:not([type=group])"); }, //Get the full name of the configuration file. get_filepath() { const path = profile_dir.clone(); path.append(INFORSS_REPOSITORY); return path; }, //---------------------------------------------------------------------------- //Debug settings (warning: also accessed via about:config) //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //Display debug messages in a popup debug_display_popup() { return RSSList.firstChild.getAttribute("debug") == "true"; }, //---------------------------------------------------------------------------- //Display debug messages on the status bar debug_to_status_bar() { return RSSList.firstChild.getAttribute("statusbar") == "true"; }, //---------------------------------------------------------------------------- //Display debug messages in the browser log debug_to_browser_log() { return RSSList.firstChild.getAttribute("log") == "true"; }, //---------------------------------------------------------------------------- //Default values. //Note that these are given to the feed at the time the feed is created. If //you change the default, you'll only change feeds created in the future. //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //Default number of headlines to show //FIXME Using 9999 for 'unconstrained' is dubious style feeds_default_max_num_headlines() { return parseInt(RSSList.firstChild.getAttribute("defaultNbItem"), 10); }, //---------------------------------------------------------------------------- //Default max headline length to show (longer headlines will be truncated) //FIXME Using 9999 for 'unconstrained' is dubious style feeds_default_max_headline_length() { return parseInt(RSSList.firstChild.getAttribute("defaultLenghtItem"), 10); }, //---------------------------------------------------------------------------- //Default refresh time (time between polls) feeds_default_refresh_time() { return parseInt(RSSList.firstChild.getAttribute("refresh"), 10); }, //---------------------------------------------------------------------------- //Default number of days to retain a headline in the RDF file feeds_default_history_purge_days() { return parseInt(RSSList.firstChild.getAttribute("defaultPurgeHistory"), 10); }, //---------------------------------------------------------------------------- //Default state for playing podcast feed_defaults_play_podcast() { return RSSList.firstChild.getAttribute("defaultPlayPodcast") == "true"; }, //---------------------------------------------------------------------------- //Default switch for whether or not to use browser history to determine if //headline has been read feed_defaults_use_browser_history() { return RSSList.firstChild.getAttribute("defaultBrowserHistory") == "true"; }, //---------------------------------------------------------------------------- //Default icon for a group feeds_default_group_icon() { return RSSList.firstChild.getAttribute("defaultGroupIcon"); }, //---------------------------------------------------------------------------- //Default location to which to save podcasts (if empty, they don't get saved) feeds_default_podcast_location() { return RSSList.firstChild.getAttribute("savePodcastLocation"); }, //---------------------------------------------------------------------------- //Main menu should include an 'add' entry for each feed found on the current page menu_includes_page_feeds() { return RSSList.firstChild.getAttribute("currentfeed") == "true"; }, //---------------------------------------------------------------------------- //Main menu should include an 'add' entry for all livemarks menu_includes_livemarks() { return RSSList.firstChild.getAttribute("livemark") == "true"; }, //---------------------------------------------------------------------------- //Main menu should include an 'add' entry for the current clipboard contents //(if it looks something like a feed at any rate) menu_includes_clipboard() { return RSSList.firstChild.getAttribute("clipboard") == "true"; }, //---------------------------------------------------------------------------- //Sorting style for main menu. May be asc, des or off. menu_sorting_style() { return RSSList.firstChild.getAttribute("sortedMenu"); }, //---------------------------------------------------------------------------- //Main menu should show feeds that are part of a group. If this is off, it wont //show feeds that are in a group (or groups). menu_show_feeds_from_groups() { return RSSList.firstChild.getAttribute("includeAssociated") == "true"; }, //---------------------------------------------------------------------------- //If on, each feed will have a submenu showing the "latest" (i.e. first in the //XML) 20 headlines. menu_show_headlines_in_submenu() { return RSSList.firstChild.getAttribute("submenu") == "true"; }, //---------------------------------------------------------------------------- //main icon should show the icon for the current feed (rather than the globe) icon_shows_current_feed() { return RSSList.firstChild.getAttribute("synchronizeIcon") == "true"; }, //---------------------------------------------------------------------------- //main icon should flash when there is activity (i.e. it reads a feed xml). icon_flashes_on_activity() { return RSSList.firstChild.getAttribute("flashingIcon") == "true"; }, //---------------------------------------------------------------------------- //Shows or collapses the ticker display completely. This only really makes //sense if you have the display in the status bar. headline_bar_enabled() { return RSSList.firstChild.getAttribute("switch") == "true"; }, //---------------------------------------------------------------------------- //Hide headlines once they've been viewed hide_viewed_headlines() { return RSSList.firstChild.getAttribute("hideViewed") == "true"; }, //---------------------------------------------------------------------------- //Hide headlines that are considered 'old' (i.e. have been displayed for //a period of time, but not read) hide_old_headlines() { return RSSList.firstChild.getAttribute("hideOld") == "true"; }, //---------------------------------------------------------------------------- //Remember displayed headlines and state remember_headlines() { return RSSList.firstChild.getAttribute("hideHistory") == "true"; }, //---------------------------------------------------------------------------- //Show a toast (on my windows 10 it appears at the bottom right) on a new //headline show_toast_on_new_headline() { return RSSList.firstChild.getAttribute("popupMessage") == "true"; }, //---------------------------------------------------------------------------- //Plays a sound ('beep' on linux, 'Notify' on windows) on a new headline play_sound_on_new_headline() { return RSSList.firstChild.getAttribute("playSound") == "true"; }, //---------------------------------------------------------------------------- //style of tooltip on headline, can be "description", "title", "allInfo" or //"article" (which most of code treats as default) //FIXME Replace this with appropriate properties. (see below) headline_tooltip_style() { return RSSList.firstChild.getAttribute("tooltip"); }, //---------------------------------------------------------------------------- //When clicking on a headline, article loads in get new_default_tab() { return 0; }, get new_background_tab() { return 1; }, get new_foreground_tab() { return 2; }, get new_window() { return 3; }, get current_tab() { return 4; }, headline_action_on_click() { return parseInt(RSSList.firstChild.getAttribute("clickHeadline"), 10); }, //---------------------------------------------------------------------------- //This is pretty much completely the opposite of a timeslice. It returns the //delay between processing individual headlines (in milliseconds) headline_processing_backoff() { return parseInt(RSSList.firstChild.getAttribute("timeslice"), 10); }, //---------------------------------------------------------------------------- //Get the location of the headline bar. get in_status_bar() { return 0; }, get at_top() { return 1; }, get at_bottom() { return 2; }, get headline_bar_location() { return RSSList.firstChild.getAttribute("separateLine") == "false" ? this.in_status_bar : RSSList.firstChild.getAttribute("linePosition") == "top" ? this.at_top: this.at_bottom; }, set headline_bar_location(loc) { switch (loc) { case this.in_status_bar: RSSList.firstChild.setAttribute("separateLine", "false"); break; case this.at_top: RSSList.firstChild.setAttribute("separateLine", "true"); RSSList.firstChild.setAttribute("linePosition", "top"); break; case this.at_bottom: RSSList.firstChild.setAttribute("separateLine", "true"); RSSList.firstChild.setAttribute("linePosition", "bottom"); break; } }, //---------------------------------------------------------------------------- //If the headline bar is collapsed, it only uses enough of the status bar to //display necessary headlines. //FIXME should be grayed out if not using the status bar get headline_bar_collapsed() { return RSSList.firstChild.getAttribute("collapseBar") == "true"; }, set headline_bar_collapsed(state) { RSSList.firstChild.setAttribute("collapseBar", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //How much the mouse wheel will scroll. //'pixel' scrolls by the scrolling increment //'pixels' appears to scroll 10 'pixels' at a time. get by_pixel() { return 0; }, get by_pixels() { return 1; }, get by_headline() { return 2; }, get headline_bar_mousewheel_scroll() { const type = RSSList.firstChild.getAttribute("mouseWheelScroll"); return type == "pixel" ? this.by_pixel : type == "pixels" ? this.by_pixels : this.by_headline; }, set headline_bar_mousewheel_scroll(scroll) { RSSList.firstChild.setAttribute("mouseWheelScroll", (() => { switch (scroll) { case this.by_pixel: return "pixel"; case this.by_pixels: return "pixels"; case this.by_headline: return "headline"; } })()); }, //---------------------------------------------------------------------------- //Indicate how headlines appear/disappear //For fade, instead of scrolling, one headline is displayed, and it fades //into the next one. Useful for status bar. get static_display() { return 0; }, get scrolling_display() { return 1; }, get fade_into_next() { return 2; }, get headline_bar_scroll_style() { return parseInt(RSSList.firstChild.getAttribute("scrolling"), 10); }, set headline_bar_scroll_style(style) { RSSList.firstChild.setAttribute("scrolling", style); }, //---------------------------------------------------------------------------- //Scrolling speed / fade rate from 1 (slow) to 30 (fast) //Not meaningful for static //FIXME Should be disabled on option screen when not appropriate //FIXME Description should change? get headline_bar_scroll_speed() { return parseInt(RSSList.firstChild.getAttribute("scrollingspeed"), 10); }, set headline_bar_scroll_speed(speed) { RSSList.firstChild.setAttribute("scrollingspeed", speed); }, //---------------------------------------------------------------------------- //The number of pixels a headline is scrolled by, from 1 to 3. //Only meaningful for scrolling, not static or fade //FIXME Should be disabled on option screen when not appropriate get headline_bar_scroll_increment() { return parseInt(RSSList.firstChild.getAttribute("scrollingIncrement"), 10); }, set headline_bar_scroll_increment(increment) { RSSList.firstChild.setAttribute("scrollingIncrement", increment); }, //---------------------------------------------------------------------------- //Stop scrolling when mouse is over headline. I presume this stops fading as //well. //FIXME Should be disabled on option screen when not appropriate get headline_bar_stop_on_mouseover() { return RSSList.firstChild.getAttribute("stopscrolling") == "true"; }, set headline_bar_stop_on_mouseover(state) { RSSList.firstChild.setAttribute("stopscrolling", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Get the scrolling direction (rtl/ltr) //FIXME Should be disabled on option screen when not appropriate //FIXME Shouldn't be raw ascii get headline_bar_scrolling_direction() { return RSSList.firstChild.getAttribute("scrollingdirection"); }, set headline_bar_scrolling_direction(dir) { RSSList.firstChild.setAttribute("scrollingdirection", dir); }, //---------------------------------------------------------------------------- //Cycle between feeds on the headline bar //FIXME If not enabled, the left/right icons shouldn't appear in the headline //bar get headline_bar_cycle_feeds() { return RSSList.firstChild.getAttribute("cycling") == "true"; }, set headline_bar_cycle_feeds(state) { RSSList.firstChild.setAttribute("cycling", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Interval between cycling feeds (in minutes) //FIXME Shouldn't be enabled if not cycling get headline_bar_cycle_interval() { return parseInt(RSSList.firstChild.getAttribute("cyclingDelay"), 10); }, set headline_bar_cycle_interval(interval) { RSSList.firstChild.setAttribute("cyclingDelay", interval); }, //---------------------------------------------------------------------------- //Get what to display on the next cycling, either "next" or "random" //FIXME Shouldn't be enabled if not cycling //FIXME Replace this with appropriate properties (or boolean) get headline_bar_cycle_type() { return RSSList.firstChild.getAttribute("nextFeed"); }, set headline_bar_cycle_type(type) { RSSList.firstChild.setAttribute("nextFeed", type); }, //---------------------------------------------------------------------------- //Cycle feeds in group when set //FIXME Shouldn't be enabled if not cycling get headline_bar_cycle_in_group() { return RSSList.firstChild.getAttribute("cycleWithinGroup") == "true"; }, set headline_bar_cycle_in_group(state) { RSSList.firstChild.setAttribute("cycleWithinGroup", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to mark all headlines as read get headline_bar_show_mark_all_as_read_button() { return RSSList.firstChild.getAttribute("readAllIcon") == "true"; }, set headline_bar_show_mark_all_as_read_button(state) { RSSList.firstChild.setAttribute("readAllIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to switch to previous feed //FIXME Does this make sense when not cycling? get headline_bar_show_previous_feed_button() { return RSSList.firstChild.getAttribute("previousIcon") == "true"; }, set headline_bar_show_previous_feed_button(state) { RSSList.firstChild.setAttribute("previousIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle scrolling get headline_bar_show_pause_toggle() { return RSSList.firstChild.getAttribute("pauseIcon") == "true"; }, set headline_bar_show_pause_toggle(state) { RSSList.firstChild.setAttribute("pauseIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to switch to next feed //FIXME Does this make sense when not cycling? get headline_bar_show_next_feed_button() { return RSSList.firstChild.getAttribute("nextIcon") == "true"; }, set headline_bar_show_next_feed_button(state) { RSSList.firstChild.setAttribute("nextIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to view all headlines get headline_bar_show_view_all_button() { return RSSList.firstChild.getAttribute("viewAllIcon") == "true"; }, set headline_bar_show_view_all_button(state) { RSSList.firstChild.setAttribute("viewAllIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to perform manual refresh //FIXME Whatever that is get headline_bar_show_manual_refresh_button() { return RSSList.firstChild.getAttribute("refreshIcon") == "true"; }, set headline_bar_show_manual_refresh_button(state) { RSSList.firstChild.setAttribute("refreshIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle display of old (not clicked for a while) headlines //FIXME How old exactly is old? get headline_bar_show_hide_old_headlines_toggle() { return RSSList.firstChild.getAttribute("hideOldIcon") == "true"; }, set headline_bar_show_hide_old_headlines_toggle(state) { RSSList.firstChild.setAttribute("hideOldIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle display of viewed headlines get headline_bar_show_hide_viewed_headlines_toggle() { return RSSList.firstChild.getAttribute("hideViewedIcon") == "true"; }, set headline_bar_show_hide_viewed_headlines_toggle(state) { RSSList.firstChild.setAttribute("hideViewedIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle shuffling of headlines //FIXME Should this only be enabled when cycling is on? get headline_bar_show_shuffle_toggle() { return RSSList.firstChild.getAttribute("shuffleIcon") == "true"; }, set headline_bar_show_shuffle_toggle(state) { RSSList.firstChild.setAttribute("shuffleIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle scrolling direction //FIXME Only if scrolling enabled? (though not you can enable scrolling from //the headline bar) get headline_bar_show_direction_toggle() { return RSSList.firstChild.getAttribute("directionIcon") == "true"; }, set headline_bar_show_direction_toggle(state) { RSSList.firstChild.setAttribute("directionIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to toggle scrolling on/off (this completely enables/disables) get headline_bar_show_scrolling_toggle() { return RSSList.firstChild.getAttribute("scrollingIcon") == "true"; }, set headline_bar_show_scrolling_toggle(state) { RSSList.firstChild.setAttribute("scrollingIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to perform manual synchronisation //FIXME Which is what? get headline_bar_show_manual_synchronisation_button() { return RSSList.firstChild.getAttribute("synchronizationIcon") == "true"; }, set headline_bar_show_manual_synchronisation_button(state) { RSSList.firstChild.setAttribute("synchronizationIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to configure quick filter get headline_bar_show_quick_filter_button() { return RSSList.firstChild.getAttribute("filterIcon") == "true"; }, set headline_bar_show_quick_filter_button(state) { RSSList.firstChild.setAttribute("filterIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Show button to open feed home page //FIXME Doesn't make sense for certain types of feed get headline_bar_show_home_button() { return RSSList.firstChild.getAttribute("homeIcon") == "true"; }, set headline_bar_show_home_button(state) { RSSList.firstChild.setAttribute("homeIcon", state ? "true" : "false"); }, //---------------------------------------------------------------------------- //Display the feeds icon with each headline headline_shows_feed_icon() { return RSSList.firstChild.getAttribute("favicon") == "true"; }, //---------------------------------------------------------------------------- //Display podcast enclosers with each headline headline_shows_enclosure_icon() { return RSSList.firstChild.getAttribute("displayEnclosure") == "true"; }, //---------------------------------------------------------------------------- //Display ban icon (which is probably mark as read) with each headline headline_shows_ban_icon() { return RSSList.firstChild.getAttribute("displayBanned") == "true"; }, //---------------------------------------------------------------------------- //Font family in which to display headlines. //'inherit' or a font/family name. headline_font_family() { return RSSList.firstChild.getAttribute("font"); }, //---------------------------------------------------------------------------- //Font size in which to display headlines //'inherit' or something else that CSS supports headline_font_size() { return RSSList.firstChild.getAttribute("fontSize"); }, //---------------------------------------------------------------------------- //Text colour for headlines //This can be 'default', or an HTML colour value (hex, rgb) //FIXME replace with mode and value. Also should 'default' be 'inherit'? headline_text_colour() { return RSSList.firstChild.getAttribute("defaultForegroundColor"); }, //---------------------------------------------------------------------------- //Returns how many seconds a hedline remains as 'recent' recent_headline_max_age() { return parseInt(RSSList.firstChild.getAttribute("delay"), 10); }, //---------------------------------------------------------------------------- //Text colour for recent headlines //This can be 'auto', 'sameas' or a colour value. Note that the code is //somewhat obscure (and duplicated) if you have this set to auto and have a //non-default background. recent_headline_text_colour() { return RSSList.firstChild.getAttribute("foregroundColor"); }, //---------------------------------------------------------------------------- //Weight of font. This can be 'bolder' or 'normal' recent_headline_font_weight() { return RSSList.firstChild.getAttribute("bold") == "true" ? "bolder" : "normal"; }, //---------------------------------------------------------------------------- //Style of font. This can be 'italic' or 'normal' (i.e. roman) recent_headline_font_style() { return RSSList.firstChild.getAttribute("italic") == "true" ? "italic" : "normal"; }, //---------------------------------------------------------------------------- //Return the background colour for headlines. //This can be 'inherit' or a hex number recent_headline_background_colour() { return RSSList.firstChild.getAttribute("backgroundColour"); }, //---------------------------------------------------------------------------- //The width of the headline area in the status bar get scrolling_area() { return parseInt(RSSList.firstChild.getAttribute("scrollingArea"), 10); }, //---------------------------------------------------------------------------- set scrolling_area(width) { RSSList.firstChild.setAttribute("scrollingArea", width); }, //////////// //---------------------------------------------------------------------------- setHideViewed(value) { RSSList.firstChild.setAttribute("hideViewed", value); }, //---------------------------------------------------------------------------- setHideOld(value) { RSSList.firstChild.setAttribute("hideOld", value); }, //---------------------------------------------------------------------------- getFilterHeadlines(rss) { return rss.getAttribute("filterHeadlines"); }, //---------------------------------------------------------------------------- //FIXME This is broken in so far as it doesn't account for 'fade in' toggleScrolling() { RSSList.firstChild.setAttribute("scrolling", this.headline_bar_scroll_style == this.static_display ? "1" : "0"); this.save(); }, //---------------------------------------------------------------------------- setQuickFilter(active, filter) { RSSList.firstChild.setAttribute("quickFilterActif", active); RSSList.firstChild.setAttribute("quickFilter", filter); this.save(); }, //---------------------------------------------------------------------------- getQuickFilter() { return RSSList.firstChild.getAttribute("quickFilter"); }, //---------------------------------------------------------------------------- isQuickFilterActif() { return RSSList.firstChild.getAttribute("quickFilterActif") == "true"; }, //---------------------------------------------------------------------------- isPlayList() { return RSSList.firstChild.getAttribute("playlist") == "true"; }, //---------------------------------------------------------------------------- switchShuffle() { if (RSSList.firstChild.getAttribute("nextFeed") == "next") { RSSList.firstChild.setAttribute("nextFeed", "random"); } else { RSSList.firstChild.setAttribute("nextFeed", "next"); } this.save(); }, //---------------------------------------------------------------------------- switchDirection() { if (RSSList.firstChild.getAttribute("scrollingdirection") == "rtl") { RSSList.firstChild.setAttribute("scrollingdirection", "ltr"); } else { RSSList.firstChild.setAttribute("scrollingdirection", "rtl"); } this.save(); }, //---------------------------------------------------------------------------- //FIXME Why does this live in prefs and not in the xml (or why doesn't more live here?) getServerInfo() { var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("inforss."); var serverInfo = null; if (prefs.prefHasUserValue("repository.user") == false) { serverInfo = { protocol: "ftp://", server: "", directory: "", user: "", password: "", autosync: false }; this.setServerInfo(serverInfo.protocol, serverInfo.server, serverInfo.directory, serverInfo.user, serverInfo.password, serverInfo.autosync); } else { var user = prefs.getCharPref("repository.user"); var password = null; var server = prefs.getCharPref("repository.server"); var protocol = prefs.getCharPref("repository.protocol"); var autosync = null; if (prefs.prefHasUserValue("repository.autosync") == false) { autosync = false; } else { autosync = prefs.getBoolPref("repository.autosync"); } if ((user.length > 0) && (server.length > 0)) { password = this.readPassword(protocol + server, user); } serverInfo = { protocol: protocol, server: server, directory: prefs.getCharPref("repository.directory"), user: user, password: (password == null) ? "" : password, autosync: autosync }; } return serverInfo; }, //---------------------------------------------------------------------------- setServerInfo(protocol, server, directory, user, password, autosync) { var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("inforss."); prefs.setCharPref("repository.protocol", protocol); prefs.setCharPref("repository.server", server); prefs.setCharPref("repository.directory", directory); prefs.setCharPref("repository.user", user); prefs.setBoolPref("repository.autosync", autosync); if ((user != "") && (password != "")) { this.storePassword(protocol + server, user, password); } }, //---------------------------------------------------------------------------- //FIXME I don't think any of these password functions have anything to do //with this class storePassword(url, user, password) { var loginInfo = new LoginInfo(url, 'User Registration', null, user, password, "", ""); try { LoginManager.removeLogin(loginInfo); } catch (e) {} LoginManager.addLogin(loginInfo); }, //---------------------------------------------------------------------------- readPassword(url, user) { try { // Find users for the given parameters let logins = LoginManager.findLogins({}, url, 'User Registration', null); // Find user from returned array of nsILoginInfo objects for (let login of logins) { if (login.username == user) { return login.password; } } } catch (ex) {} return ""; }, //---------------------------------------------------------------------------- save() { this._save(RSSList); }, //---------------------------------------------------------------------------- _save(list) { try { //FIXME should make this atomic write to new/delete/rename let file = this.get_filepath(); let outputStream = new FileOutputStream(file, -1, -1, 0); new XMLSerializer().serializeToStream(list, outputStream, "UTF-8"); outputStream.close(); //FIXME also add this to the inforssXML reader let prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("inforss."); prefs.setBoolPref("debug.alert", list.firstChild.getAttribute("debug") == "true"); prefs.setBoolPref("debug.log", list.firstChild.getAttribute("log") == "true"); prefs.setBoolPref("debug.statusbar", list.firstChild.getAttribute("statusbar") == "true"); } catch (e) { inforssDebug(e); } }, //---------------------------------------------------------------------------- add_item(title, description, url, link, user, password, type) { inforssTraceIn(); try { if (RSSList == null) { RSSList = new DOMParser().parseFromString('<LIST-RSS/>', 'text/xml'); /**/console.log("created empty rss", RSSList); } return this._new_item(RSSList, title, description, url, link, user, password, type); } catch (e) { inforssDebug(e); return null; } finally { inforssTraceOut(); } }, //---------------------------------------------------------------------------- //FIXME maybe should pass the icon? _new_item(list, title, description, url, link, user, password, type) { inforssTraceIn(); try { let elem = list.createElement("RSS"); elem.setAttribute("url", url); elem.setAttribute("title", title); elem.setAttribute("link", link == null || link == "" ? url : link); elem.setAttribute("description", description == null || description == "" ? title : description); if (user != null && user != "") { elem.setAttribute("user", user); this.storePassword(url, user, password); } elem.setAttribute("type", type); //FIXME These also need to be updated in feeds_default array for when //updating to new version. elem.setAttribute("selected", "false"); elem.setAttribute("nbItem", this.feeds_default_max_num_headlines()); elem.setAttribute("lengthItem", this.feeds_default_max_headline_length()); elem.setAttribute("playPodcast", this.feed_defaults_play_podcast() ? "true" : "false"); elem.setAttribute("savePodcastLocation", this.feeds_default_podcast_location()); elem.setAttribute("purgeHistory", this.feeds_default_history_purge_days()); elem.setAttribute("browserHistory", this.feed_defaults_use_browser_history() ? "true" : "false"); elem.setAttribute("filterCaseSensitive", "true"); elem.setAttribute("icon", INFORSS_DEFAULT_ICO); elem.setAttribute("refresh", this.feeds_default_refresh_time()); elem.setAttribute("activity", "true"); elem.setAttribute("filter", "all"); elem.setAttribute("groupAssociated", "false"); elem.setAttribute("group", "false"); elem.setAttribute("filterPolicy", "0"); elem.setAttribute("encoding", ""); list.firstChild.appendChild(elem); return elem; } catch (e) { inforssDebug(e); return null; } finally { inforssTraceOut(); } }, //FIXME Move this back to OPML code export_to_OPML(filePath, progress) { //FIXME Should do an atomic write (to a temp file and then rename) //Might be better to just generate a string and let the client resolve where //to put it. let opmlFile = new LocalFile(filePath); let stream = new FileOutputStream(opmlFile, -1, -1, 0); let sequence = Promise.resolve(1); //FIXME Should just create the opml document then stream it, but need an //async stream to get the feedback. let opml = new DOMParser().parseFromString("<opml/>", "text/xml"); let str = '<?xml version="1.0" encoding="UTF-8"?>\n' + '<opml version="1.0">\n' + ' <head>\n' + ' <title>InfoRSS Data</title>\n' + ' </head>\n' + ' <body>\n'; stream.write(str, str.length); let serializer = new XMLSerializer(); let items = RSSList.querySelectorAll("RSS:not([type=group])"); for (let iteml of items) { let item = iteml; //Hack - according to JS6 this is unnecessary sequence = sequence.then(i => { let outline = opml.createElement("outline"); outline.setAttribute("xmlHome", item.getAttribute("link")); outline.setAttribute("xmlUrl", item.getAttribute("url")); for (let attribute of opml_attributes) { outline.setAttribute(attribute, item.getAttribute(attribute)); } serializer.serializeToStream(outline, stream, "UTF-8"); stream.write("\n", "\n".length); progress(i, items.length); //Give the javascript machine a chance to display the progress bar. return new Promise(function(resolve /*, reject*/ ) { setTimeout(i => resolve(i + 1), 0, i); }); }); } sequence = sequence.then(function() { str = ' </body>\n' + '</opml>'; stream.write(str, str.length); stream.close(); }); return sequence; }, //---------------------------------------------------------------------------- backup() { try { let file = this.get_filepath(); if (file.exists()) { let backup = profile_dir.clone(); backup.append(INFORSS_BACKUP); if (backup.exists()) { backup.remove(true); } file.copyTo(null, INFORSS_BACKUP); } } catch (e) { inforssDebug(e); } }, //---------------------------------------------------------------------------- //FIXME Move this back to OPML code? import_from_OPML(text, mode, progress) { let domFile = new DOMParser().parseFromString(text, "text/xml"); if (domFile.documentElement.nodeName != "opml") { return null; } let list = RSSList.cloneNode(mode == MODE_APPEND); let sequence = Promise.resolve( { count: 1, list: list }); let items = domFile.querySelectorAll("outline[type=rss], outline[xmlUrl]"); for (let iteml of items) { let item = iteml; //Hack for non compliant browser sequence = sequence.then(where => { let link = item.hasAttribute("xmlHome") ? item.getAttribute("xmlHome") : item.hasAttribute("htmlUrl") ? item.getAttribute("htmlUrl") : null; let rss = this._new_item(where.list, item.getAttribute("title"), item.getAttribute("text"), item.getAttribute("xmlUrl"), link, //Not entirely clear to me why we //export username to OPML null, null, item.getAttribute("type")); for (let attribute of opml_attributes) { if (item.hasAttribute(attribute)) { rss.setAttribute(attribute, item.getAttribute(attribute)); } } if (!rss.hasAttribute("icon") || rss.getAttribute("icon") == "") { //FIXME - findicon should in fact be async, would need a module for it //The mozilla api is useless. The following works, but only sometimes, //and seems to require having the page visited in the right way: /* const Cc = Components.classes; const Ci = Components.interfaces; const IO = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService); let link = rss.getAttribute('link'); console.log(link); let url = IO.newURI(link, null, null); const FaviconService = Cc["@mozilla.org/browser/favicon-service;1"].getService(Ci.nsIFaviconService); const asyncFavicons = FaviconService.QueryInterface(Ci.mozIAsyncFavicons); asyncFavicons.getFaviconDataForPage(url, function(aURI, aDataLen, aData, aMimeType) { console.log(1080, aURI.asciiSpec, aDataLen, aData, aMimeType); }); asyncFavicons.getFaviconURLForPage(url, function(aURI, aDataLen, aData, aMimeType) { console.log(1084, aURI.asciiSpec, aDataLen, aData, aMimeType); }); if (link.startsWith('http:')) { link = link.slice(0, 4) + 's' + link.slice(4); console.log(link); url = IO.newURI(link, null, null); asyncFavicons.getFaviconDataForPage(url, function(aURI, aDataLen, aData, aMimeType) { console.log(1080, aURI.asciiSpec, aDataLen, aData, aMimeType); }); } */ rss.setAttribute("icon", inforssFindIcon(rss)); } //Possibly want to do tsomething like this, though this would lose all //the custom settings above. Also if we did this we wouldn't need to add //them to the list. //var observerService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService); //observerService.notifyObservers(null, "addFeed", rss.getAttribute("url")); progress(where.count, items.length); //Give the javascript machine a chance to display the progress bar. return new Promise(function(resolve /*, reject*/ ) { setTimeout(where => { where.count = where.count + 1; resolve(where); }, 0, where); }); }); } sequence = sequence.then(where => { this.backup(); //FIXME. Do not update the list it just causes grief /**/ console.log("suppressed setting to ", where); /**/ inforssDebug(new Error()); //RSSList = where.list; return new Promise(resolve => resolve(where.list.firstChild.childNodes.length)); }); return sequence; }, //---------------------------------------------------------------------------- //FIXME once this is all in its own class, this should be in the "constructor" //need to be a bit careful about alerting the error if it's possible to keep //the error handling outside of here. read_configuration() { let file = this.get_filepath(); if (!file.exists() || file.fileSize == 0) { this.reset_xml_to_default(); } let is = new FileInputStream(file, -1, -1, 0); let sis = new ScriptableInputStream(is); let data = sis.read(-1); sis.close(); is.close(); this.load_from_string(data); }, //load configuration from xml string. //FIXME Should this take a stream instead? //FIXME Why would you convert utf-8 to utf-8? load_from_string(data) { let uConv = new UTF8Converter(); data = uConv.convertStringToUTF8(data, "UTF-8", false); let new_list = new DOMParser().parseFromString(data, "text/xml"); this._adjust_repository(new_list); RSSList = new_list; }, //write configuration to xml string. //FIXME Should this take a stream instead? to_string() { return new XMLSerializer().serializeToString(RSSList); }, //---------------------------------------------------------------------------- _convert_4_to_5(list) { let config = list.firstChild; let rename_attribute = function(old_name, new_name) { if (config.hasAttribute(old_name)) { if (!config.hasAttribute(new_name)) { config.setAttribute(new_name, config.getAttribute(old_name)); } config.removeAttribute(old_name); } }; if (config.getAttribute("switch") == "on") { config.setAttribute("switch", "true"); } if (config.getAttribute("scrolling") == "true") { config.setAttribute("scrolling", "1"); } else if (config.getAttribute("scrolling") == "false") { config.setAttribute("scrolling", "0"); } rename_attribute("purgeHistory", "defaultPurgeHistory"); for (let item of list.getElementsByTagName("RSS")) { if (item.hasAttribute("password")) { if (item.getAttribute("password") != "") { inforssXMLRepository.storePassword(item.getAttribute("url"), item.getAttribute("user"), item.getAttribute("password")); } item.removeAttribute("password"); } } }, //---------------------------------------------------------------------------- _convert_5_to_6(list) { let config = list.firstChild; let rename_attribute = function(old_name, new_name) { if (config.hasAttribute(old_name)) { if (!config.hasAttribute(new_name)) { config.setAttribute(new_name, config.getAttribute(old_name)); } config.removeAttribute(old_name); } }; rename_attribute("DefaultPurgeHistory", "defaultPurgeHistory"); rename_attribute("shuffleicon", "shuffleIcon"); let items = list.getElementsByTagName("RSS"); for (let item of items) { if (item.hasAttribute("user") && (item.getAttribute("user") == "" || item.getAttribute("user") == "null")) { item.removeAttribute("user"); } if (item.getAttribute("type") == "html" && !item.hasAttribute("htmlDirection")) { item.setAttribute("htmlDirection", "asc"); } if (!item.hasAttribute("browserHistory")) { item.setAttribute("browserHistory", "true"); if (item.getAttribute("url").indexOf("https://gmail.google.com/gmail/feed/atom") == 0 || item.getAttribute("url").indexOf(".ebay.") != -1) { item.setAttribute("browserHistory", "false"); } } if (item.getAttribute("type") == "group" && !item.hasAttribute("playlist")) { item.setAttribute("playlist", "false"); } if (item.hasAttribute("icon") && item.getAttribute("icon") == "") { item.setAttribute("icon", INFORSS_DEFAULT_ICO); } } this._set_defaults(list); }, _convert_6_to_7(list) { let config = list.firstChild; config.removeAttribute("mouseEvent"); config.removeAttribute("net"); }, _convert_7_to_8(list) { let config = list.firstChild; config.removeAttribute("groupNbItem"); config.removeAttribute("groupLenghtItem"); config.removeAttribute("groupRefresh"); config.removeAttribute("false"); //Embarassing result of fix to strange code if (config.getAttribute("font") == "auto") { config.setAttribute("font", "inherit"); } { const fontSize = config.getAttribute("fontSize"); if (fontSize == "auto") { config.setAttribute("fontSize", "inherit"); } else if (!isNaN(fontSize)) { config.setAttribute("fontSize", fontSize + "pt"); } } //If defaultForegroundColor is "sameas", we need to swap that and //foregroundColor if (config.getAttribute("defaultForegroundColor") == "sameas") { let colour = config.getAttribute("foregroundColor"); if (colour == "auto") { colour = "default"; } config.setAttribute("defaultForegroundColor", colour); config.setAttribute("foregroundColor", "sameas"); } //Convert the 3 r/g/b to one single background colour. //A note: This is questionable in a sense, but css takes html colours and //html doesn't take css colour specs. if (config.hasAttribute("red")) { const red = Number(config.getAttribute("red")); if (red == "-1") { config.setAttribute("backgroundColour", "inherit"); } else { const green = Number(config.getAttribute("green")); const blue = Number(config.getAttribute("blue")); config.setAttribute( "backgroundColour", '#' + ("000000" + ((red * 256 + green) * 256 + blue).toString(16)).substr(-6)); } config.removeAttribute("red"); config.removeAttribute("green"); config.removeAttribute("blue"); } }, //---------------------------------------------------------------------------- _adjust_repository(list) { let config = list.firstChild; if (config.getAttribute("version") <= "4") { this._convert_4_to_5(list); } if (config.getAttribute("version") <= "5") { this._convert_5_to_6(list); } if (config.getAttribute("version") <= "6") { this._convert_6_to_7(list); } if (config.getAttribute("version") <= "7") { this._convert_7_to_8(list); } //FIXME this should be done properly when saving and then it becomes part of //a normal convert. { let items = list.getElementsByTagName("RSS"); for (let item of items) { item.setAttribute("groupAssociated", "false"); } for (let group of items) { if (group.getAttribute("type") == "group") { for (let feed of group.getElementsByTagName("GROUP")) { let url = feed.getAttribute("url"); for (let item of items) { if (item.getAttribute("type") != "group" && item.getAttribute("url") == url) { item.setAttribute("groupAssociated", "true"); break; } } } } } } //NOTNOTENOTE Check this before release. //It should be set to what is up above if (config.getAttribute("version") != "7") { config.setAttribute("version", 7); this.backup(); this._save(list); } }, //---------------------------------------------------------------------------- _set_defaults(list) { //Add in missing defaults const defaults = { backgroundColour: "#7fc0ff", delay: 15, refresh: 2, "switch": true, separateLine: false, scrolling: 1, submenu: false, group: false, linePosition: "bottom", debug: false, log: false, statusbar: false, bold: true, italic: true, currentfeed: true, livemark: true, clipboard: true, scrollingspeed: 19, font: "inherit", foregroundColor: "auto", defaultForegroundColor: "default", favicon: true, scrollingArea: 500, hideViewed: false, tooltip: "description", clickHeadline: 0, hideOld: false, sortedMenu: "asc", hideHistory: true, includeAssociated: true, cycling: false, cyclingDelay: 5, nextFeed: "next", defaultPurgeHistory: 3, fontSize: "inherit", stopscrolling: true, cycleWithinGroup: false, defaultGroupIcon: "chrome://inforss/skin/group.png", scrollingdirection: "rtl", readAllIcon: true, viewAllIcon: true, shuffleIcon: true, directionIcon: true, scrollingIcon: true, previousIcon: true, pauseIcon: true, nextIcon: true, synchronizeIcon: false, refreshIcon: false, hideOldIcon: false, hideViewedIcon: false, homeIcon: true, filterIcon: true, popupMessage: true, playSound: true, flashingIcon: true, defaultPlayPodcast: true, displayEnclosure: true, displayBanned: true, savePodcastLocation: "", defaultBrowserHistory: true, collapseBar: false, scrollingIncrement: 2, quickFilter: "", quickFilterActif: false, timeslice: 90, mouseWheelScroll: "pixel", defaultNbItem: 9999, defaultLenghtItem: 25, synchronizationIcon: false, }; let config = list.firstChild; for (let attrib in defaults) { if (!defaults.hasOwnProperty(attrib)) { continue; } if (!config.hasAttribute(attrib)) { config.setAttribute(attrib, defaults[attrib]); } } //Now for the rss items //FIXME see also add_item and anywhere that creates a new item. const feed_defaults = { group: false, selected: false, nbItem: config.getAttribute("defaultNbItem"), lengthItem: config.getAttribute("defaultLenghtItem"), playPodcast: config.getAttribute("defaultPlayPodcast"), savePodcastLocation: config.getAttribute("savePodcastLocation"), purgeHistory: config.getAttribute("defaultPurgeHistory"), browserHistory: config.getAttribute("defaultBrowserHistory"), filterCaseSensitive: true, refresh: config.getAttribute("refresh"), activity: true, filter: "all", type: "rss", filterPolicy: 0, encoding: "", icon: INFORSS_DEFAULT_ICO, description: "", groupAssociated: false }; for (let item of list.getElementsByTagName("RSS")) { for (let attrib in feed_defaults) { if (!feed_defaults.hasOwnProperty(attrib)) { continue; } if (!item.hasAttribute(attrib)) { item.setAttribute(attrib, feed_defaults[attrib]); } } } }, //---------------------------------------------------------------------------- reset_xml_to_default() { //Back up the current file if it exists so recovery may be attempted { let file = this.get_filepath(); if (file.exists()) { const INFORSS_INERROR = "inforss_xml.inerror"; let dest = profile_dir.clone(); dest.append(INFORSS_INERROR); if (dest.exists()) { dest.remove(false); } file.renameTo(profile_dir, INFORSS_INERROR); } } //Copy the default setup. let source = inforssGetResourceFile("inforss.default"); if (source.exists()) { source.copyTo(profile_dir, INFORSS_REPOSITORY); } }, }; //---------------------------------------------------------------------------- /* exported inforssGetItemFromUrl */ //FIXME Should be a method of the above //FIXME replace with document.querySelector(RSS[url=url]) (i think) function inforssGetItemFromUrl(url) { inforssTraceIn(); try { for (let item of inforssXMLRepository.get_all()) { if (item.getAttribute("url") == url) { return item; } } } finally { inforssTraceOut(); } return null; } //---------------------------------------------------------------------------- /* exported getCurrentRSS */ //FIXME Should be a method of the above //FIXME Use document.querySelector function getCurrentRSS() { inforssTraceIn(); try { for (let item of inforssXMLRepository.get_all()) { if (item.getAttribute("selected") == "true") { return item; } } } finally { inforssTraceOut(); } return null; } /* exported inforssXMLRepository */ var inforssXMLRepository = new XML_Repository();
Removed dead method and sorted defaults
source/content/inforss/inforssXMLRepository.js
Removed dead method and sorted defaults
<ide><path>ource/content/inforss/inforssXMLRepository.js <ide> }, <ide> <ide> //---------------------------------------------------------------------------- <del> isPlayList() <del> { <del> return RSSList.firstChild.getAttribute("playlist") == "true"; <del> }, <del> <del> //---------------------------------------------------------------------------- <ide> switchShuffle() <ide> { <ide> if (RSSList.firstChild.getAttribute("nextFeed") == "next") <ide> //Add in missing defaults <ide> const defaults = { <ide> backgroundColour: "#7fc0ff", <del> delay: 15, <del> refresh: 2, <del> "switch": true, <del> separateLine: false, <del> scrolling: 1, <del> submenu: false, <del> group: false, <del> linePosition: "bottom", <del> debug: false, <del> log: false, <del> statusbar: false, <ide> bold: true, <del> italic: true, <add> clickHeadline: 0, <add> clipboard: true, <add> collapseBar: false, <ide> currentfeed: true, <del> livemark: true, <del> clipboard: true, <del> scrollingspeed: 19, <del> font: "inherit", <del> foregroundColor: "auto", <del> defaultForegroundColor: "default", <del> favicon: true, <del> scrollingArea: 500, <del> hideViewed: false, <del> tooltip: "description", <del> clickHeadline: 0, <del> hideOld: false, <del> sortedMenu: "asc", <del> hideHistory: true, <del> includeAssociated: true, <add> cycleWithinGroup: false, <ide> cycling: false, <ide> cyclingDelay: 5, <del> nextFeed: "next", <add> debug: false, <add> defaultBrowserHistory: true, <add> defaultForegroundColor: "default", <add> defaultGroupIcon: "chrome://inforss/skin/group.png", <add> defaultLenghtItem: 25, <add> defaultNbItem: 9999, <add> defaultPlayPodcast: true, <ide> defaultPurgeHistory: 3, <add> delay: 15, <add> directionIcon: true, <add> displayBanned: true, <add> displayEnclosure: true, <add> favicon: true, <add> filterIcon: true, <add> flashingIcon: true, <add> font: "inherit", <ide> fontSize: "inherit", <del> stopscrolling: true, <del> cycleWithinGroup: false, <del> defaultGroupIcon: "chrome://inforss/skin/group.png", <del> scrollingdirection: "rtl", <del> readAllIcon: true, <del> viewAllIcon: true, <del> shuffleIcon: true, <del> directionIcon: true, <del> scrollingIcon: true, <del> previousIcon: true, <del> pauseIcon: true, <del> nextIcon: true, <del> synchronizeIcon: false, <del> refreshIcon: false, <add> foregroundColor: "auto", <add> group: false, <add> hideHistory: true, <add> hideOld: false, <ide> hideOldIcon: false, <add> hideViewed: false, <ide> hideViewedIcon: false, <ide> homeIcon: true, <del> filterIcon: true, <add> includeAssociated: true, <add> italic: true, <add> linePosition: "bottom", <add> livemark: true, <add> log: false, <add> mouseWheelScroll: "pixel", <add> nextFeed: "next", <add> nextIcon: true, <add> pauseIcon: true, <add> playSound: true, <ide> popupMessage: true, <del> playSound: true, <del> flashingIcon: true, <del> defaultPlayPodcast: true, <del> displayEnclosure: true, <del> displayBanned: true, <del> savePodcastLocation: "", <del> defaultBrowserHistory: true, <del> collapseBar: false, <del> scrollingIncrement: 2, <add> previousIcon: true, <ide> quickFilter: "", <ide> quickFilterActif: false, <add> readAllIcon: true, <add> refresh: 2, <add> refreshIcon: false, <add> savePodcastLocation: "", <add> scrolling: 1, <add> scrollingArea: 500, <add> scrollingIcon: true, <add> scrollingIncrement: 2, <add> scrollingdirection: "rtl", <add> scrollingspeed: 19, <add> separateLine: false, <add> shuffleIcon: true, <add> sortedMenu: "asc", <add> statusbar: false, <add> stopscrolling: true, <add> submenu: false, <add> "switch": true, <add> synchronizationIcon: false, <add> synchronizeIcon: false, <ide> timeslice: 90, <del> mouseWheelScroll: "pixel", <del> defaultNbItem: 9999, <del> defaultLenghtItem: 25, <del> synchronizationIcon: false, <add> tooltip: "description", <add> viewAllIcon: true, <ide> }; <ide> <ide> let config = list.firstChild; <ide> //Now for the rss items <ide> //FIXME see also add_item and anywhere that creates a new item. <ide> const feed_defaults = { <add> activity: true, <add> browserHistory: config.getAttribute("defaultBrowserHistory"), <add> description: "", <add> encoding: "", <add> filter: "all", <add> filterCaseSensitive: true, <add> filterPolicy: 0, <ide> group: false, <add> groupAssociated: false, <add> icon: INFORSS_DEFAULT_ICO, <add> lengthItem: config.getAttribute("defaultLenghtItem"), <add> nbItem: config.getAttribute("defaultNbItem"), <add> playPodcast: config.getAttribute("defaultPlayPodcast"), <add> purgeHistory: config.getAttribute("defaultPurgeHistory"), <add> refresh: config.getAttribute("refresh"), <add> savePodcastLocation: config.getAttribute("savePodcastLocation"), <ide> selected: false, <del> nbItem: config.getAttribute("defaultNbItem"), <del> lengthItem: config.getAttribute("defaultLenghtItem"), <del> playPodcast: config.getAttribute("defaultPlayPodcast"), <del> savePodcastLocation: config.getAttribute("savePodcastLocation"), <del> purgeHistory: config.getAttribute("defaultPurgeHistory"), <del> browserHistory: config.getAttribute("defaultBrowserHistory"), <del> filterCaseSensitive: true, <del> refresh: config.getAttribute("refresh"), <del> activity: true, <del> filter: "all", <ide> type: "rss", <del> filterPolicy: 0, <del> encoding: "", <del> icon: INFORSS_DEFAULT_ICO, <del> description: "", <del> groupAssociated: false <ide> }; <ide> for (let item of list.getElementsByTagName("RSS")) <ide> {
JavaScript
mit
32f9b9daf1ec2586e88dae1bb148d3b7c544a0e3
0
drd/react-isomorphic-boilerplate
var chalk = require('chalk'); var webpack = require('webpack'); var environments = { production: { vendor: ['react', 'react-router'], plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }) ] }, development: { vendor: ['webpack-dev-server/client?http://localhost:3000', 'webpack/hot/dev-server', 'react', 'react-router'], plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }), new webpack.HotModuleReplacementPlugin() ], } }; module.exports = { context: __dirname + '/app', entry: { // output 2 bundles of javascript, one for vendor, one for application vendor: env('vendor'), app: './client.jsx' }, output: { filename: 'client.js', path: __dirname + '/dist', publicPath: '/js' }, devtool: 'eval', plugins: env('plugins'), resolve: { // Look directly in app dir for modules root: __dirname + '/app', // Allow to omit extensions when requiring these files extensions: ['', '.js', '.jsx'] }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['6to5?sourceMap&experimental'] }, // Pass *.jsx files through jsx-loader transform { test: /\.jsx$/, loaders: ['react-hot', '6to5?sourceMap&experimental', 'jsx'] }, { test: /\.css$/, loaders: ['style', 'css'] } ] } } function env(key) { var result = undefined; try { var env = process.env.NODE_ENV || 'development'; result = environments[env][key]; if (result === undefined) { console.warn(chalk.yellow('Undefined environment key', key, ' in ', env)); } return result; } catch(e) { console.error(chalk.red('Exception occurred retrieving environment config key', key, ' in ', env)); console.error(e.stack); process.exit(1); } }
webpack.config.js
var chalk = require('chalk'); var webpack = require('webpack'); module.exports = { context: __dirname + '/app', entry: { vendor: env('vendor'), app: './client.jsx' }, output: { filename: 'client.js', path: __dirname + '/dist', publicPath: '/js' }, devtool: 'eval', plugins: env('plugins'), resolve: { // Look directly in app dir for modules root: __dirname + '/app', // Allow to omit extensions when requiring these files extensions: ['', '.js', '.jsx'] }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loaders: ['6to5?sourceMap&experimental'] }, // Pass *.jsx files through jsx-loader transform { test: /\.jsx$/, loaders: ['react-hot', '6to5?sourceMap&experimental', 'jsx'] }, { test: /\.css$/, loaders: ['style', 'css'] } ] } } var environments = { production: { vendor: ['react', 'react-router'], plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }) ] }, development: { vendor: ['webpack-dev-server/client?http://localhost:3000', 'webpack/hot/dev-server', 'react', 'react-router'], plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }), new webpack.HotModuleReplacementPlugin() ], } }; function env(key) { var result = undefined; try { var env = process.env.NODE_ENV || 'development'; result = environments[env][key]; if (result === undefined) { console.warn(chalk.yellow('Undefined environment key %s in %s', key, env)); } return result; } catch(e) { console.error(chalk.red('Exception occurred retrieving environment config key %s in %s', key, env)); process.exit(1); } }
Fix derped webpack config
webpack.config.js
Fix derped webpack config
<ide><path>ebpack.config.js <ide> var chalk = require('chalk'); <ide> var webpack = require('webpack'); <del> <del> <del>module.exports = { <del> context: __dirname + '/app', <del> entry: { <del> vendor: env('vendor'), <del> app: './client.jsx' <del> }, <del> output: { <del> filename: 'client.js', <del> path: __dirname + '/dist', <del> publicPath: '/js' <del> }, <del> devtool: 'eval', <del> plugins: env('plugins'), <del> resolve: { <del> // Look directly in app dir for modules <del> root: __dirname + '/app', <del> // Allow to omit extensions when requiring these files <del> extensions: ['', '.js', '.jsx'] <del> }, <del> module: { <del> loaders: [ <del> { test: /\.js$/, exclude: /node_modules/, loaders: ['6to5?sourceMap&experimental'] }, <del> // Pass *.jsx files through jsx-loader transform <del> { test: /\.jsx$/, loaders: ['react-hot', '6to5?sourceMap&experimental', 'jsx'] }, <del> { test: /\.css$/, loaders: ['style', 'css'] } <del> ] <del> } <del>} <ide> <ide> <ide> var environments = { <ide> }; <ide> <ide> <add>module.exports = { <add> context: __dirname + '/app', <add> entry: { <add> // output 2 bundles of javascript, one for vendor, one for application <add> vendor: env('vendor'), <add> app: './client.jsx' <add> }, <add> output: { <add> filename: 'client.js', <add> path: __dirname + '/dist', <add> publicPath: '/js' <add> }, <add> devtool: 'eval', <add> plugins: env('plugins'), <add> resolve: { <add> // Look directly in app dir for modules <add> root: __dirname + '/app', <add> // Allow to omit extensions when requiring these files <add> extensions: ['', '.js', '.jsx'] <add> }, <add> module: { <add> loaders: [ <add> { test: /\.js$/, exclude: /node_modules/, loaders: ['6to5?sourceMap&experimental'] }, <add> // Pass *.jsx files through jsx-loader transform <add> { test: /\.jsx$/, loaders: ['react-hot', '6to5?sourceMap&experimental', 'jsx'] }, <add> { test: /\.css$/, loaders: ['style', 'css'] } <add> ] <add> } <add>} <add> <add> <ide> function env(key) { <ide> var result = undefined; <ide> try { <ide> var env = process.env.NODE_ENV || 'development'; <ide> result = environments[env][key]; <ide> if (result === undefined) { <del> console.warn(chalk.yellow('Undefined environment key %s in %s', key, env)); <add> console.warn(chalk.yellow('Undefined environment key', key, ' in ', env)); <ide> } <ide> return result; <ide> } catch(e) { <del> console.error(chalk.red('Exception occurred retrieving environment config key %s in %s', key, env)); <add> console.error(chalk.red('Exception occurred retrieving environment config key', key, ' in ', env)); <add> console.error(e.stack); <ide> process.exit(1); <ide> } <ide> }
Java
apache-2.0
0894b7700343a048358ec2ae3e5397e033de74dd
0
HanSolo/Medusa
/* * Copyright (c) 2016 by Gerrit Grunwald * * 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 eu.hansolo.medusa.skins; import eu.hansolo.medusa.Fonts; import eu.hansolo.medusa.Gauge; import eu.hansolo.medusa.Gauge.ScaleDirection; import eu.hansolo.medusa.Section; import eu.hansolo.medusa.tools.Helper; import javafx.geometry.Insets; import javafx.scene.CacheHint; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Skin; import javafx.scene.control.SkinBase; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.Border; import javafx.scene.layout.BorderStroke; import javafx.scene.layout.BorderStrokeStyle; import javafx.scene.layout.BorderWidths; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.Arc; import javafx.scene.shape.ArcType; import javafx.scene.shape.StrokeLineCap; import javafx.scene.text.Text; import java.util.List; /** * Created by hansolo on 25.07.16. */ public class SimpleSectionSkin extends SkinBase<Gauge> implements Skin<Gauge> { private static final double PREFERRED_WIDTH = 250; private static final double PREFERRED_HEIGHT = 250; private static final double MINIMUM_WIDTH = 50; private static final double MINIMUM_HEIGHT = 50; private static final double MAXIMUM_WIDTH = 1024; private static final double MAXIMUM_HEIGHT = 1024; private static final double ANGLE_RANGE = 300; private double size; private Canvas sectionCanvas; private GraphicsContext sectionCtx; private Arc barBackground; private Arc bar; private Text titleText; private Text valueText; private Text unitText; private Pane pane; private List<Section> sections; private String formatString; // ******************** Constructors ************************************** public SimpleSectionSkin(Gauge gauge) { super(gauge); if (gauge.isAutoScale()) gauge.calcAutoScale(); formatString = new StringBuilder("%.").append(Integer.toString(gauge.getDecimals())).append("f").toString(); sections = gauge.getSections(); initGraphics(); registerListeners(); setBar(gauge.getCurrentValue()); } // ******************** Initialization ************************************ private void initGraphics() { // Set initial size if (Double.compare(getSkinnable().getPrefWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getPrefHeight(), 0.0) <= 0 || Double.compare(getSkinnable().getWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getHeight(), 0.0) <= 0) { if (getSkinnable().getPrefWidth() > 0 && getSkinnable().getPrefHeight() > 0) { getSkinnable().setPrefSize(getSkinnable().getPrefWidth(), getSkinnable().getPrefHeight()); } else { getSkinnable().setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); } } sectionCanvas = new Canvas(PREFERRED_WIDTH, PREFERRED_HEIGHT); sectionCtx = sectionCanvas.getGraphicsContext2D(); barBackground = new Arc(PREFERRED_WIDTH * 0.5, PREFERRED_HEIGHT * 0.5, PREFERRED_WIDTH * 0.4, PREFERRED_HEIGHT * 0.4, getSkinnable().getStartAngle() + 150, ANGLE_RANGE); barBackground.setType(ArcType.OPEN); barBackground.setStroke(getSkinnable().getBarBackgroundColor()); barBackground.setStrokeWidth(PREFERRED_WIDTH * 0.125); barBackground.setStrokeLineCap(StrokeLineCap.BUTT); barBackground.setFill(null); bar = new Arc(PREFERRED_WIDTH * 0.5, PREFERRED_HEIGHT * 0.5, PREFERRED_WIDTH * 0.4, PREFERRED_HEIGHT * 0.4, getSkinnable().getStartAngle() + 90, 0); bar.setType(ArcType.OPEN); bar.setStroke(getSkinnable().getBarColor()); bar.setStrokeWidth(PREFERRED_WIDTH * 0.125); bar.setStrokeLineCap(StrokeLineCap.BUTT); bar.setFill(null); titleText = new Text(getSkinnable().getTitle()); titleText.setFill(getSkinnable().getTitleColor()); Helper.enableNode(titleText, !getSkinnable().getTitle().isEmpty()); valueText = new Text(); valueText.setStroke(null); valueText.setFill(getSkinnable().getValueColor()); Helper.enableNode(valueText, getSkinnable().isValueVisible()); unitText = new Text(); unitText.setStroke(null); unitText.setFill(getSkinnable().getUnitColor()); Helper.enableNode(unitText, getSkinnable().isValueVisible() && !getSkinnable().getUnit().isEmpty()); pane = new Pane(barBackground, sectionCanvas, titleText, valueText, unitText, bar); getChildren().setAll(pane); } private void registerListeners() { getSkinnable().widthProperty().addListener(o -> handleEvents("RESIZE")); getSkinnable().heightProperty().addListener(o -> handleEvents("RESIZE")); getSkinnable().decimalsProperty().addListener(o -> handleEvents("DECIMALS")); getSkinnable().setOnUpdate(e -> handleEvents(e.eventType.name())); getSkinnable().currentValueProperty().addListener(o -> setBar(getSkinnable().getCurrentValue())); getSkinnable().decimalsProperty().addListener(o -> handleEvents("DECIMALS")); } // ******************** Methods ******************************************* @Override protected double computeMinWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MINIMUM_WIDTH; } @Override protected double computeMinHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MINIMUM_HEIGHT; } @Override protected double computePrefWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return super.computePrefWidth(HEIGHT, TOP, RIGHT, BOTTOM, LEFT); } @Override protected double computePrefHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return super.computePrefHeight(WIDTH, TOP, RIGHT, BOTTOM, LEFT); } @Override protected double computeMaxWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MAXIMUM_WIDTH; } @Override protected double computeMaxHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MAXIMUM_HEIGHT; } private void handleEvents(final String EVENT_TYPE) { if ("VISIBILITY".equals(EVENT_TYPE)) { Helper.enableNode(valueText, getSkinnable().isValueVisible()); Helper.enableNode(unitText, getSkinnable().isValueVisible() && !getSkinnable().getUnit().isEmpty()); } else if ("SECTIONS".equals(EVENT_TYPE)) { sections = getSkinnable().getSections(); } else if ("RESIZE".equals(EVENT_TYPE)) { resize(); redraw(); } else if ("REDRAW".equals(EVENT_TYPE)) { redraw(); } else if ("RECALC".equals(EVENT_TYPE)) { redraw(); setBar(getSkinnable().getCurrentValue()); } else if ("DECIMALS".equals(EVENT_TYPE)) { formatString = new StringBuilder("%.").append(Integer.toString(getSkinnable().getDecimals())).append("f").toString(); } } // ******************** Canvas ******************************************** private void setBar(final double VALUE) { bar.setStartAngle(getSkinnable().getStartAngle() + 90 + getSkinnable().getMinValue() * getSkinnable().getAngleStep()); if (getSkinnable().getMinValue() > 0) { bar.setLength((getSkinnable().getMinValue() - VALUE) * getSkinnable().getAngleStep()); } else { bar.setLength(-VALUE * getSkinnable().getAngleStep()); } if (getSkinnable().getSectionsVisible() && !sections.isEmpty()) { bar.setStroke(getSkinnable().getBarColor()); for (Section section : sections) { if (section.contains(VALUE)) { bar.setStroke(section.getColor()); break; } } } valueText.setText(String.format(getSkinnable().getLocale(), formatString, VALUE)); valueText.setLayoutX((size - valueText.getLayoutBounds().getWidth()) * 0.5); } private void drawBackground() { sectionCanvas.setCache(false); sectionCtx.setLineCap(StrokeLineCap.BUTT); sectionCtx.clearRect(0, 0, size, size); if (getSkinnable().getSectionsVisible() && !sections.isEmpty()) { double xy = 0.012 * size; double wh = size * 0.976; double minValue = getSkinnable().getMinValue(); double maxValue = getSkinnable().getMaxValue(); double angleStep = getSkinnable().getAngleStep(); sectionCtx.setLineWidth(size * 0.025); sectionCtx.setLineCap(StrokeLineCap.BUTT); for (int i = 0; i < sections.size(); i++) { Section section = sections.get(i); double sectionStartAngle; if (Double.compare(section.getStart(), maxValue) <= 0 && Double.compare(section.getStop(), minValue) >= 0) { if (Double.compare(section.getStart(), minValue) < 0 && Double.compare(section.getStop(), maxValue) < 0) { sectionStartAngle = 0; } else { sectionStartAngle = ScaleDirection.CLOCKWISE == getSkinnable().getScaleDirection() ? (section.getStart() - minValue) * angleStep : -(section.getStart() - minValue) * angleStep; } double sectionAngleExtend; if (Double.compare(section.getStop(), maxValue) > 0) { sectionAngleExtend = ScaleDirection.CLOCKWISE == getSkinnable().getScaleDirection() ? (maxValue - section.getStart()) * angleStep : -(maxValue - section.getStart()) * angleStep; } else if (Double.compare(section.getStart(), minValue) < 0) { sectionAngleExtend = ScaleDirection.CLOCKWISE == getSkinnable().getScaleDirection() ? (section.getStop() - minValue) * getSkinnable().getAngleStep() : -(section.getStop() - minValue) * angleStep; } else { sectionAngleExtend = ScaleDirection.CLOCKWISE == getSkinnable().getScaleDirection() ? (section.getStop() - section.getStart()) * angleStep : -(section.getStop() - section.getStart()) * angleStep; } sectionCtx.save(); sectionCtx.setStroke(section.getColor()); sectionCtx.strokeArc(xy, xy, wh, wh, -(120 + sectionStartAngle), -sectionAngleExtend, ArcType.OPEN); sectionCtx.restore(); } } } sectionCanvas.setCache(true); sectionCanvas.setCacheHint(CacheHint.QUALITY); } // ******************** Resizing ****************************************** private void resizeValueText() { double maxWidth = size * 0.86466165; double fontSize = size * 0.2556391; valueText.setFont(Fonts.latoLight(fontSize)); if (valueText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(valueText, maxWidth, fontSize); } valueText.relocate((size - valueText.getLayoutBounds().getWidth()) * 0.5, (size - valueText.getLayoutBounds().getHeight()) * 0.5); } private void resizeStaticText() { double maxWidth = size * 0.35; double fontSize = size * 0.08082707; titleText.setFont(Fonts.latoBold(fontSize)); if (titleText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(titleText, maxWidth, fontSize); } titleText.relocate((size - titleText.getLayoutBounds().getWidth()) * 0.5, size * 0.22180451); titleText.setFill(Color.RED); unitText.setFont(Fonts.latoBold(fontSize)); if (unitText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(unitText, maxWidth, fontSize); } unitText.relocate((size - unitText.getLayoutBounds().getWidth()) * 0.5, size * 0.68984962); } private void resize() { double width = getSkinnable().getWidth() - getSkinnable().getInsets().getLeft() - getSkinnable().getInsets().getRight(); double height = getSkinnable().getHeight() - getSkinnable().getInsets().getTop() - getSkinnable().getInsets().getBottom(); size = width < height ? width : height; if (width > 0 && height > 0) { pane.setMaxSize(size, size); pane.setPrefSize(size, size); pane.relocate((getSkinnable().getWidth() - size) * 0.5, (getSkinnable().getHeight() - size) * 0.5); sectionCanvas.setWidth(size); sectionCanvas.setHeight(size); barBackground.setCenterX(size * 0.5); barBackground.setCenterY(size * 0.5); barBackground.setRadiusX(size * 0.4); barBackground.setRadiusY(size * 0.4); barBackground.setStrokeWidth(size * 0.125); bar.setCenterX(size * 0.5); bar.setCenterY(size * 0.5); bar.setRadiusX(size * 0.4); bar.setRadiusY(size * 0.4); bar.setStrokeWidth(size * 0.125); resizeValueText(); redraw(); } } private void redraw() { drawBackground(); setBar(getSkinnable().getCurrentValue()); titleText.setText(getSkinnable().getTitle()); unitText.setText(getSkinnable().getUnit()); resizeStaticText(); titleText.setFill(getSkinnable().getTitleColor()); valueText.setFill(getSkinnable().getValueColor()); unitText.setFill(getSkinnable().getUnitColor()); } }
src/main/java/eu/hansolo/medusa/skins/SimpleSectionSkin.java
/* * Copyright (c) 2016 by Gerrit Grunwald * * 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 eu.hansolo.medusa.skins; import eu.hansolo.medusa.Fonts; import eu.hansolo.medusa.Gauge; import eu.hansolo.medusa.Gauge.ScaleDirection; import eu.hansolo.medusa.Section; import eu.hansolo.medusa.tools.Helper; import javafx.geometry.Insets; import javafx.scene.CacheHint; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Skin; import javafx.scene.control.SkinBase; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.Border; import javafx.scene.layout.BorderStroke; import javafx.scene.layout.BorderStrokeStyle; import javafx.scene.layout.BorderWidths; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.Arc; import javafx.scene.shape.ArcType; import javafx.scene.shape.StrokeLineCap; import javafx.scene.text.Text; import java.util.List; /** * Created by hansolo on 25.07.16. */ public class SimpleSectionSkin extends SkinBase<Gauge> implements Skin<Gauge> { private static final double PREFERRED_WIDTH = 250; private static final double PREFERRED_HEIGHT = 250; private static final double MINIMUM_WIDTH = 50; private static final double MINIMUM_HEIGHT = 50; private static final double MAXIMUM_WIDTH = 1024; private static final double MAXIMUM_HEIGHT = 1024; private static final double ANGLE_RANGE = 300; private double size; private Canvas sectionCanvas; private GraphicsContext sectionCtx; private Arc barBackground; private Arc bar; private Text titleText; private Text valueText; private Text unitText; private Pane pane; private List<Section> sections; private String formatString; // ******************** Constructors ************************************** public SimpleSectionSkin(Gauge gauge) { super(gauge); if (gauge.isAutoScale()) gauge.calcAutoScale(); formatString = new StringBuilder("%.").append(Integer.toString(gauge.getDecimals())).append("f").toString(); sections = gauge.getSections(); initGraphics(); registerListeners(); setBar(gauge.getCurrentValue()); } // ******************** Initialization ************************************ private void initGraphics() { // Set initial size if (Double.compare(getSkinnable().getPrefWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getPrefHeight(), 0.0) <= 0 || Double.compare(getSkinnable().getWidth(), 0.0) <= 0 || Double.compare(getSkinnable().getHeight(), 0.0) <= 0) { if (getSkinnable().getPrefWidth() > 0 && getSkinnable().getPrefHeight() > 0) { getSkinnable().setPrefSize(getSkinnable().getPrefWidth(), getSkinnable().getPrefHeight()); } else { getSkinnable().setPrefSize(PREFERRED_WIDTH, PREFERRED_HEIGHT); } } sectionCanvas = new Canvas(PREFERRED_WIDTH, PREFERRED_HEIGHT); sectionCtx = sectionCanvas.getGraphicsContext2D(); barBackground = new Arc(PREFERRED_WIDTH * 0.5, PREFERRED_HEIGHT * 0.5, PREFERRED_WIDTH * 0.4, PREFERRED_HEIGHT * 0.4, getSkinnable().getStartAngle() + 150, ANGLE_RANGE); barBackground.setType(ArcType.OPEN); barBackground.setStroke(getSkinnable().getBarBackgroundColor()); barBackground.setStrokeWidth(PREFERRED_WIDTH * 0.125); barBackground.setStrokeLineCap(StrokeLineCap.BUTT); barBackground.setFill(null); bar = new Arc(PREFERRED_WIDTH * 0.5, PREFERRED_HEIGHT * 0.5, PREFERRED_WIDTH * 0.4, PREFERRED_HEIGHT * 0.4, getSkinnable().getStartAngle() + 90, 0); bar.setType(ArcType.OPEN); bar.setStroke(getSkinnable().getBarColor()); bar.setStrokeWidth(PREFERRED_WIDTH * 0.125); bar.setStrokeLineCap(StrokeLineCap.BUTT); bar.setFill(null); titleText = new Text(getSkinnable().getTitle()); titleText.setFill(getSkinnable().getTitleColor()); Helper.enableNode(titleText, !getSkinnable().getTitle().isEmpty()); valueText = new Text(); valueText.setStroke(null); valueText.setFill(getSkinnable().getValueColor()); Helper.enableNode(valueText, getSkinnable().isValueVisible()); unitText = new Text(); unitText.setStroke(null); unitText.setFill(getSkinnable().getUnitColor()); Helper.enableNode(unitText, getSkinnable().isValueVisible() && !getSkinnable().getUnit().isEmpty()); pane = new Pane(barBackground, sectionCanvas, titleText, valueText, unitText, bar); getChildren().setAll(pane); } private void registerListeners() { getSkinnable().widthProperty().addListener(o -> handleEvents("RESIZE")); getSkinnable().heightProperty().addListener(o -> handleEvents("RESIZE")); getSkinnable().decimalsProperty().addListener(o -> handleEvents("DECIMALS")); getSkinnable().setOnUpdate(e -> handleEvents(e.eventType.name())); getSkinnable().currentValueProperty().addListener(o -> setBar(getSkinnable().getCurrentValue())); getSkinnable().decimalsProperty().addListener(o -> handleEvents("DECIMALS")); } // ******************** Methods ******************************************* @Override protected double computeMinWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MINIMUM_WIDTH; } @Override protected double computeMinHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MINIMUM_HEIGHT; } @Override protected double computePrefWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return super.computePrefWidth(HEIGHT, TOP, RIGHT, BOTTOM, LEFT); } @Override protected double computePrefHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return super.computePrefHeight(WIDTH, TOP, RIGHT, BOTTOM, LEFT); } @Override protected double computeMaxWidth(final double HEIGHT, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MAXIMUM_WIDTH; } @Override protected double computeMaxHeight(final double WIDTH, final double TOP, final double RIGHT, final double BOTTOM, final double LEFT) { return MAXIMUM_HEIGHT; } private void handleEvents(final String EVENT_TYPE) { if ("VISIBILITY".equals(EVENT_TYPE)) { Helper.enableNode(valueText, getSkinnable().isValueVisible()); Helper.enableNode(unitText, getSkinnable().isValueVisible() && !getSkinnable().getUnit().isEmpty()); } else if ("SECTIONS".equals(EVENT_TYPE)) { sections = getSkinnable().getSections(); } else if ("RESIZE".equals(EVENT_TYPE)) { resize(); redraw(); } else if ("REDRAW".equals(EVENT_TYPE)) { redraw(); } else if ("RECALC".equals(EVENT_TYPE)) { redraw(); setBar(getSkinnable().getCurrentValue()); } else if ("DECIMALS".equals(EVENT_TYPE)) { formatString = new StringBuilder("%.").append(Integer.toString(getSkinnable().getDecimals())).append("f").toString(); } } // ******************** Canvas ******************************************** private void setBar(final double VALUE) { bar.setStartAngle(getSkinnable().getStartAngle() + 90 + getSkinnable().getMinValue() * getSkinnable().getAngleStep()); if (getSkinnable().getMinValue() > 0) { bar.setLength((getSkinnable().getMinValue() - VALUE) * getSkinnable().getAngleStep()); } else { bar.setLength(-VALUE * getSkinnable().getAngleStep()); } if (getSkinnable().getSectionsVisible() && !sections.isEmpty()) { for (Section section : sections) { if (section.contains(VALUE)) { bar.setStroke(section.getColor()); break; } } } valueText.setText(String.format(getSkinnable().getLocale(), formatString, VALUE)); valueText.setLayoutX((size - valueText.getLayoutBounds().getWidth()) * 0.5); } private void drawBackground() { sectionCanvas.setCache(false); sectionCtx.setLineCap(StrokeLineCap.BUTT); sectionCtx.clearRect(0, 0, size, size); if (getSkinnable().getSectionsVisible() && !sections.isEmpty()) { double xy = 0.012 * size; double wh = size * 0.976; double minValue = getSkinnable().getMinValue(); double maxValue = getSkinnable().getMaxValue(); double angleStep = getSkinnable().getAngleStep(); sectionCtx.setLineWidth(size * 0.025); sectionCtx.setLineCap(StrokeLineCap.BUTT); for (int i = 0; i < sections.size(); i++) { Section section = sections.get(i); double sectionStartAngle; if (Double.compare(section.getStart(), maxValue) <= 0 && Double.compare(section.getStop(), minValue) >= 0) { if (Double.compare(section.getStart(), minValue) < 0 && Double.compare(section.getStop(), maxValue) < 0) { sectionStartAngle = 0; } else { sectionStartAngle = ScaleDirection.CLOCKWISE == getSkinnable().getScaleDirection() ? (section.getStart() - minValue) * angleStep : -(section.getStart() - minValue) * angleStep; } double sectionAngleExtend; if (Double.compare(section.getStop(), maxValue) > 0) { sectionAngleExtend = ScaleDirection.CLOCKWISE == getSkinnable().getScaleDirection() ? (maxValue - section.getStart()) * angleStep : -(maxValue - section.getStart()) * angleStep; } else if (Double.compare(section.getStart(), minValue) < 0) { sectionAngleExtend = ScaleDirection.CLOCKWISE == getSkinnable().getScaleDirection() ? (section.getStop() - minValue) * getSkinnable().getAngleStep() : -(section.getStop() - minValue) * angleStep; } else { sectionAngleExtend = ScaleDirection.CLOCKWISE == getSkinnable().getScaleDirection() ? (section.getStop() - section.getStart()) * angleStep : -(section.getStop() - section.getStart()) * angleStep; } sectionCtx.save(); sectionCtx.setStroke(section.getColor()); sectionCtx.strokeArc(xy, xy, wh, wh, -(120 + sectionStartAngle), -sectionAngleExtend, ArcType.OPEN); sectionCtx.restore(); } } } sectionCanvas.setCache(true); sectionCanvas.setCacheHint(CacheHint.QUALITY); } // ******************** Resizing ****************************************** private void resizeValueText() { double maxWidth = size * 0.86466165; double fontSize = size * 0.2556391; valueText.setFont(Fonts.latoLight(fontSize)); if (valueText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(valueText, maxWidth, fontSize); } valueText.relocate((size - valueText.getLayoutBounds().getWidth()) * 0.5, (size - valueText.getLayoutBounds().getHeight()) * 0.5); } private void resizeStaticText() { double maxWidth = size * 0.35; double fontSize = size * 0.08082707; titleText.setFont(Fonts.latoBold(fontSize)); if (titleText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(titleText, maxWidth, fontSize); } titleText.relocate((size - titleText.getLayoutBounds().getWidth()) * 0.5, size * 0.22180451); titleText.setFill(Color.RED); unitText.setFont(Fonts.latoBold(fontSize)); if (unitText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(unitText, maxWidth, fontSize); } unitText.relocate((size - unitText.getLayoutBounds().getWidth()) * 0.5, size * 0.68984962); } private void resize() { double width = getSkinnable().getWidth() - getSkinnable().getInsets().getLeft() - getSkinnable().getInsets().getRight(); double height = getSkinnable().getHeight() - getSkinnable().getInsets().getTop() - getSkinnable().getInsets().getBottom(); size = width < height ? width : height; if (width > 0 && height > 0) { pane.setMaxSize(size, size); pane.setPrefSize(size, size); pane.relocate((getSkinnable().getWidth() - size) * 0.5, (getSkinnable().getHeight() - size) * 0.5); sectionCanvas.setWidth(size); sectionCanvas.setHeight(size); barBackground.setCenterX(size * 0.5); barBackground.setCenterY(size * 0.5); barBackground.setRadiusX(size * 0.4); barBackground.setRadiusY(size * 0.4); barBackground.setStrokeWidth(size * 0.125); bar.setCenterX(size * 0.5); bar.setCenterY(size * 0.5); bar.setRadiusX(size * 0.4); bar.setRadiusY(size * 0.4); bar.setStrokeWidth(size * 0.125); resizeValueText(); redraw(); } } private void redraw() { drawBackground(); setBar(getSkinnable().getCurrentValue()); titleText.setText(getSkinnable().getTitle()); unitText.setText(getSkinnable().getUnit()); resizeStaticText(); titleText.setFill(getSkinnable().getTitleColor()); valueText.setFill(getSkinnable().getValueColor()); unitText.setFill(getSkinnable().getUnitColor()); } }
Fixed bug in SimpleSectionSkin related to bar color and sections
src/main/java/eu/hansolo/medusa/skins/SimpleSectionSkin.java
Fixed bug in SimpleSectionSkin related to bar color and sections
<ide><path>rc/main/java/eu/hansolo/medusa/skins/SimpleSectionSkin.java <ide> bar.setLength(-VALUE * getSkinnable().getAngleStep()); <ide> } <ide> if (getSkinnable().getSectionsVisible() && !sections.isEmpty()) { <add> bar.setStroke(getSkinnable().getBarColor()); <ide> for (Section section : sections) { <ide> if (section.contains(VALUE)) { <ide> bar.setStroke(section.getColor());
Java
apache-2.0
d1624f3741a36969061e51233596aa2511dad856
0
leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,apache/incubator-shardingsphere
/* * 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.shardingsphere.shardingproxy.backend.response.query; import lombok.AllArgsConstructor; import lombok.Getter; import org.apache.shardingsphere.shardingproxy.backend.schema.LogicSchema; import org.apache.shardingsphere.shardingproxy.backend.schema.impl.ShardingSchema; import org.apache.shardingsphere.underlying.common.metadata.table.TableMetaData; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.Collection; /** * Query header. * * @author zhangliang */ @AllArgsConstructor @Getter public final class QueryHeader { private final String schema; private final String table; private String columnLabel; private String columnName; private final int columnLength; private final Integer columnType; private final int decimals; private final boolean signed; private final boolean primaryKey; private final boolean notNull; private final boolean autoIncrement; public QueryHeader(final ResultSetMetaData resultSetMetaData, final LogicSchema logicSchema, final int columnIndex) throws SQLException { schema = logicSchema.getName(); columnLabel = resultSetMetaData.getColumnLabel(columnIndex); columnName = resultSetMetaData.getColumnName(columnIndex); columnLength = resultSetMetaData.getColumnDisplaySize(columnIndex); columnType = resultSetMetaData.getColumnType(columnIndex); decimals = resultSetMetaData.getScale(columnIndex); signed = resultSetMetaData.isSigned(columnIndex); notNull = resultSetMetaData.isNullable(columnIndex) == ResultSetMetaData.columnNoNulls; autoIncrement = resultSetMetaData.isAutoIncrement(columnIndex); String actualTableName = resultSetMetaData.getTableName(columnIndex); if (null != actualTableName && logicSchema instanceof ShardingSchema) { Collection<String> logicTableNames = logicSchema.getShardingRule().getLogicTableNames(actualTableName); table = logicTableNames.isEmpty()? null : logicTableNames.iterator().next(); TableMetaData tableMetaData = logicSchema.getMetaData().getTables().get(table); primaryKey = null != tableMetaData && tableMetaData.getColumns().get(resultSetMetaData.getColumnName(columnIndex).toLowerCase()) .isPrimaryKey(); } else { table = actualTableName; primaryKey = false; } } /** * Set column label and column name. * * @param logicColumnName logic column name */ public void setColumnLabelAndName(final String logicColumnName) { if (columnLabel.equals(columnName)) { columnLabel = logicColumnName; columnName = logicColumnName; } else { columnName = logicColumnName; } } }
sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/response/query/QueryHeader.java
/* * 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.shardingsphere.shardingproxy.backend.response.query; import lombok.AllArgsConstructor; import lombok.Getter; import org.apache.shardingsphere.shardingproxy.backend.schema.LogicSchema; import org.apache.shardingsphere.shardingproxy.backend.schema.impl.ShardingSchema; import org.apache.shardingsphere.underlying.common.metadata.table.TableMetaData; import java.sql.ResultSetMetaData; import java.sql.SQLException; /** * Query header. * * @author zhangliang */ @AllArgsConstructor @Getter public final class QueryHeader { private final String schema; private final String table; private String columnLabel; private String columnName; private final int columnLength; private final Integer columnType; private final int decimals; private final boolean signed; private final boolean primaryKey; private final boolean notNull; private final boolean autoIncrement; public QueryHeader(final ResultSetMetaData resultSetMetaData, final LogicSchema logicSchema, final int columnIndex) throws SQLException { schema = logicSchema.getName(); columnLabel = resultSetMetaData.getColumnLabel(columnIndex); columnName = resultSetMetaData.getColumnName(columnIndex); columnLength = resultSetMetaData.getColumnDisplaySize(columnIndex); columnType = resultSetMetaData.getColumnType(columnIndex); decimals = resultSetMetaData.getScale(columnIndex); signed = resultSetMetaData.isSigned(columnIndex); notNull = resultSetMetaData.isNullable(columnIndex) == ResultSetMetaData.columnNoNulls; autoIncrement = resultSetMetaData.isAutoIncrement(columnIndex); String actualTableName = resultSetMetaData.getTableName(columnIndex); if (null != actualTableName && logicSchema instanceof ShardingSchema) { table = logicSchema.getShardingRule().getLogicTableNames(actualTableName).iterator().next(); TableMetaData tableMetaData = logicSchema.getMetaData().getTables().get(table); primaryKey = null != tableMetaData && tableMetaData.getColumns().get(resultSetMetaData.getColumnName(columnIndex).toLowerCase()) .isPrimaryKey(); } else { table = actualTableName; primaryKey = false; } } /** * Set column label and column name. * * @param logicColumnName logic column name */ public void setColumnLabelAndName(final String logicColumnName) { if (columnLabel.equals(columnName)) { columnLabel = logicColumnName; columnName = logicColumnName; } else { columnName = logicColumnName; } } }
queryheader logic table
sharding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/response/query/QueryHeader.java
queryheader logic table
<ide><path>harding-proxy/sharding-proxy-backend/src/main/java/org/apache/shardingsphere/shardingproxy/backend/response/query/QueryHeader.java <ide> <ide> import java.sql.ResultSetMetaData; <ide> import java.sql.SQLException; <add>import java.util.Collection; <ide> <ide> /** <ide> * Query header. <ide> autoIncrement = resultSetMetaData.isAutoIncrement(columnIndex); <ide> String actualTableName = resultSetMetaData.getTableName(columnIndex); <ide> if (null != actualTableName && logicSchema instanceof ShardingSchema) { <del> table = logicSchema.getShardingRule().getLogicTableNames(actualTableName).iterator().next(); <add> Collection<String> logicTableNames = logicSchema.getShardingRule().getLogicTableNames(actualTableName); <add> table = logicTableNames.isEmpty()? null : logicTableNames.iterator().next(); <ide> TableMetaData tableMetaData = logicSchema.getMetaData().getTables().get(table); <ide> primaryKey = null != tableMetaData && tableMetaData.getColumns().get(resultSetMetaData.getColumnName(columnIndex).toLowerCase()) <ide> .isPrimaryKey();
Java
apache-2.0
228bd56e6e2dfc0a08882a3d28a6933a5fa087ca
0
izonder/intellij-community,ryano144/intellij-community,allotria/intellij-community,kool79/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,asedunov/intellij-community,supersven/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,retomerz/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,consulo/consulo,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,slisson/intellij-community,vladmm/intellij-community,izonder/intellij-community,gnuhub/intellij-community,izonder/intellij-community,petteyg/intellij-community,retomerz/intellij-community,petteyg/intellij-community,holmes/intellij-community,joewalnes/idea-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,holmes/intellij-community,supersven/intellij-community,petteyg/intellij-community,signed/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,robovm/robovm-studio,allotria/intellij-community,asedunov/intellij-community,ibinti/intellij-community,samthor/intellij-community,clumsy/intellij-community,izonder/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,izonder/intellij-community,vladmm/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,jagguli/intellij-community,consulo/consulo,ernestp/consulo,slisson/intellij-community,kdwink/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,asedunov/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,slisson/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,orekyuu/intellij-community,signed/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,jexp/idea2,FHannes/intellij-community,allotria/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,da1z/intellij-community,hurricup/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,lucafavatella/intellij-community,caot/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,hurricup/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,holmes/intellij-community,kool79/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,semonte/intellij-community,ryano144/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,supersven/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,diorcety/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,kdwink/intellij-community,hurricup/intellij-community,signed/intellij-community,fitermay/intellij-community,ryano144/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,caot/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,ernestp/consulo,fengbaicanhe/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,supersven/intellij-community,jexp/idea2,ryano144/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,supersven/intellij-community,blademainer/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,fitermay/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,consulo/consulo,salguarnieri/intellij-community,kool79/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,semonte/intellij-community,samthor/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,samthor/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,kdwink/intellij-community,dslomov/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,jexp/idea2,retomerz/intellij-community,hurricup/intellij-community,fitermay/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,allotria/intellij-community,caot/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,blademainer/intellij-community,allotria/intellij-community,kdwink/intellij-community,kool79/intellij-community,blademainer/intellij-community,signed/intellij-community,diorcety/intellij-community,fnouama/intellij-community,kool79/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,caot/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,vladmm/intellij-community,xfournet/intellij-community,jexp/idea2,kdwink/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,samthor/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,fnouama/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,joewalnes/idea-community,TangHao1987/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,caot/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,allotria/intellij-community,vladmm/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,robovm/robovm-studio,slisson/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,xfournet/intellij-community,ernestp/consulo,nicolargo/intellij-community,xfournet/intellij-community,amith01994/intellij-community,jagguli/intellij-community,amith01994/intellij-community,kool79/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,da1z/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,slisson/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,apixandru/intellij-community,fitermay/intellij-community,adedayo/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,semonte/intellij-community,retomerz/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,caot/intellij-community,consulo/consulo,samthor/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,ryano144/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,slisson/intellij-community,tmpgit/intellij-community,kool79/intellij-community,robovm/robovm-studio,semonte/intellij-community,holmes/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,retomerz/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ernestp/consulo,signed/intellij-community,amith01994/intellij-community,kdwink/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,consulo/consulo,wreckJ/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,da1z/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,vladmm/intellij-community,ryano144/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,semonte/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,jexp/idea2,idea4bsd/idea4bsd,vvv1559/intellij-community,allotria/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,holmes/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,jagguli/intellij-community,supersven/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,ibinti/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,izonder/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,asedunov/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,caot/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,supersven/intellij-community,ernestp/consulo,youdonghai/intellij-community,izonder/intellij-community,vvv1559/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,slisson/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,ibinti/intellij-community,jexp/idea2,signed/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,petteyg/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,slisson/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,slisson/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,amith01994/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,holmes/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,signed/intellij-community,supersven/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,izonder/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,SerCeMan/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,allotria/intellij-community,FHannes/intellij-community,blademainer/intellij-community,asedunov/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,caot/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,allotria/intellij-community,xfournet/intellij-community,joewalnes/idea-community,da1z/intellij-community,izonder/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,ernestp/consulo,muntasirsyed/intellij-community,petteyg/intellij-community,caot/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,adedayo/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,caot/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,blademainer/intellij-community,jagguli/intellij-community,supersven/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,mglukhikh/intellij-community,kool79/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,semonte/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,signed/intellij-community,slisson/intellij-community,joewalnes/idea-community,ibinti/intellij-community,michaelgallacher/intellij-community,jexp/idea2,izonder/intellij-community,kool79/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,apixandru/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,dslomov/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,vvv1559/intellij-community,samthor/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,asedunov/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,joewalnes/idea-community,FHannes/intellij-community,signed/intellij-community,samthor/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,signed/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,ibinti/intellij-community,amith01994/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,jexp/idea2,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,vladmm/intellij-community,consulo/consulo,TangHao1987/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,hurricup/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,ibinti/intellij-community
package com.intellij.openapi.fileEditor.impl.text; import com.intellij.codeHighlighting.BackgroundEditorHighlighter; import com.intellij.codeInsight.daemon.impl.TextEditorBackgroundHighlighter; import com.intellij.codeInsight.folding.CodeFoldingManager; import com.intellij.ide.structureView.StructureViewBuilder; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.Navigatable; import com.intellij.psi.PsiDocumentManager; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; /** * @author Vladimir Kondratyev */ public final class TextEditorImpl extends UserDataHolderBase implements TextEditor{ private final Project myProject; private final PropertyChangeSupport myChangeSupport; private final TextEditorComponent myComponent; private TextEditorBackgroundHighlighter myBackgroundHighlighter; TextEditorImpl(@NotNull final Project project, @NotNull final VirtualFile file) { myProject = project; myChangeSupport = new PropertyChangeSupport(this); myComponent = new TextEditorComponent(project, file, this); } void dispose(){ myComponent.dispose(); } public JComponent getComponent() { return myComponent; } public JComponent getPreferredFocusedComponent(){ return getActiveEditor().getContentComponent(); } @NotNull public Editor getEditor(){ return getActiveEditor(); } /** * @see TextEditorComponent#getEditor() */ private Editor getActiveEditor() { return myComponent.getEditor(); } @NotNull public String getName() { return "Text"; } @NotNull public FileEditorState getState(@NotNull FileEditorStateLevel level) { TextEditorState state = new TextEditorState(); getStateImpl(myProject, getActiveEditor(), state, level); return state; } static void getStateImpl(final Project project, final Editor editor, @NotNull final TextEditorState state, @NotNull FileEditorStateLevel level){ state.LINE = editor.getCaretModel().getLogicalPosition().line; state.COLUMN = editor.getCaretModel().getLogicalPosition().column; state.SELECTION_START = editor.getSelectionModel().getSelectionStart(); state.SELECTION_END = editor.getSelectionModel().getSelectionEnd(); // Save folding only on FULL level. It's very expensive to commit document on every // type (caused by undo). if(FileEditorStateLevel.FULL == level){ // Folding if (project != null) { PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); state.FOLDING_STATE = CodeFoldingManager.getInstance(project).saveFoldingState(editor); } else { state.FOLDING_STATE = null; } } // Saving scrolling proportion on UNDO may cause undesirable results of undo action fails to perform since // scrolling proportion restored sligtly differs from what have been saved. state.VERTICAL_SCROLL_PROPORTION = level == FileEditorStateLevel.UNDO ? -1 : EditorUtil.calcVerticalScrollProportion(editor); } public void setState(@NotNull final FileEditorState state) { setStateImpl(myProject, getActiveEditor(), (TextEditorState)state); } static void setStateImpl(final Project project, final Editor editor, final TextEditorState state){ LogicalPosition pos = new LogicalPosition(state.LINE, state.COLUMN); editor.getCaretModel().moveToLogicalPosition(pos); editor.getSelectionModel().removeSelection(); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); if (state.VERTICAL_SCROLL_PROPORTION != -1) { EditorUtil.setVerticalScrollProportion(editor, state.VERTICAL_SCROLL_PROPORTION); } final Document document = editor.getDocument(); if (state.SELECTION_START == state.SELECTION_END) { editor.getSelectionModel().removeSelection(); } else { int startOffset = Math.min(state.SELECTION_START, document.getTextLength()); int endOffset = Math.min(state.SELECTION_END, document.getTextLength()); editor.getSelectionModel().setSelection(startOffset, endOffset); } ((EditorEx) editor).stopOptimizedScrolling(); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); // Folding if (project != null && state.FOLDING_STATE != null){ PsiDocumentManager.getInstance(project).commitDocument(document); editor.getFoldingModel().runBatchFoldingOperation( new Runnable() { public void run() { CodeFoldingManager.getInstance(project).restoreFoldingState(editor, state.FOLDING_STATE); } } ); } } public boolean isModified() { return myComponent.isModified(); } public boolean isValid() { return myComponent.isEditorValid(); } public void selectNotify() { myComponent.selectNotify(); } public void deselectNotify() { myComponent.deselectNotify(); } void firePropertyChange(final String propertyName, final Object oldValue, final Object newValue) { myChangeSupport.firePropertyChange(propertyName, oldValue, newValue); } public void addPropertyChangeListener(@NotNull final PropertyChangeListener listener) { myChangeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(@NotNull final PropertyChangeListener listener) { myChangeSupport.removePropertyChangeListener(listener); } public BackgroundEditorHighlighter getBackgroundHighlighter() { if (myBackgroundHighlighter == null) { myBackgroundHighlighter = new TextEditorBackgroundHighlighter(myProject, getEditor()); } return myBackgroundHighlighter; } public FileEditorLocation getCurrentLocation() { return new TextEditorLocation(getEditor().getCaretModel().getLogicalPosition(), this); } public StructureViewBuilder getStructureViewBuilder() { Document document = myComponent.getEditor().getDocument(); VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file == null || !file.isValid()) return null; return file.getFileType().getStructureViewBuilder(file, myProject); } public boolean canNavigateTo(@NotNull final Navigatable navigatable) { return (navigatable instanceof OpenFileDescriptor) && (((OpenFileDescriptor)navigatable).getOffset() >= 0 || ( ((OpenFileDescriptor)navigatable).getLine() != -1 && ((OpenFileDescriptor)navigatable).getColumn() != -1)); } public void navigateTo(@NotNull final Navigatable navigatable) { assert navigatable instanceof OpenFileDescriptor; final OpenFileDescriptor descriptor = ((OpenFileDescriptor)navigatable); final Editor _editor = getEditor(); if (descriptor.getOffset() >= 0) { _editor.getCaretModel().moveToOffset(Math.min(descriptor.getOffset(), _editor.getDocument().getTextLength())); //_editor.getSelectionModel().removeSelection(); _editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); } else if (descriptor.getLine() != -1 && descriptor.getColumn() != -1) { final LogicalPosition pos = new LogicalPosition(descriptor.getLine(), descriptor.getColumn()); _editor.getCaretModel().moveToLogicalPosition(pos); //_editor.getSelectionModel().removeSelection(); _editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); } } }
source/com/intellij/openapi/fileEditor/impl/text/TextEditorImpl.java
package com.intellij.openapi.fileEditor.impl.text; import com.intellij.codeHighlighting.BackgroundEditorHighlighter; import com.intellij.codeInsight.daemon.impl.TextEditorBackgroundHighlighter; import com.intellij.codeInsight.folding.CodeFoldingManager; import com.intellij.ide.structureView.StructureViewBuilder; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.fileEditor.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.UserDataHolderBase; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.pom.Navigatable; import javax.swing.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import org.jetbrains.annotations.NotNull; /** * @author Vladimir Kondratyev */ public final class TextEditorImpl extends UserDataHolderBase implements TextEditor{ private final Project myProject; private final PropertyChangeSupport myChangeSupport; private final TextEditorComponent myComponent; private TextEditorBackgroundHighlighter myBackgroundHighlighter; TextEditorImpl(@NotNull final Project project, @NotNull final VirtualFile file) { myProject = project; myChangeSupport = new PropertyChangeSupport(this); myComponent = new TextEditorComponent(project, file, this); } void dispose(){ myComponent.dispose(); } public JComponent getComponent() { return myComponent; } public JComponent getPreferredFocusedComponent(){ return getActiveEditor().getContentComponent(); } @NotNull public Editor getEditor(){ return getActiveEditor(); } /** * @see TextEditorComponent#getEditor() */ private Editor getActiveEditor() { return myComponent.getEditor(); } @NotNull public String getName() { return "Text"; } @NotNull public FileEditorState getState(@NotNull FileEditorStateLevel level) { TextEditorState state = new TextEditorState(); getStateImpl(myProject, getActiveEditor(), state, level); return state; } static void getStateImpl(final Project project, final Editor editor, @NotNull final TextEditorState state, @NotNull FileEditorStateLevel level){ state.LINE = editor.getCaretModel().getLogicalPosition().line; state.COLUMN = editor.getCaretModel().getLogicalPosition().column; state.SELECTION_START = editor.getSelectionModel().getSelectionStart(); state.SELECTION_END = editor.getSelectionModel().getSelectionEnd(); // Save folding only on FULL level. It's very expensive to commit document on every // type (caused by undo). if(FileEditorStateLevel.FULL == level){ // Folding if (project != null) { PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); state.FOLDING_STATE = CodeFoldingManager.getInstance(project).saveFoldingState(editor); } else { state.FOLDING_STATE = null; } } // Saving scrolling proportion on UNDO may cause undesirable results of undo action fails to perform since // scrolling proportion restored sligtly differs from what have been saved. state.VERTICAL_SCROLL_PROPORTION = level == FileEditorStateLevel.UNDO ? -1 : EditorUtil.calcVerticalScrollProportion(editor); } public void setState(@NotNull final FileEditorState state) { setStateImpl(myProject, getActiveEditor(), (TextEditorState)state); } static void setStateImpl(final Project project, final Editor editor, final TextEditorState state){ LogicalPosition pos = new LogicalPosition(state.LINE, state.COLUMN); editor.getCaretModel().moveToLogicalPosition(pos); editor.getSelectionModel().removeSelection(); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); if (state.VERTICAL_SCROLL_PROPORTION != -1) { EditorUtil.setVerticalScrollProportion(editor, state.VERTICAL_SCROLL_PROPORTION); } final Document document = editor.getDocument(); if (state.SELECTION_START == state.SELECTION_END) { editor.getSelectionModel().removeSelection(); } else { int startOffset = Math.min(state.SELECTION_START, document.getTextLength()); int endOffset = Math.min(state.SELECTION_END, document.getTextLength()); editor.getSelectionModel().setSelection(startOffset, endOffset); } ((EditorEx) editor).stopOptimizedScrolling(); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); // Folding if (project != null && state.FOLDING_STATE != null){ PsiDocumentManager.getInstance(project).commitDocument(document); editor.getFoldingModel().runBatchFoldingOperation( new Runnable() { public void run() { CodeFoldingManager.getInstance(project).restoreFoldingState(editor, state.FOLDING_STATE); } } ); } } public boolean isModified() { return myComponent.isModified(); } public boolean isValid() { return myComponent.isEditorValid(); } public void selectNotify() { myComponent.selectNotify(); } public void deselectNotify() { myComponent.deselectNotify(); } void firePropertyChange(final String propertyName, final Object oldValue, final Object newValue) { myChangeSupport.firePropertyChange(propertyName, oldValue, newValue); } public void addPropertyChangeListener(@NotNull final PropertyChangeListener listener) { myChangeSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(@NotNull final PropertyChangeListener listener) { myChangeSupport.removePropertyChangeListener(listener); } public BackgroundEditorHighlighter getBackgroundHighlighter() { if (myBackgroundHighlighter == null) { myBackgroundHighlighter = new TextEditorBackgroundHighlighter(myProject, getEditor()); } return myBackgroundHighlighter; } public FileEditorLocation getCurrentLocation() { return new TextEditorLocation(getEditor().getCaretModel().getLogicalPosition(), this); } public StructureViewBuilder getStructureViewBuilder() { Document document = myComponent.getEditor().getDocument(); VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file == null || !file.isValid()) return null; return file.getFileType().getStructureViewBuilder(file, myProject); } public boolean canNavigateTo(@NotNull final Navigatable navigatable) { return (navigatable instanceof OpenFileDescriptor) && (((OpenFileDescriptor)navigatable).getOffset() >= 0 || ( ((OpenFileDescriptor)navigatable).getLine() != -1 && ((OpenFileDescriptor)navigatable).getColumn() != -1)); } public void navigateTo(@NotNull final Navigatable navigatable) { assert navigatable instanceof OpenFileDescriptor; final OpenFileDescriptor descriptor = ((OpenFileDescriptor)navigatable); final Editor _editor = getEditor(); if (descriptor.getOffset() >= 0) { _editor.getCaretModel().moveToOffset(Math.min(descriptor.getOffset(), _editor.getDocument().getTextLength())); _editor.getSelectionModel().removeSelection(); _editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); } else if (descriptor.getLine() != -1 && descriptor.getColumn() != -1) { final LogicalPosition pos = new LogicalPosition(descriptor.getLine(), descriptor.getColumn()); _editor.getCaretModel().moveToLogicalPosition(pos); _editor.getSelectionModel().removeSelection(); _editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); } } }
fix setSelection
source/com/intellij/openapi/fileEditor/impl/text/TextEditorImpl.java
fix setSelection
<ide><path>ource/com/intellij/openapi/fileEditor/impl/text/TextEditorImpl.java <ide> import com.intellij.openapi.project.Project; <ide> import com.intellij.openapi.util.UserDataHolderBase; <ide> import com.intellij.openapi.vfs.VirtualFile; <add>import com.intellij.pom.Navigatable; <ide> import com.intellij.psi.PsiDocumentManager; <del>import com.intellij.pom.Navigatable; <add>import org.jetbrains.annotations.NotNull; <ide> <ide> import javax.swing.*; <ide> import java.beans.PropertyChangeListener; <ide> import java.beans.PropertyChangeSupport; <del> <del>import org.jetbrains.annotations.NotNull; <ide> <ide> /** <ide> * @author Vladimir Kondratyev <ide> <ide> if (descriptor.getOffset() >= 0) { <ide> _editor.getCaretModel().moveToOffset(Math.min(descriptor.getOffset(), _editor.getDocument().getTextLength())); <del> _editor.getSelectionModel().removeSelection(); <add> //_editor.getSelectionModel().removeSelection(); <ide> _editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); <ide> } <ide> else if (descriptor.getLine() != -1 && descriptor.getColumn() != -1) { <ide> final LogicalPosition pos = new LogicalPosition(descriptor.getLine(), descriptor.getColumn()); <ide> _editor.getCaretModel().moveToLogicalPosition(pos); <del> _editor.getSelectionModel().removeSelection(); <add> //_editor.getSelectionModel().removeSelection(); <ide> _editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); <ide> } <ide> }
Java
apache-2.0
ef84b9118e8f1960ea6fba43b857ace6775fe52c
0
alibaba/java-dns-cache-manipulator,alibaba/java-dns-cache-manipulator,alibaba/java-dns-cache-manipulator,alibaba/java-dns-cache-manipulator
package com.alibaba.dcm.internal; /** * internal time util. * * @author Jerry Lee (oldratlee at gmail dot com) * @since 1.6.0 */ final class TimeUtil { /** * record point of {@link System#currentTimeMillis()} for {@link #NANO_TIME_CHECK_POINT} */ private static final long TIME_MILLIS_CHECK_POINT = System.currentTimeMillis(); /** * record point of {@link System#nanoTime()} for {@link #TIME_MILLIS_CHECK_POINT} */ private static final long NANO_TIME_CHECK_POINT = System.nanoTime(); private static final long NS_PER_MS = 1_000_000; /** * @see <a href="https://newbedev.com/how-can-i-convert-the-result-of-system-nanotime-to-a-date-in-java"> * How can I convert the result of System.nanoTime to a date in Java?</a> */ public static long convertNanoTimeToTimeMillis(long nanoTime) { return (nanoTime - NANO_TIME_CHECK_POINT) / NS_PER_MS + TIME_MILLIS_CHECK_POINT; } public static long getNanoTimeAfterMs(long millSeconds) { return System.nanoTime() + millSeconds * NS_PER_MS; } private TimeUtil() { } }
library/src/main/java/com/alibaba/dcm/internal/TimeUtil.java
package com.alibaba.dcm.internal; /** * internal time util. * * @author Jerry Lee (oldratlee at gmail dot com) * @since 1.6.0 */ final class TimeUtil { /** * record point of {@link System#currentTimeMillis()} for {@link #NANO_TIME_CHECK_POINT} */ private static final long TIME_MILLIS_CHECK_POINT = System.currentTimeMillis(); /** * record point of {@link System#nanoTime()} for {@link #TIME_MILLIS_CHECK_POINT} */ private static final long NANO_TIME_CHECK_POINT = System.nanoTime(); private static final long NS_PER_MS = 1000000; /** * @see <a href="https://newbedev.com/how-can-i-convert-the-result-of-system-nanotime-to-a-date-in-java"> * How can I convert the result of System.nanoTime to a date in Java?</a> */ public static long convertNanoTimeToTimeMillis(long nanoTime) { return (nanoTime - NANO_TIME_CHECK_POINT) / NS_PER_MS + TIME_MILLIS_CHECK_POINT; } public static long getNanoTimeAfterMs(long millSeconds) { return System.nanoTime() + millSeconds * NS_PER_MS; } private TimeUtil() { } }
style: use _ separator for big long literal
library/src/main/java/com/alibaba/dcm/internal/TimeUtil.java
style: use _ separator for big long literal
<ide><path>ibrary/src/main/java/com/alibaba/dcm/internal/TimeUtil.java <ide> */ <ide> private static final long NANO_TIME_CHECK_POINT = System.nanoTime(); <ide> <del> private static final long NS_PER_MS = 1000000; <add> private static final long NS_PER_MS = 1_000_000; <ide> <ide> /** <ide> * @see <a href="https://newbedev.com/how-can-i-convert-the-result-of-system-nanotime-to-a-date-in-java">
Java
apache-2.0
1f06ef20d680aa8b0b804c38fae9a88660f768bc
0
Fiware/cloud.SDC,Fiware/cloud.SDC,telefonicaid/fiware-sdc,telefonicaid/fiware-sdc,Fiware/cloud.SDC,Fiware/cloud.SDC,telefonicaid/fiware-sdc,telefonicaid/fiware-sdc
/** * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br> * This file is part of FI-WARE project. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. * </p> * <p> * You may obtain a copy of the License at:<br> * <br> * http://www.apache.org/licenses/LICENSE-2.0 * </p> * <p> * 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. * </p> * <p> * See the License for the specific language governing permissions and limitations under the License. * </p> * <p> * For those usages not covered by the Apache version 2.0 License please contact with [email protected] * </p> */ package com.telefonica.euro_iaas.sdc.manager.impl; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang.StringUtils; import com.telefonica.euro_iaas.commons.dao.AlreadyExistsEntityException; import com.telefonica.euro_iaas.commons.dao.EntityNotFoundException; import com.telefonica.euro_iaas.commons.dao.InvalidEntityException; import com.telefonica.euro_iaas.sdc.dao.ProductDao; import com.telefonica.euro_iaas.sdc.manager.ProductManager; import com.telefonica.euro_iaas.sdc.manager.ProductReleaseManager; import com.telefonica.euro_iaas.sdc.model.Metadata; import com.telefonica.euro_iaas.sdc.model.Product; import com.telefonica.euro_iaas.sdc.model.ProductRelease; import com.telefonica.euro_iaas.sdc.model.dto.ProductAndReleaseDto; import com.telefonica.euro_iaas.sdc.model.searchcriteria.ProductReleaseSearchCriteria; import com.telefonica.euro_iaas.sdc.model.searchcriteria.ProductSearchCriteria; import com.xmlsolutions.annotation.UseCase; /** * Default ProductManager implementation. * * @author Sergio Arroyo, Jesus M. Movilla */ @UseCase(traceTo = "UC_101", status = "partially implemented") public class ProductManagerImpl extends BaseInstallableManager implements ProductManager { private ProductDao productDao; private ProductReleaseManager productReleaseManager; private static Logger log = Logger.getLogger("ProductManagerImpl"); public Product insert(Product product, String tenantId) throws AlreadyExistsEntityException, InvalidEntityException { Product productOut; try { productOut = productDao.load(product.getName()); log.log(Level.INFO, "Product " + productOut.getName() + " LOADED"); } catch (EntityNotFoundException e) { List<Metadata> metadatas = new ArrayList<Metadata>(); metadatas.add(new Metadata("image", "df44f62d-9d66-4dc5-b084-2d6c7bc4cfe4")); // centos6.3_sdc metadatas.add(new Metadata("cookbook_url", "")); metadatas.add(new Metadata("cloud", "yes")); metadatas.add(new Metadata("installator", "chef")); metadatas.add(new Metadata("open_ports", "80 22")); metadatas.add(new Metadata("tenant_id", tenantId)); List<Metadata> defaultmetadatas = new ArrayList<Metadata>(); defaultmetadatas.add(new Metadata("image", "df44f62d-9d66-4dc5-b084-2d6c7bc4cfe4")); defaultmetadatas.add(new Metadata("cookbook_url", "")); defaultmetadatas.add(new Metadata("cloud", "yes")); defaultmetadatas.add(new Metadata("installator", "chef")); defaultmetadatas.add(new Metadata("open_ports", "80 22")); defaultmetadatas.add(new Metadata("tenant_id", tenantId)); for (Metadata external_metadata : product.getMetadatas()) { boolean defaultmetadata = false; for (Metadata default_metadata : defaultmetadatas) { if (external_metadata.getKey().equals(default_metadata.getKey())) { metadatas.get(metadatas.indexOf(default_metadata)).setValue(external_metadata.getValue()); defaultmetadata = true; } } if (!defaultmetadata) { metadatas.add(external_metadata); } } product.setMetadatas(metadatas); productOut = productDao.create(product); } return productOut; } /** * {@inheritDoc} */ @Override public List<Product> findAll() { return productDao.findAll(); } /** * {@inheritDoc} */ @Override public List<Product> findByCriteria(ProductSearchCriteria criteria) { return productDao.findByCriteria(criteria); } /** * {@inheritDoc} */ @Override public List<ProductAndReleaseDto> findProductAndReleaseByCriteria(ProductSearchCriteria criteria) { List<Product> productList = productDao.findByCriteria(criteria); ProductReleaseSearchCriteria prCriteria = new ProductReleaseSearchCriteria(); prCriteria.setPage(criteria.getPage()); prCriteria.setPageSize(criteria.getPageSize()); prCriteria.setOrderBy(criteria.getOrderBy()); prCriteria.setOrderType(criteria.getOrderType()); List<ProductAndReleaseDto> result = new ArrayList<ProductAndReleaseDto>(); for (Product p : productList) { if (!StringUtils.isEmpty(p.getName())) { prCriteria.setProduct(p); List<ProductRelease> productReleaseList = productReleaseManager.findReleasesByCriteria(prCriteria); for (ProductRelease pr : productReleaseList) { ProductAndReleaseDto productAndRelease = new ProductAndReleaseDto(); productAndRelease.setProduct(p); productAndRelease.setVersion(pr.getVersion()); result.add(productAndRelease); } } } return result; } /** * {@inheritDoc} */ @Override public Product load(String name) throws EntityNotFoundException { return productDao.load(name); } public boolean exist(String name) { try { load(name); return true; } catch (EntityNotFoundException e) { return false; } } @Override public void delete(Product product) { productDao.remove(product); } /** * @param productDao * the productDao to set */ public void setProductDao(ProductDao productDao) { this.productDao = productDao; } public void setProductReleaseManager(ProductReleaseManager productReleaseManager) { this.productReleaseManager = productReleaseManager; } }
core/src/main/java/com/telefonica/euro_iaas/sdc/manager/impl/ProductManagerImpl.java
/** * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U <br> * This file is part of FI-WARE project. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. * </p> * <p> * You may obtain a copy of the License at:<br> * <br> * http://www.apache.org/licenses/LICENSE-2.0 * </p> * <p> * 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. * </p> * <p> * See the License for the specific language governing permissions and limitations under the License. * </p> * <p> * For those usages not covered by the Apache version 2.0 License please contact with [email protected] * </p> */ package com.telefonica.euro_iaas.sdc.manager.impl; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang.StringUtils; import com.telefonica.euro_iaas.commons.dao.AlreadyExistsEntityException; import com.telefonica.euro_iaas.commons.dao.EntityNotFoundException; import com.telefonica.euro_iaas.commons.dao.InvalidEntityException; import com.telefonica.euro_iaas.sdc.dao.ProductDao; import com.telefonica.euro_iaas.sdc.manager.ProductManager; import com.telefonica.euro_iaas.sdc.manager.ProductReleaseManager; import com.telefonica.euro_iaas.sdc.model.Metadata; import com.telefonica.euro_iaas.sdc.model.Product; import com.telefonica.euro_iaas.sdc.model.ProductRelease; import com.telefonica.euro_iaas.sdc.model.dto.ProductAndReleaseDto; import com.telefonica.euro_iaas.sdc.model.searchcriteria.ProductReleaseSearchCriteria; import com.telefonica.euro_iaas.sdc.model.searchcriteria.ProductSearchCriteria; import com.xmlsolutions.annotation.UseCase; /** * Default ProductManager implementation. * * @author Sergio Arroyo, Jesus M. Movilla */ @UseCase(traceTo = "UC_101", status = "partially implemented") public class ProductManagerImpl extends BaseInstallableManager implements ProductManager { private ProductDao productDao; private ProductReleaseManager productReleaseManager; private static Logger log = Logger.getLogger("ProductManagerImpl"); public Product insert(Product product, String tenantId) throws AlreadyExistsEntityException, InvalidEntityException { Product productOut; try { productOut = productDao.load(product.getName()); log.log(Level.INFO, "Product " + productOut.getName() + " LOADED"); } catch (EntityNotFoundException e) { List<Metadata> metadatas = new ArrayList<Metadata>(); metadatas.add(new Metadata("image", "df44f62d-9d66-4dc5-b084-2d6c7bc4cfe4")); // centos6.3_sdc metadatas.add(new Metadata("cookbook_url", "")); metadatas.add(new Metadata("cloud", "yes")); metadatas.add(new Metadata("installator", "chef")); metadatas.add(new Metadata("open_ports", "80 22")); metadatas.add(new Metadata("tenant_id", tenantId)); List<Metadata> defaultmetadatas = new ArrayList<Metadata>(); defaultmetadatas.add(new Metadata("image", "df44f62d-9d66-4dc5-b084-2d6c7bc4cfe4")); defaultmetadatas.add(new Metadata("cookbook_url", "")); defaultmetadatas.add(new Metadata("cloud", "yes")); defaultmetadatas.add(new Metadata("installator", "chef")); defaultmetadatas.add(new Metadata("open_ports", "80 22")); defaultmetadatas.add(new Metadata("tenant_id", tenantId)); for (Metadata external_metadata : product.getMetadatas()) { boolean defaultmetadata = false; for (Metadata default_metadata : defaultmetadatas) { if (external_metadata.getKey().equals(default_metadata.getKey())) { metadatas.get(metadatas.indexOf(default_metadata)).setValue(external_metadata.getValue()); defaultmetadata = true; } } if (!defaultmetadata) { metadatas.add(external_metadata); } } product.setMetadatas(metadatas); productOut = productDao.create(product); } return productOut; } /** * {@inheritDoc} */ @Override public List<Product> findAll() { return productDao.findAll(); } /** * {@inheritDoc} */ @Override public List<Product> findByCriteria(ProductSearchCriteria criteria) { return productDao.findByCriteria(criteria); } /** * {@inheritDoc} */ @Override public List<ProductAndReleaseDto> findProductAndReleaseByCriteria(ProductSearchCriteria criteria) { List<Product> productList = productDao.findByCriteria(criteria); ProductReleaseSearchCriteria prCriteria = new ProductReleaseSearchCriteria(); prCriteria.setPage(criteria.getPage()); prCriteria.setPageSize(criteria.getPageSize()); prCriteria.setOrderBy(criteria.getOrderBy()); prCriteria.setOrderType(criteria.getOrderType()); List<ProductAndReleaseDto> result = new ArrayList<ProductAndReleaseDto>(); for (Product p : productList) { if (!StringUtils.isEmpty(p.getName())) { prCriteria.setProduct(p); List<ProductRelease> productReleaseList = productReleaseManager.findReleasesByCriteria(prCriteria); for (ProductRelease pr : productReleaseList) { ProductAndReleaseDto productAndRelease = new ProductAndReleaseDto(); productAndRelease.setProduct(p); productAndRelease.setVersion(pr.getVersion()); result.add(productAndRelease); } } } return result; } /** * {@inheritDoc} */ @Override public Product load(String name) throws EntityNotFoundException { return productDao.load(name); } public boolean exist(String name) { try { load(name); return true; } catch (EntityNotFoundException e) { return false; } } @Override public void delete(Product product) { productDao.remove(product); } /** * @param productDao * the productDao to set */ public void setProductDao(ProductDao productDao) { this.productDao = productDao; } public void setProductReleaseManager(ProductReleaseManager productReleaseManager) { this.productReleaseManager = productReleaseManager; } }
trying to synchronize master with develop
core/src/main/java/com/telefonica/euro_iaas/sdc/manager/impl/ProductManagerImpl.java
trying to synchronize master with develop
<ide><path>ore/src/main/java/com/telefonica/euro_iaas/sdc/manager/impl/ProductManagerImpl.java <ide> List<ProductRelease> productReleaseList = productReleaseManager.findReleasesByCriteria(prCriteria); <ide> <ide> for (ProductRelease pr : productReleaseList) { <del> <add> <ide> ProductAndReleaseDto productAndRelease = new ProductAndReleaseDto(); <ide> productAndRelease.setProduct(p); <ide> productAndRelease.setVersion(pr.getVersion()); <ide> public Product load(String name) throws EntityNotFoundException { <ide> return productDao.load(name); <ide> } <del> <add> <ide> public boolean exist(String name) { <ide> try { <del> load(name); <del> return true; <del> } catch (EntityNotFoundException e) { <del> return false; <del> } <add> load(name); <add> return true; <add> } catch (EntityNotFoundException e) { <add> return false; <add> } <ide> } <ide> <ide> @Override
Java
apache-2.0
094f35800248b6311f706c4fa04a47e7dbf35c15
0
hopshadoop/hops,hopshadoop/hops,hopshadoop/hops,hopshadoop/hops,hopshadoop/hops,hopshadoop/hops,hopshadoop/hops,hopshadoop/hops
/** * 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.hdfs.server.blockmanagement; import java.util.AbstractList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.TreeMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.hops.transaction.lock.TransactionLockTypes; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.protocol.DatanodeID; import org.apache.hadoop.hdfs.server.namenode.Namesystem; import org.apache.hadoop.hdfs.util.CyclicIteration; import org.apache.hadoop.util.ChunkedArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Preconditions.checkArgument; import io.hops.common.INodeUtil; import io.hops.exception.StorageException; import io.hops.exception.TransactionContextException; import io.hops.metadata.hdfs.entity.INodeIdentifier; import io.hops.transaction.EntityManager; import io.hops.transaction.handler.HDFSOperationType; import io.hops.transaction.handler.HopsTransactionalRequestHandler; import io.hops.transaction.lock.LockFactory; import io.hops.transaction.lock.LockFactory.BLK; import io.hops.transaction.lock.TransactionLocks; import io.hops.util.Slicer; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import static org.apache.hadoop.util.Time.monotonicNow; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import org.apache.hadoop.hdfs.server.namenode.FSNamesystem; import org.apache.hadoop.hdfs.server.namenode.INode; /** * Manages datanode decommissioning. A background monitor thread * periodically checks the status of datanodes that are in-progress of * decommissioning. * <p/> * A datanode can be decommissioned in a few situations: * <ul> * <li>If a DN is dead, it is decommissioned immediately.</li> * <li>If a DN is alive, it is decommissioned after all of its blocks * are sufficiently replicated. Merely under-replicated blocks do not * block decommissioning as long as they are above a replication * threshold.</li> * </ul> * In the second case, the datanode transitions to a * decommission-in-progress state and is tracked by the monitor thread. The * monitor periodically scans through the list of insufficiently replicated * blocks on these datanodes to * determine if they can be decommissioned. The monitor also prunes this list * as blocks become replicated, so monitor scans will become more efficient * over time. * <p/> * Decommission-in-progress nodes that become dead do not progress to * decommissioned until they become live again. This prevents potential * durability loss for singly-replicated blocks (see HDFS-6791). * <p/> * This class depends on the FSNamesystem lock for synchronization. */ @InterfaceAudience.Private public class DecommissionManager { private static final Logger LOG = LoggerFactory.getLogger(DecommissionManager .class); private final Namesystem namesystem; private final BlockManager blockManager; private final HeartbeatManager hbManager; private final ScheduledExecutorService executor; /** * Map containing the decommission-in-progress datanodes that are being * tracked so they can be be marked as decommissioned. * <p/> * This holds a set of references to the under-replicated blocks on the DN at * the time the DN is added to the map, i.e. the blocks that are preventing * the node from being marked as decommissioned. During a monitor tick, this * list is pruned as blocks becomes replicated. * <p/> * Note also that the reference to the list of under-replicated blocks * will be null on initial add * <p/> * However, this map can become out-of-date since it is not updated by block * reports or other events. Before being finally marking as decommissioned, * another check is done with the actual block map. */ private final TreeMap<DatanodeDescriptor, AbstractList<BlockInfoContiguous>> decomNodeBlocks; /** * Tracking a node in decomNodeBlocks consumes additional memory. To limit * the impact on NN memory consumption, we limit the number of nodes in * decomNodeBlocks. Additional nodes wait in pendingNodes. */ private final Queue<DatanodeDescriptor> pendingNodes; private Monitor monitor = null; DecommissionManager(final Namesystem namesystem, final BlockManager blockManager, final HeartbeatManager hbManager) { this.namesystem = namesystem; this.blockManager = blockManager; this.hbManager = hbManager; executor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setNameFormat("DecommissionMonitor-%d") .setDaemon(true).build()); decomNodeBlocks = new TreeMap<>(); pendingNodes = new LinkedList<>(); } /** * Start the decommission monitor thread. * @param conf */ void activate(Configuration conf) { final int intervalSecs = conf.getInt(DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_INTERVAL_KEY, DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_INTERVAL_DEFAULT); checkArgument(intervalSecs >= 0, "Cannot set a negative " + "value for " + DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_INTERVAL_KEY); // By default, the new configuration key overrides the deprecated one. // No # node limit is set. int blocksPerInterval = conf.getInt( DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_BLOCKS_PER_INTERVAL_KEY, DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_BLOCKS_PER_INTERVAL_DEFAULT); int nodesPerInterval = Integer.MAX_VALUE; // If the expected key isn't present and the deprecated one is, // use the deprecated one into the new one. This overrides the // default. // // Also print a deprecation warning. final String deprecatedKey = "dfs.namenode.decommission.nodes.per.interval"; final String strNodes = conf.get(deprecatedKey); if (strNodes != null) { nodesPerInterval = Integer.parseInt(strNodes); blocksPerInterval = Integer.MAX_VALUE; LOG.warn("Using deprecated configuration key {} value of {}.", deprecatedKey, nodesPerInterval); LOG.warn("Please update your configuration to use {} instead.", DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_BLOCKS_PER_INTERVAL_KEY); } checkArgument(blocksPerInterval > 0, "Must set a positive value for " + DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_BLOCKS_PER_INTERVAL_KEY); final int maxConcurrentTrackedNodes = conf.getInt( DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_MAX_CONCURRENT_TRACKED_NODES, DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_MAX_CONCURRENT_TRACKED_NODES_DEFAULT); checkArgument(maxConcurrentTrackedNodes >= 0, "Cannot set a negative " + "value for " + DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_MAX_CONCURRENT_TRACKED_NODES); monitor = new Monitor(blocksPerInterval, nodesPerInterval, maxConcurrentTrackedNodes); executor.scheduleAtFixedRate(monitor, intervalSecs, intervalSecs, TimeUnit.SECONDS); LOG.debug("Activating DecommissionManager with interval {} seconds, " + "{} max blocks per interval, {} max nodes per interval, " + "{} max concurrently tracked nodes.", intervalSecs, blocksPerInterval, nodesPerInterval, maxConcurrentTrackedNodes); } /** * Stop the decommission monitor thread, waiting briefly for it to terminate. */ void close() { executor.shutdownNow(); try { executor.awaitTermination(3000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) {} } /** * Start decommissioning the specified datanode. * @param node */ @VisibleForTesting public void startDecommission(DatanodeDescriptor node) throws IOException { if (!node.isDecommissionInProgress() && !node.isDecommissioned()) { // Update DN stats maintained by HeartbeatManager hbManager.startDecommission(node); // hbManager.startDecommission will set dead node to decommissioned. if (node.isDecommissionInProgress()) { for (DatanodeStorageInfo storage : node.getStorageInfos()) { LOG.info("Starting decommission of {} {} with {} blocks", node, storage, storage.numBlocks()); } node.decommissioningStatus.setStartTime(monotonicNow()); pendingNodes.add(node); } } else { LOG.trace("startDecommission: Node {} in {}, nothing to do." + node, node.getAdminState()); } } /** * Stop decommissioning the specified datanode. * @param node */ @VisibleForTesting public void stopDecommission(DatanodeDescriptor node) throws IOException { if (node.isDecommissionInProgress() || node.isDecommissioned()) { // Update DN stats maintained by HeartbeatManager hbManager.stopDecommission(node); // Over-replicated blocks will be detected and processed when // the dead node comes back and send in its full block report. if (node.isAlive) { blockManager.processOverReplicatedBlocksOnReCommission(node); } // Remove from tracking in DecommissionManager pendingNodes.remove(node); decomNodeBlocks.remove(node); } else { LOG.trace("stopDecommission: Node {} in {}, nothing to do." + node, node.getAdminState()); } } private void setDecommissioned(DatanodeDescriptor dn) { dn.setDecommissioned(); LOG.info("Decommissioning complete for node {}", dn); } /** * Checks whether a block is sufficiently replicated for decommissioning. * Full-strength replication is not always necessary, hence "sufficient". * @return true if sufficient, else false. */ private boolean isSufficientlyReplicated(BlockInfoContiguous block, BlockCollection bc, NumberReplicas numberReplicas) throws StorageException, TransactionContextException, IOException { final int numExpected = bc.getBlockReplication(); final int numLive = numberReplicas.liveReplicas(); if (!blockManager.isNeededReplication(block, numExpected, numLive)) { // Block doesn't need replication. Skip. LOG.trace("Block {} does not need replication.", block); return true; } // Block is under-replicated LOG.trace("Block {} numExpected={}, numLive={}", block, numExpected, numLive); if (numExpected > numLive) { if (bc.isUnderConstruction() && block.equals(bc.getLastBlock())) { // Can decom a UC block as long as there will still be minReplicas if (numLive >= blockManager.minReplication) { LOG.trace("UC block {} sufficiently-replicated since numLive ({}) " + ">= minR ({})", block, numLive, blockManager.minReplication); return true; } else { LOG.trace("UC block {} insufficiently-replicated since numLive " + "({}) < minR ({})", block, numLive, blockManager.minReplication); } } else { // Can decom a non-UC as long as the default replication is met if (numLive >= blockManager.defaultReplication) { return true; } } } return false; } private static void logBlockReplicationInfo(Block block, BlockCollection bc, DatanodeDescriptor srcNode, NumberReplicas num, Iterable<DatanodeStorageInfo> storages) { int curReplicas = num.liveReplicas(); int curExpectedReplicas = bc.getBlockReplication(); StringBuilder nodeList = new StringBuilder(); for (DatanodeStorageInfo storage : storages) { final DatanodeDescriptor node = storage.getDatanodeDescriptor(); nodeList.append(node); nodeList.append(" "); } LOG.info("Block: " + block + ", Expected Replicas: " + curExpectedReplicas + ", live replicas: " + curReplicas + ", corrupt replicas: " + num.corruptReplicas() + ", decommissioned replicas: " + num.decommissioned() + ", decommissioning replicas: " + num.decommissioning() + ", excess replicas: " + num.excessReplicas() + ", Is Open File: " + bc.isUnderConstruction() + ", Datanodes having this block: " + nodeList + ", Current Datanode: " + srcNode + ", Is current datanode decommissioning: " + srcNode.isDecommissionInProgress()); } @VisibleForTesting public int getNumPendingNodes() { return pendingNodes.size(); } @VisibleForTesting public int getNumTrackedNodes() { return decomNodeBlocks.size(); } @VisibleForTesting public int getNumNodesChecked() { return monitor.numNodesChecked; } /** * Checks to see if DNs have finished decommissioning. * <p/> * Since this is done while holding the namesystem lock, * the amount of work per monitor tick is limited. */ private class Monitor implements Runnable { /** * The maximum number of blocks to check per tick. */ private final int numBlocksPerCheck; /** * The maximum number of nodes to check per tick. */ private final int numNodesPerCheck; /** * The maximum number of nodes to track in decomNodeBlocks. A value of 0 * means no limit. */ private final int maxConcurrentTrackedNodes; /** * The number of blocks that have been checked on this tick. */ private int numBlocksChecked = 0; /** * The number of nodes that have been checked on this tick. Used for * testing. */ private int numNodesChecked = 0; /** * The last datanode in decomNodeBlocks that we've processed */ private DatanodeDescriptor iterkey = new DatanodeDescriptor(null, new DatanodeID("", "", "", 0, 0, 0, 0)); Monitor(int numBlocksPerCheck, int numNodesPerCheck, int maxConcurrentTrackedNodes) { this.numBlocksPerCheck = numBlocksPerCheck; this.numNodesPerCheck = numNodesPerCheck; this.maxConcurrentTrackedNodes = maxConcurrentTrackedNodes; } private boolean exceededNumBlocksPerCheck() { LOG.trace("Processed {} blocks so far this tick", numBlocksChecked); return numBlocksChecked >= numBlocksPerCheck; } @Deprecated private boolean exceededNumNodesPerCheck() { LOG.trace("Processed {} nodes so far this tick", numNodesChecked); return numNodesChecked >= numNodesPerCheck; } @Override public void run() { if (!namesystem.isRunning()) { LOG.info("Namesystem is not running, skipping decommissioning checks" + "."); return; } // Reset the checked count at beginning of each iteration numBlocksChecked = 0; numNodesChecked = 0; // Check decom progress processPendingNodes(); try { check(); } catch (IOException ex) { LOG.warn("Failled to check decommission blocks", ex); } if (numBlocksChecked + numNodesChecked > 0) { LOG.info("Checked {} blocks and {} nodes this tick", numBlocksChecked, numNodesChecked); } } /** * Pop datanodes off the pending list and into decomNodeBlocks, * subject to the maxConcurrentTrackedNodes limit. */ private void processPendingNodes() { while (!pendingNodes.isEmpty() && (maxConcurrentTrackedNodes == 0 || decomNodeBlocks.size() < maxConcurrentTrackedNodes)) { decomNodeBlocks.put(pendingNodes.poll(), null); } } private void check() throws IOException { final Iterator<Map.Entry<DatanodeDescriptor, AbstractList<BlockInfoContiguous>>> it = new CyclicIteration<>(decomNodeBlocks, iterkey).iterator(); final LinkedList<DatanodeDescriptor> toRemove = new LinkedList<>(); while (it.hasNext() && !exceededNumBlocksPerCheck() && !exceededNumNodesPerCheck()) { numNodesChecked++; final Map.Entry<DatanodeDescriptor, AbstractList<BlockInfoContiguous>> entry = it.next(); final DatanodeDescriptor dn = entry.getKey(); AbstractList<BlockInfoContiguous> blocks = entry.getValue(); boolean fullScan = false; if (blocks == null) { // This is a newly added datanode, run through its list to schedule // under-replicated blocks for replication and collect the blocks // that are insufficiently replicated for further tracking LOG.debug("Newly-added node {}, doing full scan to find " + "insufficiently-replicated blocks.", dn); blocks = handleInsufficientlyReplicated(dn); decomNodeBlocks.put(dn, blocks); fullScan = true; } else { // This is a known datanode, check if its # of insufficiently // replicated blocks has dropped to zero and if it can be decommed LOG.debug("Processing decommission-in-progress node {}", dn); pruneSufficientlyReplicated(dn, blocks); } if (blocks.size() == 0) { if (!fullScan) { // If we didn't just do a full scan, need to re-check with the // full block map. // // We've replicated all the known insufficiently replicated // blocks. Re-check with the full block map before finally // marking the datanode as decommissioned LOG.debug("Node {} has finished replicating current set of " + "blocks, checking with the full block map.", dn); blocks = handleInsufficientlyReplicated(dn); decomNodeBlocks.put(dn, blocks); } // If the full scan is clean AND the node liveness is okay, // we can finally mark as decommissioned. final boolean isHealthy = blockManager.isNodeHealthyForDecommission(dn); if (blocks.size() == 0 && isHealthy) { setDecommissioned(dn); toRemove.add(dn); LOG.debug("Node {} is sufficiently replicated and healthy, " + "marked as decommissioned.", dn); } else { if (LOG.isDebugEnabled()) { StringBuilder b = new StringBuilder("Node {} "); if (isHealthy) { b.append("is "); } else { b.append("isn't "); } b.append("healthy and still needs to replicate {} more blocks," + " decommissioning is still in progress."); LOG.debug(b.toString(), dn, blocks.size()); } } } else { LOG.debug("Node {} still has {} blocks to replicate " + "before it is a candidate to finish decommissioning.", dn, blocks.size()); } iterkey = dn; } // Remove the datanodes that are decommissioned for (DatanodeDescriptor dn : toRemove) { Preconditions.checkState(dn.isDecommissioned(), "Removing a node that is not yet decommissioned!"); decomNodeBlocks.remove(dn); } } /** * Removes sufficiently replicated blocks from the block list of a * datanode. */ private void pruneSufficientlyReplicated(final DatanodeDescriptor datanode, final AbstractList<BlockInfoContiguous> blocks) throws IOException { final Set<Long> inodeIdsSet = new HashSet<>(); final Map<Long, List<BlockInfoContiguous>> blocksPerInodes = new HashMap<>(); for (BlockInfoContiguous block : blocks) { inodeIdsSet.add(block.getInodeId()); List<BlockInfoContiguous> blocksForInode = blocksPerInodes.get(block.getInodeId()); if(blocksForInode==null){ blocksForInode = new ArrayList<>(); blocksPerInodes.put(block.getInodeId(), blocksForInode); } blocksForInode.add(block); } final List<Long> inodeIds = new ArrayList<>(inodeIdsSet); final Queue<BlockInfoContiguous> toRemove = new ConcurrentLinkedQueue<>(); final AtomicInteger underReplicatedBlocks = new AtomicInteger(0); final AtomicInteger decommissionOnlyReplicas = new AtomicInteger(0); final AtomicInteger underReplicatedInOpenFiles = new AtomicInteger(0); try { Slicer.slice(inodeIds.size(), ((FSNamesystem) namesystem).getBlockManager().getRemovalBatchSize(), ((FSNamesystem) namesystem).getBlockManager().getRemovalNoThreads(), ((FSNamesystem) namesystem).getFSOperationsExecutor(), new Slicer.OperationHandler() { @Override public void handle(int startIndex, int endIndex) throws Exception { final List<Long> ids = inodeIds.subList(startIndex, endIndex); HopsTransactionalRequestHandler checkReplicationHandler = new HopsTransactionalRequestHandler( HDFSOperationType.CHECK_REPLICATION_IN_PROGRESS) { List<INodeIdentifier> inodeIdentifiers; @Override public void setUp() throws StorageException { inodeIdentifiers = INodeUtil.resolveINodesFromIds(ids); } @Override public void acquireLock(TransactionLocks locks) throws IOException { LockFactory lf = LockFactory.getInstance(); if (!inodeIdentifiers.isEmpty()) { locks.add( lf.getMultipleINodesLock(inodeIdentifiers, TransactionLockTypes.INodeLockType.WRITE)) .add(lf.getSqlBatchedBlocksLock()).add( lf.getSqlBatchedBlocksRelated(BLK.RE, BLK.ER, BLK.CR, BLK.UR, BLK.PE)); } } @Override public Object performTask() throws IOException { List<BlockInfoContiguous> blocksToProcess = new ArrayList<>(); //it is ok to work with ids and blocksPerInodes here, even if they come from another transaction //because in processBlocksForDecomInternal we check that these blocks actually still exist. for(Long inodeIds: ids){ blocksToProcess.addAll(blocksPerInodes.get(inodeIds)); } Set<Long> existingInodes = new HashSet<>(); for(INodeIdentifier identifier : inodeIdentifiers){ INode inode = EntityManager.find(INode.Finder.ByINodeIdFTIS, identifier.getInodeId()); if(inode==null){ //The inode does not exist anymore. LOG.debug("inode " + identifier.getInodeId() + " does not exist anymore"); continue; } existingInodes.add(inode.getId()); } processBlocksForDecomInternal(datanode, blocksToProcess.iterator(), null, true, existingInodes, toRemove, underReplicatedBlocks, underReplicatedInOpenFiles, decommissionOnlyReplicas); return null; } }; checkReplicationHandler.handle(); } }); blocks.removeAll(toRemove); } catch (Exception ex) { throw new IOException(ex); } datanode.decommissioningStatus.set(underReplicatedBlocks.get(),decommissionOnlyReplicas.get(), underReplicatedInOpenFiles.get()); } /** * Returns a list of blocks on a datanode that are insufficiently * replicated, i.e. are under-replicated enough to prevent decommission. * <p/> * As part of this, it also schedules replication work for * any under-replicated blocks. * * @param datanode * @return List of insufficiently replicated blocks */ private AbstractList<BlockInfoContiguous> handleInsufficientlyReplicated( final DatanodeDescriptor datanode) throws IOException { final Queue<BlockInfoContiguous> insuf = new ConcurrentLinkedQueue<>(); Map<Long, Long> blocksOnNode = datanode.getAllStorageReplicas(((FSNamesystem) namesystem).getBlockManager(). getNumBuckets(), ((FSNamesystem) namesystem).getBlockManager().getBlockFetcherNBThreads(), ((FSNamesystem) namesystem).getBlockManager().getBlockFetcherBucketsPerThread(), ((FSNamesystem) namesystem). getFSOperationsExecutor()); final Map<Long, List<Long>> inodeIdsToBlockMap = new HashMap<>(); for (Map.Entry<Long, Long> entry : blocksOnNode.entrySet()) { List<Long> list = inodeIdsToBlockMap.get(entry.getValue()); if (list == null) { list = new ArrayList<>(); inodeIdsToBlockMap.put(entry.getValue(), list); } list.add(entry.getKey()); } final List<Long> inodeIds = new ArrayList<>(inodeIdsToBlockMap.keySet()); final Queue<BlockInfoContiguous> toRemove = new ConcurrentLinkedQueue<>(); final AtomicInteger underReplicatedBlocks = new AtomicInteger(0); final AtomicInteger decommissionOnlyReplicas = new AtomicInteger(0); final AtomicInteger underReplicatedInOpenFiles = new AtomicInteger(0); try { Slicer.slice(inodeIds.size(), ((FSNamesystem) namesystem).getBlockManager().getRemovalBatchSize(), ((FSNamesystem) namesystem).getBlockManager().getRemovalNoThreads(), ((FSNamesystem) namesystem).getFSOperationsExecutor(), new Slicer.OperationHandler() { @Override public void handle(int startIndex, int endIndex) throws Exception { final List<Long> ids = inodeIds.subList(startIndex, endIndex); HopsTransactionalRequestHandler checkReplicationHandler = new HopsTransactionalRequestHandler( HDFSOperationType.CHECK_REPLICATION_IN_PROGRESS) { List<INodeIdentifier> inodeIdentifiers; @Override public void setUp() throws StorageException { inodeIdentifiers = INodeUtil.resolveINodesFromIds(ids); } @Override public void acquireLock(TransactionLocks locks) throws IOException { LockFactory lf = LockFactory.getInstance(); locks.add( lf.getMultipleINodesLock(inodeIdentifiers, TransactionLockTypes.INodeLockType.WRITE)) .add(lf.getSqlBatchedBlocksLock()).add( lf.getSqlBatchedBlocksRelated(BLK.RE, BLK.ER, BLK.CR, BLK.UR, BLK.PE)); } @Override public Object performTask() throws IOException { List<BlockInfoContiguous> toCheck = new ArrayList<>(); Set<Long> existingInodes = new HashSet<>(); for (INodeIdentifier identifier : inodeIdentifiers) { INode inode = EntityManager.find(INode.Finder.ByINodeIdFTIS, identifier.getInodeId()); if(inode==null){ //The inode does not exist anymore. LOG.debug("inode " + identifier.getInodeId() + " does not exist anymore"); continue; } existingInodes.add(inode.getId()); //it is ok if we skip blocks that do not exist anymore here because we never use the //toRemove queue. for (long blockId : inodeIdsToBlockMap.get(inode.getId())) { BlockInfoContiguous block = EntityManager. find(BlockInfoContiguous.Finder.ByBlockIdAndINodeId, blockId); toCheck.add(block); } } processBlocksForDecomInternal(datanode, toCheck.iterator(), insuf, false, existingInodes, toRemove, underReplicatedBlocks, underReplicatedInOpenFiles, decommissionOnlyReplicas); return null; } }; checkReplicationHandler.handle(); } }); } catch (Exception ex) { throw new IOException(ex); } datanode.decommissioningStatus.set(underReplicatedBlocks.get(),decommissionOnlyReplicas.get(), underReplicatedInOpenFiles.get()); AbstractList<BlockInfoContiguous> insufficient = new ChunkedArrayList<>(); insufficient.addAll(insuf); return insufficient; } /** * Used while checking if decommission-in-progress datanodes can be marked * as decommissioned. Combines shared logic of * pruneSufficientlyReplicated and handleInsufficientlyReplicated. * * @param datanode Datanode * @param it Iterator over the blocks on the * datanode * @param insufficientlyReplicated Return parameter. If it's not null, * will contain the insufficiently * replicated-blocks from the list. * @param pruneSufficientlyReplicated whether to remove sufficiently * replicated blocks from the iterator * @return true if there are under-replicated blocks in the provided block * iterator, else false. */ private void processBlocksForDecomInternal( final DatanodeDescriptor datanode, final Iterator<BlockInfoContiguous> it, final Queue<BlockInfoContiguous> insufficientlyReplicated, boolean pruneSufficientlyReplicated, Set<Long> existingInodes, Queue<BlockInfoContiguous> toRemove, AtomicInteger underReplicatedBlocks, AtomicInteger underReplicatedInOpenFiles, AtomicInteger decommissionOnlyReplicas) throws IOException { boolean firstReplicationLog = true; while (it.hasNext()) { numBlocksChecked++; final BlockInfoContiguous block = it.next(); // Remove the block from the list if it's no longer in the block map, // e.g. the containing file has been deleted if (!existingInodes.contains(block.getInodeId()) || blockManager.blocksMap.getStoredBlock(block) == null) { LOG.trace("Removing unknown block {}", block); toRemove.add(block); continue; } BlockCollection bc = blockManager.blocksMap.getBlockCollection(block); if (bc == null) { // Orphan block, will be invalidated eventually. Skip. continue; } final NumberReplicas num = blockManager.countNodes(block); final int liveReplicas = num.liveReplicas(); final int curReplicas = liveReplicas; // Schedule under-replicated blocks for replication if not already // pending if (blockManager.isNeededReplication(block, bc.getBlockReplication(), liveReplicas)) { if (!blockManager.neededReplications.contains(block) && blockManager.pendingReplications.getNumReplicas(block) == 0 && namesystem.isPopulatingReplQueues()) { // Process these blocks only when active NN is out of safe mode. blockManager.neededReplications.add(block, curReplicas, num.decommissionedAndDecommissioning(), bc.getBlockReplication()); } } // Even if the block is under-replicated, // it doesn't block decommission if it's sufficiently replicated if (isSufficientlyReplicated(block, bc, num)) { if (pruneSufficientlyReplicated) { toRemove.add(block); } continue; } // We've found an insufficiently replicated block. if (insufficientlyReplicated != null) { insufficientlyReplicated.add(block); } // Log if this is our first time through if (firstReplicationLog) { logBlockReplicationInfo(block, bc, datanode, num, blockManager.blocksMap.getStorages(block)); firstReplicationLog = false; } // Update various counts underReplicatedBlocks.incrementAndGet(); if (bc.isUnderConstruction()) { underReplicatedInOpenFiles.incrementAndGet(); } if ((curReplicas == 0) && (num.decommissionedAndDecommissioning() > 0)) { decommissionOnlyReplicas.incrementAndGet(); } } //HOPS: need to be done out of the slicer // datanode.decommissioningStatus.set(underReplicatedBlocks, // decommissionOnlyReplicas, // underReplicatedInOpenFiles); } } @VisibleForTesting void runMonitor() throws ExecutionException, InterruptedException { Future f = executor.submit(monitor); f.get(); } }
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DecommissionManager.java
/** * 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.hdfs.server.blockmanagement; import java.util.AbstractList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.TreeMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ThreadFactoryBuilder; import io.hops.transaction.lock.TransactionLockTypes; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.protocol.DatanodeID; import org.apache.hadoop.hdfs.server.namenode.Namesystem; import org.apache.hadoop.hdfs.util.CyclicIteration; import org.apache.hadoop.util.ChunkedArrayList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Preconditions.checkArgument; import io.hops.common.INodeUtil; import io.hops.exception.StorageException; import io.hops.exception.TransactionContextException; import io.hops.metadata.hdfs.entity.INodeIdentifier; import io.hops.transaction.EntityManager; import io.hops.transaction.handler.HDFSOperationType; import io.hops.transaction.handler.HopsTransactionalRequestHandler; import io.hops.transaction.lock.LockFactory; import io.hops.transaction.lock.LockFactory.BLK; import io.hops.transaction.lock.TransactionLocks; import io.hops.util.Slicer; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import static org.apache.hadoop.util.Time.monotonicNow; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import org.apache.hadoop.hdfs.server.namenode.FSNamesystem; /** * Manages datanode decommissioning. A background monitor thread * periodically checks the status of datanodes that are in-progress of * decommissioning. * <p/> * A datanode can be decommissioned in a few situations: * <ul> * <li>If a DN is dead, it is decommissioned immediately.</li> * <li>If a DN is alive, it is decommissioned after all of its blocks * are sufficiently replicated. Merely under-replicated blocks do not * block decommissioning as long as they are above a replication * threshold.</li> * </ul> * In the second case, the datanode transitions to a * decommission-in-progress state and is tracked by the monitor thread. The * monitor periodically scans through the list of insufficiently replicated * blocks on these datanodes to * determine if they can be decommissioned. The monitor also prunes this list * as blocks become replicated, so monitor scans will become more efficient * over time. * <p/> * Decommission-in-progress nodes that become dead do not progress to * decommissioned until they become live again. This prevents potential * durability loss for singly-replicated blocks (see HDFS-6791). * <p/> * This class depends on the FSNamesystem lock for synchronization. */ @InterfaceAudience.Private public class DecommissionManager { private static final Logger LOG = LoggerFactory.getLogger(DecommissionManager .class); private final Namesystem namesystem; private final BlockManager blockManager; private final HeartbeatManager hbManager; private final ScheduledExecutorService executor; /** * Map containing the decommission-in-progress datanodes that are being * tracked so they can be be marked as decommissioned. * <p/> * This holds a set of references to the under-replicated blocks on the DN at * the time the DN is added to the map, i.e. the blocks that are preventing * the node from being marked as decommissioned. During a monitor tick, this * list is pruned as blocks becomes replicated. * <p/> * Note also that the reference to the list of under-replicated blocks * will be null on initial add * <p/> * However, this map can become out-of-date since it is not updated by block * reports or other events. Before being finally marking as decommissioned, * another check is done with the actual block map. */ private final TreeMap<DatanodeDescriptor, AbstractList<BlockInfoContiguous>> decomNodeBlocks; /** * Tracking a node in decomNodeBlocks consumes additional memory. To limit * the impact on NN memory consumption, we limit the number of nodes in * decomNodeBlocks. Additional nodes wait in pendingNodes. */ private final Queue<DatanodeDescriptor> pendingNodes; private Monitor monitor = null; DecommissionManager(final Namesystem namesystem, final BlockManager blockManager, final HeartbeatManager hbManager) { this.namesystem = namesystem; this.blockManager = blockManager; this.hbManager = hbManager; executor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setNameFormat("DecommissionMonitor-%d") .setDaemon(true).build()); decomNodeBlocks = new TreeMap<>(); pendingNodes = new LinkedList<>(); } /** * Start the decommission monitor thread. * @param conf */ void activate(Configuration conf) { final int intervalSecs = conf.getInt(DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_INTERVAL_KEY, DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_INTERVAL_DEFAULT); checkArgument(intervalSecs >= 0, "Cannot set a negative " + "value for " + DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_INTERVAL_KEY); // By default, the new configuration key overrides the deprecated one. // No # node limit is set. int blocksPerInterval = conf.getInt( DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_BLOCKS_PER_INTERVAL_KEY, DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_BLOCKS_PER_INTERVAL_DEFAULT); int nodesPerInterval = Integer.MAX_VALUE; // If the expected key isn't present and the deprecated one is, // use the deprecated one into the new one. This overrides the // default. // // Also print a deprecation warning. final String deprecatedKey = "dfs.namenode.decommission.nodes.per.interval"; final String strNodes = conf.get(deprecatedKey); if (strNodes != null) { nodesPerInterval = Integer.parseInt(strNodes); blocksPerInterval = Integer.MAX_VALUE; LOG.warn("Using deprecated configuration key {} value of {}.", deprecatedKey, nodesPerInterval); LOG.warn("Please update your configuration to use {} instead.", DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_BLOCKS_PER_INTERVAL_KEY); } checkArgument(blocksPerInterval > 0, "Must set a positive value for " + DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_BLOCKS_PER_INTERVAL_KEY); final int maxConcurrentTrackedNodes = conf.getInt( DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_MAX_CONCURRENT_TRACKED_NODES, DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_MAX_CONCURRENT_TRACKED_NODES_DEFAULT); checkArgument(maxConcurrentTrackedNodes >= 0, "Cannot set a negative " + "value for " + DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_MAX_CONCURRENT_TRACKED_NODES); monitor = new Monitor(blocksPerInterval, nodesPerInterval, maxConcurrentTrackedNodes); executor.scheduleAtFixedRate(monitor, intervalSecs, intervalSecs, TimeUnit.SECONDS); LOG.debug("Activating DecommissionManager with interval {} seconds, " + "{} max blocks per interval, {} max nodes per interval, " + "{} max concurrently tracked nodes.", intervalSecs, blocksPerInterval, nodesPerInterval, maxConcurrentTrackedNodes); } /** * Stop the decommission monitor thread, waiting briefly for it to terminate. */ void close() { executor.shutdownNow(); try { executor.awaitTermination(3000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) {} } /** * Start decommissioning the specified datanode. * @param node */ @VisibleForTesting public void startDecommission(DatanodeDescriptor node) throws IOException { if (!node.isDecommissionInProgress() && !node.isDecommissioned()) { // Update DN stats maintained by HeartbeatManager hbManager.startDecommission(node); // hbManager.startDecommission will set dead node to decommissioned. if (node.isDecommissionInProgress()) { for (DatanodeStorageInfo storage : node.getStorageInfos()) { LOG.info("Starting decommission of {} {} with {} blocks", node, storage, storage.numBlocks()); } node.decommissioningStatus.setStartTime(monotonicNow()); pendingNodes.add(node); } } else { LOG.trace("startDecommission: Node {} in {}, nothing to do." + node, node.getAdminState()); } } /** * Stop decommissioning the specified datanode. * @param node */ @VisibleForTesting public void stopDecommission(DatanodeDescriptor node) throws IOException { if (node.isDecommissionInProgress() || node.isDecommissioned()) { // Update DN stats maintained by HeartbeatManager hbManager.stopDecommission(node); // Over-replicated blocks will be detected and processed when // the dead node comes back and send in its full block report. if (node.isAlive) { blockManager.processOverReplicatedBlocksOnReCommission(node); } // Remove from tracking in DecommissionManager pendingNodes.remove(node); decomNodeBlocks.remove(node); } else { LOG.trace("stopDecommission: Node {} in {}, nothing to do." + node, node.getAdminState()); } } private void setDecommissioned(DatanodeDescriptor dn) { dn.setDecommissioned(); LOG.info("Decommissioning complete for node {}", dn); } /** * Checks whether a block is sufficiently replicated for decommissioning. * Full-strength replication is not always necessary, hence "sufficient". * @return true if sufficient, else false. */ private boolean isSufficientlyReplicated(BlockInfoContiguous block, BlockCollection bc, NumberReplicas numberReplicas) throws StorageException, TransactionContextException, IOException { final int numExpected = bc.getBlockReplication(); final int numLive = numberReplicas.liveReplicas(); if (!blockManager.isNeededReplication(block, numExpected, numLive)) { // Block doesn't need replication. Skip. LOG.trace("Block {} does not need replication.", block); return true; } // Block is under-replicated LOG.trace("Block {} numExpected={}, numLive={}", block, numExpected, numLive); if (numExpected > numLive) { if (bc.isUnderConstruction() && block.equals(bc.getLastBlock())) { // Can decom a UC block as long as there will still be minReplicas if (numLive >= blockManager.minReplication) { LOG.trace("UC block {} sufficiently-replicated since numLive ({}) " + ">= minR ({})", block, numLive, blockManager.minReplication); return true; } else { LOG.trace("UC block {} insufficiently-replicated since numLive " + "({}) < minR ({})", block, numLive, blockManager.minReplication); } } else { // Can decom a non-UC as long as the default replication is met if (numLive >= blockManager.defaultReplication) { return true; } } } return false; } private static void logBlockReplicationInfo(Block block, BlockCollection bc, DatanodeDescriptor srcNode, NumberReplicas num, Iterable<DatanodeStorageInfo> storages) { int curReplicas = num.liveReplicas(); int curExpectedReplicas = bc.getBlockReplication(); StringBuilder nodeList = new StringBuilder(); for (DatanodeStorageInfo storage : storages) { final DatanodeDescriptor node = storage.getDatanodeDescriptor(); nodeList.append(node); nodeList.append(" "); } LOG.info("Block: " + block + ", Expected Replicas: " + curExpectedReplicas + ", live replicas: " + curReplicas + ", corrupt replicas: " + num.corruptReplicas() + ", decommissioned replicas: " + num.decommissioned() + ", decommissioning replicas: " + num.decommissioning() + ", excess replicas: " + num.excessReplicas() + ", Is Open File: " + bc.isUnderConstruction() + ", Datanodes having this block: " + nodeList + ", Current Datanode: " + srcNode + ", Is current datanode decommissioning: " + srcNode.isDecommissionInProgress()); } @VisibleForTesting public int getNumPendingNodes() { return pendingNodes.size(); } @VisibleForTesting public int getNumTrackedNodes() { return decomNodeBlocks.size(); } @VisibleForTesting public int getNumNodesChecked() { return monitor.numNodesChecked; } /** * Checks to see if DNs have finished decommissioning. * <p/> * Since this is done while holding the namesystem lock, * the amount of work per monitor tick is limited. */ private class Monitor implements Runnable { /** * The maximum number of blocks to check per tick. */ private final int numBlocksPerCheck; /** * The maximum number of nodes to check per tick. */ private final int numNodesPerCheck; /** * The maximum number of nodes to track in decomNodeBlocks. A value of 0 * means no limit. */ private final int maxConcurrentTrackedNodes; /** * The number of blocks that have been checked on this tick. */ private int numBlocksChecked = 0; /** * The number of nodes that have been checked on this tick. Used for * testing. */ private int numNodesChecked = 0; /** * The last datanode in decomNodeBlocks that we've processed */ private DatanodeDescriptor iterkey = new DatanodeDescriptor(null, new DatanodeID("", "", "", 0, 0, 0, 0)); Monitor(int numBlocksPerCheck, int numNodesPerCheck, int maxConcurrentTrackedNodes) { this.numBlocksPerCheck = numBlocksPerCheck; this.numNodesPerCheck = numNodesPerCheck; this.maxConcurrentTrackedNodes = maxConcurrentTrackedNodes; } private boolean exceededNumBlocksPerCheck() { LOG.trace("Processed {} blocks so far this tick", numBlocksChecked); return numBlocksChecked >= numBlocksPerCheck; } @Deprecated private boolean exceededNumNodesPerCheck() { LOG.trace("Processed {} nodes so far this tick", numNodesChecked); return numNodesChecked >= numNodesPerCheck; } @Override public void run() { if (!namesystem.isRunning()) { LOG.info("Namesystem is not running, skipping decommissioning checks" + "."); return; } // Reset the checked count at beginning of each iteration numBlocksChecked = 0; numNodesChecked = 0; // Check decom progress processPendingNodes(); try { check(); } catch (IOException ex) { LOG.warn("Failled to check decommission blocks", ex); } if (numBlocksChecked + numNodesChecked > 0) { LOG.info("Checked {} blocks and {} nodes this tick", numBlocksChecked, numNodesChecked); } } /** * Pop datanodes off the pending list and into decomNodeBlocks, * subject to the maxConcurrentTrackedNodes limit. */ private void processPendingNodes() { while (!pendingNodes.isEmpty() && (maxConcurrentTrackedNodes == 0 || decomNodeBlocks.size() < maxConcurrentTrackedNodes)) { decomNodeBlocks.put(pendingNodes.poll(), null); } } private void check() throws IOException { final Iterator<Map.Entry<DatanodeDescriptor, AbstractList<BlockInfoContiguous>>> it = new CyclicIteration<>(decomNodeBlocks, iterkey).iterator(); final LinkedList<DatanodeDescriptor> toRemove = new LinkedList<>(); while (it.hasNext() && !exceededNumBlocksPerCheck() && !exceededNumNodesPerCheck()) { numNodesChecked++; final Map.Entry<DatanodeDescriptor, AbstractList<BlockInfoContiguous>> entry = it.next(); final DatanodeDescriptor dn = entry.getKey(); AbstractList<BlockInfoContiguous> blocks = entry.getValue(); boolean fullScan = false; if (blocks == null) { // This is a newly added datanode, run through its list to schedule // under-replicated blocks for replication and collect the blocks // that are insufficiently replicated for further tracking LOG.debug("Newly-added node {}, doing full scan to find " + "insufficiently-replicated blocks.", dn); blocks = handleInsufficientlyReplicated(dn); decomNodeBlocks.put(dn, blocks); fullScan = true; } else { // This is a known datanode, check if its # of insufficiently // replicated blocks has dropped to zero and if it can be decommed LOG.debug("Processing decommission-in-progress node {}", dn); pruneSufficientlyReplicated(dn, blocks); } if (blocks.size() == 0) { if (!fullScan) { // If we didn't just do a full scan, need to re-check with the // full block map. // // We've replicated all the known insufficiently replicated // blocks. Re-check with the full block map before finally // marking the datanode as decommissioned LOG.debug("Node {} has finished replicating current set of " + "blocks, checking with the full block map.", dn); blocks = handleInsufficientlyReplicated(dn); decomNodeBlocks.put(dn, blocks); } // If the full scan is clean AND the node liveness is okay, // we can finally mark as decommissioned. final boolean isHealthy = blockManager.isNodeHealthyForDecommission(dn); if (blocks.size() == 0 && isHealthy) { setDecommissioned(dn); toRemove.add(dn); LOG.debug("Node {} is sufficiently replicated and healthy, " + "marked as decommissioned.", dn); } else { if (LOG.isDebugEnabled()) { StringBuilder b = new StringBuilder("Node {} "); if (isHealthy) { b.append("is "); } else { b.append("isn't "); } b.append("healthy and still needs to replicate {} more blocks," + " decommissioning is still in progress."); LOG.debug(b.toString(), dn, blocks.size()); } } } else { LOG.debug("Node {} still has {} blocks to replicate " + "before it is a candidate to finish decommissioning.", dn, blocks.size()); } iterkey = dn; } // Remove the datanodes that are decommissioned for (DatanodeDescriptor dn : toRemove) { Preconditions.checkState(dn.isDecommissioned(), "Removing a node that is not yet decommissioned!"); decomNodeBlocks.remove(dn); } } /** * Removes sufficiently replicated blocks from the block list of a * datanode. */ private void pruneSufficientlyReplicated(final DatanodeDescriptor datanode, final AbstractList<BlockInfoContiguous> blocks) throws IOException { final Set<Long> inodeIdsSet = new HashSet<>(); final Map<Long, List<BlockInfoContiguous>> blocksPerInodes = new HashMap<>(); for (BlockInfoContiguous block : blocks) { inodeIdsSet.add(block.getInodeId()); List<BlockInfoContiguous> blocksForInode = blocksPerInodes.get(block.getInodeId()); if(blocksForInode==null){ blocksForInode = new ArrayList<>(); blocksPerInodes.put(block.getInodeId(), blocksForInode); } blocksForInode.add(block); } final List<Long> inodeIds = new ArrayList<>(inodeIdsSet); final Queue<BlockInfoContiguous> toRemove = new ConcurrentLinkedQueue<>(); final AtomicInteger underReplicatedBlocks = new AtomicInteger(0); final AtomicInteger decommissionOnlyReplicas = new AtomicInteger(0); final AtomicInteger underReplicatedInOpenFiles = new AtomicInteger(0); try { Slicer.slice(inodeIds.size(), ((FSNamesystem) namesystem).getBlockManager().getRemovalBatchSize(), ((FSNamesystem) namesystem).getBlockManager().getRemovalNoThreads(), ((FSNamesystem) namesystem).getFSOperationsExecutor(), new Slicer.OperationHandler() { @Override public void handle(int startIndex, int endIndex) throws Exception { final List<Long> ids = inodeIds.subList(startIndex, endIndex); HopsTransactionalRequestHandler checkReplicationHandler = new HopsTransactionalRequestHandler( HDFSOperationType.CHECK_REPLICATION_IN_PROGRESS) { List<INodeIdentifier> inodeIdentifiers; @Override public void setUp() throws StorageException { inodeIdentifiers = INodeUtil.resolveINodesFromIds(ids); } @Override public void acquireLock(TransactionLocks locks) throws IOException { LockFactory lf = LockFactory.getInstance(); if (!inodeIdentifiers.isEmpty()) { locks.add( lf.getMultipleINodesLock(inodeIdentifiers, TransactionLockTypes.INodeLockType.WRITE)) .add(lf.getSqlBatchedBlocksLock()).add( lf.getSqlBatchedBlocksRelated(BLK.RE, BLK.ER, BLK.CR, BLK.UR, BLK.PE)); } } @Override public Object performTask() throws IOException { List<BlockInfoContiguous> blocksToProcess = new ArrayList<>(); for(Long inodeIds: ids){ blocksToProcess.addAll(blocksPerInodes.get(inodeIds)); } Set<Long> existingInodes = new HashSet<>(); for(INodeIdentifier inode : inodeIdentifiers){ existingInodes.add(inode.getInodeId()); } processBlocksForDecomInternal(datanode, blocksToProcess.iterator(), null, true, existingInodes, toRemove, underReplicatedBlocks, underReplicatedInOpenFiles, decommissionOnlyReplicas); return null; } }; checkReplicationHandler.handle(); } }); blocks.removeAll(toRemove); } catch (Exception ex) { throw new IOException(ex); } datanode.decommissioningStatus.set(underReplicatedBlocks.get(),decommissionOnlyReplicas.get(), underReplicatedInOpenFiles.get()); } /** * Returns a list of blocks on a datanode that are insufficiently * replicated, i.e. are under-replicated enough to prevent decommission. * <p/> * As part of this, it also schedules replication work for * any under-replicated blocks. * * @param datanode * @return List of insufficiently replicated blocks */ private AbstractList<BlockInfoContiguous> handleInsufficientlyReplicated( final DatanodeDescriptor datanode) throws IOException { final Queue<BlockInfoContiguous> insuf = new ConcurrentLinkedQueue<>(); Map<Long, Long> blocksOnNode = datanode.getAllStorageReplicas(((FSNamesystem) namesystem).getBlockManager(). getNumBuckets(), ((FSNamesystem) namesystem).getBlockManager().getBlockFetcherNBThreads(), ((FSNamesystem) namesystem).getBlockManager().getBlockFetcherBucketsPerThread(), ((FSNamesystem) namesystem). getFSOperationsExecutor()); final Map<Long, List<Long>> inodeIdsToBlockMap = new HashMap<>(); for (Map.Entry<Long, Long> entry : blocksOnNode.entrySet()) { List<Long> list = inodeIdsToBlockMap.get(entry.getValue()); if (list == null) { list = new ArrayList<>(); inodeIdsToBlockMap.put(entry.getValue(), list); } list.add(entry.getKey()); } final List<Long> inodeIds = new ArrayList<>(inodeIdsToBlockMap.keySet()); final Queue<BlockInfoContiguous> toRemove = new ConcurrentLinkedQueue<>(); final AtomicInteger underReplicatedBlocks = new AtomicInteger(0); final AtomicInteger decommissionOnlyReplicas = new AtomicInteger(0); final AtomicInteger underReplicatedInOpenFiles = new AtomicInteger(0); try { Slicer.slice(inodeIds.size(), ((FSNamesystem) namesystem).getBlockManager().getRemovalBatchSize(), ((FSNamesystem) namesystem).getBlockManager().getRemovalNoThreads(), ((FSNamesystem) namesystem).getFSOperationsExecutor(), new Slicer.OperationHandler() { @Override public void handle(int startIndex, int endIndex) throws Exception { final List<Long> ids = inodeIds.subList(startIndex, endIndex); HopsTransactionalRequestHandler checkReplicationHandler = new HopsTransactionalRequestHandler( HDFSOperationType.CHECK_REPLICATION_IN_PROGRESS) { List<INodeIdentifier> inodeIdentifiers; @Override public void setUp() throws StorageException { inodeIdentifiers = INodeUtil.resolveINodesFromIds(ids); } @Override public void acquireLock(TransactionLocks locks) throws IOException { LockFactory lf = LockFactory.getInstance(); locks.add( lf.getMultipleINodesLock(inodeIdentifiers, TransactionLockTypes.INodeLockType.WRITE)) .add(lf.getSqlBatchedBlocksLock()).add( lf.getSqlBatchedBlocksRelated(BLK.RE, BLK.ER, BLK.CR, BLK.UR, BLK.PE)); } @Override public Object performTask() throws IOException { List<BlockInfoContiguous> toCheck = new ArrayList<>(); Set<Long> existingInodes = new HashSet<>(); for (INodeIdentifier identifier : inodeIdentifiers) { existingInodes.add(identifier.getInodeId()); for (long blockId : inodeIdsToBlockMap.get(identifier.getInodeId())) { BlockInfoContiguous block = EntityManager. find(BlockInfoContiguous.Finder.ByBlockIdAndINodeId, blockId); toCheck.add(block); } } processBlocksForDecomInternal(datanode, toCheck.iterator(), insuf, false, existingInodes, toRemove, underReplicatedBlocks, underReplicatedInOpenFiles, decommissionOnlyReplicas); return null; } }; checkReplicationHandler.handle(); } }); } catch (Exception ex) { throw new IOException(ex); } datanode.decommissioningStatus.set(underReplicatedBlocks.get(),decommissionOnlyReplicas.get(), underReplicatedInOpenFiles.get()); AbstractList<BlockInfoContiguous> insufficient = new ChunkedArrayList<>(); insufficient.addAll(insuf); return insufficient; } /** * Used while checking if decommission-in-progress datanodes can be marked * as decommissioned. Combines shared logic of * pruneSufficientlyReplicated and handleInsufficientlyReplicated. * * @param datanode Datanode * @param it Iterator over the blocks on the * datanode * @param insufficientlyReplicated Return parameter. If it's not null, * will contain the insufficiently * replicated-blocks from the list. * @param pruneSufficientlyReplicated whether to remove sufficiently * replicated blocks from the iterator * @return true if there are under-replicated blocks in the provided block * iterator, else false. */ private void processBlocksForDecomInternal( final DatanodeDescriptor datanode, final Iterator<BlockInfoContiguous> it, final Queue<BlockInfoContiguous> insufficientlyReplicated, boolean pruneSufficientlyReplicated, Set<Long> existingInodes, Queue<BlockInfoContiguous> toRemove, AtomicInteger underReplicatedBlocks, AtomicInteger underReplicatedInOpenFiles, AtomicInteger decommissionOnlyReplicas) throws IOException { boolean firstReplicationLog = true; while (it.hasNext()) { numBlocksChecked++; final BlockInfoContiguous block = it.next(); // Remove the block from the list if it's no longer in the block map, // e.g. the containing file has been deleted if (!existingInodes.contains(block.getInodeId()) || blockManager.blocksMap.getStoredBlock(block) == null) { LOG.trace("Removing unknown block {}", block); toRemove.add(block); continue; } BlockCollection bc = blockManager.blocksMap.getBlockCollection(block); if (bc == null) { // Orphan block, will be invalidated eventually. Skip. continue; } final NumberReplicas num = blockManager.countNodes(block); final int liveReplicas = num.liveReplicas(); final int curReplicas = liveReplicas; // Schedule under-replicated blocks for replication if not already // pending if (blockManager.isNeededReplication(block, bc.getBlockReplication(), liveReplicas)) { if (!blockManager.neededReplications.contains(block) && blockManager.pendingReplications.getNumReplicas(block) == 0 && namesystem.isPopulatingReplQueues()) { // Process these blocks only when active NN is out of safe mode. blockManager.neededReplications.add(block, curReplicas, num.decommissionedAndDecommissioning(), bc.getBlockReplication()); } } // Even if the block is under-replicated, // it doesn't block decommission if it's sufficiently replicated if (isSufficientlyReplicated(block, bc, num)) { if (pruneSufficientlyReplicated) { toRemove.add(block); } continue; } // We've found an insufficiently replicated block. if (insufficientlyReplicated != null) { insufficientlyReplicated.add(block); } // Log if this is our first time through if (firstReplicationLog) { logBlockReplicationInfo(block, bc, datanode, num, blockManager.blocksMap.getStorages(block)); firstReplicationLog = false; } // Update various counts underReplicatedBlocks.incrementAndGet(); if (bc.isUnderConstruction()) { underReplicatedInOpenFiles.incrementAndGet(); } if ((curReplicas == 0) && (num.decommissionedAndDecommissioning() > 0)) { decommissionOnlyReplicas.incrementAndGet(); } } //HOPS: need to be done out of the slicer // datanode.decommissioningStatus.set(underReplicatedBlocks, // decommissionOnlyReplicas, // underReplicatedInOpenFiles); } } @VisibleForTesting void runMonitor() throws ExecutionException, InterruptedException { Future f = executor.submit(monitor); f.get(); } }
[HOPS-1596] and [HOPS-1597] fix passing object between transactions in DecommissionManager
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DecommissionManager.java
[HOPS-1596] and [HOPS-1597] fix passing object between transactions in DecommissionManager
<ide><path>adoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DecommissionManager.java <ide> import java.util.concurrent.ConcurrentLinkedQueue; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> import org.apache.hadoop.hdfs.server.namenode.FSNamesystem; <add>import org.apache.hadoop.hdfs.server.namenode.INode; <ide> <ide> /** <ide> * Manages datanode decommissioning. A background monitor thread <ide> @Override <ide> public Object performTask() throws IOException { <ide> List<BlockInfoContiguous> blocksToProcess = new ArrayList<>(); <add> //it is ok to work with ids and blocksPerInodes here, even if they come from another transaction <add> //because in processBlocksForDecomInternal we check that these blocks actually still exist. <ide> for(Long inodeIds: ids){ <ide> blocksToProcess.addAll(blocksPerInodes.get(inodeIds)); <ide> } <ide> Set<Long> existingInodes = new HashSet<>(); <del> for(INodeIdentifier inode : inodeIdentifiers){ <del> existingInodes.add(inode.getInodeId()); <add> for(INodeIdentifier identifier : inodeIdentifiers){ <add> INode inode = EntityManager.find(INode.Finder.ByINodeIdFTIS, identifier.getInodeId()); <add> if(inode==null){ <add> //The inode does not exist anymore. <add> LOG.debug("inode " + identifier.getInodeId() + " does not exist anymore"); <add> continue; <add> } <add> existingInodes.add(inode.getId()); <ide> } <ide> processBlocksForDecomInternal(datanode, blocksToProcess.iterator(), null, true, existingInodes, toRemove, <ide> underReplicatedBlocks, underReplicatedInOpenFiles, decommissionOnlyReplicas); <ide> List<BlockInfoContiguous> toCheck = new ArrayList<>(); <ide> Set<Long> existingInodes = new HashSet<>(); <ide> for (INodeIdentifier identifier : inodeIdentifiers) { <del> existingInodes.add(identifier.getInodeId()); <del> for (long blockId : inodeIdsToBlockMap.get(identifier.getInodeId())) { <add> INode inode = EntityManager.find(INode.Finder.ByINodeIdFTIS, identifier.getInodeId()); <add> if(inode==null){ <add> //The inode does not exist anymore. <add> LOG.debug("inode " + identifier.getInodeId() + " does not exist anymore"); <add> continue; <add> } <add> existingInodes.add(inode.getId()); <add> //it is ok if we skip blocks that do not exist anymore here because we never use the <add> //toRemove queue. <add> for (long blockId : inodeIdsToBlockMap.get(inode.getId())) { <ide> BlockInfoContiguous block = EntityManager. <ide> find(BlockInfoContiguous.Finder.ByBlockIdAndINodeId, blockId); <ide> toCheck.add(block);
Java
apache-2.0
1eb47c176f41a694708cfd6755d3770f3ae3c8a4
0
LukasKnuth/connectbot-xoom,LukasKnuth/connectbot-xoom,LukasKnuth/connectbot-xoom
/* * ConnectBot: simple, powerful, open-source SSH client for Android * Copyright 2007 Kenny Root, Jeffrey Sharkey * * 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.connectbot.service; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.connectbot.R; import org.connectbot.TerminalView; import org.connectbot.bean.HostBean; import org.connectbot.bean.PortForwardBean; import org.connectbot.bean.SelectionArea; import org.connectbot.transport.AbsTransport; import org.connectbot.transport.TransportFactory; import org.connectbot.util.HostDatabase; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.FontMetrics; import android.graphics.Typeface; import android.text.ClipboardManager; import android.util.Log; import de.mud.terminal.VDUBuffer; import de.mud.terminal.VDUDisplay; import de.mud.terminal.vt320; /** * Provides a bridge between a MUD terminal buffer and a possible TerminalView. * This separation allows us to keep the TerminalBridge running in a background * service. A TerminalView shares down a bitmap that we can use for rendering * when available. * * This class also provides SSH hostkey verification prompting, and password * prompting. */ @SuppressWarnings("deprecation") // for ClipboardManager public class TerminalBridge implements VDUDisplay { public final static String TAG = "ConnectBot.TerminalBridge"; public final static int DEFAULT_FONT_SIZE = 10; private final static int FONT_SIZE_STEP = 2; public Integer[] color; public int defaultFg = HostDatabase.DEFAULT_FG_COLOR; public int defaultBg = HostDatabase.DEFAULT_BG_COLOR; protected final TerminalManager manager; public HostBean host; /* package */ AbsTransport transport; final Paint defaultPaint; private Relay relay; private final String emulation; private final int scrollback; public Bitmap bitmap = null; public VDUBuffer buffer = null; private TerminalView parent = null; private final Canvas canvas = new Canvas(); private boolean disconnected = false; private boolean awaitingClose = false; private boolean forcedSize = false; private int columns; private int rows; /* package */ final TerminalKeyListener keyListener; private boolean selectingForCopy = false; private final SelectionArea selectionArea; // TODO add support for the new clipboard API private ClipboardManager clipboard; public int charWidth = -1; public int charHeight = -1; private int charTop = -1; private float fontSize = -1; private final List<FontSizeChangedListener> fontSizeChangedListeners; private final List<String> localOutput; /** * Flag indicating if we should perform a full-screen redraw during our next * rendering pass. */ private boolean fullRedraw = false; public PromptHelper promptHelper; protected BridgeDisconnectedListener disconnectListener = null; /** * Create a new terminal bridge suitable for unit testing. */ public TerminalBridge() { buffer = new vt320() { @Override public void write(byte[] b) {} @Override public void write(int b) {} @Override public void sendTelnetCommand(byte cmd) {} @Override public void setWindowSize(int c, int r) {} @Override public void debug(String s) {} }; emulation = null; manager = null; defaultPaint = new Paint(); selectionArea = new SelectionArea(); scrollback = 1; localOutput = new LinkedList<String>(); fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>(); transport = null; keyListener = new TerminalKeyListener(manager, this, buffer, null); } /** * Create new terminal bridge with following parameters. We will immediately * launch thread to start SSH connection and handle any hostkey verification * and password authentication. */ public TerminalBridge(final TerminalManager manager, final HostBean host) throws IOException { this.manager = manager; this.host = host; emulation = manager.getEmulation(); scrollback = manager.getScrollback(); // create prompt helper to relay password and hostkey requests up to gui promptHelper = new PromptHelper(this); // create our default paint defaultPaint = new Paint(); defaultPaint.setAntiAlias(true); defaultPaint.setTypeface(Typeface.MONOSPACE); defaultPaint.setFakeBoldText(true); // more readable? localOutput = new LinkedList<String>(); fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>(); int hostFontSize = host.getFontSize(); if (hostFontSize <= 0) hostFontSize = DEFAULT_FONT_SIZE; setFontSize(hostFontSize); // create terminal buffer and handle outgoing data // this is probably status reply information buffer = new vt320() { @Override public void debug(String s) { Log.d(TAG, s); } @Override public void write(byte[] b) { try { if (b != null && transport != null) transport.write(b); } catch (IOException e) { Log.e(TAG, "Problem writing outgoing data in vt320() thread", e); } } @Override public void write(int b) { try { if (transport != null) transport.write(b); } catch (IOException e) { Log.e(TAG, "Problem writing outgoing data in vt320() thread", e); } } // We don't use telnet sequences. @Override public void sendTelnetCommand(byte cmd) { } // We don't want remote to resize our window. @Override public void setWindowSize(int c, int r) { } @Override public void beep() { if (parent.isShown()) manager.playBeep(); else manager.sendActivityNotification(host); } }; // Don't keep any scrollback if a session is not being opened. if (host.getWantSession()) buffer.setBufferSize(scrollback); else buffer.setBufferSize(0); resetColors(); buffer.setDisplay(this); selectionArea = new SelectionArea(); keyListener = new TerminalKeyListener(manager, this, buffer, host.getEncoding()); } public PromptHelper getPromptHelper() { return promptHelper; } /** * Spawn thread to open connection and start login process. */ protected void startConnection() { transport = TransportFactory.getTransport(host.getProtocol()); transport.setBridge(this); transport.setManager(manager); transport.setHost(host); // TODO make this more abstract so we don't litter on AbsTransport transport.setCompression(host.getCompression()); transport.setUseAuthAgent(host.getUseAuthAgent()); transport.setEmulation(emulation); if (transport.canForwardPorts()) { for (PortForwardBean portForward : manager.hostdb.getPortForwardsForHost(host)) transport.addPortForward(portForward); } outputLine(manager.res.getString(R.string.terminal_connecting, host.getHostname(), host.getPort(), host.getProtocol())); Thread connectionThread = new Thread(new Runnable() { public void run() { transport.connect(); } }); connectionThread.setName("Connection"); connectionThread.setDaemon(true); connectionThread.start(); } /** * Handle challenges from keyboard-interactive authentication mode. */ public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) { String[] responses = new String[numPrompts]; for(int i = 0; i < numPrompts; i++) { // request response from user for each prompt responses[i] = promptHelper.requestStringPrompt(instruction, prompt[i]); } return responses; } /** * @return charset in use by bridge */ public Charset getCharset() { return relay.getCharset(); } /** * Sets the encoding used by the terminal. If the connection is live, * then the character set is changed for the next read. * @param encoding the canonical name of the character encoding */ public void setCharset(String encoding) { if (relay != null) relay.setCharset(encoding); keyListener.setCharset(encoding); } /** * Convenience method for writing a line into the underlying MUD buffer. * Should never be called once the session is established. */ public final void outputLine(String line) { if (transport != null && transport.isSessionOpen()) Log.e(TAG, "Session established, cannot use outputLine!", new IOException("outputLine call traceback")); synchronized (localOutput) { final String s = line + "\r\n"; localOutput.add(s); ((vt320) buffer).putString(s); // For accessibility final char[] charArray = s.toCharArray(); propagateConsoleText(charArray, charArray.length); } } /** * Inject a specific string into this terminal. Used for post-login strings * and pasting clipboard. */ public void injectString(final String string) { if (string == null || string.length() == 0) return; Thread injectStringThread = new Thread(new Runnable() { public void run() { try { transport.write(string.getBytes(host.getEncoding())); } catch (Exception e) { Log.e(TAG, "Couldn't inject string to remote host: ", e); } } }); injectStringThread.setName("InjectString"); injectStringThread.start(); } /** * Internal method to request actual PTY terminal once we've finished * authentication. If called before authenticated, it will just fail. */ public void onConnected() { disconnected = false; ((vt320) buffer).reset(); // We no longer need our local output. localOutput.clear(); // previously tried vt100 and xterm for emulation modes // "screen" works the best for color and escape codes ((vt320) buffer).setAnswerBack(emulation); if (HostDatabase.DELKEY_BACKSPACE.equals(host.getDelKey())) ((vt320) buffer).setBackspace(vt320.DELETE_IS_BACKSPACE); else ((vt320) buffer).setBackspace(vt320.DELETE_IS_DEL); // create thread to relay incoming connection data to buffer relay = new Relay(this, transport, (vt320) buffer, host.getEncoding()); Thread relayThread = new Thread(relay); relayThread.setDaemon(true); relayThread.setName("Relay"); relayThread.start(); // force font-size to make sure we resizePTY as needed setFontSize(fontSize); // finally send any post-login string, if requested injectString(host.getPostLogin()); } /** * @return whether a session is open or not */ public boolean isSessionOpen() { if (transport != null) return transport.isSessionOpen(); return false; } public void setOnDisconnectedListener(BridgeDisconnectedListener disconnectListener) { this.disconnectListener = disconnectListener; } /** * Force disconnection of this terminal bridge. */ public void dispatchDisconnect(boolean immediate) { // We don't need to do this multiple times. synchronized (this) { if (disconnected && !immediate) return; disconnected = true; } // Cancel any pending prompts. promptHelper.cancelPrompt(); // disconnection request hangs if we havent really connected to a host yet // temporary fix is to just spawn disconnection into a thread Thread disconnectThread = new Thread(new Runnable() { public void run() { if (transport != null && transport.isConnected()) transport.close(); } }); disconnectThread.setName("Disconnect"); disconnectThread.start(); if (immediate) { awaitingClose = true; if (disconnectListener != null) disconnectListener.onDisconnected(TerminalBridge.this); } else { { final String line = manager.res.getString(R.string.alert_disconnect_msg); ((vt320) buffer).putString("\r\n" + line + "\r\n"); } if (host.getStayConnected()) { manager.requestReconnect(this); return; } Thread disconnectPromptThread = new Thread(new Runnable() { public void run() { Boolean result = promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_host_disconnected)); if (result == null || result.booleanValue()) { awaitingClose = true; // Tell the TerminalManager that we can be destroyed now. if (disconnectListener != null) disconnectListener.onDisconnected(TerminalBridge.this); } } }); disconnectPromptThread.setName("DisconnectPrompt"); disconnectPromptThread.setDaemon(true); disconnectPromptThread.start(); } } public void setSelectingForCopy(boolean selectingForCopy) { this.selectingForCopy = selectingForCopy; } public boolean isSelectingForCopy() { return selectingForCopy; } public SelectionArea getSelectionArea() { return selectionArea; } public synchronized void tryKeyVibrate() { manager.tryKeyVibrate(); } /** * Request a different font size. Will make call to parentChanged() to make * sure we resize PTY if needed. */ /* package */ final void setFontSize(float size) { if (size <= 0.0) return; defaultPaint.setTextSize(size); fontSize = size; // read new metrics to get exact pixel dimensions FontMetrics fm = defaultPaint.getFontMetrics(); charTop = (int)Math.ceil(fm.top); float[] widths = new float[1]; defaultPaint.getTextWidths("X", widths); charWidth = (int)Math.ceil(widths[0]); charHeight = (int)Math.ceil(fm.descent - fm.top); // refresh any bitmap with new font size if(parent != null) parentChanged(parent); for (FontSizeChangedListener ofscl : fontSizeChangedListeners) ofscl.onFontSizeChanged(size); host.setFontSize((int) fontSize); manager.hostdb.updateFontSize(host); forcedSize = false; } /** * Add an {@link FontSizeChangedListener} to the list of listeners for this * bridge. * * @param listener * listener to add */ public void addFontSizeChangedListener(FontSizeChangedListener listener) { fontSizeChangedListeners.add(listener); } /** * Remove an {@link FontSizeChangedListener} from the list of listeners for * this bridge. * * @param listener */ public void removeFontSizeChangedListener(FontSizeChangedListener listener) { fontSizeChangedListeners.remove(listener); } /** * Something changed in our parent {@link TerminalView}, maybe it's a new * parent, or maybe it's an updated font size. We should recalculate * terminal size information and request a PTY resize. */ public final synchronized void parentChanged(TerminalView parent) { if (manager != null && !manager.isResizeAllowed()) { Log.d(TAG, "Resize is not allowed now"); return; } this.parent = parent; final int width = parent.getWidth(); final int height = parent.getHeight(); // Something has gone wrong with our layout; we're 0 width or height! if (width <= 0 || height <= 0) return; clipboard = (ClipboardManager) parent.getContext().getSystemService(Context.CLIPBOARD_SERVICE); keyListener.setClipboardManager(clipboard); if (!forcedSize) { // recalculate buffer size int newColumns, newRows; newColumns = width / charWidth; newRows = height / charHeight; // If nothing has changed in the terminal dimensions and not an intial // draw then don't blow away scroll regions and such. if (newColumns == columns && newRows == rows) return; columns = newColumns; rows = newRows; } // reallocate new bitmap if needed boolean newBitmap = (bitmap == null); if(bitmap != null) newBitmap = (bitmap.getWidth() != width || bitmap.getHeight() != height); if (newBitmap) { discardBitmap(); bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); canvas.setBitmap(bitmap); } // clear out any old buffer information defaultPaint.setColor(Color.BLACK); canvas.drawPaint(defaultPaint); // Stroke the border of the terminal if the size is being forced; if (forcedSize) { int borderX = (columns * charWidth) + 1; int borderY = (rows * charHeight) + 1; defaultPaint.setColor(Color.GRAY); defaultPaint.setStrokeWidth(0.0f); if (width >= borderX) canvas.drawLine(borderX, 0, borderX, borderY + 1, defaultPaint); if (height >= borderY) canvas.drawLine(0, borderY, borderX + 1, borderY, defaultPaint); } try { // request a terminal pty resize synchronized (buffer) { buffer.setScreenSize(columns, rows, true); } if(transport != null) { new Thread(new Runnable() { public void run() { try { transport.setDimensions(columns, rows, width, height); } catch (Exception e) { e.printStackTrace(); } } }).start(); } } catch(Exception e) { Log.e(TAG, "Problem while trying to resize screen or PTY", e); } // redraw local output if we don't have a sesson to receive our resize request if (transport == null) { synchronized (localOutput) { ((vt320) buffer).reset(); for (String line : localOutput) ((vt320) buffer).putString(line); } } // force full redraw with new buffer size fullRedraw = true; redraw(); parent.notifyUser(String.format("%d x %d", columns, rows)); Log.i(TAG, String.format("parentChanged() now width=%d, height=%d", columns, rows)); } /** * Somehow our parent {@link TerminalView} was destroyed. Now we don't need * to redraw anywhere, and we can recycle our internal bitmap. */ public synchronized void parentDestroyed() { parent = null; discardBitmap(); } private void discardBitmap() { if (bitmap != null) bitmap.recycle(); bitmap = null; } public void setVDUBuffer(VDUBuffer buffer) { this.buffer = buffer; } public VDUBuffer getVDUBuffer() { return buffer; } public void propagateConsoleText(char[] rawText, int length) { if (parent != null) { parent.propagateConsoleText(rawText, length); } } public void onDraw() { int fg, bg; synchronized (buffer) { boolean entireDirty = buffer.update[0] || fullRedraw; boolean isWideCharacter = false; // walk through all lines in the buffer for(int l = 0; l < buffer.height; l++) { // check if this line is dirty and needs to be repainted // also check for entire-buffer dirty flags if (!entireDirty && !buffer.update[l + 1]) continue; // reset dirty flag for this line buffer.update[l + 1] = false; // walk through all characters in this line for (int c = 0; c < buffer.width; c++) { int addr = 0; int currAttr = buffer.charAttributes[buffer.windowBase + l][c]; { int fgcolor = defaultFg; // check if foreground color attribute is set if ((currAttr & VDUBuffer.COLOR_FG) != 0) fgcolor = ((currAttr & VDUBuffer.COLOR_FG) >> VDUBuffer.COLOR_FG_SHIFT) - 1; if (fgcolor < 8 && (currAttr & VDUBuffer.BOLD) != 0) fg = color[fgcolor + 8]; else fg = color[fgcolor]; } // check if background color attribute is set if ((currAttr & VDUBuffer.COLOR_BG) != 0) bg = color[((currAttr & VDUBuffer.COLOR_BG) >> VDUBuffer.COLOR_BG_SHIFT) - 1]; else bg = color[defaultBg]; // support character inversion by swapping background and foreground color if ((currAttr & VDUBuffer.INVERT) != 0) { int swapc = bg; bg = fg; fg = swapc; } // set underlined attributes if requested defaultPaint.setUnderlineText((currAttr & VDUBuffer.UNDERLINE) != 0); isWideCharacter = (currAttr & VDUBuffer.FULLWIDTH) != 0; if (isWideCharacter) addr++; else { // determine the amount of continuous characters with the same settings and print them all at once while(c + addr < buffer.width && buffer.charAttributes[buffer.windowBase + l][c + addr] == currAttr) { addr++; } } // Save the current clip region canvas.save(Canvas.CLIP_SAVE_FLAG); // clear this dirty area with background color defaultPaint.setColor(bg); if (isWideCharacter) { canvas.clipRect(c * charWidth, l * charHeight, (c + 2) * charWidth, (l + 1) * charHeight); } else { canvas.clipRect(c * charWidth, l * charHeight, (c + addr) * charWidth, (l + 1) * charHeight); } canvas.drawPaint(defaultPaint); // write the text string starting at 'c' for 'addr' number of characters defaultPaint.setColor(fg); if((currAttr & VDUBuffer.INVISIBLE) == 0) canvas.drawText(buffer.charArray[buffer.windowBase + l], c, addr, c * charWidth, (l * charHeight) - charTop, defaultPaint); // Restore the previous clip region canvas.restore(); // advance to the next text block with different characteristics c += addr - 1; if (isWideCharacter) c++; } } // reset entire-buffer flags buffer.update[0] = false; } fullRedraw = false; } public void redraw() { if (parent != null) parent.postInvalidate(); } // We don't have a scroll bar. public void updateScrollBar() { } /** * Resize terminal to fit [rows]x[cols] in screen of size [width]x[height] * @param rows * @param cols * @param width * @param height */ public synchronized void resizeComputed(int cols, int rows, int width, int height) { float size = 8.0f; float step = 8.0f; float limit = 0.125f; int direction; while ((direction = fontSizeCompare(size, cols, rows, width, height)) < 0) size += step; if (direction == 0) { Log.d("fontsize", String.format("Found match at %f", size)); return; } step /= 2.0f; size -= step; while ((direction = fontSizeCompare(size, cols, rows, width, height)) != 0 && step >= limit) { step /= 2.0f; if (direction > 0) { size -= step; } else { size += step; } } if (direction > 0) size -= step; this.columns = cols; this.rows = rows; setFontSize(size); forcedSize = true; } private int fontSizeCompare(float size, int cols, int rows, int width, int height) { // read new metrics to get exact pixel dimensions defaultPaint.setTextSize(size); FontMetrics fm = defaultPaint.getFontMetrics(); float[] widths = new float[1]; defaultPaint.getTextWidths("X", widths); int termWidth = (int)widths[0] * cols; int termHeight = (int)Math.ceil(fm.descent - fm.top) * rows; Log.d("fontsize", String.format("font size %f resulted in %d x %d", size, termWidth, termHeight)); // Check to see if it fits in resolution specified. if (termWidth > width || termHeight > height) return 1; if (termWidth == width || termHeight == height) return 0; return -1; } /** * @return whether underlying transport can forward ports */ public boolean canFowardPorts() { return transport.canForwardPorts(); } /** * Adds the {@link PortForwardBean} to the list. * @param portForward the port forward bean to add * @return true on successful addition */ public boolean addPortForward(PortForwardBean portForward) { return transport.addPortForward(portForward); } /** * Removes the {@link PortForwardBean} from the list. * @param portForward the port forward bean to remove * @return true on successful removal */ public boolean removePortForward(PortForwardBean portForward) { return transport.removePortForward(portForward); } /** * @return the list of port forwards */ public List<PortForwardBean> getPortForwards() { return transport.getPortForwards(); } /** * Enables a port forward member. After calling this method, the port forward should * be operational. * @param portForward member of our current port forwards list to enable * @return true on successful port forward setup */ public boolean enablePortForward(PortForwardBean portForward) { if (!transport.isConnected()) { Log.i(TAG, "Attempt to enable port forward while not connected"); return false; } return transport.enablePortForward(portForward); } /** * Disables a port forward member. After calling this method, the port forward should * be non-functioning. * @param portForward member of our current port forwards list to enable * @return true on successful port forward tear-down */ public boolean disablePortForward(PortForwardBean portForward) { if (!transport.isConnected()) { Log.i(TAG, "Attempt to disable port forward while not connected"); return false; } return transport.disablePortForward(portForward); } /** * @return whether the TerminalBridge should close */ public boolean isAwaitingClose() { return awaitingClose; } /** * @return whether this connection had started and subsequently disconnected */ public boolean isDisconnected() { return disconnected; } /* (non-Javadoc) * @see de.mud.terminal.VDUDisplay#setColor(byte, byte, byte, byte) */ public void setColor(int index, int red, int green, int blue) { // Don't allow the system colors to be overwritten for now. May violate specs. if (index < color.length && index >= 16) color[index] = 0xff000000 | red << 16 | green << 8 | blue; } public final void resetColors() { int[] defaults = manager.hostdb.getDefaultColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME); defaultFg = defaults[0]; defaultBg = defaults[1]; color = manager.hostdb.getColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME); } // based on http://www.ietf.org/rfc/rfc2396.txt private static final String URL_SCHEME = "[A-Za-z][-+.0-9A-Za-z]*"; private static final String URL_UNRESERVED = "[-._~0-9A-Za-z]"; private static final String URL_PCT_ENCODED = "%[0-9A-Fa-f]{2}"; private static final String URL_SUB_DELIMS = "[!$&'()*+,;:=]"; private static final String URL_USERINFO = "(?:" + URL_UNRESERVED + "|" + URL_PCT_ENCODED + "|" + URL_SUB_DELIMS + "|:)*"; private static final String URL_H16 = "[0-9A-Fa-f]{1,4}"; private static final String URL_DEC_OCTET = "(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; private static final String URL_IPV4_ADDRESS = URL_DEC_OCTET + "\\." + URL_DEC_OCTET + "\\." + URL_DEC_OCTET + "\\." + URL_DEC_OCTET; private static final String URL_LS32 = "(?:" + URL_H16 + ":" + URL_H16 + "|" + URL_IPV4_ADDRESS + ")"; private static final String URL_IPV6_ADDRESS = "(?:(?:" + URL_H16 + "){6}" + URL_LS32 + ")"; private static final String URL_IPV_FUTURE = "v[0-9A-Fa-f]+.(?:" + URL_UNRESERVED + "|" + URL_SUB_DELIMS + "|:)+"; private static final String URL_IP_LITERAL = "\\[(?:" + URL_IPV6_ADDRESS + "|" + URL_IPV_FUTURE + ")\\]"; private static final String URL_REG_NAME = "(?:" + URL_UNRESERVED + "|" + URL_PCT_ENCODED + "|" + URL_SUB_DELIMS + ")*"; private static final String URL_HOST = "(?:" + URL_IP_LITERAL + "|" + URL_IPV4_ADDRESS + "|" + URL_REG_NAME + ")"; private static final String URL_PORT = "[0-9]*"; private static final String URL_AUTHORITY = "(?:" + URL_USERINFO + "@)?" + URL_HOST + "(?::" + URL_PORT + ")?"; private static final String URL_PCHAR = "(?:" + URL_UNRESERVED + "|" + URL_PCT_ENCODED + "|" + URL_SUB_DELIMS + "|@)"; private static final String URL_SEGMENT = URL_PCHAR + "*"; private static final String URL_PATH_ABEMPTY = "(?:/" + URL_SEGMENT + ")*"; private static final String URL_SEGMENT_NZ = URL_PCHAR + "+"; private static final String URL_PATH_ABSOLUTE = "/(?:" + URL_SEGMENT_NZ + "(?:/" + URL_SEGMENT + ")*)?"; private static final String URL_PATH_ROOTLESS = URL_SEGMENT_NZ + "(?:/" + URL_SEGMENT + ")*"; private static final String URL_HIER_PART = "(?://" + URL_AUTHORITY + URL_PATH_ABEMPTY + "|" + URL_PATH_ABSOLUTE + "|" + URL_PATH_ROOTLESS + ")"; private static final String URL_QUERY = "(?:" + URL_PCHAR + "|/|\\?)*"; private static final String URL_FRAGMENT = "(?:" + URL_PCHAR + "|/|\\?)*"; private static final String URI_REGEX = URL_SCHEME + ":" + URL_HIER_PART + "(?:" + URL_QUERY + ")?(?:#" + URL_FRAGMENT + ")?"; private static final Pattern URL_PATTERN = Pattern.compile(URI_REGEX); /** * @return */ public List<String> scanForURLs() { final List<String> urls = new ArrayList<String>(); final char[] visibleBuffer = new char[buffer.height * buffer.width]; for (int l = 0; l < buffer.height; l++) System.arraycopy(buffer.charArray[buffer.windowBase + l], 0, visibleBuffer, l * buffer.width, buffer.width); final Matcher urlMatcher = URL_PATTERN.matcher(new String(visibleBuffer)); while (urlMatcher.find()) urls.add(urlMatcher.group()); return urls; } /** * @return */ public boolean isUsingNetwork() { return transport.usesNetwork(); } /** * @return */ public TerminalKeyListener getKeyHandler() { return keyListener; } /** * */ public void resetScrollPosition() { // if we're in scrollback, scroll to bottom of window on input if (buffer.windowBase != buffer.screenBase) buffer.setWindowBase(buffer.screenBase); } /** * */ public void increaseFontSize() { setFontSize(fontSize + FONT_SIZE_STEP); } /** * */ public void decreaseFontSize() { setFontSize(fontSize - FONT_SIZE_STEP); } }
src/org/connectbot/service/TerminalBridge.java
/* * ConnectBot: simple, powerful, open-source SSH client for Android * Copyright 2007 Kenny Root, Jeffrey Sharkey * * 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.connectbot.service; import java.io.IOException; import java.nio.charset.Charset; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.connectbot.R; import org.connectbot.TerminalView; import org.connectbot.bean.HostBean; import org.connectbot.bean.PortForwardBean; import org.connectbot.bean.SelectionArea; import org.connectbot.transport.AbsTransport; import org.connectbot.transport.TransportFactory; import org.connectbot.util.HostDatabase; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.FontMetrics; import android.graphics.Typeface; import android.text.ClipboardManager; import android.util.Log; import de.mud.terminal.VDUBuffer; import de.mud.terminal.VDUDisplay; import de.mud.terminal.vt320; /** * Provides a bridge between a MUD terminal buffer and a possible TerminalView. * This separation allows us to keep the TerminalBridge running in a background * service. A TerminalView shares down a bitmap that we can use for rendering * when available. * * This class also provides SSH hostkey verification prompting, and password * prompting. */ @SuppressWarnings("deprecation") // for ClipboardManager public class TerminalBridge implements VDUDisplay { public final static String TAG = "ConnectBot.TerminalBridge"; public final static int DEFAULT_FONT_SIZE = 10; private final static int FONT_SIZE_STEP = 2; public Integer[] color; public int defaultFg = HostDatabase.DEFAULT_FG_COLOR; public int defaultBg = HostDatabase.DEFAULT_BG_COLOR; protected final TerminalManager manager; public HostBean host; /* package */ AbsTransport transport; final Paint defaultPaint; private Relay relay; private final String emulation; private final int scrollback; public Bitmap bitmap = null; public VDUBuffer buffer = null; private TerminalView parent = null; private final Canvas canvas = new Canvas(); private boolean disconnected = false; private boolean awaitingClose = false; private boolean forcedSize = false; private int columns; private int rows; /* package */ final TerminalKeyListener keyListener; private boolean selectingForCopy = false; private final SelectionArea selectionArea; // TODO add support for the new clipboard API private ClipboardManager clipboard; public int charWidth = -1; public int charHeight = -1; private int charTop = -1; private float fontSize = -1; private final List<FontSizeChangedListener> fontSizeChangedListeners; private final List<String> localOutput; /** * Flag indicating if we should perform a full-screen redraw during our next * rendering pass. */ private boolean fullRedraw = false; public PromptHelper promptHelper; protected BridgeDisconnectedListener disconnectListener = null; /** * Create a new terminal bridge suitable for unit testing. */ public TerminalBridge() { buffer = new vt320() { @Override public void write(byte[] b) {} @Override public void write(int b) {} @Override public void sendTelnetCommand(byte cmd) {} @Override public void setWindowSize(int c, int r) {} @Override public void debug(String s) {} }; emulation = null; manager = null; defaultPaint = new Paint(); selectionArea = new SelectionArea(); scrollback = 1; localOutput = new LinkedList<String>(); fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>(); transport = null; keyListener = new TerminalKeyListener(manager, this, buffer, null); } /** * Create new terminal bridge with following parameters. We will immediately * launch thread to start SSH connection and handle any hostkey verification * and password authentication. */ public TerminalBridge(final TerminalManager manager, final HostBean host) throws IOException { this.manager = manager; this.host = host; emulation = manager.getEmulation(); scrollback = manager.getScrollback(); // create prompt helper to relay password and hostkey requests up to gui promptHelper = new PromptHelper(this); // create our default paint defaultPaint = new Paint(); defaultPaint.setAntiAlias(true); defaultPaint.setTypeface(Typeface.MONOSPACE); defaultPaint.setFakeBoldText(true); // more readable? localOutput = new LinkedList<String>(); fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>(); int hostFontSize = host.getFontSize(); if (hostFontSize <= 0) hostFontSize = DEFAULT_FONT_SIZE; setFontSize(hostFontSize); // create terminal buffer and handle outgoing data // this is probably status reply information buffer = new vt320() { @Override public void debug(String s) { Log.d(TAG, s); } @Override public void write(byte[] b) { try { if (b != null && transport != null) transport.write(b); } catch (IOException e) { Log.e(TAG, "Problem writing outgoing data in vt320() thread", e); } } @Override public void write(int b) { try { if (transport != null) transport.write(b); } catch (IOException e) { Log.e(TAG, "Problem writing outgoing data in vt320() thread", e); } } // We don't use telnet sequences. @Override public void sendTelnetCommand(byte cmd) { } // We don't want remote to resize our window. @Override public void setWindowSize(int c, int r) { } @Override public void beep() { if (parent.isShown()) manager.playBeep(); else manager.sendActivityNotification(host); } }; // Don't keep any scrollback if a session is not being opened. if (host.getWantSession()) buffer.setBufferSize(scrollback); else buffer.setBufferSize(0); resetColors(); buffer.setDisplay(this); selectionArea = new SelectionArea(); keyListener = new TerminalKeyListener(manager, this, buffer, host.getEncoding()); } public PromptHelper getPromptHelper() { return promptHelper; } /** * Spawn thread to open connection and start login process. */ protected void startConnection() { transport = TransportFactory.getTransport(host.getProtocol()); transport.setBridge(this); transport.setManager(manager); transport.setHost(host); // TODO make this more abstract so we don't litter on AbsTransport transport.setCompression(host.getCompression()); transport.setUseAuthAgent(host.getUseAuthAgent()); transport.setEmulation(emulation); if (transport.canForwardPorts()) { for (PortForwardBean portForward : manager.hostdb.getPortForwardsForHost(host)) transport.addPortForward(portForward); } outputLine(manager.res.getString(R.string.terminal_connecting, host.getHostname(), host.getPort(), host.getProtocol())); Thread connectionThread = new Thread(new Runnable() { public void run() { transport.connect(); } }); connectionThread.setName("Connection"); connectionThread.setDaemon(true); connectionThread.start(); } /** * Handle challenges from keyboard-interactive authentication mode. */ public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) { String[] responses = new String[numPrompts]; for(int i = 0; i < numPrompts; i++) { // request response from user for each prompt responses[i] = promptHelper.requestStringPrompt(instruction, prompt[i]); } return responses; } /** * @return charset in use by bridge */ public Charset getCharset() { return relay.getCharset(); } /** * Sets the encoding used by the terminal. If the connection is live, * then the character set is changed for the next read. * @param encoding the canonical name of the character encoding */ public void setCharset(String encoding) { if (relay != null) relay.setCharset(encoding); keyListener.setCharset(encoding); } /** * Convenience method for writing a line into the underlying MUD buffer. * Should never be called once the session is established. */ public final void outputLine(String line) { if (transport != null && transport.isSessionOpen()) Log.e(TAG, "Session established, cannot use outputLine!", new IOException("outputLine call traceback")); synchronized (localOutput) { final String s = line + "\r\n"; localOutput.add(s); ((vt320) buffer).putString(s); // For accessibility final char[] charArray = s.toCharArray(); propagateConsoleText(charArray, charArray.length); } } /** * Inject a specific string into this terminal. Used for post-login strings * and pasting clipboard. */ public void injectString(final String string) { if (string == null || string.length() == 0) return; Thread injectStringThread = new Thread(new Runnable() { public void run() { try { transport.write(string.getBytes(host.getEncoding())); } catch (Exception e) { Log.e(TAG, "Couldn't inject string to remote host: ", e); } } }); injectStringThread.setName("InjectString"); injectStringThread.start(); } /** * Internal method to request actual PTY terminal once we've finished * authentication. If called before authenticated, it will just fail. */ public void onConnected() { disconnected = false; ((vt320) buffer).reset(); // We no longer need our local output. localOutput.clear(); // previously tried vt100 and xterm for emulation modes // "screen" works the best for color and escape codes ((vt320) buffer).setAnswerBack(emulation); if (HostDatabase.DELKEY_BACKSPACE.equals(host.getDelKey())) ((vt320) buffer).setBackspace(vt320.DELETE_IS_BACKSPACE); else ((vt320) buffer).setBackspace(vt320.DELETE_IS_DEL); // create thread to relay incoming connection data to buffer relay = new Relay(this, transport, (vt320) buffer, host.getEncoding()); Thread relayThread = new Thread(relay); relayThread.setDaemon(true); relayThread.setName("Relay"); relayThread.start(); // force font-size to make sure we resizePTY as needed setFontSize(fontSize); // finally send any post-login string, if requested injectString(host.getPostLogin()); } /** * @return whether a session is open or not */ public boolean isSessionOpen() { if (transport != null) return transport.isSessionOpen(); return false; } public void setOnDisconnectedListener(BridgeDisconnectedListener disconnectListener) { this.disconnectListener = disconnectListener; } /** * Force disconnection of this terminal bridge. */ public void dispatchDisconnect(boolean immediate) { // We don't need to do this multiple times. synchronized (this) { if (disconnected && !immediate) return; disconnected = true; } // Cancel any pending prompts. promptHelper.cancelPrompt(); // disconnection request hangs if we havent really connected to a host yet // temporary fix is to just spawn disconnection into a thread Thread disconnectThread = new Thread(new Runnable() { public void run() { if (transport != null && transport.isConnected()) transport.close(); } }); disconnectThread.setName("Disconnect"); disconnectThread.start(); if (immediate) { awaitingClose = true; if (disconnectListener != null) disconnectListener.onDisconnected(TerminalBridge.this); } else { { final String line = manager.res.getString(R.string.alert_disconnect_msg); ((vt320) buffer).putString("\r\n" + line + "\r\n"); } if (host.getStayConnected()) { manager.requestReconnect(this); return; } Thread disconnectPromptThread = new Thread(new Runnable() { public void run() { Boolean result = promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_host_disconnected)); if (result == null || result.booleanValue()) { awaitingClose = true; // Tell the TerminalManager that we can be destroyed now. if (disconnectListener != null) disconnectListener.onDisconnected(TerminalBridge.this); } } }); disconnectPromptThread.setName("DisconnectPrompt"); disconnectPromptThread.setDaemon(true); disconnectPromptThread.start(); } } public void setSelectingForCopy(boolean selectingForCopy) { this.selectingForCopy = selectingForCopy; } public boolean isSelectingForCopy() { return selectingForCopy; } public SelectionArea getSelectionArea() { return selectionArea; } public synchronized void tryKeyVibrate() { manager.tryKeyVibrate(); } /** * Request a different font size. Will make call to parentChanged() to make * sure we resize PTY if needed. */ /* package */ final void setFontSize(float size) { if (size <= 0.0) return; defaultPaint.setTextSize(size); fontSize = size; // read new metrics to get exact pixel dimensions FontMetrics fm = defaultPaint.getFontMetrics(); charTop = (int)Math.ceil(fm.top); float[] widths = new float[1]; defaultPaint.getTextWidths("X", widths); charWidth = (int)Math.ceil(widths[0]); charHeight = (int)Math.ceil(fm.descent - fm.top); // refresh any bitmap with new font size if(parent != null) parentChanged(parent); for (FontSizeChangedListener ofscl : fontSizeChangedListeners) ofscl.onFontSizeChanged(size); host.setFontSize((int) fontSize); manager.hostdb.updateFontSize(host); forcedSize = false; } /** * Add an {@link FontSizeChangedListener} to the list of listeners for this * bridge. * * @param listener * listener to add */ public void addFontSizeChangedListener(FontSizeChangedListener listener) { fontSizeChangedListeners.add(listener); } /** * Remove an {@link FontSizeChangedListener} from the list of listeners for * this bridge. * * @param listener */ public void removeFontSizeChangedListener(FontSizeChangedListener listener) { fontSizeChangedListeners.remove(listener); } /** * Something changed in our parent {@link TerminalView}, maybe it's a new * parent, or maybe it's an updated font size. We should recalculate * terminal size information and request a PTY resize. */ public final synchronized void parentChanged(TerminalView parent) { if (manager != null && !manager.isResizeAllowed()) { Log.d(TAG, "Resize is not allowed now"); return; } this.parent = parent; final int width = parent.getWidth(); final int height = parent.getHeight(); // Something has gone wrong with our layout; we're 0 width or height! if (width <= 0 || height <= 0) return; clipboard = (ClipboardManager) parent.getContext().getSystemService(Context.CLIPBOARD_SERVICE); keyListener.setClipboardManager(clipboard); if (!forcedSize) { // recalculate buffer size int newColumns, newRows; newColumns = width / charWidth; newRows = height / charHeight; // If nothing has changed in the terminal dimensions and not an intial // draw then don't blow away scroll regions and such. if (newColumns == columns && newRows == rows) return; columns = newColumns; rows = newRows; } // reallocate new bitmap if needed boolean newBitmap = (bitmap == null); if(bitmap != null) newBitmap = (bitmap.getWidth() != width || bitmap.getHeight() != height); if (newBitmap) { discardBitmap(); bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); canvas.setBitmap(bitmap); } // clear out any old buffer information defaultPaint.setColor(Color.BLACK); canvas.drawPaint(defaultPaint); // Stroke the border of the terminal if the size is being forced; if (forcedSize) { int borderX = (columns * charWidth) + 1; int borderY = (rows * charHeight) + 1; defaultPaint.setColor(Color.GRAY); defaultPaint.setStrokeWidth(0.0f); if (width >= borderX) canvas.drawLine(borderX, 0, borderX, borderY + 1, defaultPaint); if (height >= borderY) canvas.drawLine(0, borderY, borderX + 1, borderY, defaultPaint); } try { // request a terminal pty resize synchronized (buffer) { buffer.setScreenSize(columns, rows, true); } if(transport != null) { new Thread(new Runnable() { public void run() { try { transport.setDimensions(columns, rows, width, height); } catch (Exception e) { e.printStackTrace(); } } }).start(); } } catch(Exception e) { Log.e(TAG, "Problem while trying to resize screen or PTY", e); } // redraw local output if we don't have a sesson to receive our resize request if (transport == null) { synchronized (localOutput) { ((vt320) buffer).reset(); for (String line : localOutput) ((vt320) buffer).putString(line); } } // force full redraw with new buffer size fullRedraw = true; redraw(); parent.notifyUser(String.format("%d x %d", columns, rows)); Log.i(TAG, String.format("parentChanged() now width=%d, height=%d", columns, rows)); } /** * Somehow our parent {@link TerminalView} was destroyed. Now we don't need * to redraw anywhere, and we can recycle our internal bitmap. */ public synchronized void parentDestroyed() { parent = null; discardBitmap(); } private void discardBitmap() { if (bitmap != null) bitmap.recycle(); bitmap = null; } public void setVDUBuffer(VDUBuffer buffer) { this.buffer = buffer; } public VDUBuffer getVDUBuffer() { return buffer; } public void propagateConsoleText(char[] rawText, int length) { if (parent != null) { parent.propagateConsoleText(rawText, length); } } public void onDraw() { int fg, bg; synchronized (buffer) { boolean entireDirty = buffer.update[0] || fullRedraw; boolean isWideCharacter = false; // walk through all lines in the buffer for(int l = 0; l < buffer.height; l++) { // check if this line is dirty and needs to be repainted // also check for entire-buffer dirty flags if (!entireDirty && !buffer.update[l + 1]) continue; // reset dirty flag for this line buffer.update[l + 1] = false; // walk through all characters in this line for (int c = 0; c < buffer.width; c++) { int addr = 0; int currAttr = buffer.charAttributes[buffer.windowBase + l][c]; { int fgcolor = defaultFg; // check if foreground color attribute is set if ((currAttr & VDUBuffer.COLOR_FG) != 0) fgcolor = ((currAttr & VDUBuffer.COLOR_FG) >> VDUBuffer.COLOR_FG_SHIFT) - 1; if (fgcolor < 8 && (currAttr & VDUBuffer.BOLD) != 0) fg = color[fgcolor + 8]; else fg = color[fgcolor]; } // check if background color attribute is set if ((currAttr & VDUBuffer.COLOR_BG) != 0) bg = color[((currAttr & VDUBuffer.COLOR_BG) >> VDUBuffer.COLOR_BG_SHIFT) - 1]; else bg = color[defaultBg]; // support character inversion by swapping background and foreground color if ((currAttr & VDUBuffer.INVERT) != 0) { int swapc = bg; bg = fg; fg = swapc; } // set underlined attributes if requested defaultPaint.setUnderlineText((currAttr & VDUBuffer.UNDERLINE) != 0); isWideCharacter = (currAttr & VDUBuffer.FULLWIDTH) != 0; if (isWideCharacter) addr++; else { // determine the amount of continuous characters with the same settings and print them all at once while(c + addr < buffer.width && buffer.charAttributes[buffer.windowBase + l][c + addr] == currAttr) { addr++; } } // Save the current clip region canvas.save(Canvas.CLIP_SAVE_FLAG); // clear this dirty area with background color defaultPaint.setColor(bg); if (isWideCharacter) { canvas.clipRect(c * charWidth, l * charHeight, (c + 2) * charWidth, (l + 1) * charHeight); } else { canvas.clipRect(c * charWidth, l * charHeight, (c + addr) * charWidth, (l + 1) * charHeight); } canvas.drawPaint(defaultPaint); // write the text string starting at 'c' for 'addr' number of characters defaultPaint.setColor(fg); if((currAttr & VDUBuffer.INVISIBLE) == 0) canvas.drawText(buffer.charArray[buffer.windowBase + l], c, addr, c * charWidth, (l * charHeight) - charTop, defaultPaint); // Restore the previous clip region canvas.restore(); // advance to the next text block with different characteristics c += addr - 1; if (isWideCharacter) c++; } } // reset entire-buffer flags buffer.update[0] = false; } fullRedraw = false; } public void redraw() { if (parent != null) parent.postInvalidate(); } // We don't have a scroll bar. public void updateScrollBar() { } /** * Resize terminal to fit [rows]x[cols] in screen of size [width]x[height] * @param rows * @param cols * @param width * @param height */ public synchronized void resizeComputed(int cols, int rows, int width, int height) { float size = 8.0f; float step = 8.0f; float limit = 0.125f; int direction; while ((direction = fontSizeCompare(size, cols, rows, width, height)) < 0) size += step; if (direction == 0) { Log.d("fontsize", String.format("Found match at %f", size)); return; } step /= 2.0f; size -= step; while ((direction = fontSizeCompare(size, cols, rows, width, height)) != 0 && step >= limit) { step /= 2.0f; if (direction > 0) { size -= step; } else { size += step; } } if (direction > 0) size -= step; this.columns = cols; this.rows = rows; setFontSize(size); forcedSize = true; } private int fontSizeCompare(float size, int cols, int rows, int width, int height) { // read new metrics to get exact pixel dimensions defaultPaint.setTextSize(size); FontMetrics fm = defaultPaint.getFontMetrics(); float[] widths = new float[1]; defaultPaint.getTextWidths("X", widths); int termWidth = (int)widths[0] * cols; int termHeight = (int)Math.ceil(fm.descent - fm.top) * rows; Log.d("fontsize", String.format("font size %f resulted in %d x %d", size, termWidth, termHeight)); // Check to see if it fits in resolution specified. if (termWidth > width || termHeight > height) return 1; if (termWidth == width || termHeight == height) return 0; return -1; } /** * @return whether underlying transport can forward ports */ public boolean canFowardPorts() { return transport.canForwardPorts(); } /** * Adds the {@link PortForwardBean} to the list. * @param portForward the port forward bean to add * @return true on successful addition */ public boolean addPortForward(PortForwardBean portForward) { return transport.addPortForward(portForward); } /** * Removes the {@link PortForwardBean} from the list. * @param portForward the port forward bean to remove * @return true on successful removal */ public boolean removePortForward(PortForwardBean portForward) { return transport.removePortForward(portForward); } /** * @return the list of port forwards */ public List<PortForwardBean> getPortForwards() { return transport.getPortForwards(); } /** * Enables a port forward member. After calling this method, the port forward should * be operational. * @param portForward member of our current port forwards list to enable * @return true on successful port forward setup */ public boolean enablePortForward(PortForwardBean portForward) { if (!transport.isConnected()) { Log.i(TAG, "Attempt to enable port forward while not connected"); return false; } return transport.enablePortForward(portForward); } /** * Disables a port forward member. After calling this method, the port forward should * be non-functioning. * @param portForward member of our current port forwards list to enable * @return true on successful port forward tear-down */ public boolean disablePortForward(PortForwardBean portForward) { if (!transport.isConnected()) { Log.i(TAG, "Attempt to disable port forward while not connected"); return false; } return transport.disablePortForward(portForward); } /** * @return whether the TerminalBridge should close */ public boolean isAwaitingClose() { return awaitingClose; } /** * @return whether this connection had started and subsequently disconnected */ public boolean isDisconnected() { return disconnected; } /* (non-Javadoc) * @see de.mud.terminal.VDUDisplay#setColor(byte, byte, byte, byte) */ public void setColor(int index, int red, int green, int blue) { // Don't allow the system colors to be overwritten for now. May violate specs. if (index < color.length && index >= 16) color[index] = 0xff000000 | red << 16 | green << 8 | blue; } public final void resetColors() { int[] defaults = manager.hostdb.getDefaultColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME); defaultFg = defaults[0]; defaultBg = defaults[1]; color = manager.hostdb.getColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME); } private static Pattern urlPattern = null; /** * @return */ public List<String> scanForURLs() { List<String> urls = new LinkedList<String>(); if (urlPattern == null) { // based on http://www.ietf.org/rfc/rfc2396.txt String scheme = "[A-Za-z][-+.0-9A-Za-z]*"; String unreserved = "[-._~0-9A-Za-z]"; String pctEncoded = "%[0-9A-Fa-f]{2}"; String subDelims = "[!$&'()*+,;:=]"; String userinfo = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + "|:)*"; String h16 = "[0-9A-Fa-f]{1,4}"; String decOctet = "(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; String ipv4address = decOctet + "\\." + decOctet + "\\." + decOctet + "\\." + decOctet; String ls32 = "(?:" + h16 + ":" + h16 + "|" + ipv4address + ")"; String ipv6address = "(?:(?:" + h16 + "){6}" + ls32 + ")"; String ipvfuture = "v[0-9A-Fa-f]+.(?:" + unreserved + "|" + subDelims + "|:)+"; String ipLiteral = "\\[(?:" + ipv6address + "|" + ipvfuture + ")\\]"; String regName = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + ")*"; String host = "(?:" + ipLiteral + "|" + ipv4address + "|" + regName + ")"; String port = "[0-9]*"; String authority = "(?:" + userinfo + "@)?" + host + "(?::" + port + ")?"; String pchar = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + "|@)"; String segment = pchar + "*"; String pathAbempty = "(?:/" + segment + ")*"; String segmentNz = pchar + "+"; String pathAbsolute = "/(?:" + segmentNz + "(?:/" + segment + ")*)?"; String pathRootless = segmentNz + "(?:/" + segment + ")*"; String hierPart = "(?://" + authority + pathAbempty + "|" + pathAbsolute + "|" + pathRootless + ")"; String query = "(?:" + pchar + "|/|\\?)*"; String fragment = "(?:" + pchar + "|/|\\?)*"; String uriRegex = scheme + ":" + hierPart + "(?:" + query + ")?(?:#" + fragment + ")?"; urlPattern = Pattern.compile(uriRegex); } char[] visibleBuffer = new char[buffer.height * buffer.width]; for (int l = 0; l < buffer.height; l++) System.arraycopy(buffer.charArray[buffer.windowBase + l], 0, visibleBuffer, l * buffer.width, buffer.width); Matcher urlMatcher = urlPattern.matcher(new String(visibleBuffer)); while (urlMatcher.find()) urls.add(urlMatcher.group()); return urls; } /** * @return */ public boolean isUsingNetwork() { return transport.usesNetwork(); } /** * @return */ public TerminalKeyListener getKeyHandler() { return keyListener; } /** * */ public void resetScrollPosition() { // if we're in scrollback, scroll to bottom of window on input if (buffer.windowBase != buffer.screenBase) buffer.setWindowBase(buffer.screenBase); } /** * */ public void increaseFontSize() { setFontSize(fontSize + FONT_SIZE_STEP); } /** * */ public void decreaseFontSize() { setFontSize(fontSize - FONT_SIZE_STEP); } }
Statically initialize URL matcher
src/org/connectbot/service/TerminalBridge.java
Statically initialize URL matcher
<ide><path>rc/org/connectbot/service/TerminalBridge.java <ide> <ide> import java.io.IOException; <ide> import java.nio.charset.Charset; <add>import java.util.ArrayList; <ide> import java.util.LinkedList; <ide> import java.util.List; <ide> import java.util.regex.Matcher; <ide> color = manager.hostdb.getColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME); <ide> } <ide> <del> private static Pattern urlPattern = null; <add> // based on http://www.ietf.org/rfc/rfc2396.txt <add> private static final String URL_SCHEME = "[A-Za-z][-+.0-9A-Za-z]*"; <add> private static final String URL_UNRESERVED = "[-._~0-9A-Za-z]"; <add> private static final String URL_PCT_ENCODED = "%[0-9A-Fa-f]{2}"; <add> private static final String URL_SUB_DELIMS = "[!$&'()*+,;:=]"; <add> private static final String URL_USERINFO = "(?:" + URL_UNRESERVED + "|" + URL_PCT_ENCODED + "|" <add> + URL_SUB_DELIMS + "|:)*"; <add> private static final String URL_H16 = "[0-9A-Fa-f]{1,4}"; <add> private static final String URL_DEC_OCTET = "(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; <add> private static final String URL_IPV4_ADDRESS = URL_DEC_OCTET + "\\." + URL_DEC_OCTET + "\\." <add> + URL_DEC_OCTET + "\\." + URL_DEC_OCTET; <add> private static final String URL_LS32 = "(?:" + URL_H16 + ":" + URL_H16 + "|" + URL_IPV4_ADDRESS <add> + ")"; <add> private static final String URL_IPV6_ADDRESS = "(?:(?:" + URL_H16 + "){6}" + URL_LS32 + ")"; <add> private static final String URL_IPV_FUTURE = "v[0-9A-Fa-f]+.(?:" + URL_UNRESERVED + "|" <add> + URL_SUB_DELIMS + "|:)+"; <add> private static final String URL_IP_LITERAL = "\\[(?:" + URL_IPV6_ADDRESS + "|" + URL_IPV_FUTURE <add> + ")\\]"; <add> private static final String URL_REG_NAME = "(?:" + URL_UNRESERVED + "|" + URL_PCT_ENCODED + "|" <add> + URL_SUB_DELIMS + ")*"; <add> private static final String URL_HOST = "(?:" + URL_IP_LITERAL + "|" + URL_IPV4_ADDRESS + "|" <add> + URL_REG_NAME + ")"; <add> private static final String URL_PORT = "[0-9]*"; <add> private static final String URL_AUTHORITY = "(?:" + URL_USERINFO + "@)?" + URL_HOST + "(?::" <add> + URL_PORT + ")?"; <add> private static final String URL_PCHAR = "(?:" + URL_UNRESERVED + "|" + URL_PCT_ENCODED + "|" <add> + URL_SUB_DELIMS + "|@)"; <add> private static final String URL_SEGMENT = URL_PCHAR + "*"; <add> private static final String URL_PATH_ABEMPTY = "(?:/" + URL_SEGMENT + ")*"; <add> private static final String URL_SEGMENT_NZ = URL_PCHAR + "+"; <add> private static final String URL_PATH_ABSOLUTE = "/(?:" + URL_SEGMENT_NZ + "(?:/" + URL_SEGMENT <add> + ")*)?"; <add> private static final String URL_PATH_ROOTLESS = URL_SEGMENT_NZ + "(?:/" + URL_SEGMENT + ")*"; <add> private static final String URL_HIER_PART = "(?://" + URL_AUTHORITY + URL_PATH_ABEMPTY + "|" <add> + URL_PATH_ABSOLUTE + "|" + URL_PATH_ROOTLESS + ")"; <add> private static final String URL_QUERY = "(?:" + URL_PCHAR + "|/|\\?)*"; <add> private static final String URL_FRAGMENT = "(?:" + URL_PCHAR + "|/|\\?)*"; <add> private static final String URI_REGEX = URL_SCHEME + ":" + URL_HIER_PART + "(?:" + URL_QUERY <add> + ")?(?:#" + URL_FRAGMENT + ")?"; <add> <add> private static final Pattern URL_PATTERN = Pattern.compile(URI_REGEX); <ide> <ide> /** <ide> * @return <ide> */ <ide> public List<String> scanForURLs() { <del> List<String> urls = new LinkedList<String>(); <del> <del> if (urlPattern == null) { <del> // based on http://www.ietf.org/rfc/rfc2396.txt <del> String scheme = "[A-Za-z][-+.0-9A-Za-z]*"; <del> String unreserved = "[-._~0-9A-Za-z]"; <del> String pctEncoded = "%[0-9A-Fa-f]{2}"; <del> String subDelims = "[!$&'()*+,;:=]"; <del> String userinfo = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + "|:)*"; <del> String h16 = "[0-9A-Fa-f]{1,4}"; <del> String decOctet = "(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])"; <del> String ipv4address = decOctet + "\\." + decOctet + "\\." + decOctet + "\\." + decOctet; <del> String ls32 = "(?:" + h16 + ":" + h16 + "|" + ipv4address + ")"; <del> String ipv6address = "(?:(?:" + h16 + "){6}" + ls32 + ")"; <del> String ipvfuture = "v[0-9A-Fa-f]+.(?:" + unreserved + "|" + subDelims + "|:)+"; <del> String ipLiteral = "\\[(?:" + ipv6address + "|" + ipvfuture + ")\\]"; <del> String regName = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + ")*"; <del> String host = "(?:" + ipLiteral + "|" + ipv4address + "|" + regName + ")"; <del> String port = "[0-9]*"; <del> String authority = "(?:" + userinfo + "@)?" + host + "(?::" + port + ")?"; <del> String pchar = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + "|@)"; <del> String segment = pchar + "*"; <del> String pathAbempty = "(?:/" + segment + ")*"; <del> String segmentNz = pchar + "+"; <del> String pathAbsolute = "/(?:" + segmentNz + "(?:/" + segment + ")*)?"; <del> String pathRootless = segmentNz + "(?:/" + segment + ")*"; <del> String hierPart = "(?://" + authority + pathAbempty + "|" + pathAbsolute + "|" + pathRootless + ")"; <del> String query = "(?:" + pchar + "|/|\\?)*"; <del> String fragment = "(?:" + pchar + "|/|\\?)*"; <del> String uriRegex = scheme + ":" + hierPart + "(?:" + query + ")?(?:#" + fragment + ")?"; <del> urlPattern = Pattern.compile(uriRegex); <del> } <del> <del> char[] visibleBuffer = new char[buffer.height * buffer.width]; <add> final List<String> urls = new ArrayList<String>(); <add> <add> final char[] visibleBuffer = new char[buffer.height * buffer.width]; <ide> for (int l = 0; l < buffer.height; l++) <ide> System.arraycopy(buffer.charArray[buffer.windowBase + l], 0, <ide> visibleBuffer, l * buffer.width, buffer.width); <ide> <del> Matcher urlMatcher = urlPattern.matcher(new String(visibleBuffer)); <add> final Matcher urlMatcher = URL_PATTERN.matcher(new String(visibleBuffer)); <ide> while (urlMatcher.find()) <ide> urls.add(urlMatcher.group()); <ide>
Java
mit
55ec7376a4590da37e2c0100088fde7ff5ebac99
0
kobylinsky/algorithms-sorting
package com.kobylinsky.algorithms.sorting; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.Random; import static java.util.Arrays.asList; import static org.junit.Assert.assertArrayEquals; /** * @author bogdankobylinsky */ @RunWith(Parameterized.class) public class SortTest { private Integer[] testArray; @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> arrays() { return asList(new Object[][] { { new Integer[]{} }, { new Integer[]{0} }, { new Integer[]{0, 1} }, { new Integer[]{0, 0, 0, 0, 0} }, { newRandomArray(10) }, }); } public SortTest(Integer[] testArray) { this.testArray = testArray; } @Test public void testSelectionSort() { // Given final Sort selectionSort = new SelectionSort(); System.out.println("Initial: " + Arrays.toString(testArray)); final Integer[] expected = getProperlySortedArray(testArray); System.out.println("Expected: " + Arrays.toString(expected)); // When selectionSort.sort(testArray); System.out.println("Actual: " + Arrays.toString(testArray)); // Then assertArrayEquals(expected, testArray); } private static Integer[] newRandomArray(final int size) { final Random random = new Random(); final Integer[] array = new Integer[size]; for (int i = 0; i < size; i++) { array[i] = random.nextInt(size); } return array; } private static Integer[] getProperlySortedArray(final Integer[] array) { Integer[] reference = Arrays.copyOf(array, array.length); Arrays.sort(reference); return reference; } }
src/test/java/com/kobylinsky/algorithms/sorting/SortTest.java
package com.kobylinsky.algorithms.sorting; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import java.util.Random; /** * @author bogdankobylinsky */ @RunWith(Parameterized.class) public class SortTest { private Integer[] testArray; @Parameterized.Parameters(name = "{0}") public static Collection<Object[]> arrays() { return Arrays.asList(new Object[][] { { newRandomArray(100) } }); } @Test public void testSelectionSort() { // Given final Sort selectionSort = new SelectionSort(); final Integer[] expected = getProperlySortedArray(testArray); // When selectionSort.sort(testArray); Assert.assertArrayEquals(expected, testArray); } private static Integer[] newRandomArray(final int size) { final Random random = new Random(); final Integer[] array = new Integer[size]; for (int i = 0; i < size; i++) { array[i] = random.nextInt(size); } return array; } private static Integer[] getProperlySortedArray(final Integer[] array) { Integer[] reference = Arrays.copyOf(array, array.length); Arrays.sort(reference); return reference; } }
Additional test cases in SortTest
src/test/java/com/kobylinsky/algorithms/sorting/SortTest.java
Additional test cases in SortTest
<ide><path>rc/test/java/com/kobylinsky/algorithms/sorting/SortTest.java <ide> package com.kobylinsky.algorithms.sorting; <ide> <del>import org.junit.Assert; <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <ide> import org.junit.runners.Parameterized; <ide> import java.util.Arrays; <ide> import java.util.Collection; <ide> import java.util.Random; <add> <add>import static java.util.Arrays.asList; <add>import static org.junit.Assert.assertArrayEquals; <ide> <ide> /** <ide> * @author bogdankobylinsky <ide> <ide> @Parameterized.Parameters(name = "{0}") <ide> public static Collection<Object[]> arrays() { <del> return Arrays.asList(new Object[][] { { newRandomArray(100) } }); <add> return asList(new Object[][] { <add> { new Integer[]{} }, <add> { new Integer[]{0} }, <add> { new Integer[]{0, 1} }, <add> { new Integer[]{0, 0, 0, 0, 0} }, <add> { newRandomArray(10) }, <add> }); <add> } <add> <add> public SortTest(Integer[] testArray) { <add> this.testArray = testArray; <ide> } <ide> <ide> @Test <ide> public void testSelectionSort() { <ide> // Given <ide> final Sort selectionSort = new SelectionSort(); <add> System.out.println("Initial: " + Arrays.toString(testArray)); <ide> final Integer[] expected = getProperlySortedArray(testArray); <add> System.out.println("Expected: " + Arrays.toString(expected)); <ide> <ide> // When <ide> selectionSort.sort(testArray); <add> System.out.println("Actual: " + Arrays.toString(testArray)); <ide> <del> Assert.assertArrayEquals(expected, testArray); <add> // Then <add> assertArrayEquals(expected, testArray); <ide> } <ide> <ide> private static Integer[] newRandomArray(final int size) {
Java
lgpl-2.1
8d70954ebccc358f2c588d54482196b460f37886
0
zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform
/* * Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the * @author tags. See the copyright.txt file in the distribution for a full * listing of individual contributors. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF * site: http://www.fsf.org. */ package org.zanata.webtrans.client.editor.table; import static org.zanata.webtrans.client.editor.table.TableConstants.MAX_PAGE_ROW; import static org.zanata.webtrans.client.editor.table.TableConstants.PAGE_SIZE; import java.util.ArrayList; import java.util.List; import net.customware.gwt.presenter.client.EventBus; import net.customware.gwt.presenter.client.widget.WidgetDisplay; import org.zanata.common.EditState; import org.zanata.webtrans.client.action.UndoableTransUnitUpdateAction; import org.zanata.webtrans.client.action.UndoableTransUnitUpdateHandler; import org.zanata.webtrans.client.editor.DocumentEditorPresenter; import org.zanata.webtrans.client.editor.HasPageNavigation; import org.zanata.webtrans.client.events.CopySourceEvent; import org.zanata.webtrans.client.events.CopySourceEventHandler; import org.zanata.webtrans.client.events.DocumentSelectionEvent; import org.zanata.webtrans.client.events.DocumentSelectionHandler; import org.zanata.webtrans.client.events.FindMessageEvent; import org.zanata.webtrans.client.events.FindMessageHandler; import org.zanata.webtrans.client.events.NavTransUnitEvent; import org.zanata.webtrans.client.events.NavTransUnitEvent.NavigationType; import org.zanata.webtrans.client.events.NavTransUnitHandler; import org.zanata.webtrans.client.events.NotificationEvent; import org.zanata.webtrans.client.events.NotificationEvent.Severity; import org.zanata.webtrans.client.events.EnterKeyEnabledEvent; import org.zanata.webtrans.client.events.EnterKeyEnabledEventHandler; import org.zanata.webtrans.client.events.RedoFailureEvent; import org.zanata.webtrans.client.events.TransMemoryCopyEvent; import org.zanata.webtrans.client.events.TransMemoryCopyHandler; import org.zanata.webtrans.client.events.TransUnitEditEvent; import org.zanata.webtrans.client.events.TransUnitEditEventHandler; import org.zanata.webtrans.client.events.TransUnitSelectionEvent; import org.zanata.webtrans.client.events.TransUnitUpdatedEvent; import org.zanata.webtrans.client.events.TransUnitUpdatedEventHandler; import org.zanata.webtrans.client.events.UndoAddEvent; import org.zanata.webtrans.client.events.UndoFailureEvent; import org.zanata.webtrans.client.events.UndoRedoFinishEvent; import org.zanata.webtrans.client.rpc.CachingDispatchAsync; import org.zanata.webtrans.shared.auth.AuthenticationError; import org.zanata.webtrans.shared.auth.AuthorizationError; import org.zanata.webtrans.shared.auth.Identity; import org.zanata.webtrans.shared.model.DocumentId; import org.zanata.webtrans.shared.model.TransUnit; import org.zanata.webtrans.shared.model.TransUnitId; import org.zanata.webtrans.shared.rpc.EditingTranslationAction; import org.zanata.webtrans.shared.rpc.EditingTranslationResult; import org.zanata.webtrans.shared.rpc.GetTransUnitList; import org.zanata.webtrans.shared.rpc.GetTransUnitListResult; import org.zanata.webtrans.shared.rpc.GetTransUnitsNavigation; import org.zanata.webtrans.shared.rpc.GetTransUnitsNavigationResult; import org.zanata.webtrans.shared.rpc.UpdateTransUnit; import org.zanata.webtrans.shared.rpc.UpdateTransUnitResult; import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.logical.shared.HasSelectionHandlers; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.gen2.table.client.TableModel; import com.google.gwt.gen2.table.client.TableModel.Callback; import com.google.gwt.gen2.table.client.TableModelHelper.Request; import com.google.gwt.gen2.table.client.TableModelHelper.SerializableResponse; import com.google.gwt.gen2.table.event.client.HasPageChangeHandlers; import com.google.gwt.gen2.table.event.client.HasPageCountChangeHandlers; import com.google.gwt.gen2.table.event.client.PageChangeHandler; import com.google.gwt.gen2.table.event.client.PageCountChangeHandler; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Event.NativePreviewHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.inject.Inject; public class TableEditorPresenter extends DocumentEditorPresenter<TableEditorPresenter.Display> implements HasPageNavigation { public interface Display extends WidgetDisplay, HasPageNavigation { HasSelectionHandlers<TransUnit> getSelectionHandlers(); HasPageChangeHandlers getPageChangeHandlers(); HasPageCountChangeHandlers getPageCountChangeHandlers(); RedirectingCachedTableModel<TransUnit> getTableModel(); void setTableModelHandler(TableModelHandler<TransUnit> hadler); void reloadPage(); void setPageSize(int size); void gotoRow(int row); void gotoRow(int row, boolean andEdit); int getCurrentPageNumber(); TransUnit getTransUnitValue(int row); InlineTargetCellEditor getTargetCellEditor(); List<TransUnit> getRowValues(); boolean isFirstPage(); boolean isLastPage(); int getCurrentPage(); int getPageSize(); void setFindMessage(String findMessage); void startProcessing(); void stopProcessing(); } private DocumentId documentId; private final CachingDispatchAsync dispatcher; private final Identity identity; private TransUnit selectedTransUnit; // private int lastRowNum; private List<Long> transIdNextNewFuzzyCache = new ArrayList<Long>(); private List<Long> transIdPrevNewFuzzyCache = new ArrayList<Long>(); private List<Long> transIdNextFuzzyCache = new ArrayList<Long>(); private List<Long> transIdPrevFuzzyCache = new ArrayList<Long>(); private List<Long> transIdNextNewCache = new ArrayList<Long>(); private List<Long> transIdPrevNewCache = new ArrayList<Long>(); private int curRowIndex; private int curPage; private String findMessage; private final TableEditorMessages messages; private UndoableTransUnitUpdateAction inProcessing; private final UndoableTransUnitUpdateHandler undoableTransUnitUpdateHandler = new UndoableTransUnitUpdateHandler() { @Override public void undo(final UndoableTransUnitUpdateAction action) { action.setUndo(true); action.setRedo(false); inProcessing = action; if (selectedTransUnit != null) { Log.info("cancel edit"); display.getTargetCellEditor().cancelEdit(); } dispatcher.rollback(action.getAction(), action.getResult(), new AsyncCallback<Void>() { @Override public void onFailure(Throwable e) { Log.error("UpdateTransUnit failure " + e, e); eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyUpdateFailed(e.getLocalizedMessage()))); inProcessing = null; // put back the old cell value display.getTableModel().clearCache(); display.reloadPage(); eventBus.fireEvent(new UndoFailureEvent(action)); } @Override public void onSuccess(Void result) { } }); } @Override public void redo(final UndoableTransUnitUpdateAction action) { action.setRedo(true); action.setUndo(false); inProcessing = action; final UpdateTransUnit updateTransUnit = action.getAction(); updateTransUnit.setRedo(true); updateTransUnit.setVerNum(action.getResult().getCurrentVersionNum()); dispatcher.execute(updateTransUnit, new AsyncCallback<UpdateTransUnitResult>() { @Override public void onFailure(Throwable e) { Log.error("redo failure " + e, e); eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyUpdateFailed(e.getLocalizedMessage()))); inProcessing = null; // put back the old cell value display.getTableModel().clearCache(); display.reloadPage(); eventBus.fireEvent(new RedoFailureEvent(action)); } @Override public void onSuccess(UpdateTransUnitResult result) { } }); } }; @Inject public TableEditorPresenter(final Display display, final EventBus eventBus, final CachingDispatchAsync dispatcher, final Identity identity, final TableEditorMessages messages) { super(display, eventBus); this.dispatcher = dispatcher; this.identity = identity; this.messages = messages; } @Override protected void onBind() { display.setTableModelHandler(tableModelHandler); display.setPageSize(TableConstants.PAGE_SIZE); registerHandler(display.getSelectionHandlers().addSelectionHandler(new SelectionHandler<TransUnit>() { @Override public void onSelection(SelectionEvent<TransUnit> event) { TransUnit newSelectedItem = event.getSelectedItem(); selectTransUnit(newSelectedItem); } })); registerHandler(eventBus.addHandler(DocumentSelectionEvent.getType(), new DocumentSelectionHandler() { @Override public void onDocumentSelected(DocumentSelectionEvent event) { if (!event.getDocument().getId().equals(documentId)) { display.startProcessing(); documentId = event.getDocument().getId(); display.getTableModel().clearCache(); display.getTableModel().setRowCount(TableModel.UNKNOWN_ROW_COUNT); display.gotoPage(0, true); display.stopProcessing(); } } })); registerHandler(eventBus.addHandler(FindMessageEvent.getType(), new FindMessageHandler() { @Override public void onFindMessage(FindMessageEvent event) { Log.info("Find Message Event: " + event.getMessage()); display.getTargetCellEditor().savePendingChange(true); if (selectedTransUnit != null) { Log.info("cancelling selection"); display.getTargetCellEditor().clearSelection(); } display.startProcessing(); findMessage = event.getMessage(); display.setFindMessage(findMessage); display.getTableModel().clearCache(); display.getTableModel().setRowCount(TableModel.UNKNOWN_ROW_COUNT); display.gotoPage(0, true); display.stopProcessing(); } })); registerHandler(eventBus.addHandler(TransUnitUpdatedEvent.getType(), new TransUnitUpdatedEventHandler() { @Override public void onTransUnitUpdated(TransUnitUpdatedEvent event) { if (documentId != null && documentId.equals(event.getDocumentId())) { // Clear the cache if (!transIdNextNewFuzzyCache.isEmpty()) transIdNextNewFuzzyCache.clear(); if (!transIdPrevNewFuzzyCache.isEmpty()) transIdPrevNewFuzzyCache.clear(); // TODO this test never succeeds if (selectedTransUnit != null && selectedTransUnit.getId().equals(event.getTransUnit().getId())) { // handle change in current selection // eventBus.fireEvent(new NotificationEvent(Severity.Warning, // "Someone else updated this translation unit. you're in trouble...")); // display.getTableModel().setRowValue(row, rowValue); Log.info("selected TU updated; cancelling edit"); display.getTargetCellEditor().cancelEdit(); // TODO reload page and return } boolean reloadPage = false; if (reloadPage) { display.getTargetCellEditor().cancelEdit(); display.getTableModel().clearCache(); display.reloadPage(); } else { final Integer rowOffset = getRowOffset(event.getTransUnit().getId()); // - add TU index to model if (rowOffset != null) { final int row = display.getCurrentPage() * display.getPageSize() + rowOffset; Log.info("row calculated as " + row); display.getTableModel().setRowValueOverride(row, event.getTransUnit()); if (inProcessing != null) { if (inProcessing.getAction().getTransUnitId().equals(event.getTransUnit().getId())) { Log.info("go to row:" + row); tableModelHandler.gotoRow(row); eventBus.fireEvent(new UndoRedoFinishEvent(inProcessing)); inProcessing = null; } } } else { display.getTableModel().clearCache(); display.getTargetCellEditor().cancelEdit(); if (inProcessing != null) { if (inProcessing.getAction().getTransUnitId().equals(event.getTransUnit().getId())) { int pageNum = inProcessing.getCurrentPage(); int rowNum = inProcessing.getRowNum(); int row = pageNum * PAGE_SIZE + rowNum; Log.info("go to row:" + row); Log.info("go to page:" + pageNum); tableModelHandler.gotoRow(row); eventBus.fireEvent(new UndoRedoFinishEvent(inProcessing)); inProcessing = null; } } } } } } })); registerHandler(eventBus.addHandler(TransUnitEditEvent.getType(), new TransUnitEditEventHandler() { @Override public void onTransUnitEdit(TransUnitEditEvent event) { if (documentId != null && documentId.equals(event.getDocumentId())) { if (selectedTransUnit != null && selectedTransUnit.getId().equals(event.getTransUnitId())) { // handle change in current selection if (!event.getSessionId().equals(identity.getSessionId())) eventBus.fireEvent(new NotificationEvent(Severity.Warning, messages.notifyInEdit())); } // display.getTableModel().clearCache(); // display.reloadPage(); } } })); registerHandler(eventBus.addHandler(NavTransUnitEvent.getType(), new NavTransUnitHandler() { @Override public void onNavTransUnit(NavTransUnitEvent event) { if (selectedTransUnit != null) { int step = event.getStep(); Log.info("Step " + step); // Send message to server to stop editing current selection // stopEditing(selectedTransUnit); InlineTargetCellEditor editor = display.getTargetCellEditor(); // If goto Next or Prev Fuzzy/New Trans Unit if (event.getRowType() == NavigationType.PrevEntry) { editor.gotoRow(NavigationType.PrevEntry); } if (event.getRowType() == NavigationType.NextEntry) { editor.gotoRow(NavigationType.NextEntry); } if (event.getRowType() == NavigationType.PrevFuzzyOrUntranslated) { editor.saveAndMoveNextState(NavigationType.PrevEntry); } if (event.getRowType() == NavigationType.NextFuzzyOrUntranslated) { editor.saveAndMoveNextState(NavigationType.NextEntry); } } } })); registerHandler(eventBus.addHandler(TransMemoryCopyEvent.getType(), new TransMemoryCopyHandler() { @Override public void onTransMemoryCopy(TransMemoryCopyEvent event) { // When user clicked on copy-to-target anchor, it checks // if user is editing any target. Notifies if not. if (display.getTargetCellEditor().isEditing()) { display.getTargetCellEditor().setText(event.getTargetResult()); display.getTargetCellEditor().autoSize(); eventBus.fireEvent(new NotificationEvent(Severity.Info, messages.notifyCopied())); } else eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyUnopened())); } })); registerHandler(eventBus.addHandler(CopySourceEvent.getType(), new CopySourceEventHandler() { @Override public void onCopySource(CopySourceEvent event) { int rowOffset = getRowOffset(event.getTransUnit().getId()); int row = display.getCurrentPage() * display.getPageSize() + rowOffset; tableModelHandler.gotoRow(row); display.getTargetCellEditor().setText(event.getTransUnit().getSource()); display.getTargetCellEditor().autoSize(); } })); registerHandler(eventBus.addHandler(EnterKeyEnabledEvent.getType(), new EnterKeyEnabledEventHandler() { @Override public void onValueChanged(EnterKeyEnabledEvent event) { display.getTargetCellEditor().setEnterKeyEnabled(event.isEnabled()); } })); Event.addNativePreviewHandler(new NativePreviewHandler() { @Override public void onPreviewNativeEvent(NativePreviewEvent event) { // Only when the Table is showed and editor is closed, the keyboard // event will be processed. if (display.asWidget().isVisible() && !display.getTargetCellEditor().isFocused()) { NativeEvent nativeEvent = event.getNativeEvent(); String nativeEventType = nativeEvent.getType(); int keyCode = nativeEvent.getKeyCode(); boolean shiftKey = nativeEvent.getShiftKey(); boolean altKey = nativeEvent.getAltKey(); boolean ctrlKey = nativeEvent.getCtrlKey(); if (nativeEventType.equals("keypress") && !shiftKey && !altKey && !ctrlKey) { // PageDown key switch (keyCode) { case KeyCodes.KEY_PAGEDOWN: Log.info("fired event of type " + event.getAssociatedType().getClass().getName()); if (!display.isLastPage()) gotoNextPage(); event.cancel(); break; // PageUp key case KeyCodes.KEY_PAGEUP: Log.info("fired event of type " + event.getAssociatedType().getClass().getName()); if (!display.isFirstPage()) gotoPreviousPage(); event.cancel(); break; // Home case KeyCodes.KEY_HOME: Log.info("fired event of type " + event.getAssociatedType().getClass().getName()); display.gotoFirstPage(); event.cancel(); break; // End case KeyCodes.KEY_END: Log.info("fired event of type " + event.getAssociatedType().getClass().getName()); display.gotoLastPage(); event.cancel(); break; default: break; } } } } }); display.gotoFirstPage(); } public Integer getRowOffset(TransUnitId transUnitId) { // TODO inefficient! for (int i = 0; i < display.getRowValues().size(); i++) { if (transUnitId.equals(display.getTransUnitValue(i).getId())) { Log.info("getRowOffset returning " + i); return i; } } return null; } private final TableModelHandler<TransUnit> tableModelHandler = new TableModelHandler<TransUnit>() { @Override public void requestRows(final Request request, final Callback<TransUnit> callback) { int numRows = request.getNumRows(); int startRow = request.getStartRow(); Log.info("Table requesting " + numRows + " starting from " + startRow); if (documentId == null) { callback.onFailure(new RuntimeException("No DocumentId")); return; } dispatcher.execute(new GetTransUnitList(documentId, startRow, numRows, findMessage), new AsyncCallback<GetTransUnitListResult>() { @Override public void onSuccess(GetTransUnitListResult result) { Log.info("find message:" + findMessage); SerializableResponse<TransUnit> response = new SerializableResponse<TransUnit>(result.getUnits()); Log.info("Got " + result.getUnits().size() + " rows back"); callback.onRowsReady(request, response); Log.info("Total of " + result.getTotalCount() + " rows available"); display.getTableModel().setRowCount(result.getTotalCount()); } @Override public void onFailure(Throwable caught) { if (caught instanceof AuthenticationError) { eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyNotLoggedIn())); } else if (caught instanceof AuthorizationError) { eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyLoadFailed())); } else { Log.error("GetTransUnits failure " + caught, caught); eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyUnknownError())); } } }); } @Override public boolean onSetRowValue(int row, TransUnit rowValue) { final UpdateTransUnit updateTransUnit = new UpdateTransUnit(rowValue.getId(), rowValue.getTarget(), rowValue.getStatus()); dispatcher.execute(updateTransUnit, new AsyncCallback<UpdateTransUnitResult>() { @Override public void onFailure(Throwable e) { Log.error("UpdateTransUnit failure " + e, e); eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyUpdateFailed(e.getLocalizedMessage()))); display.getTableModel().clearCache(); display.reloadPage(); } @Override public void onSuccess(UpdateTransUnitResult result) { eventBus.fireEvent(new NotificationEvent(Severity.Info, messages.notifyUpdateSaved())); UndoableTransUnitUpdateAction undoAction = new UndoableTransUnitUpdateAction(updateTransUnit, result, curRowIndex, curPage); undoAction.setHandler(undoableTransUnitUpdateHandler); eventBus.fireEvent(new UndoAddEvent(undoAction)); // Need to reload cached table if page changes // TODO need focus on curRow, its not focus at the moment if (curPage != display.getCurrentPage()) { display.getTargetCellEditor().cancelEdit(); display.getTableModel().clearCache(); display.reloadPage(); } } }); stopEditing(rowValue); return true; } public void onCancel(TransUnit rowValue) { // stopEditing(rowValue); } public void updatePageAndRowIndex(int row) { curPage = display.getCurrentPage(); // Convert row number to row Index in table curRowIndex = curPage * TableConstants.PAGE_SIZE + row; Log.info("Current Row Index" + curRowIndex); } @Override public void gotoNextRow(int row) { updatePageAndRowIndex(row); int rowIndex = curPage * TableConstants.PAGE_SIZE + row + 1; if (rowIndex < display.getTableModel().getRowCount()) { gotoRow(rowIndex); } } @Override public void gotoPrevRow(int row) { updatePageAndRowIndex(row); int rowIndex = curPage * TableConstants.PAGE_SIZE + row - 1; if (rowIndex >= 0) { gotoRow(rowIndex); } } @Override public void nextFuzzyNewIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex < display.getTableModel().getRowCount()) gotoNextState(true, true); } @Override public void prevFuzzyNewIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex > 0) gotoPrevState(true, true); } @Override public void nextFuzzyIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex < display.getTableModel().getRowCount()) gotoNextState(false, true); } @Override public void prevFuzzyIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex > 0) gotoPrevState(false, true); } @Override public void nextNewIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex < display.getTableModel().getRowCount()) gotoNextState(true, false); } @Override public void prevNewIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex > 0) gotoPrevState(true, false); } @Override public void gotoRow(int rowIndex) { curPage = display.getCurrentPage(); int pageNum = rowIndex / (MAX_PAGE_ROW + 1); int rowNum = rowIndex % (MAX_PAGE_ROW + 1); if (pageNum != curPage) { display.gotoPage(pageNum, false); } selectTransUnit(display.getTransUnitValue(rowNum)); display.gotoRow(rowNum); if (pageNum != curPage) { display.getTargetCellEditor().cancelEdit(); } } }; private void stopEditing(TransUnit rowValue) { dispatcher.execute(new EditingTranslationAction(rowValue.getId(), EditState.StopEditing), new AsyncCallback<EditingTranslationResult>() { @Override public void onSuccess(EditingTranslationResult result) { // eventBus.fireEvent(new NotificationEvent(Severity.Warning, // "TransUnit Editing is finished")); } @Override public void onFailure(Throwable caught) { Log.error("EditingTranslationAction failure " + caught, caught); eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyStopFailed())); } }); } boolean isReqComplete = true; private void cacheNextState(final NavigationCacheCallback callBack, final List<Long> cacheList, final boolean isNewState, final boolean isFuzzyState) { isReqComplete = false; dispatcher.execute(new GetTransUnitsNavigation(selectedTransUnit.getId().getId(), 3, false, findMessage, isNewState, isFuzzyState), new AsyncCallback<GetTransUnitsNavigationResult>() { @Override public void onSuccess(GetTransUnitsNavigationResult result) { isReqComplete = true; if (!result.getUnits().isEmpty()) { for (Long offset : result.getUnits()) { cacheList.add(offset + curRowIndex); } callBack.next(isNewState, isFuzzyState); } } @Override public void onFailure(Throwable caught) { Log.error("GetTransUnitsStates failure " + caught, caught); } }); } private void cachePrevState(final NavigationCacheCallback callBack, final List<Long> cacheList, final boolean isNewState, final boolean isFuzzyState) { isReqComplete = false; dispatcher.execute(new GetTransUnitsNavigation(selectedTransUnit.getId().getId(), 3, true, findMessage, isNewState, isFuzzyState), new AsyncCallback<GetTransUnitsNavigationResult>() { @Override public void onSuccess(GetTransUnitsNavigationResult result) { isReqComplete = true; if (!result.getUnits().isEmpty()) { for (Long offset : result.getUnits()) { cacheList.add(curRowIndex - offset); } callBack.prev(isNewState, isFuzzyState); } } @Override public void onFailure(Throwable caught) { Log.error("GetTransUnitsStates failure " + caught, caught); } }); } NavigationCacheCallback cacheCallback = new NavigationCacheCallback() { @Override public void next(boolean isNewState, boolean isFuzzyState) { gotoNextState(isNewState, isFuzzyState); } @Override public void prev(boolean isNewState, boolean isFuzzyState) { gotoPrevState(isNewState, isFuzzyState); } }; private void gotoNextState(boolean isNewState, boolean isFuzzyState) { if (isNewState && isFuzzyState) { Log.info("go to Next Fuzzy Or Untranslated State"); transIdPrevNewFuzzyCache.clear(); gotoNextState(transIdNextNewFuzzyCache, true, true); } else if (isNewState) { Log.info("go to Next Untranslated State"); transIdPrevNewCache.clear(); gotoNextState(transIdNextNewCache, true, false); } else if (isFuzzyState) { Log.info("go to Next Fuzzy State"); transIdPrevFuzzyCache.clear(); gotoNextState(transIdNextFuzzyCache, false, true); } } private void gotoPrevState(boolean isNewState, boolean isFuzzyState) { if (isNewState && isFuzzyState) { Log.info("go to Prev Fuzzy Or Untranslated State"); // Clean the cache for Next Fuzzy to avoid issues about cache is // obsolete transIdNextNewFuzzyCache.clear(); gotoPrevState(transIdPrevNewFuzzyCache, true, true); } else if (isNewState) { Log.info("go to Prev Untranslated State"); // Clean the cache for Next Fuzzy to avoid issues about cache is // obsolete transIdNextNewCache.clear(); gotoPrevState(transIdPrevNewCache, true, false); } else if (isFuzzyState) { Log.info("go to Prev Fuzzy State"); // Clean the cache for Next Fuzzy to avoid issues about cache is // obsolete transIdNextFuzzyCache.clear(); gotoPrevState(transIdPrevFuzzyCache, false, true); } } private void gotoPrevState(List<Long> transIdPrevCache, boolean isNewState, boolean isFuzzyState) { // If the catch of row is empty and request is complete, generate // one if (transIdPrevCache.isEmpty()) { if (isReqComplete) cachePrevState(cacheCallback, transIdPrevCache, isNewState, isFuzzyState); } else { int size = transIdPrevCache.size(); int offset = transIdPrevCache.get(size - 1).intValue(); if (curRowIndex > offset) { for (int i = 0; i < size; i++) { int newRowIndex = transIdPrevCache.get(i).intValue(); if (curRowIndex > newRowIndex) { display.getTargetCellEditor().cancelEdit(); tableModelHandler.gotoRow(newRowIndex); break; } } } else { transIdPrevCache.clear(); cachePrevState(cacheCallback, transIdPrevCache, isNewState, isFuzzyState); } } } private void gotoNextState(List<Long> transIdNextCache, boolean isNewState, boolean isFuzzyState) { // If the cache of next is empty, generate one if (transIdNextCache.isEmpty()) { if (isReqComplete) cacheNextState(cacheCallback, transIdNextCache, isNewState, isFuzzyState); } else { int size = transIdNextCache.size(); int offset = transIdNextCache.get(size - 1).intValue(); if (curRowIndex < offset) { for (int i = 0; i < size; i++) { int newRowIndex = transIdNextCache.get(i).intValue(); if (curRowIndex < newRowIndex) { display.getTargetCellEditor().cancelEdit(); tableModelHandler.gotoRow(newRowIndex); break; } } } else { transIdNextCache.clear(); cacheNextState(cacheCallback, transIdNextCache, isNewState, isFuzzyState); } } } public TransUnit getSelectedTransUnit() { return selectedTransUnit; } @Override protected void onUnbind() { } @Override public void onRevealDisplay() { } @Override public void gotoFirstPage() { display.gotoFirstPage(); } @Override public void gotoLastPage() { display.gotoLastPage(); } @Override public void gotoNextPage() { display.gotoNextPage(); } @Override public void gotoPage(int page, boolean forced) { display.gotoPage(page, forced); } @Override public void gotoPreviousPage() { display.gotoPreviousPage(); } public void addPageChangeHandler(PageChangeHandler handler) { display.getPageChangeHandlers().addPageChangeHandler(handler); } public void addPageCountChangeHandler(PageCountChangeHandler handler) { display.getPageCountChangeHandlers().addPageCountChangeHandler(handler); } public DocumentId getDocumentId() { return documentId; } /** * Selects the given TransUnit and fires associated TU Selection event * * @param transUnit the new TO to select */ public void selectTransUnit(TransUnit transUnit) { if (selectedTransUnit == null || !transUnit.getId().equals(selectedTransUnit.getId())) { selectedTransUnit = transUnit; Log.info("SelectedTransUnit " + selectedTransUnit.getId()); // Clean the cache when we click the new entry if (!transIdNextNewFuzzyCache.isEmpty()) transIdNextNewFuzzyCache.clear(); if (!transIdPrevNewFuzzyCache.isEmpty()) transIdPrevNewFuzzyCache.clear(); eventBus.fireEvent(new TransUnitSelectionEvent(selectedTransUnit)); } } }
server/zanata-war/src/main/java/org/zanata/webtrans/client/editor/table/TableEditorPresenter.java
/* * Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the * @author tags. See the copyright.txt file in the distribution for a full * listing of individual contributors. * * This is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this software; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF * site: http://www.fsf.org. */ package org.zanata.webtrans.client.editor.table; import static org.zanata.webtrans.client.editor.table.TableConstants.MAX_PAGE_ROW; import static org.zanata.webtrans.client.editor.table.TableConstants.PAGE_SIZE; import java.util.ArrayList; import java.util.List; import net.customware.gwt.presenter.client.EventBus; import net.customware.gwt.presenter.client.widget.WidgetDisplay; import org.zanata.common.EditState; import org.zanata.webtrans.client.action.UndoableTransUnitUpdateAction; import org.zanata.webtrans.client.action.UndoableTransUnitUpdateHandler; import org.zanata.webtrans.client.editor.DocumentEditorPresenter; import org.zanata.webtrans.client.editor.HasPageNavigation; import org.zanata.webtrans.client.events.CopySourceEvent; import org.zanata.webtrans.client.events.CopySourceEventHandler; import org.zanata.webtrans.client.events.DocumentSelectionEvent; import org.zanata.webtrans.client.events.DocumentSelectionHandler; import org.zanata.webtrans.client.events.FindMessageEvent; import org.zanata.webtrans.client.events.FindMessageHandler; import org.zanata.webtrans.client.events.NavTransUnitEvent; import org.zanata.webtrans.client.events.NavTransUnitEvent.NavigationType; import org.zanata.webtrans.client.events.NavTransUnitHandler; import org.zanata.webtrans.client.events.NotificationEvent; import org.zanata.webtrans.client.events.NotificationEvent.Severity; import org.zanata.webtrans.client.events.EnterKeyEnabledEvent; import org.zanata.webtrans.client.events.EnterKeyEnabledEventHandler; import org.zanata.webtrans.client.events.RedoFailureEvent; import org.zanata.webtrans.client.events.TransMemoryCopyEvent; import org.zanata.webtrans.client.events.TransMemoryCopyHandler; import org.zanata.webtrans.client.events.TransUnitEditEvent; import org.zanata.webtrans.client.events.TransUnitEditEventHandler; import org.zanata.webtrans.client.events.TransUnitSelectionEvent; import org.zanata.webtrans.client.events.TransUnitUpdatedEvent; import org.zanata.webtrans.client.events.TransUnitUpdatedEventHandler; import org.zanata.webtrans.client.events.UndoAddEvent; import org.zanata.webtrans.client.events.UndoFailureEvent; import org.zanata.webtrans.client.events.UndoRedoFinishEvent; import org.zanata.webtrans.client.rpc.CachingDispatchAsync; import org.zanata.webtrans.shared.auth.AuthenticationError; import org.zanata.webtrans.shared.auth.AuthorizationError; import org.zanata.webtrans.shared.auth.Identity; import org.zanata.webtrans.shared.model.DocumentId; import org.zanata.webtrans.shared.model.TransUnit; import org.zanata.webtrans.shared.model.TransUnitId; import org.zanata.webtrans.shared.rpc.EditingTranslationAction; import org.zanata.webtrans.shared.rpc.EditingTranslationResult; import org.zanata.webtrans.shared.rpc.GetTransUnitList; import org.zanata.webtrans.shared.rpc.GetTransUnitListResult; import org.zanata.webtrans.shared.rpc.GetTransUnitsNavigation; import org.zanata.webtrans.shared.rpc.GetTransUnitsNavigationResult; import org.zanata.webtrans.shared.rpc.UpdateTransUnit; import org.zanata.webtrans.shared.rpc.UpdateTransUnitResult; import com.allen_sauer.gwt.log.client.Log; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.logical.shared.HasSelectionHandlers; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.gen2.table.client.TableModel; import com.google.gwt.gen2.table.client.TableModel.Callback; import com.google.gwt.gen2.table.client.TableModelHelper.Request; import com.google.gwt.gen2.table.client.TableModelHelper.SerializableResponse; import com.google.gwt.gen2.table.event.client.HasPageChangeHandlers; import com.google.gwt.gen2.table.event.client.HasPageCountChangeHandlers; import com.google.gwt.gen2.table.event.client.PageChangeHandler; import com.google.gwt.gen2.table.event.client.PageCountChangeHandler; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.Event.NativePreviewEvent; import com.google.gwt.user.client.Event.NativePreviewHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.inject.Inject; public class TableEditorPresenter extends DocumentEditorPresenter<TableEditorPresenter.Display> implements HasPageNavigation { public interface Display extends WidgetDisplay, HasPageNavigation { HasSelectionHandlers<TransUnit> getSelectionHandlers(); HasPageChangeHandlers getPageChangeHandlers(); HasPageCountChangeHandlers getPageCountChangeHandlers(); RedirectingCachedTableModel<TransUnit> getTableModel(); void setTableModelHandler(TableModelHandler<TransUnit> hadler); void reloadPage(); void setPageSize(int size); void gotoRow(int row); void gotoRow(int row, boolean andEdit); int getCurrentPageNumber(); TransUnit getTransUnitValue(int row); InlineTargetCellEditor getTargetCellEditor(); List<TransUnit> getRowValues(); boolean isFirstPage(); boolean isLastPage(); int getCurrentPage(); int getPageSize(); void setFindMessage(String findMessage); void startProcessing(); void stopProcessing(); } private DocumentId documentId; private final CachingDispatchAsync dispatcher; private final Identity identity; private TransUnit selectedTransUnit; // private int lastRowNum; private List<Long> transIdNextNewFuzzyCache = new ArrayList<Long>(); private List<Long> transIdPrevNewFuzzyCache = new ArrayList<Long>(); private List<Long> transIdNextFuzzyCache = new ArrayList<Long>(); private List<Long> transIdPrevFuzzyCache = new ArrayList<Long>(); private List<Long> transIdNextNewCache = new ArrayList<Long>(); private List<Long> transIdPrevNewCache = new ArrayList<Long>(); private int curRowIndex; private int curPage; private String findMessage; private final TableEditorMessages messages; private UndoableTransUnitUpdateAction inProcessing; private final UndoableTransUnitUpdateHandler undoableTransUnitUpdateHandler = new UndoableTransUnitUpdateHandler() { @Override public void undo(final UndoableTransUnitUpdateAction action) { action.setUndo(true); action.setRedo(false); inProcessing = action; if (selectedTransUnit != null) { Log.info("cancel edit"); display.getTargetCellEditor().cancelEdit(); } dispatcher.rollback(action.getAction(), action.getResult(), new AsyncCallback<Void>() { @Override public void onFailure(Throwable e) { Log.error("UpdateTransUnit failure " + e, e); eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyUpdateFailed(e.getLocalizedMessage()))); inProcessing = null; // put back the old cell value display.getTableModel().clearCache(); display.reloadPage(); eventBus.fireEvent(new UndoFailureEvent(action)); } @Override public void onSuccess(Void result) { } }); } @Override public void redo(final UndoableTransUnitUpdateAction action) { action.setRedo(true); action.setUndo(false); inProcessing = action; final UpdateTransUnit updateTransUnit = action.getAction(); updateTransUnit.setRedo(true); updateTransUnit.setVerNum(action.getResult().getCurrentVersionNum()); dispatcher.execute(updateTransUnit, new AsyncCallback<UpdateTransUnitResult>() { @Override public void onFailure(Throwable e) { Log.error("redo failure " + e, e); eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyUpdateFailed(e.getLocalizedMessage()))); inProcessing = null; // put back the old cell value display.getTableModel().clearCache(); display.reloadPage(); eventBus.fireEvent(new RedoFailureEvent(action)); } @Override public void onSuccess(UpdateTransUnitResult result) { } }); } }; @Inject public TableEditorPresenter(final Display display, final EventBus eventBus, final CachingDispatchAsync dispatcher, final Identity identity, final TableEditorMessages messages) { super(display, eventBus); this.dispatcher = dispatcher; this.identity = identity; this.messages = messages; } @Override protected void onBind() { display.setTableModelHandler(tableModelHandler); display.setPageSize(TableConstants.PAGE_SIZE); registerHandler(display.getSelectionHandlers().addSelectionHandler(new SelectionHandler<TransUnit>() { @Override public void onSelection(SelectionEvent<TransUnit> event) { TransUnit newSelectedItem = event.getSelectedItem(); selectTransUnit(newSelectedItem); } })); registerHandler(eventBus.addHandler(DocumentSelectionEvent.getType(), new DocumentSelectionHandler() { @Override public void onDocumentSelected(DocumentSelectionEvent event) { if (!event.getDocument().getId().equals(documentId)) { display.startProcessing(); documentId = event.getDocument().getId(); display.getTableModel().clearCache(); display.getTableModel().setRowCount(TableModel.UNKNOWN_ROW_COUNT); display.gotoPage(0, true); display.stopProcessing(); } } })); registerHandler(eventBus.addHandler(FindMessageEvent.getType(), new FindMessageHandler() { @Override public void onFindMessage(FindMessageEvent event) { Log.info("Find Message Event: " + event.getMessage()); display.getTargetCellEditor().savePendingChange(true); if (selectedTransUnit != null) { Log.info("cancelling selection"); display.getTargetCellEditor().clearSelection(); } display.startProcessing(); findMessage = event.getMessage(); display.setFindMessage(findMessage); display.getTableModel().clearCache(); display.getTableModel().setRowCount(TableModel.UNKNOWN_ROW_COUNT); display.gotoPage(0, true); display.stopProcessing(); } })); registerHandler(eventBus.addHandler(TransUnitUpdatedEvent.getType(), new TransUnitUpdatedEventHandler() { @Override public void onTransUnitUpdated(TransUnitUpdatedEvent event) { if (documentId != null && documentId.equals(event.getDocumentId())) { // Clear the cache if (!transIdNextNewFuzzyCache.isEmpty()) transIdNextNewFuzzyCache.clear(); if (!transIdPrevNewFuzzyCache.isEmpty()) transIdPrevNewFuzzyCache.clear(); // TODO this test never succeeds if (selectedTransUnit != null && selectedTransUnit.getId().equals(event.getTransUnit().getId())) { // handle change in current selection // eventBus.fireEvent(new NotificationEvent(Severity.Warning, // "Someone else updated this translation unit. you're in trouble...")); // display.getTableModel().setRowValue(row, rowValue); Log.info("selected TU updated; cancelling edit"); display.getTargetCellEditor().cancelEdit(); // TODO reload page and return } boolean reloadPage = false; if (reloadPage) { display.getTargetCellEditor().cancelEdit(); display.getTableModel().clearCache(); display.reloadPage(); } else { final Integer rowOffset = getRowOffset(event.getTransUnit().getId()); // - add TU index to model if (rowOffset != null) { final int row = display.getCurrentPage() * display.getPageSize() + rowOffset; Log.info("row calculated as " + row); display.getTableModel().setRowValueOverride(row, event.getTransUnit()); if (inProcessing != null) { if (inProcessing.getAction().getTransUnitId().equals(event.getTransUnit().getId())) { Log.info("go to row:" + row); tableModelHandler.gotoRow(row); eventBus.fireEvent(new UndoRedoFinishEvent(inProcessing)); inProcessing = null; } } } else { display.getTableModel().clearCache(); display.getTargetCellEditor().cancelEdit(); if (inProcessing != null) { if (inProcessing.getAction().getTransUnitId().equals(event.getTransUnit().getId())) { int pageNum = inProcessing.getCurrentPage(); int rowNum = inProcessing.getRowNum(); int row = pageNum * PAGE_SIZE + rowNum; Log.info("go to row:" + row); Log.info("go to page:" + pageNum); tableModelHandler.gotoRow(row); eventBus.fireEvent(new UndoRedoFinishEvent(inProcessing)); inProcessing = null; } } } } } } })); registerHandler(eventBus.addHandler(TransUnitEditEvent.getType(), new TransUnitEditEventHandler() { @Override public void onTransUnitEdit(TransUnitEditEvent event) { if (documentId != null && documentId.equals(event.getDocumentId())) { if (selectedTransUnit != null && selectedTransUnit.getId().equals(event.getTransUnitId())) { // handle change in current selection if (!event.getSessionId().equals(identity.getSessionId())) eventBus.fireEvent(new NotificationEvent(Severity.Warning, messages.notifyInEdit())); } // display.getTableModel().clearCache(); // display.reloadPage(); } } })); registerHandler(eventBus.addHandler(NavTransUnitEvent.getType(), new NavTransUnitHandler() { @Override public void onNavTransUnit(NavTransUnitEvent event) { if (selectedTransUnit != null) { int step = event.getStep(); Log.info("Step " + step); // Send message to server to stop editing current selection // stopEditing(selectedTransUnit); InlineTargetCellEditor editor = display.getTargetCellEditor(); // If goto Next or Prev Fuzzy/New Trans Unit if (event.getRowType() == NavigationType.PrevEntry) { editor.gotoRow(NavigationType.PrevEntry); } if (event.getRowType() == NavigationType.NextEntry) { editor.gotoRow(NavigationType.NextEntry); } if (event.getRowType() == NavigationType.PrevFuzzyOrUntranslated) { editor.saveAndMoveNextState(NavigationType.PrevEntry); } if (event.getRowType() == NavigationType.NextFuzzyOrUntranslated) { editor.saveAndMoveNextState(NavigationType.NextEntry); } } } })); registerHandler(eventBus.addHandler(TransMemoryCopyEvent.getType(), new TransMemoryCopyHandler() { @Override public void onTransMemoryCopy(TransMemoryCopyEvent event) { // When user clicked on copy-to-target anchor, it checks // if user is editing any target. Notifies if not. if (display.getTargetCellEditor().isEditing()) { display.getTargetCellEditor().setText(event.getTargetResult()); display.getTargetCellEditor().autoSize(); eventBus.fireEvent(new NotificationEvent(Severity.Info, messages.notifyCopied())); } else eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyUnopened())); } })); registerHandler(eventBus.addHandler(CopySourceEvent.getType(), new CopySourceEventHandler() { @Override public void onCopySource(CopySourceEvent event) { int rowOffset = getRowOffset(event.getTransUnit().getId()); int row = display.getCurrentPage() * display.getPageSize() + rowOffset; tableModelHandler.gotoRow(row); display.getTargetCellEditor().setText(event.getTransUnit().getSource()); display.getTargetCellEditor().autoSize(); } })); registerHandler(eventBus.addHandler(ButtonDisplayChangeEvent.getType(), new ButtonDisplayChangeEventHandler() { @Override public void onButtonDisplayChange(ButtonDisplayChangeEvent event) { display.getTargetCellEditor().setShowOperationButtons(event.isShowButtons()); display.setShowCopyButtons(event.isShowButtons()); } })); registerHandler(eventBus.addHandler(EnterKeyEnabledEvent.getType(), new EnterKeyEnabledEventHandler() { @Override public void onValueChanged(EnterKeyEnabledEvent event) { display.getTargetCellEditor().setEnterKeyEnabled(event.isEnabled()); } })); Event.addNativePreviewHandler(new NativePreviewHandler() { @Override public void onPreviewNativeEvent(NativePreviewEvent event) { // Only when the Table is showed and editor is closed, the keyboard // event will be processed. if (display.asWidget().isVisible() && !display.getTargetCellEditor().isFocused()) { NativeEvent nativeEvent = event.getNativeEvent(); String nativeEventType = nativeEvent.getType(); int keyCode = nativeEvent.getKeyCode(); boolean shiftKey = nativeEvent.getShiftKey(); boolean altKey = nativeEvent.getAltKey(); boolean ctrlKey = nativeEvent.getCtrlKey(); if (nativeEventType.equals("keypress") && !shiftKey && !altKey && !ctrlKey) { // PageDown key switch (keyCode) { case KeyCodes.KEY_PAGEDOWN: Log.info("fired event of type " + event.getAssociatedType().getClass().getName()); if (!display.isLastPage()) gotoNextPage(); event.cancel(); break; // PageUp key case KeyCodes.KEY_PAGEUP: Log.info("fired event of type " + event.getAssociatedType().getClass().getName()); if (!display.isFirstPage()) gotoPreviousPage(); event.cancel(); break; // Home case KeyCodes.KEY_HOME: Log.info("fired event of type " + event.getAssociatedType().getClass().getName()); display.gotoFirstPage(); event.cancel(); break; // End case KeyCodes.KEY_END: Log.info("fired event of type " + event.getAssociatedType().getClass().getName()); display.gotoLastPage(); event.cancel(); break; default: break; } } } } }); display.gotoFirstPage(); } public Integer getRowOffset(TransUnitId transUnitId) { // TODO inefficient! for (int i = 0; i < display.getRowValues().size(); i++) { if (transUnitId.equals(display.getTransUnitValue(i).getId())) { Log.info("getRowOffset returning " + i); return i; } } return null; } private final TableModelHandler<TransUnit> tableModelHandler = new TableModelHandler<TransUnit>() { @Override public void requestRows(final Request request, final Callback<TransUnit> callback) { int numRows = request.getNumRows(); int startRow = request.getStartRow(); Log.info("Table requesting " + numRows + " starting from " + startRow); if (documentId == null) { callback.onFailure(new RuntimeException("No DocumentId")); return; } dispatcher.execute(new GetTransUnitList(documentId, startRow, numRows, findMessage), new AsyncCallback<GetTransUnitListResult>() { @Override public void onSuccess(GetTransUnitListResult result) { Log.info("find message:" + findMessage); SerializableResponse<TransUnit> response = new SerializableResponse<TransUnit>(result.getUnits()); Log.info("Got " + result.getUnits().size() + " rows back"); callback.onRowsReady(request, response); Log.info("Total of " + result.getTotalCount() + " rows available"); display.getTableModel().setRowCount(result.getTotalCount()); } @Override public void onFailure(Throwable caught) { if (caught instanceof AuthenticationError) { eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyNotLoggedIn())); } else if (caught instanceof AuthorizationError) { eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyLoadFailed())); } else { Log.error("GetTransUnits failure " + caught, caught); eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyUnknownError())); } } }); } @Override public boolean onSetRowValue(int row, TransUnit rowValue) { final UpdateTransUnit updateTransUnit = new UpdateTransUnit(rowValue.getId(), rowValue.getTarget(), rowValue.getStatus()); dispatcher.execute(updateTransUnit, new AsyncCallback<UpdateTransUnitResult>() { @Override public void onFailure(Throwable e) { Log.error("UpdateTransUnit failure " + e, e); eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyUpdateFailed(e.getLocalizedMessage()))); display.getTableModel().clearCache(); display.reloadPage(); } @Override public void onSuccess(UpdateTransUnitResult result) { eventBus.fireEvent(new NotificationEvent(Severity.Info, messages.notifyUpdateSaved())); UndoableTransUnitUpdateAction undoAction = new UndoableTransUnitUpdateAction(updateTransUnit, result, curRowIndex, curPage); undoAction.setHandler(undoableTransUnitUpdateHandler); eventBus.fireEvent(new UndoAddEvent(undoAction)); // Need to reload cached table if page changes // TODO need focus on curRow, its not focus at the moment if (curPage != display.getCurrentPage()) { display.getTargetCellEditor().cancelEdit(); display.getTableModel().clearCache(); display.reloadPage(); } } }); stopEditing(rowValue); return true; } public void onCancel(TransUnit rowValue) { // stopEditing(rowValue); } public void updatePageAndRowIndex(int row) { curPage = display.getCurrentPage(); // Convert row number to row Index in table curRowIndex = curPage * TableConstants.PAGE_SIZE + row; Log.info("Current Row Index" + curRowIndex); } @Override public void gotoNextRow(int row) { updatePageAndRowIndex(row); int rowIndex = curPage * TableConstants.PAGE_SIZE + row + 1; if (rowIndex < display.getTableModel().getRowCount()) { gotoRow(rowIndex); } } @Override public void gotoPrevRow(int row) { updatePageAndRowIndex(row); int rowIndex = curPage * TableConstants.PAGE_SIZE + row - 1; if (rowIndex >= 0) { gotoRow(rowIndex); } } @Override public void nextFuzzyNewIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex < display.getTableModel().getRowCount()) gotoNextState(true, true); } @Override public void prevFuzzyNewIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex > 0) gotoPrevState(true, true); } @Override public void nextFuzzyIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex < display.getTableModel().getRowCount()) gotoNextState(false, true); } @Override public void prevFuzzyIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex > 0) gotoPrevState(false, true); } @Override public void nextNewIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex < display.getTableModel().getRowCount()) gotoNextState(true, false); } @Override public void prevNewIndex(int row) { updatePageAndRowIndex(row); if (curRowIndex > 0) gotoPrevState(true, false); } @Override public void gotoRow(int rowIndex) { curPage = display.getCurrentPage(); int pageNum = rowIndex / (MAX_PAGE_ROW + 1); int rowNum = rowIndex % (MAX_PAGE_ROW + 1); if (pageNum != curPage) { display.gotoPage(pageNum, false); } selectTransUnit(display.getTransUnitValue(rowNum)); display.gotoRow(rowNum); if (pageNum != curPage) { display.getTargetCellEditor().cancelEdit(); } } }; private void stopEditing(TransUnit rowValue) { dispatcher.execute(new EditingTranslationAction(rowValue.getId(), EditState.StopEditing), new AsyncCallback<EditingTranslationResult>() { @Override public void onSuccess(EditingTranslationResult result) { // eventBus.fireEvent(new NotificationEvent(Severity.Warning, // "TransUnit Editing is finished")); } @Override public void onFailure(Throwable caught) { Log.error("EditingTranslationAction failure " + caught, caught); eventBus.fireEvent(new NotificationEvent(Severity.Error, messages.notifyStopFailed())); } }); } boolean isReqComplete = true; private void cacheNextState(final NavigationCacheCallback callBack, final List<Long> cacheList, final boolean isNewState, final boolean isFuzzyState) { isReqComplete = false; dispatcher.execute(new GetTransUnitsNavigation(selectedTransUnit.getId().getId(), 3, false, findMessage, isNewState, isFuzzyState), new AsyncCallback<GetTransUnitsNavigationResult>() { @Override public void onSuccess(GetTransUnitsNavigationResult result) { isReqComplete = true; if (!result.getUnits().isEmpty()) { for (Long offset : result.getUnits()) { cacheList.add(offset + curRowIndex); } callBack.next(isNewState, isFuzzyState); } } @Override public void onFailure(Throwable caught) { Log.error("GetTransUnitsStates failure " + caught, caught); } }); } private void cachePrevState(final NavigationCacheCallback callBack, final List<Long> cacheList, final boolean isNewState, final boolean isFuzzyState) { isReqComplete = false; dispatcher.execute(new GetTransUnitsNavigation(selectedTransUnit.getId().getId(), 3, true, findMessage, isNewState, isFuzzyState), new AsyncCallback<GetTransUnitsNavigationResult>() { @Override public void onSuccess(GetTransUnitsNavigationResult result) { isReqComplete = true; if (!result.getUnits().isEmpty()) { for (Long offset : result.getUnits()) { cacheList.add(curRowIndex - offset); } callBack.prev(isNewState, isFuzzyState); } } @Override public void onFailure(Throwable caught) { Log.error("GetTransUnitsStates failure " + caught, caught); } }); } NavigationCacheCallback cacheCallback = new NavigationCacheCallback() { @Override public void next(boolean isNewState, boolean isFuzzyState) { gotoNextState(isNewState, isFuzzyState); } @Override public void prev(boolean isNewState, boolean isFuzzyState) { gotoPrevState(isNewState, isFuzzyState); } }; private void gotoNextState(boolean isNewState, boolean isFuzzyState) { if (isNewState && isFuzzyState) { Log.info("go to Next Fuzzy Or Untranslated State"); transIdPrevNewFuzzyCache.clear(); gotoNextState(transIdNextNewFuzzyCache, true, true); } else if (isNewState) { Log.info("go to Next Untranslated State"); transIdPrevNewCache.clear(); gotoNextState(transIdNextNewCache, true, false); } else if (isFuzzyState) { Log.info("go to Next Fuzzy State"); transIdPrevFuzzyCache.clear(); gotoNextState(transIdNextFuzzyCache, false, true); } } private void gotoPrevState(boolean isNewState, boolean isFuzzyState) { if (isNewState && isFuzzyState) { Log.info("go to Prev Fuzzy Or Untranslated State"); // Clean the cache for Next Fuzzy to avoid issues about cache is // obsolete transIdNextNewFuzzyCache.clear(); gotoPrevState(transIdPrevNewFuzzyCache, true, true); } else if (isNewState) { Log.info("go to Prev Untranslated State"); // Clean the cache for Next Fuzzy to avoid issues about cache is // obsolete transIdNextNewCache.clear(); gotoPrevState(transIdPrevNewCache, true, false); } else if (isFuzzyState) { Log.info("go to Prev Fuzzy State"); // Clean the cache for Next Fuzzy to avoid issues about cache is // obsolete transIdNextFuzzyCache.clear(); gotoPrevState(transIdPrevFuzzyCache, false, true); } } private void gotoPrevState(List<Long> transIdPrevCache, boolean isNewState, boolean isFuzzyState) { // If the catch of row is empty and request is complete, generate // one if (transIdPrevCache.isEmpty()) { if (isReqComplete) cachePrevState(cacheCallback, transIdPrevCache, isNewState, isFuzzyState); } else { int size = transIdPrevCache.size(); int offset = transIdPrevCache.get(size - 1).intValue(); if (curRowIndex > offset) { for (int i = 0; i < size; i++) { int newRowIndex = transIdPrevCache.get(i).intValue(); if (curRowIndex > newRowIndex) { display.getTargetCellEditor().cancelEdit(); tableModelHandler.gotoRow(newRowIndex); break; } } } else { transIdPrevCache.clear(); cachePrevState(cacheCallback, transIdPrevCache, isNewState, isFuzzyState); } } } private void gotoNextState(List<Long> transIdNextCache, boolean isNewState, boolean isFuzzyState) { // If the cache of next is empty, generate one if (transIdNextCache.isEmpty()) { if (isReqComplete) cacheNextState(cacheCallback, transIdNextCache, isNewState, isFuzzyState); } else { int size = transIdNextCache.size(); int offset = transIdNextCache.get(size - 1).intValue(); if (curRowIndex < offset) { for (int i = 0; i < size; i++) { int newRowIndex = transIdNextCache.get(i).intValue(); if (curRowIndex < newRowIndex) { display.getTargetCellEditor().cancelEdit(); tableModelHandler.gotoRow(newRowIndex); break; } } } else { transIdNextCache.clear(); cacheNextState(cacheCallback, transIdNextCache, isNewState, isFuzzyState); } } } public TransUnit getSelectedTransUnit() { return selectedTransUnit; } @Override protected void onUnbind() { } @Override public void onRevealDisplay() { } @Override public void gotoFirstPage() { display.gotoFirstPage(); } @Override public void gotoLastPage() { display.gotoLastPage(); } @Override public void gotoNextPage() { display.gotoNextPage(); } @Override public void gotoPage(int page, boolean forced) { display.gotoPage(page, forced); } @Override public void gotoPreviousPage() { display.gotoPreviousPage(); } public void addPageChangeHandler(PageChangeHandler handler) { display.getPageChangeHandlers().addPageChangeHandler(handler); } public void addPageCountChangeHandler(PageCountChangeHandler handler) { display.getPageCountChangeHandlers().addPageCountChangeHandler(handler); } public DocumentId getDocumentId() { return documentId; } /** * Selects the given TransUnit and fires associated TU Selection event * * @param transUnit the new TO to select */ public void selectTransUnit(TransUnit transUnit) { if (selectedTransUnit == null || !transUnit.getId().equals(selectedTransUnit.getId())) { selectedTransUnit = transUnit; Log.info("SelectedTransUnit " + selectedTransUnit.getId()); // Clean the cache when we click the new entry if (!transIdNextNewFuzzyCache.isEmpty()) transIdNextNewFuzzyCache.clear(); if (!transIdPrevNewFuzzyCache.isEmpty()) transIdPrevNewFuzzyCache.clear(); eventBus.fireEvent(new TransUnitSelectionEvent(selectedTransUnit)); } } }
Remove unused event handler
server/zanata-war/src/main/java/org/zanata/webtrans/client/editor/table/TableEditorPresenter.java
Remove unused event handler
<ide><path>erver/zanata-war/src/main/java/org/zanata/webtrans/client/editor/table/TableEditorPresenter.java <ide> <ide> })); <ide> <del> registerHandler(eventBus.addHandler(ButtonDisplayChangeEvent.getType(), new ButtonDisplayChangeEventHandler() <del> { <del> <del> @Override <del> public void onButtonDisplayChange(ButtonDisplayChangeEvent event) <del> { <del> display.getTargetCellEditor().setShowOperationButtons(event.isShowButtons()); <del> display.setShowCopyButtons(event.isShowButtons()); <del> } <del> })); <del> <ide> registerHandler(eventBus.addHandler(EnterKeyEnabledEvent.getType(), new EnterKeyEnabledEventHandler() <ide> { <ide>
JavaScript
unlicense
e0cb97cf428fd262cc0bc0bb03df22921a76fd68
0
mikegagnon/hundo,mikegagnon/hundo
/** * Unless otherwise noted, the contents of this file are free and unencumbered * software released into the public domain. * See UNLICENSE.txt */ var hundo = {} /** * Enums ******************************************************************************/ hundo.PieceTypeEnum = { BALL: "BALL", BLOCK: "BLOCK", GOAL: "GOAL", ICE: "ICE", ARROW: "ARROW", GBLOCK: "GBLOCK" } hundo.DirectionEnum = { UP: "UP", DOWN: "DOWN", LEFT: "LEFT", RIGHT: "RIGHT", NODIR: "NODIR" } /** * Function common to all pieces ******************************************************************************/ hundo.equalsTypeRowCol = function(a, b) { return a.type == b.type && a.row == b.row && a.col == b.col; } /** * Block board pieces ******************************************************************************/ // id is a uuid relative to board pieces hundo.Block = function(id, row, col) { this.id = id; this.type = hundo.PieceTypeEnum.BLOCK; this.row = row; this.col = col; this.origRow = row; this.origCol = col; } // returns true iff the piece were pushed in direction dir hundo.Block.prototype.nudge = function(dir, board) { return [false, []]; } hundo.Block.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece); } /** * Ball board piece ******************************************************************************/ hundo.Ball = function(id, row, col, dir) { this.id = id; this.type = hundo.PieceTypeEnum.BALL; this.row = row; this.col = col; this.origRow = row; this.origCol = col; this.dir = dir; } hundo.Ball.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece) && this.dir == piece.dir; } hundo.Ball.prototype.nudge = function(dir, board, commit) { var [dr, dc] = hundo.Board.drdc(dir); var row = this.row + dr; var col = this.col + dc; var [nudged, animations] = board.nudge(row, col, dir, commit) if (nudged) { if (commit) { board.movePiece(this, row, col); } animations.push( { "move": { "ball": this, "dir": dir, } }); return [true, animations]; } else { return [false, animations]; } } /** * Goal board pieces ******************************************************************************/ hundo.Goal = function(id, row, col, dir) { this.id = id; this.type = hundo.PieceTypeEnum.GOAL; this.row = row; this.col = col; this.origRow = row; this.origCol = col; this.dir = dir; } hundo.Goal.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece) && this.dir == piece.dir; } hundo.Goal.getPusher = function(row, col, dir) { var [dr, dc] = hundo.Board.drdc(dir); dr *= -1; dc *= -1; return [row + dr, col + dc]; } hundo.oppositeDir = function(dir) { if (dir == hundo.DirectionEnum.UP) { return hundo.DirectionEnum.DOWN; } else if (dir == hundo.DirectionEnum.DOWN) { return hundo.DirectionEnum.UP; } else if (dir == hundo.DirectionEnum.LEFT) { return hundo.DirectionEnum.RIGHT; } else if (dir == hundo.DirectionEnum.RIGHT) { return hundo.DirectionEnum.LEFT; } else { console.error("Bad direction: " + dir) } } // dir is the direction of the momentum of piece doing the nudging // returns true if this piece can accept the nudging piece hundo.Goal.prototype.nudge = function(dir, board) { var [pusherRow, pusherCol] = hundo.Goal.getPusher(this.row, this.col, dir); // gblocks not allowed in arrows if (board.getPiece(pusherRow, pusherCol, hundo.PieceTypeEnum.GBLOCK)) { return [false, []]; } return [this.dir == hundo.oppositeDir(dir), []]; } /** * Ice cube board pieces ******************************************************************************/ hundo.Ice = function(id, row, col) { this.id = id; this.type = hundo.PieceTypeEnum.ICE; this.row = row; this.col = col; this.origRow = row; this.origCol = col; } hundo.Ice.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece); } hundo.Ice.prototype.nudge = function(dir, board, commit) { // If ice is in the goal, then it can't move var occupyGoal = false; _.each(board.matrix[this.row][this.col], function(piece) { if (piece.type == hundo.PieceTypeEnum.GOAL) { occupyGoal = true; } }) if (occupyGoal) { return [false, []]; } var [dr, dc] = hundo.Board.drdc(dir); var row = this.row + dr; var col = this.col + dc; var [nudged, animations] = board.nudge(row, col, dir, commit) if (nudged) { if (commit) { board.movePiece(this, row, col); } animations.push( { "move": { "ice": this, "dir": dir } }); return [true, animations]; } else { return [false, animations]; } } /** * Arrow board pieces ******************************************************************************/ hundo.Arrow = function(id, row, col, dir) { this.id = id; this.type = hundo.PieceTypeEnum.ARROW; this.row = row; this.col = col; this.origRow = row; this.origCol = col; this.dir = dir; } hundo.Arrow.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece) && this.dir == piece.dir; } hundo.Arrow.getPusher = hundo.Goal.getPusher; // TODO: implement hundo.Arrow.prototype.nudge = function(dir, board) { var [pusherRow, pusherCol] = hundo.Arrow.getPusher(this.row, this.col, dir); // gblocks not allowed in arrows if (board.getPiece(pusherRow, pusherCol, hundo.PieceTypeEnum.GBLOCK)) { return [false, []]; } var result = this.dir == dir || ( board.matrix[this.row][this.col].length == 2 && board.getPiece(this.row, this.col, hundo.PieceTypeEnum.BALL) && this.dir == hundo.oppositeDir(dir)) return [result, []]; } /** * Gblock board pieces ******************************************************************************/ hundo.Gblock = function(id, row, col, groupNum) { this.id = id; this.type = hundo.PieceTypeEnum.GBLOCK; this.row = row; this.col = col; this.origRow = row; this.origCol = col; this.groupNum = groupNum; } hundo.Gblock.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece) && this.groupNum == piece.groupNum; } hundo.Gblock.prototype.nudge = function(dir, board, commit, fromGblock) { // nudge this block's neighbors, but only if this nudge isn't already // part of a neighbor check if (!fromGblock) { var neighbors = board.gblocks[this.groupNum]; var THIS = this; // nudgeResults == the list of nudge results for each neighbor var nudgeResults = _.map(neighbors, function(neighbor) { return neighbor.nudge(dir, board, commit, true); }); // If there are any false values in nudgeResults, then this nudge // fails var i = _.findIndex(nudgeResults, function(result) { return !result[0]; }); // Get the animations of the neighbors var animations = _.flatMap(nudgeResults, function(result) { return result[1]; }); if (i >= 0) { return [false, animations]; } else { return [true, animations]; } } else { var [dr, dc] = hundo.Board.drdc(dir); var row = this.row + dr; var col = this.col + dc; var nudged, animations; var pushingIntoGblock; // TODO: factor out this if expression into a function if (row >= 0 && row < board.numRows && col >= 0 && col < board.numCols) { pushingIntoGblock = board.getPiece(row, col, hundo.PieceTypeEnum.GBLOCK); } if (row < 0 || row >= board.numRows || col < 0 || col >= board.numCols) { nudged = false; animations = []; } else if (pushingIntoGblock && pushingIntoGblock.groupNum == this.groupNum) { nudged = true; animations = []; } else { var [nudged, animations] = board.nudge(row, col, dir, commit) } if (nudged) { if (commit) { board.movePiece(this, row, col); } animations.push( { "move": { "gblock": this, "dir": dir } }); return [true, animations]; } else { return [false, animations]; } } } /** * Generates uuids for board pieces ******************************************************************************/ hundo.IdGenerator = function() { this.nextId = 0; } // I'll be impressed if this ever overflows hundo.IdGenerator.prototype.next = function() { return this.nextId++; } hundo.idGenerator = new hundo.IdGenerator(); /** * Board encapsulates the model of the game (MVC style) ******************************************************************************/ // TODO: Assume boardConfig is untrusted hundo.Board = function(boardConfig, idGen) { // is the ball at rest? this.atRest = true; // is the board finished? namely, if the ball has gone out // of bounds or reached a goal this.done = false; this.solved = false; this.numRows = boardConfig.numRows; this.numCols = boardConfig.numCols; // The set of pieces that have moved out of bounds this.oob = []; // this.gblocks[gblock.groupNum] == the set of gblocks in that group this.gblocks = {} // this.matrix[row][call] == array of piece objects this.matrix = new Array(); for (var i = 0; i < this.numRows; i++) { this.matrix[i] = new Array(); for (var j = 0; j < this.numCols; j++) { this.matrix[i][j] = new Array(); } } var THIS = this; // TODO: check return values for addPiece // Add blocks to the matrix _.each(boardConfig.blocks, function(block){ var piece = new hundo.Block(idGen.next(), block.row, block.col) THIS.addPiece(piece); }); // Add the ball to the matrix if ("ball" in boardConfig) { var row = boardConfig.ball.row; var col = boardConfig.ball.col; var ball = new hundo.Ball(idGen.next(), row, col, hundo.DirectionEnum.NODIR); this.addPiece(ball); } // Add goals to the matrix _.each(boardConfig.goals, function(goal) { var row = goal.row; var col = goal.col; var dir = goal.dir; var piece = new hundo.Goal(idGen.next(), row, col, dir); THIS.addPiece(piece); }); // Add ice to the matrix _.each(boardConfig.ice, function(ice) { var row = ice.row; var col = ice.col; var piece = new hundo.Ice(idGen.next(), row, col); THIS.addPiece(piece); }); // Add arrows to the matrix _.each(boardConfig.arrows, function(arrow) { var row = arrow.row; var col = arrow.col; var dir = arrow.dir; var piece = new hundo.Arrow(idGen.next(), row, col, dir); THIS.addPiece(piece); }); // Add gblocks to the matrix _.each(boardConfig.gblocks, function(gblock) { var row = gblock.row; var col = gblock.col; var groupNum = gblock.groupNum; var piece = new hundo.Gblock(idGen.next(), row, col, groupNum); THIS.addPiece(piece); }); } // TODO: is there a better way to do this? hundo.setEq = function(set1, set2) { if (set1.length != set2.length) { return false; } var matches = true; _.each(set1, function(x) { var singleMatch = false; _.each(set2, function(y) { if (x.eq(y)) { singleMatch = true; } }) if (!singleMatch) { matches = false; } }); return matches; } hundo.Board.prototype.eq = function(board) { if (this.numRows != board.numRows || this.numCols != board.numCols) { return false; } if (this.ball && !board.ball || !this.ball && board.ball) { return false; } if (this.ball && board.ball) { if (this.ball.row != board.ball.row || this.ball.col != board.ball.col) { return false; } } for (var r = 0; r < this.numRows; r++) { for (var c = 0; c < this.numCols; c++) { if (!hundo.setEq(this.matrix[r][c], board.matrix[r][c])) { return false; } } } return true; } hundo.Board.prototype.isEmptyCell = function(row, col) { return this.matrix[row][col].length == 0; } hundo.Board.prototype.hasBall = function() { var balls = this.getPieces(function(piece) { return piece.type == hundo.PieceTypeEnum.BALL; }); return balls.length >= 1; } hundo.Board.prototype.clearCell = function(row, col) { if (typeof this.ball != "undefined" && this.ball.row == row && this.ball.col == col) { this.ball = undefined; } this.matrix[row][col] = []; } hundo.Board.prototype.getPiece = function(row, col, type) { return _.find(this.matrix[row][col], function(piece){ return piece.type == type; }); } hundo.Board.prototype.canAddPiece = function(piece) { if (piece.type == hundo.PieceTypeEnum.BALL && this.hasBall()) { return false; } else if (piece.type == hundo.PieceTypeEnum.BLOCK || piece.type == hundo.PieceTypeEnum.BALL) { return this.matrix[piece.row][piece.col].length == 0; } // TOD: allow ICE to be added to arrow else if (piece.type == hundo.PieceTypeEnum.ICE) { return this.matrix[piece.row][piece.col].length == 0 || (this.matrix[piece.row][piece.col].length == 1 && this.getPiece(piece.row, piece.col, hundo.PieceTypeEnum.GOAL)); } else if (piece.type == hundo.PieceTypeEnum.GOAL) { return this.matrix[piece.row][piece.col].length == 0 || (this.matrix[piece.row][piece.col].length == 1 && (this.getPiece(piece.row, piece.col, hundo.PieceTypeEnum.ICE))); } else if (piece.type == hundo.PieceTypeEnum.ARROW) { return this.matrix[piece.row][piece.col].length == 0 || (this.matrix[piece.row][piece.col].length == 1 && (this.getPiece(piece.row, piece.col, hundo.PieceTypeEnum.ICE) || this.getPiece(piece.row, piece.col, hundo.PieceTypeEnum.BALL))); } else if (piece.type == hundo.PieceTypeEnum.GBLOCK) { return this.matrix[piece.row][piece.col].length == 0; } else { console.error("Unimplemented addPiece"); console.error(piece); return false; } } hundo.Board.prototype.addPiece = function(piece) { if (this.canAddPiece(piece)) { this.matrix[piece.row][piece.col].push(piece) if (piece.type == hundo.PieceTypeEnum.BALL) { this.ball = piece; } else if (piece.type == hundo.PieceTypeEnum.GBLOCK) { if (!(piece.groupNum in this.gblocks)){ this.gblocks[piece.groupNum] = []; } this.gblocks[piece.groupNum].push(piece); } return true; } else { return false; } } hundo.Board.prototype.reset = function() { var THIS = this; // moved is the set of all pieces that have moved var moved = this.getPieces(function(piece) { return (piece.row != piece.origRow) || (piece.col != piece.origCol); }); _.each(moved, function(piece){ THIS.movePiece(piece, piece.origRow, piece.origCol); }); this.done = false; this.solved = false; return moved; } hundo.Board.prototype.setDir = function(direction) { this.ball.dir = direction; this.atRest = false; } // func(piece) should return true iff the piece is of the type being gotten hundo.Board.prototype.getPieces = function(func) { var pieces = []; _.each(this.matrix, function(row) { _.each(row, function(col) { _.each(col, function(piece) { if (func(piece)) { pieces.push(piece); } }) }) }); _.each(this.oob, function(piece){ if (func(piece)) { pieces.push(piece); } }) return pieces; } hundo.Board.prototype.getBlocks = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.BLOCK; }); }; hundo.Board.prototype.getBalls = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.BALL; }); }; hundo.Board.prototype.getGoals = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.GOAL; }); }; hundo.Board.prototype.getIce = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.ICE; }); }; hundo.Board.prototype.getArrows = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.ARROW; }); }; hundo.Board.prototype.getGblocks = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.GBLOCK; }); }; hundo.Board.prototype.getJson = function() { var j = { numRows: this.numRows, numCols: this.numCols, blocks: _.map(this.getBlocks(), function(block) { return { row: block.row, col: block.col } }), goals: _.map(this.getGoals(), function(goal) { return { row: goal.row, col: goal.col, dir: goal.dir } }), ice: _.map(this.getIce(), function(ice) { return { row: ice.row, col: ice.col } }), arrows: _.map(this.getArrows(), function(arrow) { return { row: arrow.row, col: arrow.col, dir: arrow.dir } }), gblocks: _.map(this.getGblocks(), function(gblock) { return { row: gblock.row, col: gblock.col, groupNum: gblock.groupNum } }), } if (typeof this.ball != "undefined") { j.ball = { row: this.ball.row, col: this.ball.col } } return j; } // removes the first element in array for which func(element) is true // if an element is removed, returns the index of the element removed // otherwise, returns -1 hundo.arrayRemove = function(array, func) { var i = _.findIndex(array, func); if (i < 0) { return -1; } array.splice(i, 1); return i; } hundo.Board.prototype.movePiece = function(piece, row, col) { var i; if (piece.row < 0 || piece.row >= this.numRows || piece.col < 0 || piece.col >= this.numCols) { i = hundo.arrayRemove(this.oob, function(p) { return p.id == piece.id; }) } else { var pieces = this.matrix[piece.row][piece.col]; i = hundo.arrayRemove(pieces, function(p) { return p.id == piece.id; }) } if (i == -1) { console.error("Could not remove piece"); return; } if (row < 0 || row >= this.numRows || col < 0 || col >= this.numCols) { this.oob.push(piece); } else { // add the piece to its new location this.matrix[row][col].push(piece); } piece.row = row; piece.col = col; } // see hundo.nudge hundo.Board.prototype.nudge = function(row, col, dir, commit) { if (row < 0 || row >= this.numRows || col < 0 || col >= this.numCols) { return [true, []]; } var pieces = this.matrix[row][col]; var result = true; var animations = [] var THIS = this; _.each(pieces, function(piece) { var [nudged, newAnimations] = piece.nudge(dir, THIS, commit); animations = _.concat(animations, newAnimations); if (!nudged) { result = false; } }); return [result, animations]; } hundo.Board.prototype.checkSolved = function() { var pieces = this.matrix[this.ball.row][this.ball.col] var result = _.filter(pieces, function(piece){ return piece.type == hundo.PieceTypeEnum.GOAL; }) return result.length == 1; } hundo.Board.drdc = function(direction) { var dr = 0, dc = 0; if (direction == hundo.DirectionEnum.UP) { dr = -1; } else if (direction == hundo.DirectionEnum.DOWN) { dr = 1; } else if (direction == hundo.DirectionEnum.LEFT) { dc = -1; } else if (direction == hundo.DirectionEnum.RIGHT) { dc = 1; } else { console.error("Bad direction: " + direction); return null; } return [dr, dc]; } // returns null on fatal error // else, returns an animation object, which describes how the // the step should be animated hundo.Board.prototype.step = function() { var direction = this.ball.dir; if (direction == hundo.DirectionEnum.NODIR) { console.error("Ball must have a direction to step"); return null; } var [dr, dc] = hundo.Board.drdc(direction); var newRow = this.ball.row + dr; var newCol = this.ball.col + dc; // Check for out of bounds if (newRow < 0 || newRow >= this.numRows || newCol < 0 || newCol >= this.numCols) { this.atRest = true; this.done = true; this.ball.dir = hundo.DirectionEnum.NODIR; this.movePiece(this.ball, newRow, newCol); return [{ "move": { "ball": this.ball, "dir": direction, "solved": false }, }]; } var [nudged, animations] = this.nudge(this.ball.row, this.ball.col, this.ball.dir, false); if (nudged) { // now commit the nudge [nudged, animations] = this.nudge(this.ball.row, this.ball.col, this.ball.dir, true); if (this.checkSolved()) { this.solved = true; this.atRest = true; this.ball.dir = hundo.DirectionEnum.NODIR; } return animations; } else { this.ball.dir = hundo.DirectionEnum.NODIR; this.atRest = true; var recipients = []; var gblock = this.getPiece(newRow, newCol, hundo.PieceTypeEnum.GBLOCK); if (gblock) { recipients = _.concat(recipients, this.gblocks[gblock.groupNum]); } recipients = _.concat(recipients, this.matrix[newRow][newCol].slice(0)); recipients = _.concat(recipients, this.matrix[this.ball.row][this.ball.col]); return [{ "collide": { "dir": direction, "recipients": recipients } }]; } } // Deep copy the board hundo.Board.prototype.clone = function() { var config = this.getJson(); return new hundo.Board(config, hundo.idGenerator); } /** * Code not released into the public domain ******************************************************************************/ // Thank you nicbell! https://gist.github.com/nicbell/6081098 Object.compare = function (obj1, obj2) { //Loop through properties in object 1 for (var p in obj1) { //Check property exists on both objects if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) return false; switch (typeof (obj1[p])) { //Deep compare objects case 'object': if (!Object.compare(obj1[p], obj2[p])) return false; break; //Compare function code case 'function': if (typeof (obj2[p]) == 'undefined' || (p != 'compare' && obj1[p].toString() != obj2[p].toString())) return false; break; //Compare values default: if (obj1[p] != obj2[p]) return false; } } //Check object 2 for any extra properties for (var p in obj2) { if (typeof (obj1[p]) == 'undefined') return false; } return true; }; /** * Solver solves puzzles ******************************************************************************/ // BUG: Solver fails here: level-editor.html?level=fl86-455a848a99-6b2-7988-- // But then if you go right, the solver works // Thank you Wikipedia! // https://en.wikipedia.org/wiki/Graph_traversal#Pseudocode hundo.Solver = function(board) { this.edges = []; this.winningEdges = []; // vertices this.boards = []; if (typeof board.ball == "undefined" || typeof board.ball.row == "undefined" || typeof board.ball.col == "undefined") { return; } this.winningEdges = this.explore(board); } hundo.Solver.prototype.hasExploredVertex = function(board1) { var matches = _.flatMap(this.boards, function(board2) { if (board1.eq(board2)) { return [true]; } else { return []; } }) if (matches.length == 0) { return false; } else if (matches.length == 1) { return true; } else { console.error("multiple matches for has explored: " + matches); } } hundo.Solver.prototype.hasExploredEdge = function(edge1) { var matches = _.flatMap(this.edges, function(edge2) { if (Object.compare(edge1[0].getJson(), edge2[0].getJson()) && Object.compare(edge1[1].getJson(), edge2[1].getJson())) { return [true]; } else { return []; } }) if (matches.length == 0) { return false; } else if (matches.length == 1) { return true; } else { console.error("multiple matches for has explored: " + matches); } } // push the ball in direction dir hundo.Solver.move = function(board, dir) { board.setDir(dir); board.step(); while (!board.done && !board.solved && !board.atRest) { board.step(); } return board; } hundo.Solver.prototype.getCellEdges = function() { return _.map(this.edges, function(edge) { var [b1, b2] = edge; return { row1: b1.ball.row, col1: b1.ball.col, row2: b2.ball.row, col2: b2.ball.col } }); } hundo.Solver.prototype.getCellWinningEdges = function() { return _.map(this.winningEdges, function(edge) { var [b1, b2] = edge; return { row1: b1.ball.row, col1: b1.ball.col, row2: b2.ball.row, col2: b2.ball.col } }); } hundo.Solver.prototype.explore = function(board) { this.boards.push(board); // if out of bounds or solved if (board.ball.row < 0 || board.ball.row >= board.numRows || board.ball.col < 0 || board.ball.col >= board.numCols || board.solved) { return []; } var boards = []; boards[0] = hundo.Solver.move(board.clone(), hundo.DirectionEnum.UP); boards[1] = hundo.Solver.move(board.clone(), hundo.DirectionEnum.DOWN); boards[2] = hundo.Solver.move(board.clone(), hundo.DirectionEnum.LEFT); boards[3] = hundo.Solver.move(board.clone(), hundo.DirectionEnum.RIGHT); var THIS = this; var winningEdges = []; _.each(boards, function(newBoard, i) { var edge = [board, newBoard] if (!THIS.hasExploredEdge(edge)) { if (!THIS.hasExploredVertex(newBoard)) { THIS.edges.push(edge); var w = THIS.explore(newBoard) winningEdges = _.concat(winningEdges, w) if (w.length > 0 || newBoard.solved) { winningEdges.push(edge); } } } }); return winningEdges; } /** * The Hundo class is what clients use to create a Hundo game ******************************************************************************/ Hundo = function(config) { // clone hundo.defaultVizConfig so it doesn't get clobbered by extend var defaultVizConfig = jQuery.extend(true, {}, hundo.defaultVizConfig); if (!"vizConfig" in config) { config.viz = {}; } config.viz = $.extend(defaultVizConfig, config.viz); viz = new hundo.Viz(config); hundo.instances[config.id] = viz; if (_.size(hundo.instances) == 1) { hundo.vizz = viz; } } /** * Viz encapsulates the view and the controller ******************************************************************************/ hundo.Viz = function(config) { // TODO: validate vizConfig and levels this.vizConfig = config.viz; this.maker = { on: config.maker, play: false, mouseRow: undefined, mouseCol: undefined, showSolution: false, showGraph: false, } var levelFromUrl = hundo.Viz.levelFromUrl(); if (levelFromUrl) { this.maker.on = true; } if (this.maker.on) { if (levelFromUrl) { this.levels = [levelFromUrl]; } else { this.levels = [ { numRows: config.viz.numRows, numCols: config.viz.numCols } ] } config.viz.levelSelect = false; this.paletteSelection = { type: hundo.PieceTypeEnum.BLOCK }; } else { this.levels = config.levels; } this.id = config.id; this.level = 0; this.levelMax = config.viz.levelMax; this.drawSvgGrid(); if (config.viz.playButton) { this.addPlayButton(); } if (config.viz.levelSelect) { this.addLevelSelect(); } if (this.maker.on) { this.addSave(); this.addShowSolution(); this.addPalette(); this.addLevelUrlField(); } this.boardSvg = d3.select("#" + this.boardSvgId()) .attr("width", this.vizConfig.numCols * this.vizConfig.cellSize) .attr("height", this.vizConfig.numRows * this.vizConfig.cellSize) .on("click", hundo.Viz.clickBoard); this.boardSvg.select("#background") .attr("width", this.vizConfig.numCols * this.vizConfig.cellSize) .attr("height", this.vizConfig.numRows * this.vizConfig.cellSize) .attr("style", "fill:black"); this.boardSvg.select("#perim") .attr("width", this.vizConfig.numCols * this.vizConfig.cellSize) .attr("height", this.vizConfig.numRows * this.vizConfig.cellSize) this.drawGrid(); this.idGen = hundo.idGenerator; var boardConfig = this.levels[0]; this.board = new hundo.Board(boardConfig, this.idGen); this.drawBoard(); this.updateLevelSelect(); this.boardSvg .on("mousemove", hundo.Viz.mousemove) .on("mouseleave", hundo.Viz.mouseleave); } // TODO: assume untrusted input and write tests hundo.Viz.getParams = function() { var url = window.location.href; var params = _.split(url, "?")[1] if (typeof params == "undefined") { return {} } var paramList = params.split("&"); var paramObj = {} _.each(paramList, function(param) { var [key, value] = param.split("="); paramObj[key] = value; }); return paramObj } hundo.Viz.levelFromUrl = function() { var params = hundo.Viz.getParams() if (!("level" in params)) { return false; } var compressedLevel = decodeURIComponent(params.level); var level = hundo.Compress.decompressLevel(compressedLevel); return level; } hundo.Viz.prototype.removeHighlight = function() { this.boardSvg.select("#" + this.highlightId()) .remove(); } // BUG TODO: it seems that mousemove and mouseleave are interferring // with each other because mousemove updates the highlighter // on every pixel change (as opposed to only updating the // highlighter on cell changes). mouseleave only works when // the mouse exits the board at high speed. hundo.Viz.prototype.mousemove = function(x, y) { if (!this.maker.on || this.maker.play) { return; } var [row, col] = this.cellFromXY(x, y) this.removeHighlight(); if (this.paletteSelection.delete) { if (this.board.isEmptyCell(row, col)) { return; } } else { var piece = this.getPieceFromPalette(row, col); if (!this.board.canAddPiece(piece)) { return; } } this.maker.mouseRow = row; this.maker.mouseCol = col; this.boardSvg.selectAll() .data([0]) .enter() .append("rect") .attr("x", col * this.vizConfig.cellSize) .attr("y", row * this.vizConfig.cellSize) .attr("height", this.vizConfig.cellSize) .attr("width", this.vizConfig.cellSize) .attr("style", "fill:#3D8E37; fill-opacity: 0.5; cursor: pointer;") .attr("id", this.highlightId()) } hundo.Viz.mousemove = function() { var [x, y] = d3.mouse(this); var id = hundo.Viz.getIdFromBoardSvg(this); var viz = hundo.instances[id] viz.mousemove(x, y); } hundo.Viz.prototype.mouseleave = function() { this.removeHighlight(); } hundo.Viz.mouseleave = function() { var id = hundo.Viz.getIdFromBoardSvg(this); var viz = hundo.instances[id] viz.mouseleave(); } hundo.Viz.prototype.drawSvgGrid = function(name) { var blockTemplate = ` <rect x="0" y="0" width="20" height="20" fill="#888" /> <path d="M0 0 L26 0 L20 6 L6 6 Z" stroke="none" fill="#aaa"/> <path d="M0 0 L6 6 L6 20 L0 26 Z" stroke="none" fill="#aaa"/> <path d="M26 0 L20 6 L20 20 L26 26 Z" stroke="none" fill="#666"/> <path d="M26 26 L20 20 L6 20 L0 26 Z" stroke="none" fill="#666"/>` var svgContents = ` <div> <svg id="${this.boardSvgId(name)}" xmlns="http://www.w3.org/2000/svg"> <defs> <g id="blockTemplate" height="20" width="20" > ${blockTemplate} </g> <g id="goalTemplate" height="20" width="20"> <polygon points="0,26 0,13 13,26" style="fill:red" /> <polygon points="13,26 26,13 26,26" style="fill:red" /> <rect x="0" y="23" width="26" height="3" fill="red" /> </g> <g id="arrowTemplate" height="20" width="20"> <polygon points="0,13 13,0 26,13 20,13 20,26 6,26 6,13" style="fill:yellow; stroke-width: 1; stroke: black;" /> </g> <g id="gblockTemplate-0" height="26" width="26"> ${blockTemplate} <rect x="0" y="0" width="26" height="26" style="fill:red" fill-opacity="0.3" /> </g> <g id="gblockTemplate-1" height="26" width="26"> <rect x="0" y="0" width="20" height="20" fill="#888" /> ${blockTemplate} <rect x="0" y="0" width="26" height="26" style="fill:yellow" fill-opacity="0.3" /> </g> <g id="gblockTemplate-2" height="26" width="26"> <rect x="0" y="0" width="20" height="20" fill="#888" /> ${blockTemplate} <rect x="0" y="0" width="26" height="26" style="fill:blue" fill-opacity="0.3" /> </g> <g id="gblockTemplate-3" height="26" width="26"> <rect x="0" y="0" width="20" height="20" fill="#888" /> ${blockTemplate} <rect x="0" y="0" width="26" height="26" style="fill:green" fill-opacity="0.3" /> </g> </defs> <rect id="background" x="0" y="0" style="fill:black" /> <rect id="perim" x="0" y="0" style="stroke-width:3;stroke:#999" fill-opacity="0.0"/> <!-- hard coded to standard numCols numRows --> <text x="85" y="150" font-family="Impact" font-size="55"> TOTAL VICTORY! </text> </svg> </div> <div id="${this.consoleId()}"> </div>` var svg = $('<div/>').html(svgContents).contents(); $("#" + this.hundoId()).append(svg); } hundo.Viz.prototype.cellFromXY = function(x, y) { var row = Math.floor(y / this.vizConfig.cellSize); var col = Math.floor(x / this.vizConfig.cellSize); return [row, col]; } hundo.Viz.prototype.getPieceFromPalette = function(row, col) { if (this.paletteSelection.type == hundo.PieceTypeEnum.BALL) { return new hundo.Ball(this.idGen.next(), row, col); } else if (this.paletteSelection.type == hundo.PieceTypeEnum.BLOCK) { return new hundo.Block(this.idGen.next(), row, col); } else if (this.paletteSelection.type == hundo.PieceTypeEnum.GOAL) { return new hundo.Goal(this.idGen.next(), row, col, this.paletteSelection.dir); } else if (this.paletteSelection.type == hundo.PieceTypeEnum.ICE) { return new hundo.Ice(this.idGen.next(), row, col); } else if (this.paletteSelection.type == hundo.PieceTypeEnum.ARROW) { return new hundo.Arrow(this.idGen.next(), row, col, this.paletteSelection.dir); } else if (this.paletteSelection.type == hundo.PieceTypeEnum.GBLOCK) { return new hundo.Gblock(this.idGen.next(), row, col, this.paletteSelection.groupNum); } else { console.error("Unrecognized piece type") } } hundo.Viz.prototype.clickBoard = function(x, y) { if (!this.maker.on || this.maker.play) { return false; } var [row, col] = this.cellFromXY(x, y); if (this.paletteSelection.delete) { this.animateSolvedQuick(); this.board.clearCell(row, col); this.drawBoardQuick(); return; } var piece = this.getPieceFromPalette(row, col); if (this.board.addPiece(piece)) { this.animateSolvedQuick(); this.drawBoardQuick(); this.removeHighlight(); } else { console.log("Could not add: " + piece); } } hundo.Viz.getIdFromBoardSvg = function(boardSvg) { var boardSvgId = boardSvg.getAttribute("id") var id = _.split(boardSvgId, "boardSvg")[1] return id; } hundo.Viz.clickBoard = function(){ var id = hundo.Viz.getIdFromBoardSvg(this); var [x, y] = d3.mouse(this); var viz = hundo.instances[id] viz.clickBoard(x, y); } hundo.Viz.prototype.addPlayButton = function() { var contents = `<button id="${this.playButtonId()}" onclick="hundo.clickPlay(${this.id})" type="button" class="button">Play</button>` var playButton = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(playButton); } hundo.Viz.prototype.addLevelSelect = function() { var contents = ` <button id="${this.levelBackButtonId()}" onclick="hundo.clickLevelBack(${this.id})" type="button" class="button" onmouseover="" style="cursor: pointer;">◀</button> <span id="${this.levelTextId()}""></span> <button id="${this.levelForwardButtonId()}" onclick="hundo.clickLevelForward(${this.id})" type="button" class="button" onmouseover="" style="color:#bbb">▶</button> ` var levelSelect = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(levelSelect); } hundo.Viz.prototype.paletteButtonHtml = function(image, config) { return ` <img src="img/${image}.png" onclick='hundo.clickPalette(${this.id}, ${JSON.stringify(config)})' onmouseover="" style="cursor: pointer; width: ${this.vizConfig.cellSize}px; height: ${this.vizConfig.cellSize}px" />` } hundo.Viz.prototype.addPalette = function() { var buttons = [ { image: "delete", config: { delete: true } }, { image: "ball", config: { type: hundo.PieceTypeEnum.BALL } }, { image: "block", config: { type: hundo.PieceTypeEnum.BLOCK } }, { image: "goal-up", config: { type: hundo.PieceTypeEnum.GOAL, dir: hundo.DirectionEnum.UP } }, { image: "goal-down", config: { type: hundo.PieceTypeEnum.GOAL, dir: hundo.DirectionEnum.DOWN } }, { image: "goal-left", config: { type: hundo.PieceTypeEnum.GOAL, dir: hundo.DirectionEnum.LEFT } }, { image: "goal-right", config: { type: hundo.PieceTypeEnum.GOAL, dir: hundo.DirectionEnum.RIGHT } }, { image: "ice", config: { type: hundo.PieceTypeEnum.ICE } }, { image: "arrow-up", config: { type: hundo.PieceTypeEnum.ARROW, dir: hundo.DirectionEnum.UP } }, { image: "arrow-down", config: { type: hundo.PieceTypeEnum.ARROW, dir: hundo.DirectionEnum.DOWN } }, { image: "arrow-left", config: { type: hundo.PieceTypeEnum.ARROW, dir: hundo.DirectionEnum.LEFT } }, { image: "arrow-right", config: { type: hundo.PieceTypeEnum.ARROW, dir: hundo.DirectionEnum.RIGHT } }, { image: "gblock-0", config: { type: hundo.PieceTypeEnum.GBLOCK, groupNum: 0 } }, { image: "gblock-1", config: { type: hundo.PieceTypeEnum.GBLOCK, groupNum: 1 } }, { image: "gblock-2", config: { type: hundo.PieceTypeEnum.GBLOCK, groupNum: 2 } }, { image: "gblock-3", config: { type: hundo.PieceTypeEnum.GBLOCK, groupNum: 3 } }, ] var THIS = this; var contents = _.map(buttons, function(pieceDescription) { return THIS.paletteButtonHtml( pieceDescription.image, pieceDescription.config ) }) .join("") var palette = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(palette); } hundo.Viz.prototype.addSave = function() { var contents = `<button id="${this.saveButtonId()}" onclick="hundo.clickSave(${this.id})" type="button" class="button">Save</button>` var saveButton = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(saveButton); } hundo.Viz.prototype.addShowSolution = function() { var contents = `<button id="${this.solutionButtonId()}" onclick="hundo.clickShowSolution(${this.id})" type="button" class="button">Show solution</button>` var solutionButton = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(solutionButton); } hundo.Viz.prototype.addLevelUrlField = function() { var contents = `<div>URL for this level: <input type="text" id="${this.levelUrlFieldId()}" value=""></input></div>` var saveButton = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(saveButton); } hundo.Viz.prototype.hundoId = function() { return "hundo" + this.id; } hundo.Viz.prototype.boardSvgId = function() { return "boardSvg" + this.id; } hundo.Viz.prototype.highlightId = function() { return "highlight" + this.id; } hundo.Viz.prototype.playButtonId = function() { return "playButton" + this.id; } hundo.Viz.prototype.saveButtonId = function() { return "saveButton" + this.id; } hundo.Viz.prototype.solutionButtonId = function() { return "solutionButton" + this.id; } hundo.Viz.prototype.levelUrlFieldId = function() { return "levelUrlField" + this.id } hundo.Viz.prototype.consoleId = function() { return "console" + this.id; } hundo.Viz.prototype.levelTextId = function() { return "levelText" + this.id; } hundo.Viz.prototype.levelBackButtonId = function() { return "levelBackButton" + this.id; } hundo.Viz.prototype.levelForwardButtonId = function() { return "levelForwardButton" + this.id; } hundo.Viz.prototype.drawGrid = function() { var vizConfig = this.vizConfig; var rows = _.range(1, vizConfig.numRows); this.boardSvg.selectAll() .data(rows) .enter() .append("line") .attr("class", "grid") .attr("x1", vizConfig.perimStrokeWidth) .attr("y1", function(row) { return row * vizConfig.cellSize; }) .attr("x2", vizConfig.numCols * vizConfig.cellSize - vizConfig.perimStrokeWidth) .attr("y2", function(row) { return row * vizConfig.cellSize; }) .attr("style", "stroke:rgb(0,0,255);stroke-width:1;opacity:0.3"); var cols = _.range(1, vizConfig.numCols); this.boardSvg.selectAll() .data(cols) .enter() .append("line") .attr("class", "grid") .attr("y1", vizConfig.perimStrokeWidth) .attr("x1", function(col) { return col * vizConfig.cellSize; }) .attr("y2", vizConfig.numRows * vizConfig.cellSize - vizConfig.perimStrokeWidth) .attr("x2", function(col) { return col * vizConfig.cellSize; }) .attr("style", "stroke:rgb(0,0,255);stroke-width:1;opacity:0.3"); } hundo.Viz.pieceId = function(piece) { return "piece" + piece.id; } hundo.Viz.dirToDegrees = function(dir) { if (dir == hundo.DirectionEnum.UP) { return 0; } else if (dir == hundo.DirectionEnum.DOWN) { return 180; } else if (dir == hundo.DirectionEnum.LEFT) { return 270; } else if (dir == hundo.DirectionEnum.RIGHT) { return 90; } else { console.error("Invalid direction:" + dir); } } hundo.Viz.prototype.transform = function(piece, transformation) { if (typeof transformation == "undefined") { transformation = {}; } var x = piece.col * this.vizConfig.cellSize; var y = piece.row * this.vizConfig.cellSize; if ("dx" in transformation) { x += transformation.dx; } if ("dy" in transformation) { y += transformation.dy; } var t = []; t.push("translate(" + x + ", " + y + ")"); if ("scale" in transformation) { t.push("scale(" + transformation.scale + ")"); } if (piece.type == hundo.PieceTypeEnum.BALL || piece.type == hundo.PieceTypeEnum.BLOCK || piece.type == hundo.PieceTypeEnum.ICE || piece.type == hundo.PieceTypeEnum.GBLOCK) { return _.join(t, ","); } else if (piece.type == hundo.PieceTypeEnum.GOAL || piece.type == hundo.PieceTypeEnum.ARROW) { var z = this.vizConfig.cellSize / 2; var degrees = hundo.Viz.dirToDegrees(piece.dir); t.push("rotate(" + degrees + ", " + z + ", " + z + ")"); return _.join(t, ","); } else { console.error("Bad piece type: " + piece.type); } } hundo.getRandom = function (min, max) { return Math.random() * (max - min) + min; } hundo.Viz.prototype.removeSolution = function() { this.boardSvg.selectAll(".solution").remove(); } hundo.Viz.prototype.drawEdges = function(edges, style) { var THIS = this; this.boardSvg.selectAll() .data(edges) .enter() .append("line") .attr("class", "solution") .attr("x1", function(edge) { return edge.col1 * THIS.vizConfig.cellSize + THIS.vizConfig.cellSize / 2; }) .attr("y1", function(edge) { return edge.row1 * THIS.vizConfig.cellSize + THIS.vizConfig.cellSize / 2; }) .attr("x2", function(edge) { return edge.col2 * THIS.vizConfig.cellSize + THIS.vizConfig.cellSize / 2; }) .attr("y2", function(edge) { return edge.row2 * THIS.vizConfig.cellSize + THIS.vizConfig.cellSize / 2; }) .attr("style", style); } hundo.Viz.prototype.drawSolution = function() { var solver = new hundo.Solver(this.board); if (this.maker.showGraph) { this.drawEdges(solver.getCellEdges(), "stroke:#FFF;stroke-width:1;opacity:0.4"); } this.drawEdges(solver.getCellWinningEdges(), "stroke:#B00000;stroke-width:4;opacity:1.0"); } hundo.Viz.prototype.drawPieces = function(transformation) { var THIS = this; this.boardSvg.selectAll() .data(this.board.getBlocks()) .enter() .append("svg:use") .attr("class", "block") .attr("id", hundo.Viz.pieceId) .attr("xlink:href", "#blockTemplate") .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); // <ellipse cx="10" cy="10" rx="10" ry="10" style="fill:#eee" /> this.boardSvg.selectAll() .data(this.board.getBalls()) .enter() .append("ellipse") .attr("cx", this.vizConfig.cellSize / 2) .attr("cy", this.vizConfig.cellSize / 2) .attr("rx", this.vizConfig.cellSize / 2) .attr("ry", this.vizConfig.cellSize / 2) .attr("style", "fill:#eee") .attr("class", "ball") .attr("id", hundo.Viz.pieceId) .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); this.boardSvg.selectAll() .data(this.board.getGoals()) .enter() .append("svg:use") .attr("class", "goal") .attr("id", hundo.Viz.pieceId) .attr("xlink:href", "#goalTemplate") .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); var iceMargin = Math.floor(this.vizConfig.cellSize / 6); this.boardSvg.selectAll() .data(this.board.getIce()) .enter() .append("rect") .attr("x", iceMargin) .attr("y", iceMargin) .attr("width", this.vizConfig.cellSize - iceMargin * 2) .attr("height", this.vizConfig.cellSize - iceMargin * 2) .attr("rx", iceMargin) .attr("ry", iceMargin) .attr("style", "fill:#63ADD2") .attr("class", "ice") .attr("id", hundo.Viz.pieceId) .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); this.boardSvg.selectAll() .data(this.board.getGblocks()) .enter() .append("svg:use") .attr("class", "gblock") .attr("id", hundo.Viz.pieceId) .attr("xlink:href", function (piece) { return "#gblockTemplate-" + piece.groupNum; }) .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); this.boardSvg.selectAll() .data(this.board.getArrows()) .enter() .append("svg:use") .attr("class", "arrow") .attr("id", hundo.Viz.pieceId) .attr("xlink:href", "#arrowTemplate") .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); if (this.maker.showSolution) { this.drawSolution(); } } hundo.Viz.prototype.drawBoardQuick = function() { this.drawPieces({}) } hundo.Viz.prototype.drawBoard = function() { var dxdy = this.vizConfig.cellSize / 2; var THIS = this; this.drawPieces({ dx: dxdy, dy: dxdy, scale: 0 }) var dxdy = -(this.vizConfig.cellSize / 2) * this.vizConfig.blowupScale; // TODO var pieces = this.board.getPieces(function(){ return true; }); var delays = _.range(0, pieces.length) .map(function(){ return hundo.getRandom(0, THIS.vizConfig.flyInDuration / 2); }); _.each(pieces, function(piece, i){ var id = "#" + hundo.Viz.pieceId(piece); var delay = delays[i]; THIS.boardSvg.select(id) .transition() .ease("linear") .delay(delay) .attr("transform", function() { return THIS.transform(piece, { dx: dxdy, dy: dxdy, scale: THIS.vizConfig.blowupScale }); }) .duration(THIS.vizConfig.flyInDuration / 2); }); setTimeout(function(){ _.each(pieces, function(piece, i){ var piece = pieces[i]; var id = "#" + hundo.Viz.pieceId(piece); var delay = delays[i]; THIS.boardSvg.select(id) .transition() .ease("linear") .delay(delay) .attr("transform", function() { return THIS.transform(piece); }) .duration(THIS.vizConfig.flyInDuration / 2); }); }, this.vizConfig.flyInDuration / 2); } // TODO hundo.Viz.prototype.reset = function() { var pieces = this.board.getPieces(function(piece) { return (piece.row != piece.origRow) || (piece.col != piece.origCol); }) this.board.reset(); var THIS = this; _.each(pieces, function(piece, i){ var piece = pieces[i]; if (piece.type == hundo.PieceTypeEnum.BALL) { THIS.boardSvg.select("#" + hundo.Viz.pieceId(piece)) .transition() .ease("linear") // undo the ball squish .attr("rx", THIS.vizConfig.cellSize / 2) .attr("ry", THIS.vizConfig.cellSize / 2) .attr("transform", function() { return THIS.transform(piece); }) .duration(0); } else { THIS.boardSvg.select("#" + hundo.Viz.pieceId(piece)) .transition() .ease("linear") .attr("transform", function() { return THIS.transform(piece); }) .duration(0); } }); } hundo.Viz.dxdy = function(dir) { if (dir == hundo.DirectionEnum.UP) { return [0, -1]; } else if (dir == hundo.DirectionEnum.DOWN) { return [0, 1]; } else if (dir == hundo.DirectionEnum.LEFT) { return [-1, 0]; } else if (dir == hundo.DirectionEnum.RIGHT) { return [1, 0]; } else { console.error("Bad direction: " + dir); } } hundo.Viz.prototype.undoAnimateVictory = function() { this.boardSvg.select("#background") .style("fill", "#000") this.drawGrid(); } // TODO: Cleanup hundo.Viz.prototype.animateVictory = function() { var THIS = this; this.boardSvg.select("#background") .transition() .style("fill", "#EEE") .duration(0); this.boardSvg.selectAll(".grid") .remove(); } hundo.Viz.prototype.animateSolvedQuick = function() { var pieces = this.board.getPieces(function(){ return true; }); _.each(pieces, function(piece,i){ var id = "#" + hundo.Viz.pieceId(piece); $(id).remove(); }) this.removeSolution(); } hundo.Viz.prototype.animateSolved = function() { var pieces = this.board.getPieces(function(){ return true; }); var dxdy = this.vizConfig.cellSize / 2; var THIS = this; var delays = _.range(0, pieces.length) .map(function(){ return hundo.getRandom(0, THIS.vizConfig.flyInDuration / 2); }) _.each(pieces, function(piece, i){ var id = "#" + hundo.Viz.pieceId(piece); var delay = delays[i]; THIS.boardSvg.select(id) .transition() .ease("linear") .delay(delay) .attr("transform", function() { return THIS.transform(piece, { dx: dxdy, dy: dxdy, scale: 0 }); }) .duration(THIS.vizConfig.flyInDuration) .remove(); }); this.removeSolution(); } hundo.Viz.prototype.prevLevel = function() { if (this.level <= 0) { return; } if (this.level == "victory") { this.level = this.levels.length; } this.animateSolvedQuick(); this.level--; this.board = new hundo.Board(this.levels[this.level], this.idGen); this.drawBoardQuick(); this.updateLevelSelect(); if (this.level == this.levels.length - 1) { this.undoAnimateVictory(); } } hundo.Viz.prototype.loadNextLevel = function(quick) { if (this.level < this.levels.length - 1) { this.level++; if (this.level > this.levelMax) { this.levelMax = this.level; } this.board = new hundo.Board(this.levels[this.level], this.idGen); if (quick) { this.drawBoardQuick(); } else { this.drawBoard(); } } else { // all levels solved this.level = "victory"; this.animateVictory(); this.levelMax = this.levels.length; } this.updateLevelSelect(); } hundo.Viz.prototype.nextLevel = function(quick) { var THIS = this; if (quick) { this.animateSolvedQuick(); this.loadNextLevel(quick); } else { setTimeout(function(){ THIS.loadNextLevel(); }, this.vizConfig.flyInDuration / 2); this.animateSolved(); } } hundo.Viz.prototype.updateLevelSelect = function() { var levelText; if (this.level == "victory" ) { levelText = "VICTORY" } else { levelText = "Level " + (this.level + 1) + "/" + this.levels.length; } $("#" + this.levelTextId()).text(levelText); if (this.level == "victory" || this.level > 0) { $("#" + this.levelBackButtonId()) .css({ color: "#000", "cursor": "pointer" }); } else { $("#" + this.levelBackButtonId()) .css({ color: "#bbb", cursor: "" }) } if (this.level != "victory" && this.level < this.levelMax) { $("#" + this.levelForwardButtonId()) .css({ color: "#000", "cursor": "pointer" }); } else { $("#" + this.levelForwardButtonId()) .css({ color: "#bbb", cursor: "" }) } } hundo.Viz.prototype.animateBall = function(animation) { ball = animation.move.ball; ballId = "#" + hundo.Viz.pieceId(ball); var dx; var dy; if (ball.dir != hundo.DirectionEnum.NODIR) { [dx, dy] = hundo.Viz.dxdy(ball.dir); } else { dx = 0; dy = 0; } var THIS = this; this.boardSvg.select(ballId) .transition() .ease("linear") .attr("rx", function() { if (dy != 0) { return THIS.vizConfig.cellSize / 4; } else { return THIS.vizConfig.cellSize / 2; } }) .attr("ry", function() { if (dx != 0) { return THIS.vizConfig.cellSize / 4; } else { return THIS.vizConfig.cellSize / 2; } }) .attr("transform", function() { return THIS.transform(ball); }) .duration(this.vizConfig.stepDuration); // leave a trail behind the ball this.boardSvg.selectAll() .data([{row: ball.row, col: ball.col}]) .enter() .append("circle") .attr("cx", ball.col * this.vizConfig.cellSize + this.vizConfig.cellSize / 2 ) .attr("cy", ball.row * this.vizConfig.cellSize + this.vizConfig.cellSize / 2 ) .attr("r", this.vizConfig.cellSize / 2 - this.vizConfig.cellSize / 8) .attr("style", "fill:#bbb") .transition() .duration(this.vizConfig.stepDuration * 4) .attr("r", "0") .remove(); } // TODO: move common code (in animateBall) into seperate function hundo.Viz.prototype.animateIce = function(animation) { ice = animation.move.ice; iceId = "#" + hundo.Viz.pieceId(ice); var THIS = this; this.boardSvg.select(iceId) .transition() .ease("linear") .attr("transform", function() { return THIS.transform(ice); }) .duration(this.vizConfig.stepDuration); } hundo.Viz.prototype.animateGblock = function(animation) { gblock = animation.move.gblock; gblockId = "#" + hundo.Viz.pieceId(gblock); var THIS = this; this.boardSvg.select(gblockId) .transition() .ease("linear") .attr("transform", function() { return THIS.transform(gblock); }) .duration(this.vizConfig.stepDuration); } hundo.Viz.prototype.animateCollide = function(animation) { var THIS = this; var recipients = animation.collide.recipients; var dir = animation.collide.dir; for (var i = 0; i < recipients.length; i++) { var piece = recipients[i]; var id = "#" + hundo.Viz.pieceId(piece); if (piece.type == hundo.PieceTypeEnum.BALL) { this.boardSvg.select(id) .transition() .ease("linear") // undo the ball squish .attr("rx", this.vizConfig.cellSize / 2) .attr("ry", this.vizConfig.cellSize / 2) .attr("transform", function() { var [dx, dy] = hundo.Viz.dxdy(dir); dx *= THIS.vizConfig.cellSize / 3; dy *= THIS.vizConfig.cellSize / 3; return THIS.transform(piece, {dx: dx, dy: dy}); }) .duration(this.vizConfig.stepDuration / 2); } else { this.boardSvg.select(id) .transition() .ease("linear") .attr("transform", function() { var [dx, dy] = hundo.Viz.dxdy(dir); dx *= THIS.vizConfig.cellSize / 3; dy *= THIS.vizConfig.cellSize / 3; return THIS.transform(piece, {dx: dx, dy: dy}); }) .duration(this.vizConfig.stepDuration / 2); } } setTimeout(function(){ for (var i = 0; i < recipients.length; i++) { var piece = recipients[i]; var id = "#" + hundo.Viz.pieceId(piece); THIS.boardSvg.select(id) .transition() .ease("linear") .attr("transform", function() { return THIS.transform(piece); }) .duration(THIS.vizConfig.stepDuration / 2); } }, this.vizConfig.stepDuration / 2); } hundo.Viz.prototype.stepAnimate = function() { var THIS = this; var animations = this.board.step(); if (this.board.atRest) { clearInterval(this.animateInterval); } if (this.board.done) { setTimeout( function(){THIS.reset(this.board);}, THIS.animateInterval); } var THIS = this; _.each(animations, function(animation) { if ("move" in animation && "ball" in animation.move) { THIS.animateBall(animation); } else if ("move" in animation && "ice" in animation.move) { THIS.animateIce(animation); } else if ("move" in animation && "gblock" in animation.move) { THIS.animateGblock(animation); } else if ("collide" in animation) { THIS.animateCollide(animation); } }) if (this.board.solved) { if (this.maker.on) { this.reset(this.board); } else { this.nextLevel(false); } } } hundo.Viz.prototype.checkKey = function(e) { if (!this.board.atRest) { return; } if (this.board.solved) { return; } if (this.maker.on && !this.maker.play) { return; } var e = e || window.event; var direction; // diable browser scrolling on arrow keys if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) { e.preventDefault(); } if (e.keyCode == '38') { direction = hundo.DirectionEnum.UP; } else if (e.keyCode == '40') { direction = hundo.DirectionEnum.DOWN; } else if (e.keyCode == '37') { direction = hundo.DirectionEnum.LEFT; } else if (e.keyCode == '39') { direction = hundo.DirectionEnum.RIGHT; } else { return; } this.board.setDir(direction); this.stepAnimate(); var THIS = this; if (!this.board.atRest) { this.animateInterval = setInterval( function(){THIS.stepAnimate();}, this.vizConfig.stepDuration); } } // TODO: hoist code into Viz.prototype.checkKey hundo.Viz.checkKey = function(e) { hundo.vizz.checkKey(e); } hundo.Viz.prototype.clickPlay = function() { if (!this.maker.on) { return; } this.maker.play = !this.maker.play; if (this.maker.play) { $("#" + this.playButtonId()).text("Edit"); } else { $("#" + this.playButtonId()).text("Play"); } } hundo.clickPlay = function(id) { hundo.vizz = hundo.instances[id]; hundo.vizz.clickPlay(); } hundo.Viz.prototype.clickSave = function() { console.log("save"); var url = this.getBoardUrl() $("#" + this.levelUrlFieldId()).attr("value", url); $("#" + this.levelUrlFieldId()).select(); console.log(JSON.stringify(this.board.getJson())); } hundo.clickSave = function(id) { hundo.vizz = hundo.instances[id]; hundo.vizz.clickSave(); } hundo.Viz.prototype.clickShowSolution = function() { this.maker.showSolution = !this.maker.showSolution; this.maker.showGraph = this.maker.showSolution; if (this.maker.showSolution) { $("#" + this.solutionButtonId()).text("Hide solution"); } else { $("#" + this.solutionButtonId()).text("Show solution"); } this.animateSolvedQuick(); this.drawBoardQuick(); } hundo.clickShowSolution = function(id) { hundo.vizz = hundo.instances[id]; hundo.vizz.clickShowSolution(); } // TODO: bug, hundo.vizz is unsafe here because // you might click level left on one Hundo and do nextLevel // on another level hundo.clickLevelForward = function(id) { if (hundo.vizz.level != "victory" && hundo.vizz.level < hundo.vizz.levelMax) { hundo.vizz.nextLevel(true); } } hundo.clickLevelBack = function(id) { hundo.vizz.prevLevel(); } hundo.Viz.prototype.clickPalette = function(config) { this.paletteSelection = config; } hundo.clickPalette = function(id, config) { var viz = hundo.instances[id] viz.clickPalette(config); } hundo.Viz.prototype.getBoardUrl = function() { var levelParam = hundo.Compress.compressLevel(this.board.getJson()); var url = window.location.href; url = _.split(url, "?")[0]; url += "?level=" + encodeURIComponent(levelParam) return url; } hundo.cheat = function() { hundo.vizz.maker.showSolution = !hundo.vizz.maker.showSolution; hundo.vizz.maker.showGraph = false; if (hundo.vizz.maker.showSolution) { hundo.vizz.drawSolution(); } else { hundo.vizz.removeSolution(); } } /** * Compress functions enable levels to be encoded in URLs ******************************************************************************/ hundo.Compress = {} hundo.Compress.toBase64Digit = function (number) { if (number < 0 || number >= 62) { console.error("Cannot convert to base64: " + number); return null; } if (number < 10) { return "" + number } else if (number < 36) { return String.fromCharCode("a".charCodeAt(0) + number - 10) } else { return String.fromCharCode("A".charCodeAt(0) + number - 36) } } hundo.Compress.fromBase64Digit = function(digit) { var charCode = digit.charCodeAt(0); if (charCode >= "0".charCodeAt(0) && charCode <= "9".charCodeAt(0)) { return charCode - "0".charCodeAt(0); } else if (charCode >= "a".charCodeAt(0) && charCode <= "z".charCodeAt(0)) { return charCode - "a".charCodeAt(0) + 10; } else if (charCode >= "A".charCodeAt(0) && charCode <= "Z".charCodeAt(0)) { return charCode - "A".charCodeAt(0) + 36; } else { console.error("Cannot convert from base64: " + digit); return null; } } hundo.Compress.dirToNum = function(dir) { if (dir == hundo.DirectionEnum.UP) { return "0"; } else if (dir == hundo.DirectionEnum.DOWN) { return "1"; } else if (dir == hundo.DirectionEnum.LEFT) { return "2"; } else if (dir == hundo.DirectionEnum.RIGHT) { return "3"; } else { console.error("Bad direction: " + dir); return null; } } hundo.Compress.numToDir = function(num) { if (num == "0") { return hundo.DirectionEnum.UP; } else if (num == "1") { return hundo.DirectionEnum.DOWN; } else if (num == "2") { return hundo.DirectionEnum.LEFT; } else if (num == "3") { return hundo.DirectionEnum.RIGHT; } else { console.error("Bad num: " + num); return null; } } hundo.Compress.sep = "-"; // assumes numRows, numCols < 32 hundo.Compress.compressLevel = function(level) { var levelArray = []; // The first two bytes encode numRows, numCols levelArray.push(hundo.Compress.toBase64Digit(level.numRows)); levelArray.push(hundo.Compress.toBase64Digit(level.numCols)); // The next two bytes encode ball.row, ball.col if (typeof level.ball != "undefined") { levelArray.push(hundo.Compress.toBase64Digit(level.ball.row)); levelArray.push(hundo.Compress.toBase64Digit(level.ball.col)); } // signifies beginning of blocks levelArray.push(hundo.Compress.sep); // Encode each block as (block.row, block.col) pair _.each(level.blocks, function(block){ levelArray.push(hundo.Compress.toBase64Digit(block.row)); levelArray.push(hundo.Compress.toBase64Digit(block.col)); }); // separates blocks and goals levelArray.push(hundo.Compress.sep); // Encode the goals, like blocks _.each(level.goals, function(goal){ levelArray.push(hundo.Compress.toBase64Digit(goal.row)); levelArray.push(hundo.Compress.toBase64Digit(goal.col)); levelArray.push(hundo.Compress.dirToNum(goal.dir)) }); // separator levelArray.push(hundo.Compress.sep); // Encode the ice _.each(level.ice, function(ice){ levelArray.push(hundo.Compress.toBase64Digit(ice.row)); levelArray.push(hundo.Compress.toBase64Digit(ice.col)); }); // separator levelArray.push(hundo.Compress.sep); // Encode the arrows _.each(level.arrows, function(arrow){ levelArray.push(hundo.Compress.toBase64Digit(arrow.row)); levelArray.push(hundo.Compress.toBase64Digit(arrow.col)); levelArray.push(hundo.Compress.dirToNum(arrow.dir)) }); // separator levelArray.push(hundo.Compress.sep); // Encode the gblocks _.each(level.gblocks, function(gblock){ levelArray.push(hundo.Compress.toBase64Digit(gblock.row)); levelArray.push(hundo.Compress.toBase64Digit(gblock.col)); levelArray.push(hundo.Compress.toBase64Digit(gblock.groupNum)); }); return _.join(levelArray, ""); } hundo.Compress.getRowCol = function(bytes) { var row = hundo.Compress.fromBase64Digit(bytes[0]); var col = hundo.Compress.fromBase64Digit(bytes[1]); bytes.shift(); bytes.shift(); return [row, col]; } // 64-bit bytes // TODO: factor out common code hundo.Compress.decompressLevel = function(byteString) { var level = { blocks: [], goals: [], ice: [], arrows: [], gblocks: [] }; var bytes = _.split(byteString, "") var [r, c] = hundo.Compress.getRowCol(bytes); level.numRows = r; level.numCols = c; // Get the ball, if it's there if (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); level.ball = { row: r, col: c } } // shift past the sep if (bytes.length > 0) { if (bytes[0] != hundo.Compress.sep) { console.error("Could not parse level"); return null; } bytes.shift(); } // Get the blocks while (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); block = { row: r, col: c } level.blocks.push(block); } // shift past the sep if (bytes.length > 0) { if (bytes[0] != hundo.Compress.sep) { console.error("Could not parse level"); return null; } bytes.shift(); } // Get the goals while (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); var dir = hundo.Compress.numToDir(bytes[0]); bytes.shift(); goal = { row: r, col: c, dir: dir } level.goals.push(goal); } // shift past the sep if (bytes.length > 0) { if (bytes[0] != hundo.Compress.sep) { console.error("Could not parse level"); return null; } bytes.shift(); } while (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); ice = { row: r, col: c } level.ice.push(ice); } // shift past the sep if (bytes.length > 0) { if (bytes[0] != hundo.Compress.sep) { console.error("Could not parse level"); return null; } bytes.shift(); } // Get the arrows while (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); var dir = hundo.Compress.numToDir(bytes[0]); bytes.shift(); arrow = { row: r, col: c, dir: dir } level.arrows.push(arrow); } // shift past the sep if (bytes.length > 0) { if (bytes[0] != hundo.Compress.sep) { console.error("Could not parse level"); return null; } bytes.shift(); } // Get the gblocks while (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); var groupNum = hundo.Compress.fromBase64Digit(bytes[0]); bytes.shift(); gblock = { row: r, col: c, groupNum: groupNum } level.gblocks.push(gblock); } return level; } hundo.instances = {} hundo.vizz = null; hundo.defaultVizConfig = { cellSize: 26, stepDuration: 50, flyInDuration: 250, blowupScale: 3, perimStrokeWidth: 3, numRows: 15, numCols: 21, playButton: false, levelSelect: true, levelMax: 0 } document.onkeydown = hundo.Viz.checkKey;
public/js/hundo.js
/** * Unless otherwise noted, the contents of this file are free and unencumbered * software released into the public domain. * See UNLICENSE.txt */ var hundo = {} /** * Enums ******************************************************************************/ hundo.PieceTypeEnum = { BALL: "BALL", BLOCK: "BLOCK", GOAL: "GOAL", ICE: "ICE", ARROW: "ARROW", GBLOCK: "GBLOCK" } hundo.DirectionEnum = { UP: "UP", DOWN: "DOWN", LEFT: "LEFT", RIGHT: "RIGHT", NODIR: "NODIR" } /** * Function common to all pieces ******************************************************************************/ hundo.equalsTypeRowCol = function(a, b) { return a.type == b.type && a.row == b.row && a.col == b.col; } /** * Block board pieces ******************************************************************************/ // id is a uuid relative to board pieces hundo.Block = function(id, row, col) { this.id = id; this.type = hundo.PieceTypeEnum.BLOCK; this.row = row; this.col = col; this.origRow = row; this.origCol = col; } // returns true iff the piece were pushed in direction dir hundo.Block.prototype.nudge = function(dir, board) { return [false, []]; } hundo.Block.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece); } /** * Ball board piece ******************************************************************************/ hundo.Ball = function(id, row, col, dir) { this.id = id; this.type = hundo.PieceTypeEnum.BALL; this.row = row; this.col = col; this.origRow = row; this.origCol = col; this.dir = dir; } hundo.Ball.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece) && this.dir == piece.dir; } hundo.Ball.prototype.nudge = function(dir, board, commit) { var [dr, dc] = hundo.Board.drdc(dir); var row = this.row + dr; var col = this.col + dc; var [nudged, animations] = board.nudge(row, col, dir, commit) if (nudged) { if (commit) { board.movePiece(this, row, col); } animations.push( { "move": { "ball": this, "dir": dir, } }); return [true, animations]; } else { return [false, animations]; } } /** * Goal board pieces ******************************************************************************/ hundo.Goal = function(id, row, col, dir) { this.id = id; this.type = hundo.PieceTypeEnum.GOAL; this.row = row; this.col = col; this.origRow = row; this.origCol = col; this.dir = dir; } hundo.Goal.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece) && this.dir == piece.dir; } hundo.Goal.getPusher = function(row, col, dir) { var [dr, dc] = hundo.Board.drdc(dir); dr *= -1; dc *= -1; return [row + dr, col + dc]; } hundo.oppositeDir = function(dir) { if (dir == hundo.DirectionEnum.UP) { return hundo.DirectionEnum.DOWN; } else if (dir == hundo.DirectionEnum.DOWN) { return hundo.DirectionEnum.UP; } else if (dir == hundo.DirectionEnum.LEFT) { return hundo.DirectionEnum.RIGHT; } else if (dir == hundo.DirectionEnum.RIGHT) { return hundo.DirectionEnum.LEFT; } else { console.error("Bad direction: " + dir) } } // dir is the direction of the momentum of piece doing the nudging // returns true if this piece can accept the nudging piece hundo.Goal.prototype.nudge = function(dir, board) { var [pusherRow, pusherCol] = hundo.Goal.getPusher(this.row, this.col, dir); // gblocks not allowed in arrows if (board.getPiece(pusherRow, pusherCol, hundo.PieceTypeEnum.GBLOCK)) { return [false, []]; } return [this.dir == hundo.oppositeDir(dir), []]; } /** * Ice cube board pieces ******************************************************************************/ hundo.Ice = function(id, row, col) { this.id = id; this.type = hundo.PieceTypeEnum.ICE; this.row = row; this.col = col; this.origRow = row; this.origCol = col; } hundo.Ice.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece); } hundo.Ice.prototype.nudge = function(dir, board, commit) { // If ice is in the goal, then it can't move var occupyGoal = false; _.each(board.matrix[this.row][this.col], function(piece) { if (piece.type == hundo.PieceTypeEnum.GOAL) { occupyGoal = true; } }) if (occupyGoal) { return [false, []]; } var [dr, dc] = hundo.Board.drdc(dir); var row = this.row + dr; var col = this.col + dc; var [nudged, animations] = board.nudge(row, col, dir, commit) if (nudged) { if (commit) { board.movePiece(this, row, col); } animations.push( { "move": { "ice": this, "dir": dir } }); return [true, animations]; } else { return [false, animations]; } } /** * Arrow board pieces ******************************************************************************/ hundo.Arrow = function(id, row, col, dir) { this.id = id; this.type = hundo.PieceTypeEnum.ARROW; this.row = row; this.col = col; this.origRow = row; this.origCol = col; this.dir = dir; } hundo.Arrow.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece) && this.dir == piece.dir; } hundo.Arrow.getPusher = hundo.Goal.getPusher; // TODO: implement hundo.Arrow.prototype.nudge = function(dir, board) { var [pusherRow, pusherCol] = hundo.Arrow.getPusher(this.row, this.col, dir); // gblocks not allowed in arrows if (board.getPiece(pusherRow, pusherCol, hundo.PieceTypeEnum.GBLOCK)) { return [false, []]; } var result = this.dir == dir || ( board.matrix[this.row][this.col].length == 2 && board.getPiece(this.row, this.col, hundo.PieceTypeEnum.BALL) && this.dir == hundo.oppositeDir(dir)) return [result, []]; } /** * Gblock board pieces ******************************************************************************/ hundo.Gblock = function(id, row, col, groupNum) { this.id = id; this.type = hundo.PieceTypeEnum.GBLOCK; this.row = row; this.col = col; this.origRow = row; this.origCol = col; this.groupNum = groupNum; } hundo.Gblock.prototype.eq = function(piece) { return hundo.equalsTypeRowCol(this, piece) && this.groupNum == piece.groupNum; } hundo.Gblock.prototype.nudge = function(dir, board, commit, fromGblock) { // nudge this block's neighbors, but only if this nudge isn't already // part of a neighbor check if (!fromGblock) { var neighbors = board.gblocks[this.groupNum]; var THIS = this; // nudgeResults == the list of nudge results for each neighbor var nudgeResults = _.map(neighbors, function(neighbor) { return neighbor.nudge(dir, board, commit, true); }); // If there are any false values in nudgeResults, then this nudge // fails var i = _.findIndex(nudgeResults, function(result) { return !result[0]; }); // Get the animations of the neighbors var animations = _.flatMap(nudgeResults, function(result) { return result[1]; }); if (i >= 0) { return [false, animations]; } else { return [true, animations]; } } else { var [dr, dc] = hundo.Board.drdc(dir); var row = this.row + dr; var col = this.col + dc; var nudged, animations; var pushingIntoGblock; // TODO: factor out this if expression into a function if (row >= 0 && row < board.numRows && col >= 0 && col < board.numCols) { pushingIntoGblock = board.getPiece(row, col, hundo.PieceTypeEnum.GBLOCK); } if (row < 0 || row >= board.numRows || col < 0 || col >= board.numCols) { nudged = false; animations = []; } else if (pushingIntoGblock && pushingIntoGblock.groupNum == this.groupNum) { nudged = true; animations = []; } else { var [nudged, animations] = board.nudge(row, col, dir, commit) } if (nudged) { if (commit) { board.movePiece(this, row, col); } animations.push( { "move": { "gblock": this, "dir": dir } }); return [true, animations]; } else { return [false, animations]; } } } /** * Generates uuids for board pieces ******************************************************************************/ hundo.IdGenerator = function() { this.nextId = 0; } // I'll be impressed if this ever overflows hundo.IdGenerator.prototype.next = function() { return this.nextId++; } hundo.idGenerator = new hundo.IdGenerator(); /** * Board encapsulates the model of the game (MVC style) ******************************************************************************/ // TODO: Assume boardConfig is untrusted hundo.Board = function(boardConfig, idGen) { // is the ball at rest? this.atRest = true; // is the board finished? namely, if the ball has gone out // of bounds or reached a goal this.done = false; this.solved = false; this.numRows = boardConfig.numRows; this.numCols = boardConfig.numCols; // The set of pieces that have moved out of bounds this.oob = []; // this.gblocks[gblock.groupNum] == the set of gblocks in that group this.gblocks = {} // this.matrix[row][call] == array of piece objects this.matrix = new Array(); for (var i = 0; i < this.numRows; i++) { this.matrix[i] = new Array(); for (var j = 0; j < this.numCols; j++) { this.matrix[i][j] = new Array(); } } var THIS = this; // TODO: check return values for addPiece // Add blocks to the matrix _.each(boardConfig.blocks, function(block){ var piece = new hundo.Block(idGen.next(), block.row, block.col) THIS.addPiece(piece); }); // Add the ball to the matrix if ("ball" in boardConfig) { var row = boardConfig.ball.row; var col = boardConfig.ball.col; var ball = new hundo.Ball(idGen.next(), row, col, hundo.DirectionEnum.NODIR); this.addPiece(ball); } // Add goals to the matrix _.each(boardConfig.goals, function(goal) { var row = goal.row; var col = goal.col; var dir = goal.dir; var piece = new hundo.Goal(idGen.next(), row, col, dir); THIS.addPiece(piece); }); // Add ice to the matrix _.each(boardConfig.ice, function(ice) { var row = ice.row; var col = ice.col; var piece = new hundo.Ice(idGen.next(), row, col); THIS.addPiece(piece); }); // Add arrows to the matrix _.each(boardConfig.arrows, function(arrow) { var row = arrow.row; var col = arrow.col; var dir = arrow.dir; var piece = new hundo.Arrow(idGen.next(), row, col, dir); THIS.addPiece(piece); }); // Add gblocks to the matrix _.each(boardConfig.gblocks, function(gblock) { var row = gblock.row; var col = gblock.col; var groupNum = gblock.groupNum; var piece = new hundo.Gblock(idGen.next(), row, col, groupNum); THIS.addPiece(piece); }); } // TODO: is there a better way to do this? hundo.setEq = function(set1, set2) { if (set1.length != set2.length) { return false; } var matches = true; _.each(set1, function(x) { var singleMatch = false; _.each(set2, function(y) { if (x.eq(y)) { singleMatch = true; } }) if (!singleMatch) { matches = false; } }); return matches; } hundo.Board.prototype.eq = function(board) { if (this.numRows != board.numRows || this.numCols != board.numCols) { return false; } if (this.ball && !board.ball || !this.ball && board.ball) { return false; } if (this.ball && board.ball) { if (this.ball.row != board.ball.row || this.ball.col != board.ball.col) { return false; } } for (var r = 0; r < this.numRows; r++) { for (var c = 0; c < this.numCols; c++) { if (!hundo.setEq(this.matrix[r][c], board.matrix[r][c])) { return false; } } } return true; } hundo.Board.prototype.isEmptyCell = function(row, col) { return this.matrix[row][col].length == 0; } hundo.Board.prototype.hasBall = function() { var balls = this.getPieces(function(piece) { return piece.type == hundo.PieceTypeEnum.BALL; }); return balls.length >= 1; } hundo.Board.prototype.clearCell = function(row, col) { if (typeof this.ball != "undefined" && this.ball.row == row && this.ball.col == col) { this.ball = undefined; } this.matrix[row][col] = []; } hundo.Board.prototype.getPiece = function(row, col, type) { return _.find(this.matrix[row][col], function(piece){ return piece.type == type; }); } hundo.Board.prototype.canAddPiece = function(piece) { if (piece.type == hundo.PieceTypeEnum.BALL && this.hasBall()) { return false; } else if (piece.type == hundo.PieceTypeEnum.BLOCK || piece.type == hundo.PieceTypeEnum.BALL) { return this.matrix[piece.row][piece.col].length == 0; } // TOD: allow ICE to be added to arrow else if (piece.type == hundo.PieceTypeEnum.ICE) { return this.matrix[piece.row][piece.col].length == 0 || (this.matrix[piece.row][piece.col].length == 1 && this.getPiece(piece.row, piece.col, hundo.PieceTypeEnum.GOAL)); } else if (piece.type == hundo.PieceTypeEnum.GOAL) { return this.matrix[piece.row][piece.col].length == 0 || (this.matrix[piece.row][piece.col].length == 1 && (this.getPiece(piece.row, piece.col, hundo.PieceTypeEnum.ICE))); } else if (piece.type == hundo.PieceTypeEnum.ARROW) { return this.matrix[piece.row][piece.col].length == 0 || (this.matrix[piece.row][piece.col].length == 1 && (this.getPiece(piece.row, piece.col, hundo.PieceTypeEnum.ICE) || this.getPiece(piece.row, piece.col, hundo.PieceTypeEnum.BALL))); } else if (piece.type == hundo.PieceTypeEnum.GBLOCK) { return this.matrix[piece.row][piece.col].length == 0; } else { console.error("Unimplemented addPiece"); console.error(piece); return false; } } hundo.Board.prototype.addPiece = function(piece) { if (this.canAddPiece(piece)) { this.matrix[piece.row][piece.col].push(piece) if (piece.type == hundo.PieceTypeEnum.BALL) { this.ball = piece; } else if (piece.type == hundo.PieceTypeEnum.GBLOCK) { if (!(piece.groupNum in this.gblocks)){ this.gblocks[piece.groupNum] = []; } this.gblocks[piece.groupNum].push(piece); } return true; } else { return false; } } hundo.Board.prototype.reset = function() { var THIS = this; // moved is the set of all pieces that have moved var moved = this.getPieces(function(piece) { return (piece.row != piece.origRow) || (piece.col != piece.origCol); }); _.each(moved, function(piece){ THIS.movePiece(piece, piece.origRow, piece.origCol); }); this.done = false; this.solved = false; return moved; } hundo.Board.prototype.setDir = function(direction) { this.ball.dir = direction; this.atRest = false; } // func(piece) should return true iff the piece is of the type being gotten hundo.Board.prototype.getPieces = function(func) { var pieces = []; _.each(this.matrix, function(row) { _.each(row, function(col) { _.each(col, function(piece) { if (func(piece)) { pieces.push(piece); } }) }) }); _.each(this.oob, function(piece){ if (func(piece)) { pieces.push(piece); } }) return pieces; } hundo.Board.prototype.getBlocks = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.BLOCK; }); }; hundo.Board.prototype.getBalls = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.BALL; }); }; hundo.Board.prototype.getGoals = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.GOAL; }); }; hundo.Board.prototype.getIce = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.ICE; }); }; hundo.Board.prototype.getArrows = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.ARROW; }); }; hundo.Board.prototype.getGblocks = function() { return this.getPieces(function(piece){ return piece.type == hundo.PieceTypeEnum.GBLOCK; }); }; hundo.Board.prototype.getJson = function() { var j = { numRows: this.numRows, numCols: this.numCols, blocks: _.map(this.getBlocks(), function(block) { return { row: block.row, col: block.col } }), goals: _.map(this.getGoals(), function(goal) { return { row: goal.row, col: goal.col, dir: goal.dir } }), ice: _.map(this.getIce(), function(ice) { return { row: ice.row, col: ice.col } }), arrows: _.map(this.getArrows(), function(arrow) { return { row: arrow.row, col: arrow.col, dir: arrow.dir } }), gblocks: _.map(this.getGblocks(), function(gblock) { return { row: gblock.row, col: gblock.col, groupNum: gblock.groupNum } }), } if (typeof this.ball != "undefined") { j.ball = { row: this.ball.row, col: this.ball.col } } return j; } // removes the first element in array for which func(element) is true // if an element is removed, returns the index of the element removed // otherwise, returns -1 hundo.arrayRemove = function(array, func) { var i = _.findIndex(array, func); if (i < 0) { return -1; } array.splice(i, 1); return i; } hundo.Board.prototype.movePiece = function(piece, row, col) { var i; if (piece.row < 0 || piece.row >= this.numRows || piece.col < 0 || piece.col >= this.numCols) { i = hundo.arrayRemove(this.oob, function(p) { return p.id == piece.id; }) } else { var pieces = this.matrix[piece.row][piece.col]; i = hundo.arrayRemove(pieces, function(p) { return p.id == piece.id; }) } if (i == -1) { console.error("Could not remove piece"); return; } if (row < 0 || row >= this.numRows || col < 0 || col >= this.numCols) { this.oob.push(piece); } else { // add the piece to its new location this.matrix[row][col].push(piece); } piece.row = row; piece.col = col; } // see hundo.nudge hundo.Board.prototype.nudge = function(row, col, dir, commit) { if (row < 0 || row >= this.numRows || col < 0 || col >= this.numCols) { return [true, []]; } var pieces = this.matrix[row][col]; var result = true; var animations = [] var THIS = this; _.each(pieces, function(piece) { var [nudged, newAnimations] = piece.nudge(dir, THIS, commit); animations = _.concat(animations, newAnimations); if (!nudged) { result = false; } }); return [result, animations]; } hundo.Board.prototype.checkSolved = function() { var pieces = this.matrix[this.ball.row][this.ball.col] var result = _.filter(pieces, function(piece){ return piece.type == hundo.PieceTypeEnum.GOAL; }) return result.length == 1; } hundo.Board.drdc = function(direction) { var dr = 0, dc = 0; if (direction == hundo.DirectionEnum.UP) { dr = -1; } else if (direction == hundo.DirectionEnum.DOWN) { dr = 1; } else if (direction == hundo.DirectionEnum.LEFT) { dc = -1; } else if (direction == hundo.DirectionEnum.RIGHT) { dc = 1; } else { console.error("Bad direction: " + direction); return null; } return [dr, dc]; } // returns null on fatal error // else, returns an animation object, which describes how the // the step should be animated hundo.Board.prototype.step = function() { var direction = this.ball.dir; if (direction == hundo.DirectionEnum.NODIR) { console.error("Ball must have a direction to step"); return null; } var [dr, dc] = hundo.Board.drdc(direction); var newRow = this.ball.row + dr; var newCol = this.ball.col + dc; // Check for out of bounds if (newRow < 0 || newRow >= this.numRows || newCol < 0 || newCol >= this.numCols) { this.atRest = true; this.done = true; this.ball.dir = hundo.DirectionEnum.NODIR; this.movePiece(this.ball, newRow, newCol); return [{ "move": { "ball": this.ball, "dir": direction, "solved": false }, }]; } var [nudged, animations] = this.nudge(this.ball.row, this.ball.col, this.ball.dir, false); if (nudged) { // now commit the nudge [nudged, animations] = this.nudge(this.ball.row, this.ball.col, this.ball.dir, true); if (this.checkSolved()) { this.solved = true; this.atRest = true; this.ball.dir = hundo.DirectionEnum.NODIR; } return animations; } else { this.ball.dir = hundo.DirectionEnum.NODIR; this.atRest = true; var recipients = []; var gblock = this.getPiece(newRow, newCol, hundo.PieceTypeEnum.GBLOCK); if (gblock) { recipients = _.concat(recipients, this.gblocks[gblock.groupNum]); } recipients = _.concat(recipients, this.matrix[newRow][newCol].slice(0)); recipients = _.concat(recipients, this.matrix[this.ball.row][this.ball.col]); return [{ "collide": { "dir": direction, "recipients": recipients } }]; } } // Deep copy the board hundo.Board.prototype.clone = function() { var config = this.getJson(); return new hundo.Board(config, hundo.idGenerator); } /** * Code not released into the public domain ******************************************************************************/ // Thank you nicbell! https://gist.github.com/nicbell/6081098 Object.compare = function (obj1, obj2) { //Loop through properties in object 1 for (var p in obj1) { //Check property exists on both objects if (obj1.hasOwnProperty(p) !== obj2.hasOwnProperty(p)) return false; switch (typeof (obj1[p])) { //Deep compare objects case 'object': if (!Object.compare(obj1[p], obj2[p])) return false; break; //Compare function code case 'function': if (typeof (obj2[p]) == 'undefined' || (p != 'compare' && obj1[p].toString() != obj2[p].toString())) return false; break; //Compare values default: if (obj1[p] != obj2[p]) return false; } } //Check object 2 for any extra properties for (var p in obj2) { if (typeof (obj1[p]) == 'undefined') return false; } return true; }; /** * Solver solves puzzles ******************************************************************************/ // BUG: Solver fails here: level-editor.html?level=fl86-455a848a99-6b2-7988-- // But then if you go right, the solver works // Thank you Wikipedia! // https://en.wikipedia.org/wiki/Graph_traversal#Pseudocode hundo.Solver = function(board) { this.edges = []; this.winningEdges = []; // vertices this.boards = []; if (typeof board.ball == "undefined" || typeof board.ball.row == "undefined" || typeof board.ball.col == "undefined") { return; } this.winningEdges = this.explore(board); } hundo.Solver.prototype.hasExploredVertex = function(board1) { var matches = _.flatMap(this.boards, function(board2) { if (Object.compare(board1, board2)) { return [true]; } else { return []; } }) if (matches.length == 0) { return false; } else if (matches.length == 1) { return true; } else { console.error("multiple matches for has explored: " + matches); } } hundo.Solver.prototype.hasExploredEdge = function(edge1) { var matches = _.flatMap(this.edges, function(edge2) { if (Object.compare(edge1[0].getJson(), edge2[0].getJson()) && Object.compare(edge1[1].getJson(), edge2[1].getJson())) { return [true]; } else { return []; } }) if (matches.length == 0) { return false; } else if (matches.length == 1) { return true; } else { console.error("multiple matches for has explored: " + matches); } } // push the ball in direction dir hundo.Solver.move = function(board, dir) { board.setDir(dir); board.step(); while (!board.done && !board.solved && !board.atRest) { board.step(); } return board; } hundo.Solver.prototype.getCellEdges = function() { return _.map(this.edges, function(edge) { var [b1, b2] = edge; return { row1: b1.ball.row, col1: b1.ball.col, row2: b2.ball.row, col2: b2.ball.col } }); } hundo.Solver.prototype.getCellWinningEdges = function() { return _.map(this.winningEdges, function(edge) { var [b1, b2] = edge; return { row1: b1.ball.row, col1: b1.ball.col, row2: b2.ball.row, col2: b2.ball.col } }); } hundo.Solver.prototype.explore = function(board) { this.boards.push(board); // if out of bounds or solved if (board.ball.row < 0 || board.ball.row >= board.numRows || board.ball.col < 0 || board.ball.col >= board.numCols || board.solved) { return []; } var boards = []; boards[0] = hundo.Solver.move(board.clone(), hundo.DirectionEnum.UP); boards[1] = hundo.Solver.move(board.clone(), hundo.DirectionEnum.DOWN); boards[2] = hundo.Solver.move(board.clone(), hundo.DirectionEnum.LEFT); boards[3] = hundo.Solver.move(board.clone(), hundo.DirectionEnum.RIGHT); var THIS = this; var winningEdges = []; _.each(boards, function(newBoard, i) { var edge = [board, newBoard] if (!THIS.hasExploredEdge(edge)) { if (!THIS.hasExploredVertex(newBoard)) { THIS.edges.push(edge); var w = THIS.explore(newBoard) winningEdges = _.concat(winningEdges, w) if (w.length > 0 || newBoard.solved) { winningEdges.push(edge); } } } }); return winningEdges; } /** * The Hundo class is what clients use to create a Hundo game ******************************************************************************/ Hundo = function(config) { // clone hundo.defaultVizConfig so it doesn't get clobbered by extend var defaultVizConfig = jQuery.extend(true, {}, hundo.defaultVizConfig); if (!"vizConfig" in config) { config.viz = {}; } config.viz = $.extend(defaultVizConfig, config.viz); viz = new hundo.Viz(config); hundo.instances[config.id] = viz; if (_.size(hundo.instances) == 1) { hundo.vizz = viz; } } /** * Viz encapsulates the view and the controller ******************************************************************************/ hundo.Viz = function(config) { // TODO: validate vizConfig and levels this.vizConfig = config.viz; this.maker = { on: config.maker, play: false, mouseRow: undefined, mouseCol: undefined, showSolution: false, showGraph: false, } var levelFromUrl = hundo.Viz.levelFromUrl(); if (levelFromUrl) { this.maker.on = true; } if (this.maker.on) { if (levelFromUrl) { this.levels = [levelFromUrl]; } else { this.levels = [ { numRows: config.viz.numRows, numCols: config.viz.numCols } ] } config.viz.levelSelect = false; this.paletteSelection = { type: hundo.PieceTypeEnum.BLOCK }; } else { this.levels = config.levels; } this.id = config.id; this.level = 0; this.levelMax = config.viz.levelMax; this.drawSvgGrid(); if (config.viz.playButton) { this.addPlayButton(); } if (config.viz.levelSelect) { this.addLevelSelect(); } if (this.maker.on) { this.addSave(); this.addShowSolution(); this.addPalette(); this.addLevelUrlField(); } this.boardSvg = d3.select("#" + this.boardSvgId()) .attr("width", this.vizConfig.numCols * this.vizConfig.cellSize) .attr("height", this.vizConfig.numRows * this.vizConfig.cellSize) .on("click", hundo.Viz.clickBoard); this.boardSvg.select("#background") .attr("width", this.vizConfig.numCols * this.vizConfig.cellSize) .attr("height", this.vizConfig.numRows * this.vizConfig.cellSize) .attr("style", "fill:black"); this.boardSvg.select("#perim") .attr("width", this.vizConfig.numCols * this.vizConfig.cellSize) .attr("height", this.vizConfig.numRows * this.vizConfig.cellSize) this.drawGrid(); this.idGen = hundo.idGenerator; var boardConfig = this.levels[0]; this.board = new hundo.Board(boardConfig, this.idGen); this.drawBoard(); this.updateLevelSelect(); this.boardSvg .on("mousemove", hundo.Viz.mousemove) .on("mouseleave", hundo.Viz.mouseleave); } // TODO: assume untrusted input and write tests hundo.Viz.getParams = function() { var url = window.location.href; var params = _.split(url, "?")[1] if (typeof params == "undefined") { return {} } var paramList = params.split("&"); var paramObj = {} _.each(paramList, function(param) { var [key, value] = param.split("="); paramObj[key] = value; }); return paramObj } hundo.Viz.levelFromUrl = function() { var params = hundo.Viz.getParams() if (!("level" in params)) { return false; } var compressedLevel = decodeURIComponent(params.level); var level = hundo.Compress.decompressLevel(compressedLevel); return level; } hundo.Viz.prototype.removeHighlight = function() { this.boardSvg.select("#" + this.highlightId()) .remove(); } // BUG TODO: it seems that mousemove and mouseleave are interferring // with each other because mousemove updates the highlighter // on every pixel change (as opposed to only updating the // highlighter on cell changes). mouseleave only works when // the mouse exits the board at high speed. hundo.Viz.prototype.mousemove = function(x, y) { if (!this.maker.on || this.maker.play) { return; } var [row, col] = this.cellFromXY(x, y) this.removeHighlight(); if (this.paletteSelection.delete) { if (this.board.isEmptyCell(row, col)) { return; } } else { var piece = this.getPieceFromPalette(row, col); if (!this.board.canAddPiece(piece)) { return; } } this.maker.mouseRow = row; this.maker.mouseCol = col; this.boardSvg.selectAll() .data([0]) .enter() .append("rect") .attr("x", col * this.vizConfig.cellSize) .attr("y", row * this.vizConfig.cellSize) .attr("height", this.vizConfig.cellSize) .attr("width", this.vizConfig.cellSize) .attr("style", "fill:#3D8E37; fill-opacity: 0.5; cursor: pointer;") .attr("id", this.highlightId()) } hundo.Viz.mousemove = function() { var [x, y] = d3.mouse(this); var id = hundo.Viz.getIdFromBoardSvg(this); var viz = hundo.instances[id] viz.mousemove(x, y); } hundo.Viz.prototype.mouseleave = function() { this.removeHighlight(); } hundo.Viz.mouseleave = function() { var id = hundo.Viz.getIdFromBoardSvg(this); var viz = hundo.instances[id] viz.mouseleave(); } hundo.Viz.prototype.drawSvgGrid = function(name) { var blockTemplate = ` <rect x="0" y="0" width="20" height="20" fill="#888" /> <path d="M0 0 L26 0 L20 6 L6 6 Z" stroke="none" fill="#aaa"/> <path d="M0 0 L6 6 L6 20 L0 26 Z" stroke="none" fill="#aaa"/> <path d="M26 0 L20 6 L20 20 L26 26 Z" stroke="none" fill="#666"/> <path d="M26 26 L20 20 L6 20 L0 26 Z" stroke="none" fill="#666"/>` var svgContents = ` <div> <svg id="${this.boardSvgId(name)}" xmlns="http://www.w3.org/2000/svg"> <defs> <g id="blockTemplate" height="20" width="20" > ${blockTemplate} </g> <g id="goalTemplate" height="20" width="20"> <polygon points="0,26 0,13 13,26" style="fill:red" /> <polygon points="13,26 26,13 26,26" style="fill:red" /> <rect x="0" y="23" width="26" height="3" fill="red" /> </g> <g id="arrowTemplate" height="20" width="20"> <polygon points="0,13 13,0 26,13 20,13 20,26 6,26 6,13" style="fill:yellow; stroke-width: 1; stroke: black;" /> </g> <g id="gblockTemplate-0" height="26" width="26"> ${blockTemplate} <rect x="0" y="0" width="26" height="26" style="fill:red" fill-opacity="0.3" /> </g> <g id="gblockTemplate-1" height="26" width="26"> <rect x="0" y="0" width="20" height="20" fill="#888" /> ${blockTemplate} <rect x="0" y="0" width="26" height="26" style="fill:yellow" fill-opacity="0.3" /> </g> <g id="gblockTemplate-2" height="26" width="26"> <rect x="0" y="0" width="20" height="20" fill="#888" /> ${blockTemplate} <rect x="0" y="0" width="26" height="26" style="fill:blue" fill-opacity="0.3" /> </g> <g id="gblockTemplate-3" height="26" width="26"> <rect x="0" y="0" width="20" height="20" fill="#888" /> ${blockTemplate} <rect x="0" y="0" width="26" height="26" style="fill:green" fill-opacity="0.3" /> </g> </defs> <rect id="background" x="0" y="0" style="fill:black" /> <rect id="perim" x="0" y="0" style="stroke-width:3;stroke:#999" fill-opacity="0.0"/> <!-- hard coded to standard numCols numRows --> <text x="85" y="150" font-family="Impact" font-size="55"> TOTAL VICTORY! </text> </svg> </div> <div id="${this.consoleId()}"> </div>` var svg = $('<div/>').html(svgContents).contents(); $("#" + this.hundoId()).append(svg); } hundo.Viz.prototype.cellFromXY = function(x, y) { var row = Math.floor(y / this.vizConfig.cellSize); var col = Math.floor(x / this.vizConfig.cellSize); return [row, col]; } hundo.Viz.prototype.getPieceFromPalette = function(row, col) { if (this.paletteSelection.type == hundo.PieceTypeEnum.BALL) { return new hundo.Ball(this.idGen.next(), row, col); } else if (this.paletteSelection.type == hundo.PieceTypeEnum.BLOCK) { return new hundo.Block(this.idGen.next(), row, col); } else if (this.paletteSelection.type == hundo.PieceTypeEnum.GOAL) { return new hundo.Goal(this.idGen.next(), row, col, this.paletteSelection.dir); } else if (this.paletteSelection.type == hundo.PieceTypeEnum.ICE) { return new hundo.Ice(this.idGen.next(), row, col); } else if (this.paletteSelection.type == hundo.PieceTypeEnum.ARROW) { return new hundo.Arrow(this.idGen.next(), row, col, this.paletteSelection.dir); } else if (this.paletteSelection.type == hundo.PieceTypeEnum.GBLOCK) { return new hundo.Gblock(this.idGen.next(), row, col, this.paletteSelection.groupNum); } else { console.error("Unrecognized piece type") } } hundo.Viz.prototype.clickBoard = function(x, y) { if (!this.maker.on || this.maker.play) { return false; } var [row, col] = this.cellFromXY(x, y); if (this.paletteSelection.delete) { this.animateSolvedQuick(); this.board.clearCell(row, col); this.drawBoardQuick(); return; } var piece = this.getPieceFromPalette(row, col); if (this.board.addPiece(piece)) { this.animateSolvedQuick(); this.drawBoardQuick(); this.removeHighlight(); } else { console.log("Could not add: " + piece); } } hundo.Viz.getIdFromBoardSvg = function(boardSvg) { var boardSvgId = boardSvg.getAttribute("id") var id = _.split(boardSvgId, "boardSvg")[1] return id; } hundo.Viz.clickBoard = function(){ var id = hundo.Viz.getIdFromBoardSvg(this); var [x, y] = d3.mouse(this); var viz = hundo.instances[id] viz.clickBoard(x, y); } hundo.Viz.prototype.addPlayButton = function() { var contents = `<button id="${this.playButtonId()}" onclick="hundo.clickPlay(${this.id})" type="button" class="button">Play</button>` var playButton = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(playButton); } hundo.Viz.prototype.addLevelSelect = function() { var contents = ` <button id="${this.levelBackButtonId()}" onclick="hundo.clickLevelBack(${this.id})" type="button" class="button" onmouseover="" style="cursor: pointer;">◀</button> <span id="${this.levelTextId()}""></span> <button id="${this.levelForwardButtonId()}" onclick="hundo.clickLevelForward(${this.id})" type="button" class="button" onmouseover="" style="color:#bbb">▶</button> ` var levelSelect = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(levelSelect); } hundo.Viz.prototype.paletteButtonHtml = function(image, config) { return ` <img src="img/${image}.png" onclick='hundo.clickPalette(${this.id}, ${JSON.stringify(config)})' onmouseover="" style="cursor: pointer; width: ${this.vizConfig.cellSize}px; height: ${this.vizConfig.cellSize}px" />` } hundo.Viz.prototype.addPalette = function() { var buttons = [ { image: "delete", config: { delete: true } }, { image: "ball", config: { type: hundo.PieceTypeEnum.BALL } }, { image: "block", config: { type: hundo.PieceTypeEnum.BLOCK } }, { image: "goal-up", config: { type: hundo.PieceTypeEnum.GOAL, dir: hundo.DirectionEnum.UP } }, { image: "goal-down", config: { type: hundo.PieceTypeEnum.GOAL, dir: hundo.DirectionEnum.DOWN } }, { image: "goal-left", config: { type: hundo.PieceTypeEnum.GOAL, dir: hundo.DirectionEnum.LEFT } }, { image: "goal-right", config: { type: hundo.PieceTypeEnum.GOAL, dir: hundo.DirectionEnum.RIGHT } }, { image: "ice", config: { type: hundo.PieceTypeEnum.ICE } }, { image: "arrow-up", config: { type: hundo.PieceTypeEnum.ARROW, dir: hundo.DirectionEnum.UP } }, { image: "arrow-down", config: { type: hundo.PieceTypeEnum.ARROW, dir: hundo.DirectionEnum.DOWN } }, { image: "arrow-left", config: { type: hundo.PieceTypeEnum.ARROW, dir: hundo.DirectionEnum.LEFT } }, { image: "arrow-right", config: { type: hundo.PieceTypeEnum.ARROW, dir: hundo.DirectionEnum.RIGHT } }, { image: "gblock-0", config: { type: hundo.PieceTypeEnum.GBLOCK, groupNum: 0 } }, { image: "gblock-1", config: { type: hundo.PieceTypeEnum.GBLOCK, groupNum: 1 } }, { image: "gblock-2", config: { type: hundo.PieceTypeEnum.GBLOCK, groupNum: 2 } }, { image: "gblock-3", config: { type: hundo.PieceTypeEnum.GBLOCK, groupNum: 3 } }, ] var THIS = this; var contents = _.map(buttons, function(pieceDescription) { return THIS.paletteButtonHtml( pieceDescription.image, pieceDescription.config ) }) .join("") var palette = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(palette); } hundo.Viz.prototype.addSave = function() { var contents = `<button id="${this.saveButtonId()}" onclick="hundo.clickSave(${this.id})" type="button" class="button">Save</button>` var saveButton = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(saveButton); } hundo.Viz.prototype.addShowSolution = function() { var contents = `<button id="${this.solutionButtonId()}" onclick="hundo.clickShowSolution(${this.id})" type="button" class="button">Show solution</button>` var solutionButton = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(solutionButton); } hundo.Viz.prototype.addLevelUrlField = function() { var contents = `<div>URL for this level: <input type="text" id="${this.levelUrlFieldId()}" value=""></input></div>` var saveButton = $("<div/>").html(contents).contents(); $("#" + this.consoleId()).append(saveButton); } hundo.Viz.prototype.hundoId = function() { return "hundo" + this.id; } hundo.Viz.prototype.boardSvgId = function() { return "boardSvg" + this.id; } hundo.Viz.prototype.highlightId = function() { return "highlight" + this.id; } hundo.Viz.prototype.playButtonId = function() { return "playButton" + this.id; } hundo.Viz.prototype.saveButtonId = function() { return "saveButton" + this.id; } hundo.Viz.prototype.solutionButtonId = function() { return "solutionButton" + this.id; } hundo.Viz.prototype.levelUrlFieldId = function() { return "levelUrlField" + this.id } hundo.Viz.prototype.consoleId = function() { return "console" + this.id; } hundo.Viz.prototype.levelTextId = function() { return "levelText" + this.id; } hundo.Viz.prototype.levelBackButtonId = function() { return "levelBackButton" + this.id; } hundo.Viz.prototype.levelForwardButtonId = function() { return "levelForwardButton" + this.id; } hundo.Viz.prototype.drawGrid = function() { var vizConfig = this.vizConfig; var rows = _.range(1, vizConfig.numRows); this.boardSvg.selectAll() .data(rows) .enter() .append("line") .attr("class", "grid") .attr("x1", vizConfig.perimStrokeWidth) .attr("y1", function(row) { return row * vizConfig.cellSize; }) .attr("x2", vizConfig.numCols * vizConfig.cellSize - vizConfig.perimStrokeWidth) .attr("y2", function(row) { return row * vizConfig.cellSize; }) .attr("style", "stroke:rgb(0,0,255);stroke-width:1;opacity:0.3"); var cols = _.range(1, vizConfig.numCols); this.boardSvg.selectAll() .data(cols) .enter() .append("line") .attr("class", "grid") .attr("y1", vizConfig.perimStrokeWidth) .attr("x1", function(col) { return col * vizConfig.cellSize; }) .attr("y2", vizConfig.numRows * vizConfig.cellSize - vizConfig.perimStrokeWidth) .attr("x2", function(col) { return col * vizConfig.cellSize; }) .attr("style", "stroke:rgb(0,0,255);stroke-width:1;opacity:0.3"); } hundo.Viz.pieceId = function(piece) { return "piece" + piece.id; } hundo.Viz.dirToDegrees = function(dir) { if (dir == hundo.DirectionEnum.UP) { return 0; } else if (dir == hundo.DirectionEnum.DOWN) { return 180; } else if (dir == hundo.DirectionEnum.LEFT) { return 270; } else if (dir == hundo.DirectionEnum.RIGHT) { return 90; } else { console.error("Invalid direction:" + dir); } } hundo.Viz.prototype.transform = function(piece, transformation) { if (typeof transformation == "undefined") { transformation = {}; } var x = piece.col * this.vizConfig.cellSize; var y = piece.row * this.vizConfig.cellSize; if ("dx" in transformation) { x += transformation.dx; } if ("dy" in transformation) { y += transformation.dy; } var t = []; t.push("translate(" + x + ", " + y + ")"); if ("scale" in transformation) { t.push("scale(" + transformation.scale + ")"); } if (piece.type == hundo.PieceTypeEnum.BALL || piece.type == hundo.PieceTypeEnum.BLOCK || piece.type == hundo.PieceTypeEnum.ICE || piece.type == hundo.PieceTypeEnum.GBLOCK) { return _.join(t, ","); } else if (piece.type == hundo.PieceTypeEnum.GOAL || piece.type == hundo.PieceTypeEnum.ARROW) { var z = this.vizConfig.cellSize / 2; var degrees = hundo.Viz.dirToDegrees(piece.dir); t.push("rotate(" + degrees + ", " + z + ", " + z + ")"); return _.join(t, ","); } else { console.error("Bad piece type: " + piece.type); } } hundo.getRandom = function (min, max) { return Math.random() * (max - min) + min; } hundo.Viz.prototype.removeSolution = function() { this.boardSvg.selectAll(".solution").remove(); } hundo.Viz.prototype.drawEdges = function(edges, style) { var THIS = this; this.boardSvg.selectAll() .data(edges) .enter() .append("line") .attr("class", "solution") .attr("x1", function(edge) { return edge.col1 * THIS.vizConfig.cellSize + THIS.vizConfig.cellSize / 2; }) .attr("y1", function(edge) { return edge.row1 * THIS.vizConfig.cellSize + THIS.vizConfig.cellSize / 2; }) .attr("x2", function(edge) { return edge.col2 * THIS.vizConfig.cellSize + THIS.vizConfig.cellSize / 2; }) .attr("y2", function(edge) { return edge.row2 * THIS.vizConfig.cellSize + THIS.vizConfig.cellSize / 2; }) .attr("style", style); } hundo.Viz.prototype.drawSolution = function() { var solver = new hundo.Solver(this.board); if (this.maker.showGraph) { this.drawEdges(solver.getCellEdges(), "stroke:#FFF;stroke-width:1;opacity:0.4"); } this.drawEdges(solver.getCellWinningEdges(), "stroke:#B00000;stroke-width:4;opacity:1.0"); } hundo.Viz.prototype.drawPieces = function(transformation) { var THIS = this; this.boardSvg.selectAll() .data(this.board.getBlocks()) .enter() .append("svg:use") .attr("class", "block") .attr("id", hundo.Viz.pieceId) .attr("xlink:href", "#blockTemplate") .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); // <ellipse cx="10" cy="10" rx="10" ry="10" style="fill:#eee" /> this.boardSvg.selectAll() .data(this.board.getBalls()) .enter() .append("ellipse") .attr("cx", this.vizConfig.cellSize / 2) .attr("cy", this.vizConfig.cellSize / 2) .attr("rx", this.vizConfig.cellSize / 2) .attr("ry", this.vizConfig.cellSize / 2) .attr("style", "fill:#eee") .attr("class", "ball") .attr("id", hundo.Viz.pieceId) .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); this.boardSvg.selectAll() .data(this.board.getGoals()) .enter() .append("svg:use") .attr("class", "goal") .attr("id", hundo.Viz.pieceId) .attr("xlink:href", "#goalTemplate") .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); var iceMargin = Math.floor(this.vizConfig.cellSize / 6); this.boardSvg.selectAll() .data(this.board.getIce()) .enter() .append("rect") .attr("x", iceMargin) .attr("y", iceMargin) .attr("width", this.vizConfig.cellSize - iceMargin * 2) .attr("height", this.vizConfig.cellSize - iceMargin * 2) .attr("rx", iceMargin) .attr("ry", iceMargin) .attr("style", "fill:#63ADD2") .attr("class", "ice") .attr("id", hundo.Viz.pieceId) .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); this.boardSvg.selectAll() .data(this.board.getGblocks()) .enter() .append("svg:use") .attr("class", "gblock") .attr("id", hundo.Viz.pieceId) .attr("xlink:href", function (piece) { return "#gblockTemplate-" + piece.groupNum; }) .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); this.boardSvg.selectAll() .data(this.board.getArrows()) .enter() .append("svg:use") .attr("class", "arrow") .attr("id", hundo.Viz.pieceId) .attr("xlink:href", "#arrowTemplate") .attr("transform", function(piece) { return THIS.transform(piece, transformation); }); if (this.maker.showSolution) { this.drawSolution(); } } hundo.Viz.prototype.drawBoardQuick = function() { this.drawPieces({}) } hundo.Viz.prototype.drawBoard = function() { var dxdy = this.vizConfig.cellSize / 2; var THIS = this; this.drawPieces({ dx: dxdy, dy: dxdy, scale: 0 }) var dxdy = -(this.vizConfig.cellSize / 2) * this.vizConfig.blowupScale; // TODO var pieces = this.board.getPieces(function(){ return true; }); var delays = _.range(0, pieces.length) .map(function(){ return hundo.getRandom(0, THIS.vizConfig.flyInDuration / 2); }); _.each(pieces, function(piece, i){ var id = "#" + hundo.Viz.pieceId(piece); var delay = delays[i]; THIS.boardSvg.select(id) .transition() .ease("linear") .delay(delay) .attr("transform", function() { return THIS.transform(piece, { dx: dxdy, dy: dxdy, scale: THIS.vizConfig.blowupScale }); }) .duration(THIS.vizConfig.flyInDuration / 2); }); setTimeout(function(){ _.each(pieces, function(piece, i){ var piece = pieces[i]; var id = "#" + hundo.Viz.pieceId(piece); var delay = delays[i]; THIS.boardSvg.select(id) .transition() .ease("linear") .delay(delay) .attr("transform", function() { return THIS.transform(piece); }) .duration(THIS.vizConfig.flyInDuration / 2); }); }, this.vizConfig.flyInDuration / 2); } // TODO hundo.Viz.prototype.reset = function() { var pieces = this.board.getPieces(function(piece) { return (piece.row != piece.origRow) || (piece.col != piece.origCol); }) this.board.reset(); var THIS = this; _.each(pieces, function(piece, i){ var piece = pieces[i]; if (piece.type == hundo.PieceTypeEnum.BALL) { THIS.boardSvg.select("#" + hundo.Viz.pieceId(piece)) .transition() .ease("linear") // undo the ball squish .attr("rx", THIS.vizConfig.cellSize / 2) .attr("ry", THIS.vizConfig.cellSize / 2) .attr("transform", function() { return THIS.transform(piece); }) .duration(0); } else { THIS.boardSvg.select("#" + hundo.Viz.pieceId(piece)) .transition() .ease("linear") .attr("transform", function() { return THIS.transform(piece); }) .duration(0); } }); } hundo.Viz.dxdy = function(dir) { if (dir == hundo.DirectionEnum.UP) { return [0, -1]; } else if (dir == hundo.DirectionEnum.DOWN) { return [0, 1]; } else if (dir == hundo.DirectionEnum.LEFT) { return [-1, 0]; } else if (dir == hundo.DirectionEnum.RIGHT) { return [1, 0]; } else { console.error("Bad direction: " + dir); } } hundo.Viz.prototype.undoAnimateVictory = function() { this.boardSvg.select("#background") .style("fill", "#000") this.drawGrid(); } // TODO: Cleanup hundo.Viz.prototype.animateVictory = function() { var THIS = this; this.boardSvg.select("#background") .transition() .style("fill", "#EEE") .duration(0); this.boardSvg.selectAll(".grid") .remove(); } hundo.Viz.prototype.animateSolvedQuick = function() { var pieces = this.board.getPieces(function(){ return true; }); _.each(pieces, function(piece,i){ var id = "#" + hundo.Viz.pieceId(piece); $(id).remove(); }) this.removeSolution(); } hundo.Viz.prototype.animateSolved = function() { var pieces = this.board.getPieces(function(){ return true; }); var dxdy = this.vizConfig.cellSize / 2; var THIS = this; var delays = _.range(0, pieces.length) .map(function(){ return hundo.getRandom(0, THIS.vizConfig.flyInDuration / 2); }) _.each(pieces, function(piece, i){ var id = "#" + hundo.Viz.pieceId(piece); var delay = delays[i]; THIS.boardSvg.select(id) .transition() .ease("linear") .delay(delay) .attr("transform", function() { return THIS.transform(piece, { dx: dxdy, dy: dxdy, scale: 0 }); }) .duration(THIS.vizConfig.flyInDuration) .remove(); }); this.removeSolution(); } hundo.Viz.prototype.prevLevel = function() { if (this.level <= 0) { return; } if (this.level == "victory") { this.level = this.levels.length; } this.animateSolvedQuick(); this.level--; this.board = new hundo.Board(this.levels[this.level], this.idGen); this.drawBoardQuick(); this.updateLevelSelect(); if (this.level == this.levels.length - 1) { this.undoAnimateVictory(); } } hundo.Viz.prototype.loadNextLevel = function(quick) { if (this.level < this.levels.length - 1) { this.level++; if (this.level > this.levelMax) { this.levelMax = this.level; } this.board = new hundo.Board(this.levels[this.level], this.idGen); if (quick) { this.drawBoardQuick(); } else { this.drawBoard(); } } else { // all levels solved this.level = "victory"; this.animateVictory(); this.levelMax = this.levels.length; } this.updateLevelSelect(); } hundo.Viz.prototype.nextLevel = function(quick) { var THIS = this; if (quick) { this.animateSolvedQuick(); this.loadNextLevel(quick); } else { setTimeout(function(){ THIS.loadNextLevel(); }, this.vizConfig.flyInDuration / 2); this.animateSolved(); } } hundo.Viz.prototype.updateLevelSelect = function() { var levelText; if (this.level == "victory" ) { levelText = "VICTORY" } else { levelText = "Level " + (this.level + 1) + "/" + this.levels.length; } $("#" + this.levelTextId()).text(levelText); if (this.level == "victory" || this.level > 0) { $("#" + this.levelBackButtonId()) .css({ color: "#000", "cursor": "pointer" }); } else { $("#" + this.levelBackButtonId()) .css({ color: "#bbb", cursor: "" }) } if (this.level != "victory" && this.level < this.levelMax) { $("#" + this.levelForwardButtonId()) .css({ color: "#000", "cursor": "pointer" }); } else { $("#" + this.levelForwardButtonId()) .css({ color: "#bbb", cursor: "" }) } } hundo.Viz.prototype.animateBall = function(animation) { ball = animation.move.ball; ballId = "#" + hundo.Viz.pieceId(ball); var dx; var dy; if (ball.dir != hundo.DirectionEnum.NODIR) { [dx, dy] = hundo.Viz.dxdy(ball.dir); } else { dx = 0; dy = 0; } var THIS = this; this.boardSvg.select(ballId) .transition() .ease("linear") .attr("rx", function() { if (dy != 0) { return THIS.vizConfig.cellSize / 4; } else { return THIS.vizConfig.cellSize / 2; } }) .attr("ry", function() { if (dx != 0) { return THIS.vizConfig.cellSize / 4; } else { return THIS.vizConfig.cellSize / 2; } }) .attr("transform", function() { return THIS.transform(ball); }) .duration(this.vizConfig.stepDuration); // leave a trail behind the ball this.boardSvg.selectAll() .data([{row: ball.row, col: ball.col}]) .enter() .append("circle") .attr("cx", ball.col * this.vizConfig.cellSize + this.vizConfig.cellSize / 2 ) .attr("cy", ball.row * this.vizConfig.cellSize + this.vizConfig.cellSize / 2 ) .attr("r", this.vizConfig.cellSize / 2 - this.vizConfig.cellSize / 8) .attr("style", "fill:#bbb") .transition() .duration(this.vizConfig.stepDuration * 4) .attr("r", "0") .remove(); } // TODO: move common code (in animateBall) into seperate function hundo.Viz.prototype.animateIce = function(animation) { ice = animation.move.ice; iceId = "#" + hundo.Viz.pieceId(ice); var THIS = this; this.boardSvg.select(iceId) .transition() .ease("linear") .attr("transform", function() { return THIS.transform(ice); }) .duration(this.vizConfig.stepDuration); } hundo.Viz.prototype.animateGblock = function(animation) { gblock = animation.move.gblock; gblockId = "#" + hundo.Viz.pieceId(gblock); var THIS = this; this.boardSvg.select(gblockId) .transition() .ease("linear") .attr("transform", function() { return THIS.transform(gblock); }) .duration(this.vizConfig.stepDuration); } hundo.Viz.prototype.animateCollide = function(animation) { var THIS = this; var recipients = animation.collide.recipients; var dir = animation.collide.dir; for (var i = 0; i < recipients.length; i++) { var piece = recipients[i]; var id = "#" + hundo.Viz.pieceId(piece); if (piece.type == hundo.PieceTypeEnum.BALL) { this.boardSvg.select(id) .transition() .ease("linear") // undo the ball squish .attr("rx", this.vizConfig.cellSize / 2) .attr("ry", this.vizConfig.cellSize / 2) .attr("transform", function() { var [dx, dy] = hundo.Viz.dxdy(dir); dx *= THIS.vizConfig.cellSize / 3; dy *= THIS.vizConfig.cellSize / 3; return THIS.transform(piece, {dx: dx, dy: dy}); }) .duration(this.vizConfig.stepDuration / 2); } else { this.boardSvg.select(id) .transition() .ease("linear") .attr("transform", function() { var [dx, dy] = hundo.Viz.dxdy(dir); dx *= THIS.vizConfig.cellSize / 3; dy *= THIS.vizConfig.cellSize / 3; return THIS.transform(piece, {dx: dx, dy: dy}); }) .duration(this.vizConfig.stepDuration / 2); } } setTimeout(function(){ for (var i = 0; i < recipients.length; i++) { var piece = recipients[i]; var id = "#" + hundo.Viz.pieceId(piece); THIS.boardSvg.select(id) .transition() .ease("linear") .attr("transform", function() { return THIS.transform(piece); }) .duration(THIS.vizConfig.stepDuration / 2); } }, this.vizConfig.stepDuration / 2); } hundo.Viz.prototype.stepAnimate = function() { var THIS = this; var animations = this.board.step(); if (this.board.atRest) { clearInterval(this.animateInterval); } if (this.board.done) { setTimeout( function(){THIS.reset(this.board);}, THIS.animateInterval); } var THIS = this; _.each(animations, function(animation) { if ("move" in animation && "ball" in animation.move) { THIS.animateBall(animation); } else if ("move" in animation && "ice" in animation.move) { THIS.animateIce(animation); } else if ("move" in animation && "gblock" in animation.move) { THIS.animateGblock(animation); } else if ("collide" in animation) { THIS.animateCollide(animation); } }) if (this.board.solved) { if (this.maker.on) { this.reset(this.board); } else { this.nextLevel(false); } } } hundo.Viz.prototype.checkKey = function(e) { if (!this.board.atRest) { return; } if (this.board.solved) { return; } if (this.maker.on && !this.maker.play) { return; } var e = e || window.event; var direction; // diable browser scrolling on arrow keys if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) { e.preventDefault(); } if (e.keyCode == '38') { direction = hundo.DirectionEnum.UP; } else if (e.keyCode == '40') { direction = hundo.DirectionEnum.DOWN; } else if (e.keyCode == '37') { direction = hundo.DirectionEnum.LEFT; } else if (e.keyCode == '39') { direction = hundo.DirectionEnum.RIGHT; } else { return; } this.board.setDir(direction); this.stepAnimate(); var THIS = this; if (!this.board.atRest) { this.animateInterval = setInterval( function(){THIS.stepAnimate();}, this.vizConfig.stepDuration); } } // TODO: hoist code into Viz.prototype.checkKey hundo.Viz.checkKey = function(e) { hundo.vizz.checkKey(e); } hundo.Viz.prototype.clickPlay = function() { if (!this.maker.on) { return; } this.maker.play = !this.maker.play; if (this.maker.play) { $("#" + this.playButtonId()).text("Edit"); } else { $("#" + this.playButtonId()).text("Play"); } } hundo.clickPlay = function(id) { hundo.vizz = hundo.instances[id]; hundo.vizz.clickPlay(); } hundo.Viz.prototype.clickSave = function() { console.log("save"); var url = this.getBoardUrl() $("#" + this.levelUrlFieldId()).attr("value", url); $("#" + this.levelUrlFieldId()).select(); console.log(JSON.stringify(this.board.getJson())); } hundo.clickSave = function(id) { hundo.vizz = hundo.instances[id]; hundo.vizz.clickSave(); } hundo.Viz.prototype.clickShowSolution = function() { this.maker.showSolution = !this.maker.showSolution; this.maker.showGraph = this.maker.showSolution; if (this.maker.showSolution) { $("#" + this.solutionButtonId()).text("Hide solution"); } else { $("#" + this.solutionButtonId()).text("Show solution"); } this.animateSolvedQuick(); this.drawBoardQuick(); } hundo.clickShowSolution = function(id) { hundo.vizz = hundo.instances[id]; hundo.vizz.clickShowSolution(); } // TODO: bug, hundo.vizz is unsafe here because // you might click level left on one Hundo and do nextLevel // on another level hundo.clickLevelForward = function(id) { if (hundo.vizz.level != "victory" && hundo.vizz.level < hundo.vizz.levelMax) { hundo.vizz.nextLevel(true); } } hundo.clickLevelBack = function(id) { hundo.vizz.prevLevel(); } hundo.Viz.prototype.clickPalette = function(config) { this.paletteSelection = config; } hundo.clickPalette = function(id, config) { var viz = hundo.instances[id] viz.clickPalette(config); } hundo.Viz.prototype.getBoardUrl = function() { var levelParam = hundo.Compress.compressLevel(this.board.getJson()); var url = window.location.href; url = _.split(url, "?")[0]; url += "?level=" + encodeURIComponent(levelParam) return url; } hundo.cheat = function() { hundo.vizz.maker.showSolution = !hundo.vizz.maker.showSolution; hundo.vizz.maker.showGraph = false; if (hundo.vizz.maker.showSolution) { hundo.vizz.drawSolution(); } else { hundo.vizz.removeSolution(); } } /** * Compress functions enable levels to be encoded in URLs ******************************************************************************/ hundo.Compress = {} hundo.Compress.toBase64Digit = function (number) { if (number < 0 || number >= 62) { console.error("Cannot convert to base64: " + number); return null; } if (number < 10) { return "" + number } else if (number < 36) { return String.fromCharCode("a".charCodeAt(0) + number - 10) } else { return String.fromCharCode("A".charCodeAt(0) + number - 36) } } hundo.Compress.fromBase64Digit = function(digit) { var charCode = digit.charCodeAt(0); if (charCode >= "0".charCodeAt(0) && charCode <= "9".charCodeAt(0)) { return charCode - "0".charCodeAt(0); } else if (charCode >= "a".charCodeAt(0) && charCode <= "z".charCodeAt(0)) { return charCode - "a".charCodeAt(0) + 10; } else if (charCode >= "A".charCodeAt(0) && charCode <= "Z".charCodeAt(0)) { return charCode - "A".charCodeAt(0) + 36; } else { console.error("Cannot convert from base64: " + digit); return null; } } hundo.Compress.dirToNum = function(dir) { if (dir == hundo.DirectionEnum.UP) { return "0"; } else if (dir == hundo.DirectionEnum.DOWN) { return "1"; } else if (dir == hundo.DirectionEnum.LEFT) { return "2"; } else if (dir == hundo.DirectionEnum.RIGHT) { return "3"; } else { console.error("Bad direction: " + dir); return null; } } hundo.Compress.numToDir = function(num) { if (num == "0") { return hundo.DirectionEnum.UP; } else if (num == "1") { return hundo.DirectionEnum.DOWN; } else if (num == "2") { return hundo.DirectionEnum.LEFT; } else if (num == "3") { return hundo.DirectionEnum.RIGHT; } else { console.error("Bad num: " + num); return null; } } hundo.Compress.sep = "-"; // assumes numRows, numCols < 32 hundo.Compress.compressLevel = function(level) { var levelArray = []; // The first two bytes encode numRows, numCols levelArray.push(hundo.Compress.toBase64Digit(level.numRows)); levelArray.push(hundo.Compress.toBase64Digit(level.numCols)); // The next two bytes encode ball.row, ball.col if (typeof level.ball != "undefined") { levelArray.push(hundo.Compress.toBase64Digit(level.ball.row)); levelArray.push(hundo.Compress.toBase64Digit(level.ball.col)); } // signifies beginning of blocks levelArray.push(hundo.Compress.sep); // Encode each block as (block.row, block.col) pair _.each(level.blocks, function(block){ levelArray.push(hundo.Compress.toBase64Digit(block.row)); levelArray.push(hundo.Compress.toBase64Digit(block.col)); }); // separates blocks and goals levelArray.push(hundo.Compress.sep); // Encode the goals, like blocks _.each(level.goals, function(goal){ levelArray.push(hundo.Compress.toBase64Digit(goal.row)); levelArray.push(hundo.Compress.toBase64Digit(goal.col)); levelArray.push(hundo.Compress.dirToNum(goal.dir)) }); // separator levelArray.push(hundo.Compress.sep); // Encode the ice _.each(level.ice, function(ice){ levelArray.push(hundo.Compress.toBase64Digit(ice.row)); levelArray.push(hundo.Compress.toBase64Digit(ice.col)); }); // separator levelArray.push(hundo.Compress.sep); // Encode the arrows _.each(level.arrows, function(arrow){ levelArray.push(hundo.Compress.toBase64Digit(arrow.row)); levelArray.push(hundo.Compress.toBase64Digit(arrow.col)); levelArray.push(hundo.Compress.dirToNum(arrow.dir)) }); // separator levelArray.push(hundo.Compress.sep); // Encode the gblocks _.each(level.gblocks, function(gblock){ levelArray.push(hundo.Compress.toBase64Digit(gblock.row)); levelArray.push(hundo.Compress.toBase64Digit(gblock.col)); levelArray.push(hundo.Compress.toBase64Digit(gblock.groupNum)); }); return _.join(levelArray, ""); } hundo.Compress.getRowCol = function(bytes) { var row = hundo.Compress.fromBase64Digit(bytes[0]); var col = hundo.Compress.fromBase64Digit(bytes[1]); bytes.shift(); bytes.shift(); return [row, col]; } // 64-bit bytes // TODO: factor out common code hundo.Compress.decompressLevel = function(byteString) { var level = { blocks: [], goals: [], ice: [], arrows: [], gblocks: [] }; var bytes = _.split(byteString, "") var [r, c] = hundo.Compress.getRowCol(bytes); level.numRows = r; level.numCols = c; // Get the ball, if it's there if (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); level.ball = { row: r, col: c } } // shift past the sep if (bytes.length > 0) { if (bytes[0] != hundo.Compress.sep) { console.error("Could not parse level"); return null; } bytes.shift(); } // Get the blocks while (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); block = { row: r, col: c } level.blocks.push(block); } // shift past the sep if (bytes.length > 0) { if (bytes[0] != hundo.Compress.sep) { console.error("Could not parse level"); return null; } bytes.shift(); } // Get the goals while (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); var dir = hundo.Compress.numToDir(bytes[0]); bytes.shift(); goal = { row: r, col: c, dir: dir } level.goals.push(goal); } // shift past the sep if (bytes.length > 0) { if (bytes[0] != hundo.Compress.sep) { console.error("Could not parse level"); return null; } bytes.shift(); } while (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); ice = { row: r, col: c } level.ice.push(ice); } // shift past the sep if (bytes.length > 0) { if (bytes[0] != hundo.Compress.sep) { console.error("Could not parse level"); return null; } bytes.shift(); } // Get the arrows while (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); var dir = hundo.Compress.numToDir(bytes[0]); bytes.shift(); arrow = { row: r, col: c, dir: dir } level.arrows.push(arrow); } // shift past the sep if (bytes.length > 0) { if (bytes[0] != hundo.Compress.sep) { console.error("Could not parse level"); return null; } bytes.shift(); } // Get the gblocks while (bytes.length > 0 && bytes[0] != hundo.Compress.sep) { [r, c] = hundo.Compress.getRowCol(bytes); var groupNum = hundo.Compress.fromBase64Digit(bytes[0]); bytes.shift(); gblock = { row: r, col: c, groupNum: groupNum } level.gblocks.push(gblock); } return level; } hundo.instances = {} hundo.vizz = null; hundo.defaultVizConfig = { cellSize: 26, stepDuration: 50, flyInDuration: 250, blowupScale: 3, perimStrokeWidth: 3, numRows: 15, numCols: 21, playButton: false, levelSelect: true, levelMax: 0 } document.onkeydown = hundo.Viz.checkKey;
integrated board.eq into solver
public/js/hundo.js
integrated board.eq into solver
<ide><path>ublic/js/hundo.js <ide> hundo.Solver.prototype.hasExploredVertex = function(board1) { <ide> <ide> var matches = _.flatMap(this.boards, function(board2) { <del> if (Object.compare(board1, board2)) { <add> if (board1.eq(board2)) { <ide> return [true]; <ide> } else { <ide> return [];
Java
lgpl-2.1
5736343fe0cd5dc0e3a3875025ebb0031a0a6d32
0
sbonoc/opencms-core,sbonoc/opencms-core,gallardo/opencms-core,gallardo/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,it-tavis/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,alkacon/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,victos/opencms-core,it-tavis/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,sbonoc/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,serrapos/opencms-core,serrapos/opencms-core,gallardo/opencms-core,victos/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,serrapos/opencms-core,victos/opencms-core,ggiudetti/opencms-core,victos/opencms-core,mediaworx/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,serrapos/opencms-core,serrapos/opencms-core
/* * File : $Source: /alkacon/cvs/opencms/src/org/opencms/file/CmsObject.java,v $ * Date : $Date: 2004/04/05 05:33:46 $ * Version: $Revision: 1.25 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2002 - 2003 Alkacon Software (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.file; import org.opencms.db.CmsDriverManager; import org.opencms.db.CmsPublishList; import org.opencms.db.CmsPublishedResource; import org.opencms.lock.CmsLock; import org.opencms.main.CmsEvent; import org.opencms.main.CmsException; import org.opencms.main.CmsSessionInfoManager; import org.opencms.main.I_CmsConstants; import org.opencms.main.I_CmsEventListener; import org.opencms.main.OpenCms; import org.opencms.report.CmsShellReport; import org.opencms.report.I_CmsReport; import org.opencms.security.CmsAccessControlEntry; import org.opencms.security.CmsAccessControlList; import org.opencms.security.CmsPermissionSet; import org.opencms.security.CmsSecurityException; import org.opencms.security.I_CmsPrincipal; import org.opencms.util.CmsUUID; import org.opencms.workflow.CmsTask; import org.opencms.workflow.CmsTaskLog; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.commons.collections.ExtendedProperties; /** * This pivotal class provides all authorized access to the OpenCms resources.<p> * * It encapsulates user identification and permissions. * Think of it as the initialized "Shell" to access the OpenCms resources. * Every call to a method here will be checked for user permissions * according to the context the CmsObject instance was created with.<p> * * @author Alexander Kandzior ([email protected]) * @author Thomas Weckert ([email protected]) * @author Carsten Weinholz ([email protected]) * @author Andreas Zahner ([email protected]) * * @version $Revision: 1.25 $ */ public class CmsObject { /** * The request context. */ private CmsRequestContext m_context; /** * The driver manager to access the cms. */ private CmsDriverManager m_driverManager; /** * Method that can be invoked to find out all currently logged in users. */ private CmsSessionInfoManager m_sessionStorage; /** * The default constructor. */ public CmsObject() { // noop } /** * Initializes this CmsObject with the provided user context and database connection.<p> * * @param driverManager the driver manager to access the database * @param context the request context that contains the user authentification * @param sessionStorage the core session */ public void init( CmsDriverManager driverManager, CmsRequestContext context, CmsSessionInfoManager sessionStorage ) { m_sessionStorage = sessionStorage; m_driverManager = driverManager; m_context = context; } /** * Accept a task from the Cms. * * @param taskId the id of the task to accept. * * @throws CmsException if operation was not successful. */ public void acceptTask(int taskId) throws CmsException { m_driverManager.acceptTask(m_context, taskId); } /** * Checks if the user can access the project. * * @param projectId the id of the project. * @return <code>true</code>, if the user may access this project; <code>false</code> otherwise * * @throws CmsException if operation was not successful. */ public boolean accessProject(int projectId) throws CmsException { return (m_driverManager.accessProject(m_context, projectId)); } /** * Adds a file extension to the list of known file extensions. * <p> * <b>Security:</b> * Only members of the group administrators are allowed to add a file extension. * * @param extension a file extension like "html","txt" etc. * @param resTypeName name of the resource type associated with the extension. * * @throws CmsException if operation was not successful. */ public void addFileExtension(String extension, String resTypeName) throws CmsException { m_driverManager.addFileExtension(m_context, extension, resTypeName); } /** * Adds a user to the Cms by import. * <p> * <b>Security:</b> * Only members of the group administrators are allowed to add a user. * * @param id the id of the user * @param name the new name for the user. * @param password the new password for the user. * @param recoveryPassword the new password for the user. * @param description the description for the user. * @param firstname the firstname of the user. * @param lastname the lastname of the user. * @param email the email of the user. * @param flags the flags for a user (e.g. C_FLAG_ENABLED). * @param additionalInfos a Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param defaultGroup the default groupname for the user. * @param address the address of the user. * @param section the section of the user. * @param type the type of the user. * * @return a <code>CmsUser</code> object representing the added user. * * @throws CmsException if operation was not successful. */ public CmsUser addImportUser(String id, String name, String password, String recoveryPassword, String description, String firstname, String lastname, String email, int flags, Hashtable additionalInfos, String defaultGroup, String address, String section, int type) throws CmsException { return m_driverManager.addImportUser(m_context, id, name, password, recoveryPassword, description, firstname, lastname, email, flags, additionalInfos, defaultGroup, address, section, type); } /** * Returns the name of a resource with the complete site root name, * (e.g. /default/vfs/index.html) by adding the currently set site root prefix.<p> * * @param resourcename the resource name * @return the resource name including site root */ private String addSiteRoot(String resourcename) { return getRequestContext().addSiteRoot(resourcename); } /** * Adds a user to the OpenCms user table.<p> * * <b>Security:</b> * Only members of the group administrators are allowed to add a user.<p> * * @param name the new name for the user * @param password the password for the user * @param group the default groupname for the user * @param description the description for the user * @param additionalInfos a Hashtable with additional infos for the user * @return the newly created user * @throws CmsException if something goes wrong */ public CmsUser addUser(String name, String password, String group, String description, Hashtable additionalInfos) throws CmsException { return m_driverManager.addUser(m_context, name, password, group, description, additionalInfos); } /** * Adds a user to a group.<p> * * <b>Security:</b> * Only members of the group administrators are allowed to add a user to a group. * * @param username the name of the user that is to be added to the group * @param groupname the name of the group * @throws CmsException if something goes wrong */ public void addUserToGroup(String username, String groupname) throws CmsException { m_driverManager.addUserToGroup(m_context, username, groupname); } /** * Adds a web user to the OpenCms user table.<p> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms. * Moreover, a web user can be created by any user, the intention being that * a "Guest"user can create a personalized account from himself. * * @param name the name for the user * @param password the password for the user * @param group the default groupname for the user * @param description the description for the user * @param additionalInfos a Hashtable with additional infos for the user * @return the newly created user * @throws CmsException if something goes wrong */ public CmsUser addWebUser(String name, String password, String group, String description, Hashtable additionalInfos) throws CmsException { return m_driverManager.addWebUser(name, password, group, description, additionalInfos); } /** * Creates a backup of the published project.<p> * * @param projectId The id of the project in which the resource was published * @param versionId The version of the backup * @param publishDate The date of publishing * * @throws CmsException Throws CmsException if operation was not succesful */ public void backupProject(int projectId, int versionId, long publishDate) throws CmsException { CmsProject backupProject = m_driverManager.readProject(projectId); m_driverManager.backupProject(m_context, backupProject, versionId, publishDate); } /** * Changes the access control for a given resource and a given principal(user/group). * * @param resourceName name of the resource * @param principalType the type of the principal (currently group or user) * @param principalName name of the principal * @param allowedPermissions bitset of allowed permissions * @param deniedPermissions bitset of denied permissions * @param flags flags * @throws CmsException if something goes wrong */ public void chacc(String resourceName, String principalType, String principalName, int allowedPermissions, int deniedPermissions, int flags) throws CmsException { CmsResource res = readFileHeader(resourceName); CmsAccessControlEntry acEntry = null; I_CmsPrincipal principal = null; if ("group".equals(principalType.toLowerCase())) { principal = readGroup(principalName); acEntry = new CmsAccessControlEntry(res.getResourceId(), principal.getId(), allowedPermissions, deniedPermissions, flags); acEntry.setFlags(I_CmsConstants.C_ACCESSFLAGS_GROUP); } else if ("user".equals(principalType.toLowerCase())) { principal = readUser(principalName); acEntry = new CmsAccessControlEntry(res.getResourceId(), principal.getId(), allowedPermissions, deniedPermissions, flags); acEntry.setFlags(I_CmsConstants.C_ACCESSFLAGS_USER); } m_driverManager.writeAccessControlEntry(m_context, res, acEntry); } /** * Changes the access control for a given resource and a given principal(user/group). * * @param resourceName name of the resource * @param principalType the type of the principal (group or user) * @param principalName name of the principal * @param permissionString the permissions in the format ((+|-)(r|w|v|c|i))* * @throws CmsException if something goes wrong */ public void chacc(String resourceName, String principalType, String principalName, String permissionString) throws CmsException { CmsResource res = readFileHeader(resourceName); CmsAccessControlEntry acEntry = null; I_CmsPrincipal principal = null; if ("group".equals(principalType.toLowerCase())) { principal = readGroup(principalName); acEntry = new CmsAccessControlEntry(res.getResourceId(), principal.getId(), permissionString); acEntry.setFlags(I_CmsConstants.C_ACCESSFLAGS_GROUP); } else if ("user".equals(principalType.toLowerCase())) { principal = readUser(principalName); acEntry = new CmsAccessControlEntry(res.getResourceId(), principal.getId(), permissionString); acEntry.setFlags(I_CmsConstants.C_ACCESSFLAGS_USER); } m_driverManager.writeAccessControlEntry(m_context, res, acEntry); } /** * Changes the project-id of a resource to the new project * for publishing the resource directly.<p> * * @param projectId The new project-id * @param resourcename The name of the resource to change * @throws CmsException if something goes wrong */ public void changeLockedInProject(int projectId, String resourcename) throws CmsException { // must include files marked as deleted when publishing getResourceType(readFileHeader(resourcename, true).getType()).changeLockedInProject(this, projectId, resourcename); } /** * Changes the type of the user * * @param userId The id of the user to change * @param userType The new type of the user * @throws CmsException if something goes wrong */ public void changeUserType(CmsUUID userId, int userType) throws CmsException { m_driverManager.changeUserType(m_context, userId, userType); } /** * Changes the type of the user to webusertype * * @param username The name of the user to change * @param userType The new type of the user * @throws CmsException if something goes wrong */ public void changeUserType(String username, int userType) throws CmsException { m_driverManager.changeUserType(m_context, username, userType); } /** * Changes the resourcetype of a resource. * <br> * Only the resourcetype of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. * <p> * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename the complete path to the resource. * @param newType the name of the new resourcetype for this resource. * * @throws CmsException if operation was not successful. */ public void chtype(String filename, int newType) throws CmsException { getResourceType(readFileHeader(filename).getType()).chtype(this, filename, newType); } /** * Copies a file. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfolder. * * @throws CmsException if the file couldn't be copied, or the user * has not the appropriate rights to copy the file. * * @deprecated Use copyResource instead. */ public void copyFile(String source, String destination) throws CmsException { copyResource(source, destination, false, true, I_CmsConstants.C_COPY_PRESERVE_SIBLING); } /** * Copies a folder. * * @param source the complete path of the sourcefolder. * @param destination the complete path of the destinationfolder. * * @throws CmsException if the folder couldn't be copied, or if the * user has not the appropriate rights to copy the folder. * * @deprecated Use copyResource instead. */ public void copyFolder(String source, String destination) throws CmsException { copyResource(source, destination, false, false, I_CmsConstants.C_COPY_PRESERVE_SIBLING); } /** * Copies a file. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfolder. * * @throws CmsException if the file couldn't be copied, or the user * has not the appropriate rights to copy the file. */ public void copyResource(String source, String destination) throws CmsException { getResourceType(readFileHeader(source).getType()).copyResource(this, source, destination, false, true, I_CmsConstants.C_COPY_PRESERVE_SIBLING); } /** * Copies a file. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfolder. * @param keepFlags <code>true</code> if the copy should keep the source file's flags, * <code>false</code> if the copy should get the user's default flags. * @param lockCopy indicates if the copy should left locked after operation * @param copyMode mode of the copy operation, described how to handle linked resourced during copy. * Possible values are: * <ul> * <li>C_COPY_AS_NEW</li> * <li>C_COPY_AS_SIBLING</li> * <li>C_COPY_PRESERVE_SIBLING</li> * </ul> * @throws CmsException if the file couldn't be copied, or the user * has not the appropriate rights to copy the file. */ public void copyResource(String source, String destination, boolean keepFlags, boolean lockCopy, int copyMode) throws CmsException { getResourceType(readFileHeader(source).getType()).copyResource(this, source, destination, keepFlags, lockCopy, copyMode); } /** * Copies a resource from the online project to a new, specified project. * <br> * Copying a resource will copy the file header or folder into the specified * offline project and set its state to UNCHANGED. * * @param resource the name of the resource. * @throws CmsException if operation was not successful. */ public void copyResourceToProject(String resource) throws CmsException { getResourceType(readFileHeader(resource).getType()).copyResourceToProject(this, resource); } /** * Counts the locked resources in a project. * * @param id the id of the project * @return the number of locked resources in this project. * * @throws CmsException if operation was not successful. */ public int countLockedResources(int id) throws CmsException { return m_driverManager.countLockedResources(m_context, id); } /** * Counts the locked resources within a folder.<p> * * @param foldername the name of the folder * @return the number of locked resources in this folder * * @throws CmsException if operation was not successful. */ public int countLockedResources(String foldername) throws CmsException { return m_driverManager.countLockedResources(m_context, addSiteRoot(foldername)); } /** * Copies access control entries of a given resource to another resource.<p> * * @param sourceName the name of the resource of which the access control entries are copied * @param destName the name of the resource to which the access control entries are applied * @throws CmsException if something goes wrong */ public void cpacc(String sourceName, String destName) throws CmsException { CmsResource source = readFileHeader(sourceName); CmsResource dest = readFileHeader(destName); m_driverManager.copyAccessControlEntries(m_context, source, dest); } /** * Creates a new channel. * * @param parentChannel the complete path to the channel in which the new channel * will be created. * @param newChannelName the name of the new channel. * * @return folder a <code>CmsFolder</code> object representing the newly created channel. * * @throws CmsException if the channelname is not valid, or if the user has not the appropriate rights to create * a new channel. * */ public CmsFolder createChannel(String parentChannel, String newChannelName) throws CmsException { getRequestContext().saveSiteRoot(); try { setContextToCos(); Hashtable properties = new Hashtable(); int newChannelId = org.opencms.db.CmsDbUtil.nextId(I_CmsConstants.C_TABLE_CHANNELID); properties.put(I_CmsConstants.C_PROPERTY_CHANNELID, newChannelId + ""); return (CmsFolder)createResource(parentChannel, newChannelName, CmsResourceTypeFolder.C_RESOURCE_TYPE_ID, properties); } finally { getRequestContext().restoreSiteRoot(); } } /** * Creates a new file with the given content and resourcetype.<br> * * @param folder the complete path to the folder in which the file will be created. * @param filename the name of the new file. * @param contents the contents of the new file. * @param type the resourcetype of the new file. * * @return file a <code>CmsFile</code> object representing the newly created file. * * @throws CmsException if the resourcetype is set to folder. The CmsException is also thrown, if the * filename is not valid or if the user has not the appropriate rights to create a new file. * * @deprecated Use createResource instead. */ public CmsFile createFile(String folder, String filename, byte[] contents, int type) throws CmsException { return (CmsFile)createResource(folder, filename, type, null, contents); } /** * Creates a new file with the given content and resourcetype. * * @param folder the complete path to the folder in which the file will be created. * @param filename the name of the new file. * @param contents the contents of the new file. * @param type the resourcetype of the new file. * @param properties A Hashtable of properties, that should be set for this file. * The keys for this Hashtable are the names for properties, the values are * the values for the properties. * * @return file a <code>CmsFile</code> object representing the newly created file. * * @throws CmsException or if the resourcetype is set to folder. * The CmsException is also thrown, if the filename is not valid or if the user * has not the appropriate rights to create a new file. * * @deprecated Use createResource instead. */ public CmsFile createFile(String folder, String filename, byte[] contents, int type, Hashtable properties) throws CmsException { return (CmsFile)createResource(folder, filename, type, properties, contents); } /** * Creates a new folder. * * @param folder the complete path to the folder in which the new folder * will be created. * @param newFolderName the name of the new folder. * * @return folder a <code>CmsFolder</code> object representing the newly created folder. * * @throws CmsException if the foldername is not valid, or if the user has not the appropriate rights to create * a new folder. * * @deprecated Use createResource instead. */ public CmsFolder createFolder(String folder, String newFolderName) throws CmsException { return (CmsFolder)createResource(folder, newFolderName, CmsResourceTypeFolder.C_RESOURCE_TYPE_ID); } /** * Adds a new group to the Cms.<p> * * <b>Security:</b> * Only members of the group administrators are allowed to add a new group. * * @param name the name of the new group * @param description the description of the new group * @param flags the flags for the new group * @param parent the parent group * * @return a <code>CmsGroup</code> object representing the newly created group. * * @throws CmsException if operation was not successful. */ public CmsGroup createGroup(String name, String description, int flags, String parent) throws CmsException { return (m_driverManager.createGroup(m_context, name, description, flags, parent)); } /** * Adds a new group to the Cms.<p> * * <b>Security:</b> * Only members of the group administrators are allowed to add a new group. * * @param id the id of the group * @param name the name of the new group * @param description the description of the new group * @param flags the flags for the new group * @param parent the parent group * @return a <code>CmsGroup</code> object representing the newly created group. * @throws CmsException if something goes wrong */ public CmsGroup createGroup(String id, String name, String description, int flags, String parent) throws CmsException { return m_driverManager.createGroup(m_context, id, name, description, flags, parent); } /** * Creates a new project. * * @param name the name of the project to create * @param description the description for the new project * @param groupname the name of the project user group * @param managergroupname the name of the project manager group * @return the created project * @throws CmsException if something goes wrong */ public CmsProject createProject(String name, String description, String groupname, String managergroupname) throws CmsException { CmsProject newProject = m_driverManager.createProject(m_context, name, description, groupname, managergroupname, I_CmsConstants.C_PROJECT_TYPE_NORMAL); return (newProject); } /** * Creates a new project. * * @param name the name of the project to create * @param description the description for the new project * @param groupname the name of the project user group * @param managergroupname the name of the project manager group * @param projecttype the type of the project (normal or temporary) * @return the created project * @throws CmsException if operation was not successful. */ public CmsProject createProject(String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException { CmsProject newProject = m_driverManager.createProject(m_context, name, description, groupname, managergroupname, projecttype); return (newProject); } /** * Creates the property-definition for a resource type. * * @param name the name of the property-definition to overwrite * @param resourcetype the name of the resource-type for the property-definition * @return the new property definition * * @throws CmsException if operation was not successful. */ public CmsPropertydefinition createPropertydefinition(String name, int resourcetype) throws CmsException { return (m_driverManager.createPropertydefinition(m_context, name, resourcetype)); } /** * Creates a new resource.<p> * * @param newResourceName name of the resource * @param type type of the resource * @param properties properties of the resource * @param contents content of the resource * @param parameter additional parameter * @return the new resource * @throws CmsException if something goes wrong */ public CmsResource createResource(String newResourceName, int type, Map properties, byte[] contents, Object parameter) throws CmsException { return getResourceType(type).createResource(this, newResourceName, properties, contents, parameter); } /** * Creates a new resource.<p> * * @param folder name of the parent folder * @param name name of the resource * @param type type of the resource * @return the new resource * @throws CmsException if something goes wrong */ public CmsResource createResource(String folder, String name, int type) throws CmsException { return createResource(folder + name, type, new HashMap(), new byte[0], null); } /** * Creates a new resource.<p> * * @param folder name of the parent folder * @param name name of the resource * @param type type of the resource * @param properties properties of the resource * @return the new resource * @throws CmsException if something goes wrong */ public CmsResource createResource(String folder, String name, int type, Map properties) throws CmsException { return createResource(folder + name, type, properties, new byte[0], null); } /** * Creates a new resource.<p> * * @param folder name of the parent folder * @param name name of the resource * @param type type of the resource * @param properties properties of the resource * @param contents content of the resource * @return the new resource * @throws CmsException if something goes wrong */ public CmsResource createResource(String folder, String name, int type, Map properties, byte[] contents) throws CmsException { return createResource(folder + name, type, properties, contents, null); } /** * Creates a new task.<p> * * <B>Security:</B> * All users can create a new task. * * @param projectid the Id of the current project task of the user * @param agentName the User who will edit the task * @param roleName a Usergroup for the task * @param taskname a Name of the task * @param tasktype the type of the task * @param taskcomment a description of the task * @param timeout the time when the task must finished * @param priority the Id for the priority of the task * @return the created task * @throws CmsException if something goes wrong */ public CmsTask createTask(int projectid, String agentName, String roleName, String taskname, String taskcomment, int tasktype, long timeout, int priority) throws CmsException { return m_driverManager.createTask(m_context.currentUser(), projectid, agentName, roleName, taskname, taskcomment, tasktype, timeout, priority); } /** * Creates a new task.<p> * * <B>Security:</B> * All users can create a new task. * * @param agentName the User who will edit the task * @param roleName a Usergroup for the task * @param taskname the name of the task * @param timeout the time when the task must finished * @param priority the Id for the priority of the task * @return the created task * @throws CmsException if something goes wrong */ public CmsTask createTask(String agentName, String roleName, String taskname, long timeout, int priority) throws CmsException { return (m_driverManager.createTask(m_context, agentName, roleName, taskname, timeout, priority)); } /** * Creates the project for the temporary workplace files.<p> * * @return the created project for the temporary workplace files * @throws CmsException if something goes wrong */ public CmsProject createTempfileProject() throws CmsException { return m_driverManager.createTempfileProject(m_context); } /** * Creates a new sibling of the target resource.<p> * * @param linkName name of the new link * @param targetName name of the target * @param linkProperties additional properties of the link resource * @return the new link resource * @throws CmsException if something goes wrong */ public CmsResource createSibling(String linkName, String targetName, Map linkProperties) throws CmsException { // TODO new property model: creating siblings does not support the new property model yet return m_driverManager.createSibling(m_context, addSiteRoot(linkName), addSiteRoot(targetName), CmsProperty.toList(linkProperties), true); } /** * Deletes all properties for a file or folder. * * @param resourcename the name of the resource for which all properties should be deleted. * * @throws CmsException if operation was not successful. */ public void deleteAllProperties(String resourcename) throws CmsException { m_driverManager.deleteAllProperties(m_context, addSiteRoot(resourcename)); } /** * Deletes the versions from the backup tables that are older then the given timestamp and/or number of remaining versions.<p> * * The number of verions always wins, i.e. if the given timestamp would delete more versions than given in the * versions parameter, the timestamp will be ignored. * Deletion will delete file header, content and properties. * * @param timestamp timestamp which defines the date after which backup resources must be deleted * @param versions the number of versions per file which should kept in the system. * @param report the report for output logging * * @throws CmsException if something goes wrong */ public void deleteBackups(long timestamp, int versions, I_CmsReport report) throws CmsException { m_driverManager.deleteBackups(m_context, timestamp, versions, report); } /** * Deletes a folder. * <br> * This is a very complex operation, because all sub-resources may be * deleted too. * * @param foldername the complete path of the folder. * * @throws CmsException if the folder couldn't be deleted, or if the user * has not the rights to delete this folder. * */ public void deleteEmptyFolder(String foldername) throws CmsException { m_driverManager.deleteFolder(m_context, addSiteRoot(foldername)); } /** * Deletes a file. * * @param filename the complete path of the file. * * @throws CmsException if the file couldn't be deleted, or if the user * has not the appropriate rights to delete the file. * * @deprecated Use deleteResource instead. */ public void deleteFile(String filename) throws CmsException { deleteResource(filename, I_CmsConstants.C_DELETE_OPTION_IGNORE_SIBLINGS); } /** * Deletes a folder. * <br> * This is a very complex operation, because all sub-resources may be * deleted too. * * @param foldername the complete path of the folder. * * @throws CmsException if the folder couldn't be deleted, or if the user * has not the rights to delete this folder. * * @deprecated Use deleteResource instead. */ public void deleteFolder(String foldername) throws CmsException { deleteResource(foldername, I_CmsConstants.C_DELETE_OPTION_IGNORE_SIBLINGS); } /** * Deletes a group. * <p> * <b>Security:</b> * Only the admin user is allowed to delete a group. * * @param delgroup the name of the group. * @throws CmsException if operation was not successful. */ public void deleteGroup(String delgroup) throws CmsException { m_driverManager.deleteGroup(m_context, delgroup); } /** * Deletes a project.<p> * * @param id the id of the project to delete. * * @throws CmsException if operation was not successful. */ public void deleteProject(int id) throws CmsException { m_driverManager.deleteProject(m_context, id); } /** * Deletes a property for a file or folder.<p> * * @param resourcename the name of a resource for which the property should be deleted * @param key the name of the property * @throws CmsException if something goes wrong * @deprecated use {@link #writePropertyObject(String, CmsProperty)} instead */ public void deleteProperty(String resourcename, String key) throws CmsException { CmsProperty property = new CmsProperty(); property.setKey(key); property.setStructureValue(CmsProperty.C_DELETE_VALUE); m_driverManager.writePropertyObject(m_context, addSiteRoot(resourcename), property); } /** * Deletes the property-definition for a resource type.<p> * * @param name the name of the property-definition to delete * @param resourcetype the name of the resource-type for the property-definition. * * @throws CmsException if something goes wrong */ public void deletePropertydefinition(String name, int resourcetype) throws CmsException { m_driverManager.deletePropertydefinition(m_context, name, resourcetype); } /** * Deletes a resource.<p> * * @param filename the filename of the resource exlucing the site root * @param deleteOption signals how VFS links pointing to this resource should be handled * @throws CmsException if the user has insufficient acces right to delete the resource * @see org.opencms.main.I_CmsConstants#C_DELETE_OPTION_DELETE_SIBLINGS * @see org.opencms.main.I_CmsConstants#C_DELETE_OPTION_IGNORE_SIBLINGS * @see org.opencms.main.I_CmsConstants#C_DELETE_OPTION_PRESERVE_SIBLINGS */ public void deleteResource(String filename, int deleteOption) throws CmsException { getResourceType(readFileHeader(filename).getType()).deleteResource(this, filename, deleteOption); } /** * Deletes an entry in the published resource table.<p> * * @param resourceName The name of the resource to be deleted in the static export * @param linkType the type of resource deleted (0= non-paramter, 1=parameter) * @param linkParameter the parameters of the resource * @throws CmsException if something goes wrong */ public void deleteStaticExportPublishedResource(String resourceName, int linkType, String linkParameter) throws CmsException { m_driverManager.deleteStaticExportPublishedResource(m_context, resourceName, linkType, linkParameter); } /** * Deletes all entries in the published resource table.<p> * * @param linkType the type of resource deleted (0= non-paramter, 1=parameter) * @throws CmsException if something goes wrong */ public void deleteAllStaticExportPublishedResources(int linkType) throws CmsException { m_driverManager.deleteAllStaticExportPublishedResources(m_context, linkType); } /** * Deletes a user from the Cms.<p> * * <b>Security:</b> * Only a admin user is allowed to delete a user. * * @param userId the Id of the user to be deleted. * * @throws CmsException if operation was not successful. */ public void deleteUser(CmsUUID userId) throws CmsException { m_driverManager.deleteUser(m_context, userId); } /** * Deletes a user from the Cms.<p> * * <b>Security:</b> * Only a admin user is allowed to delete a user. * * @param username the name of the user to be deleted. * * @throws CmsException if operation was not successful. */ public void deleteUser(String username) throws CmsException { m_driverManager.deleteUser(m_context, username); } /** * Deletes a web user from the Cms.<p> * * @param userId the id of the user to be deleted. * * @throws CmsException if operation was not successful. */ public void deleteWebUser(CmsUUID userId) throws CmsException { m_driverManager.deleteWebUser(userId); } /** * Method to encrypt the passwords.<p> * * @param value The value to encrypt. * @return The encrypted value. */ public String digest(String value) { return m_driverManager.digest(value); } /** * Changes the project id of a resource to the current project of the user.<p> * * @param resourcename the resource to change * @throws CmsException if something goes wrong */ protected void doChangeLockedInProject(String resourcename) throws CmsException { m_driverManager.changeLockedInProject(m_context, addSiteRoot(resourcename)); } /** * Changes the resourcetype of a resource. * <br> * Only the resourcetype of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. * <p> * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename the complete path to the resource. * @param newType the name of the new resourcetype for this resource. * * @throws CmsException if operation was not successful. */ protected void doChtype(String filename, int newType) throws CmsException { m_driverManager.chtype(m_context, addSiteRoot(filename), newType); } /** * Copies a file. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfolder. * @param lockCopy flag to lock the copied resource * @param copyMode mode of the copy operation, described how to handle linked resourced during copy. * Possible values are: * <ul> * <li>C_COPY_AS_NEW</li> * <li>C_COPY_AS_SIBLING</li> * <li>C_COPY_PRESERVE_SIBLING</li> * </ul> * @throws CmsException if the file couldn't be copied, or the user * has not the appropriate rights to copy the file. */ protected void doCopyFile(String source, String destination, boolean lockCopy, int copyMode) throws CmsException { m_driverManager.copyFile(m_context, addSiteRoot(source), addSiteRoot(destination), lockCopy, false, copyMode); } /** * Copies a folder. * * @param source the complete path of the sourcefolder. * @param destination the complete path of the destinationfolder. * @param lockCopy indicates if the copy of the folder should remain locked after operation * @param preserveTimestamps true if the timestamps and users of the folder should be kept * @throws CmsException if the folder couldn't be copied, or if the * user has not the appropriate rights to copy the folder. */ protected void doCopyFolder(String source, String destination, boolean lockCopy, boolean preserveTimestamps) throws CmsException { m_driverManager.copyFolder(m_context, addSiteRoot(source), addSiteRoot(destination), lockCopy, preserveTimestamps); } /** * Copies a resource from the online project to a new, specified project. * <br> * Copying a resource will copy the file header or folder into the specified * offline project and set its state to UNCHANGED. * * @param resource the name of the resource. * @throws CmsException if operation was not successful. */ protected void doCopyResourceToProject(String resource) throws CmsException { m_driverManager.copyResourceToProject(m_context, addSiteRoot(resource)); } /** * Creates a new file with the given content and resourcetype.<br> * * @param newFileName the name of the new file. * @param contents the contents of the new file. * @param type the resourcetype of the new file. * * @return file a <code>CmsFile</code> object representing the newly created file. * * @throws CmsException if the resourcetype is set to folder. The CmsException is also thrown, if the * filename is not valid or if the user has not the appropriate rights to create a new file. */ protected CmsFile doCreateFile(String newFileName, byte[] contents, String type) throws CmsException { CmsFile file = m_driverManager.createFile(m_context, addSiteRoot(newFileName), contents, type, Collections.EMPTY_LIST); return file; } /** * Creates a new file with the given content and resourcetype. * * @param newFileName the name of the new file. * @param contents the contents of the new file. * @param type the resourcetype of the new file. * @param properties A Hashtable of properties, that should be set for this file. * The keys for this Hashtable are the names for properties, the values are * the values for the properties. * * @return file a <code>CmsFile</code> object representing the newly created file. * * @throws CmsException if the wrong properties are given, or if the resourcetype is set to folder. * The CmsException is also thrown, if the filename is not valid or if the user * has not the appropriate rights to create a new file. */ protected CmsFile doCreateFile(String newFileName, byte[] contents, String type, Map properties) throws CmsException { // avoid null-pointer exceptions if (properties == null) { properties = Collections.EMPTY_MAP; } // TODO new property model: creating files does not support the new property model yet CmsFile file = m_driverManager.createFile(m_context, addSiteRoot(newFileName), contents, type, CmsProperty.toList(properties)); return file; } /** * Creates a new folder. * * @param newFolderName the name of the new folder. * @param properties A Hashtable of properties, that should be set for this folder. * The keys for this Hashtable are the names for property-definitions, the values are * the values for the properties. * * @return a <code>CmsFolder</code> object representing the newly created folder. * @throws CmsException if the foldername is not valid, or if the user has not the appropriate rights to create * a new folder. * */ protected CmsFolder doCreateFolder(String newFolderName, Map properties) throws CmsException { // TODO new property model: creating folders does not support the new property model yet CmsFolder cmsFolder = m_driverManager.createFolder(m_context, addSiteRoot(newFolderName), CmsProperty.toList(properties)); return cmsFolder; } /** * Creates a new folder. * * @param folder the complete path to the folder in which the new folder * will be created. * @param newFolderName the name of the new folder. * * @return folder a <code>CmsFolder</code> object representing the newly created folder. * * @throws CmsException if the foldername is not valid, or if the user has not the appropriate rights to create * a new folder. */ protected CmsFolder doCreateFolder(String folder, String newFolderName) throws CmsException { CmsFolder cmsFolder = m_driverManager.createFolder(m_context, addSiteRoot(folder + newFolderName + I_CmsConstants.C_FOLDER_SEPARATOR), Collections.EMPTY_LIST); return cmsFolder; } /** * Deletes a file. * * @param filename the complete path of the file * @param deleteOption flag to delete siblings as well * * @throws CmsException if the file couldn't be deleted, or if the user * has not the appropriate rights to delete the file. */ protected void doDeleteFile(String filename, int deleteOption) throws CmsException { m_driverManager.deleteFile(m_context, addSiteRoot(filename), deleteOption); } /** * Deletes a folder. * <br> * This is a very complex operation, because all sub-resources may be * deleted too. * * @param foldername the complete path of the folder. * * @throws CmsException if the folder couldn't be deleted, or if the user * has not the rights to delete this folder. */ protected void doDeleteFolder(String foldername) throws CmsException { m_driverManager.deleteFolder(m_context, addSiteRoot(foldername)); } /** * Creates a new resource.<p> * * @param resource the resource to be imported * @param content the content of the resource if it is of type file * @param properties A Hashtable of propertyinfos, that should be set for this folder * The keys for this Hashtable are the names for propertydefinitions, the values are * the values for the propertyinfos * @param destination the name of the new resource * * @return a <code>CmsFolder</code> object representing the newly created folder * @throws CmsException if the resourcename is not valid, or if the user has not the appropriate rights to create * a new resource * */ protected CmsResource doImportResource(CmsResource resource, byte content[], Map properties, String destination) throws CmsException { // TODO new property model: the import/export does not support the new property model yet CmsResource cmsResource = m_driverManager.importResource(m_context, addSiteRoot(destination), resource, content, CmsProperty.toList(properties)); return cmsResource; } /** * Locks the given resource.<p> * * @param resource the complete path to the resource * @param mode flag indicating the mode (temporary or common) of a lock * @throws CmsException if something goes wrong */ protected void doLockResource(String resource, int mode) throws CmsException { m_driverManager.lockResource(m_context, addSiteRoot(resource), mode); } /** * Moves a file to the given destination.<p> * * @param source the complete path of the sourcefile * @param destination the complete path of the destinationfile * @throws CmsException if something goes wrong */ protected void doMoveResource(String source, String destination) throws CmsException { m_driverManager.moveResource(m_context, addSiteRoot(source), addSiteRoot(destination)); } /** * Moves a resource to the lost and found folder.<p> * * @param resourcename the complete path of the sourcefile * @param copyResource true, if the resource should be copied to its destination inside the lost+found folder * @return location of the moved resource * @throws CmsException if the user does not have the rights to move this resource, * or if the file couldn't be moved */ protected String doCopyToLostAndFound(String resourcename, boolean copyResource) throws CmsException { return m_driverManager.copyToLostAndFound(m_context, addSiteRoot(resourcename), copyResource); } /** * Renames a resource.<p> * * @param oldname the complete path to the resource which will be renamed * @param newname the new name of the resource * @throws CmsException if the user has not the rights * to rename the resource, or if the file couldn't be renamed */ protected void doRenameResource(String oldname, String newname) throws CmsException { m_driverManager.renameResource(m_context, addSiteRoot(oldname), newname); } /** * Replaces an already existing resource with new resource data.<p> * * @param resName name of the resource * @param newResContent new content of the resource * @param newResType new type of the resource * @param newResProps new properties * @return the replaced resource * @throws CmsException if something goes wrong */ protected CmsResource doReplaceResource(String resName, byte[] newResContent, int newResType, Map newResProps) throws CmsException { CmsResource res = null; // TODO new property model: replacing resource does not yet support the new property model res = m_driverManager.replaceResource(m_context, addSiteRoot(resName), newResType, CmsProperty.toList(newResProps), newResContent); return res; } /** * Restores a file in the current project with a version in the backup * * @param tagId The tag id of the resource * @param filename The name of the file to restore * * @throws CmsException Throws CmsException if operation was not succesful. */ protected void doRestoreResource(int tagId, String filename) throws CmsException { m_driverManager.restoreResource(m_context, tagId, addSiteRoot(filename)); } /** * Access the driver manager underneath to change the timestamp of a resource. * * @param resourceName the name of the resource to change * @param timestamp timestamp the new timestamp of the changed resource * @param user the user who is inserted as userladtmodified * @throws CmsException if something goes wrong */ protected void doTouch(String resourceName, long timestamp, CmsUUID user) throws CmsException { m_driverManager.touch(m_context, addSiteRoot(resourceName), timestamp, user); } /** * Undeletes a file. * * @param filename the complete path of the file. * * @throws CmsException if the file couldn't be undeleted, or if the user * has not the appropriate rights to undelete the file. */ protected void doUndeleteFile(String filename) throws CmsException { m_driverManager.undeleteResource(m_context, addSiteRoot(filename)); } /** * Undeletes a folder. * <br> * This is a very complex operation, because all sub-resources may be * undeleted too. * * @param foldername the complete path of the folder. * * @throws CmsException if the folder couldn't be undeleted, or if the user * has not the rights to undelete this folder. */ protected void doUndeleteFolder(String foldername) throws CmsException { m_driverManager.undeleteResource(m_context, addSiteRoot(foldername)); } /** * Undo changes in a file. * <br> * * @param resource the complete path to the resource to be unlocked. * * @throws CmsException if the user has not the rights * to write this resource. */ protected void doUndoChanges(String resource) throws CmsException { m_driverManager.undoChanges(m_context, addSiteRoot(resource)); } /** * Unlocks a resource. * <br> * A user can unlock a resource, so other users may lock this file. * * @param resource the complete path to the resource to be unlocked. * * @throws CmsException if the user has not the rights * to unlock this resource. */ protected void doUnlockResource(String resource) throws CmsException { m_driverManager.unlockResource(m_context, addSiteRoot(resource)); } /** * Writes a resource and its properties to the VFS.<p> * * @param resourcename the name of the resource to write * @param properties the properties of the resource * @param filecontent the new filecontent of the resource * @throws CmsException if something goes wrong */ protected void doWriteResource(String resourcename, Map properties, byte[] filecontent) throws CmsException { // TODO new property model: the import/export does not support the new property model yet m_driverManager.writeResource(m_context, addSiteRoot(resourcename), CmsProperty.toList(properties), filecontent); } /** * Ends a task.<p> * * @param taskid the ID of the task to end. * * @throws CmsException if operation was not successful. */ public void endTask(int taskid) throws CmsException { m_driverManager.endTask(m_context, taskid); } /** * Tests if a resource with the given resourceId does already exist in the Database.<p> * * @param resourceId the resource id to test for * @return true if a resource with the given id was found, false otherweise * @throws CmsException if something goes wrong */ public boolean existsResourceId (CmsUUID resourceId) throws CmsException { return m_driverManager.existsResourceId(m_context, resourceId); } /** * Exports a resource. * * @param file the resource to export * @return the resource that was exported * @throws CmsException if something goes wrong */ public CmsFile exportResource(CmsFile file) throws CmsException { return getResourceType(file.getType()).exportResource(this, file); } /** * Reads all siblings that point to the resource record of a specified resource name.<p> * * @param resourcename name of a resource * @return List of siblings of the resource * @throws CmsException if something goes wrong */ public List getAllVfsLinks(String resourcename) throws CmsException { return m_driverManager.readSiblings(m_context, addSiteRoot(resourcename), true, false); } /** * Reads all siblings that point to the resource record of a specified resource name, * excluding the specified resource from the result.<p> * * @param resourcename name of a resource * @return List of siblings of the resource * @throws CmsException if something goes wrong */ public List getAllVfsSoftLinks(String resourcename) throws CmsException { return m_driverManager.readSiblings(m_context, addSiteRoot(resourcename), false, false); } /** * Fires a CmsEvent * * @param type The type of the event * @param data A data object that contains data used by the event listeners */ private void fireEvent(int type, Object data) { OpenCms.fireCmsEvent(this, type, Collections.singletonMap("data", data)); } /** * Forwards a task to a new user. * * @param taskid the id of the task which will be forwarded. * @param newRoleName the new group for the task. * @param newUserName the new user who gets the task. * * @throws CmsException if operation was not successful. */ public void forwardTask(int taskid, String newRoleName, String newUserName) throws CmsException { m_driverManager.forwardTask(m_context, taskid, newRoleName, newUserName); } /** * Returns the vector of access control entries of a resource. * * @param resourceName the name of the resource. * @return a vector of access control entries * @throws CmsException if something goes wrong */ public Vector getAccessControlEntries(String resourceName) throws CmsException { return getAccessControlEntries(resourceName, true); } /** * Returns the vector of access control entries of a resource. * * @param resourceName the name of the resource. * @param getInherited true, if inherited access control entries should be returned, too * @return a vector of access control entries * @throws CmsException if something goes wrong */ public Vector getAccessControlEntries(String resourceName, boolean getInherited) throws CmsException { CmsResource res = readFileHeader(resourceName); return m_driverManager.getAccessControlEntries(m_context, res, getInherited); } /** * Returns the access control list (summarized access control entries) of a given resource. * * @param resourceName the name of the resource * @return the access control list of the resource * @throws CmsException if something goes wrong */ public CmsAccessControlList getAccessControlList(String resourceName) throws CmsException { return getAccessControlList(resourceName, false); } /** * Returns the access control list (summarized access control entries) of a given resource. * * @param resourceName the name of the resource * @param inheritedOnly if set, the non-inherited entries are skipped * @return the access control list of the resource * @throws CmsException if something goes wrong */ public CmsAccessControlList getAccessControlList(String resourceName, boolean inheritedOnly) throws CmsException { CmsResource res = readFileHeader(resourceName); return m_driverManager.getAccessControlList(m_context, res, inheritedOnly); } /** * Returns all projects, which the current user can access. * * @return a Vector of objects of type <code>CmsProject</code>. * * @throws CmsException if operation was not successful. */ public Vector getAllAccessibleProjects() throws CmsException { return (m_driverManager.getAllAccessibleProjects(m_context)); } /** * Returns a Vector with all projects from history * * @return Vector with all projects from history. * * @throws CmsException Throws CmsException if operation was not succesful. */ public Vector getAllBackupProjects() throws CmsException { return m_driverManager.getAllBackupProjects(); } /** * Returns all projects which are owned by the current user or which are manageable * for the group of the user. * * @return a Vector of objects of type <code>CmsProject</code>. * * @throws CmsException if operation was not successful. */ public Vector getAllManageableProjects() throws CmsException { return (m_driverManager.getAllManageableProjects(m_context)); } /** * Returns a List with all initialized resource types.<p> * * @return a List with all initialized resource types */ public List getAllResourceTypes() { I_CmsResourceType resourceTypes[] = m_driverManager.getAllResourceTypes(); List result = new ArrayList(resourceTypes.length); for (int i = 0; i < resourceTypes.length; i++) { if (resourceTypes[i] != null) { result.add(resourceTypes[i]); } } return result; } /** * Get the next version id for the published backup resources * * @return int The new version id */ public int getBackupTagId() { return m_driverManager.getBackupTagId(); } /** * Returns all child groups of a group. * * @param groupname the name of the group. * @return groups a Vector of all child groups or null. * @throws CmsException if operation was not successful. */ public Vector getChild(String groupname) throws CmsException { return (m_driverManager.getChild(m_context, groupname)); } /** * Returns all child groups of a group. * <br> * This method also returns all sub-child groups of the current group. * * @param groupname the name of the group. * @return groups a Vector of all child groups or null. * @throws CmsException if operation was not successful. */ public Vector getChilds(String groupname) throws CmsException { return (m_driverManager.getChilds(m_context, groupname)); } /** * Gets the configurations of the properties-file. * @return the configurations of the properties-file. */ public ExtendedProperties getConfigurations() { return m_driverManager.getConfigurations(); } /** * Gets all groups to which a given user directly belongs. * * @param username the name of the user to get all groups for. * @return a Vector of all groups of a user. * * @throws CmsException if operation was not successful. */ public Vector getDirectGroupsOfUser(String username) throws CmsException { return (m_driverManager.getDirectGroupsOfUser(m_context, username)); } /** * Returns the generic driver objects.<p> * * @return a mapping of class names to driver objects */ public Map getDrivers() { HashMap drivers = new HashMap(); drivers.put(this.m_driverManager.getVfsDriver().getClass().getName(), this.m_driverManager.getVfsDriver()); drivers.put(this.m_driverManager.getUserDriver().getClass().getName(), this.m_driverManager.getUserDriver()); drivers.put(this.m_driverManager.getProjectDriver().getClass().getName(), this.m_driverManager.getProjectDriver()); drivers.put(this.m_driverManager.getWorkflowDriver().getClass().getName(), this.m_driverManager.getWorkflowDriver()); drivers.put(this.m_driverManager.getBackupDriver().getClass().getName(), this.m_driverManager.getBackupDriver()); return drivers; } /** * Returns a Vector with all files of a given folder. * (only the direct subfiles, not the files in subfolders) * <br> * Files of a folder can be read from an offline Project and the online Project. * * @param foldername the complete path to the folder. * * @return subfiles a Vector with all files of the given folder. * * @throws CmsException if the user has not hte appropriate rigths to access or read the resource. */ public List getFilesInFolder(String foldername) throws CmsException { return (m_driverManager.getSubFiles(m_context, addSiteRoot(foldername), false)); } /** * Returns a Vector with all files of a given folder. * <br> * Files of a folder can be read from an offline Project and the online Project. * * @param foldername the complete path to the folder. * @param includeDeleted Include if the folder is marked as deleted * * @return subfiles a Vector with all files of the given folder. * * @throws CmsException if the user has not hte appropriate rigths to access or read the resource. */ public List getFilesInFolder(String foldername, boolean includeDeleted) throws CmsException { return (m_driverManager.getSubFiles(m_context, addSiteRoot(foldername), includeDeleted)); } /** * Returns a Vector with all resource-names of the resources that have set the given property to the given value. * * @param propertyDefinition the name of the property-definition to check. * @param propertyValue the value of the property for the resource. * * @return a Vector with all names of the resources. * * @throws CmsException if operation was not successful. */ public Vector getFilesWithProperty(String propertyDefinition, String propertyValue) throws CmsException { return m_driverManager.getFilesWithProperty(m_context, propertyDefinition, propertyValue); } /** * This method can be called, to determine if the file-system was changed in the past. * <br> * A module can compare its previously stored number with the returned number. * If they differ, the file system has been changed. * * @return the number of file-system-changes. */ public long getFileSystemFolderChanges() { return (m_driverManager.getFileSystemFolderChanges()); } /** * Returns all groups in the Cms. * * @return a Vector of all groups in the Cms. * * @throws CmsException if operation was not successful */ public Vector getGroups() throws CmsException { return (m_driverManager.getGroups(m_context)); } /** * Returns the groups of a Cms user.<p> * * @param username the name of the user * @return a vector of Cms groups * @throws CmsException if operation was not succesful. */ public Vector getGroupsOfUser(String username) throws CmsException { return m_driverManager.getGroupsOfUser(m_context, username); } /** * Returns the groups of a Cms user filtered by the specified IP address.<p> * * @param username the name of the user * @param remoteAddress the IP address to filter the groups in the result vector * @return a vector of Cms groups filtered by the specified IP address * @throws CmsException if operation was not succesful. */ public Vector getGroupsOfUser(String username, String remoteAddress) throws CmsException { return m_driverManager.getGroupsOfUser(m_context, username, remoteAddress); } /** * Returns all groups with a name like the specified pattern.<p> * * @param namePattern pattern for the group name * @return a Vector of all groups with a name like the given pattern * * @throws CmsException if something goes wrong */ public Vector getGroupsLike(String namePattern) throws CmsException { return (m_driverManager.getGroupsLike(m_context, namePattern)); } /** * Checks if a user is a direct member of a group having a name like the specified pattern.<p> * * @param username the name of the user to get all groups for. * @param groupNamePattern pattern for the group name * @return <code>true</code> if the given user is a direct member of a group having a name like the specified pattern * @throws CmsException if something goes wrong */ public boolean hasDirectGroupsOfUserLike(String username, String groupNamePattern) throws CmsException { return (m_driverManager.hasDirectGroupsOfUserLike(m_context, username, groupNamePattern)); } /** * This is the port the workplace access is limited to. With the opencms.properties * the access to the workplace can be limited to a user defined port. With this * feature a firewall can block all outside requests to this port with the result * the workplace is only available in the local net segment. * @return the portnumber or -1 if no port is set. */ public int getLimitedWorkplacePort() { return m_driverManager.getLimitedWorkplacePort(); } /** * Returns a list of all currently logged in users. * This method is only allowed for administrators. * * @return a vector of users that are currently logged in * @throws CmsException if something goes wrong */ public Vector getLoggedInUsers() throws CmsException { if (isAdmin()) { if (m_sessionStorage != null) { return m_sessionStorage.getLoggedInUsers(); } else { return null; } } else { throw new CmsSecurityException("[" + this.getClass().getName() + "] getLoggedInUsers()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED); } } /** * Returns the parent group of a group. * * @param groupname the name of the group. * @return group the parent group or null. * @throws CmsException if operation was not successful. */ public CmsGroup getParent(String groupname) throws CmsException { return (m_driverManager.getParent(groupname)); } /** * Returns the set set of permissions of the current user for a given resource. * * @param resourceName the name of the resource * @return the set of the permissions of the current user * @throws CmsException if something goes wrong */ public CmsPermissionSet getPermissions(String resourceName) throws CmsException { // reading permissions is allowed even if the resource is marked as deleted CmsResource resource = readFileHeader(resourceName, true); CmsUser user = m_context.currentUser(); return m_driverManager.getPermissions(m_context, resource, user); } /** * Returns the set set of permissions of a given user for a given resource. * * @param resourceName the name of the resource * @param userName the name of the user * @return the current permissions on this resource * @throws CmsException if something goes wrong */ public CmsPermissionSet getPermissions(String resourceName, String userName) throws CmsException { CmsAccessControlList acList = getAccessControlList(resourceName); CmsUser user = readUser(userName); return acList.getPermissions(user, getGroupsOfUser(userName)); } /** * Returns the current OpenCms registry.<p> * * @return the current OpenCms registry */ public CmsRegistry getRegistry() { return m_driverManager.getRegistry(this); } /** * Returns the current request-context. * * @return the current request-context. */ public CmsRequestContext getRequestContext() { return (m_context); } /** * Returns a Vector with the sub resources for a folder.<br> * * @param folder the name of the folder to get the subresources from. * @return subfolders a Vector with resources * @throws CmsException if operation was not succesful */ public Vector getResourcesInFolder(String folder) throws CmsException { return m_driverManager.getResourcesInFolder(m_context, addSiteRoot(folder)); } /** * Returns a List with all sub resources of a given folder that have benn modified * in a given time range.<p> * * The rertuned list is sorted descending (newest resource first). * * <B>Security:</B> * All users are granted. * * @param folder the folder to get the subresources from * @param starttime the begin of the time range * @param endtime the end of the time range * @return List with all resources * * @throws CmsException if operation was not succesful */ public List getResourcesInTimeRange(String folder, long starttime, long endtime) throws CmsException { return m_driverManager.getResourcesInTimeRange(m_context, addSiteRoot(folder), starttime, endtime); } /** * Returns a Vector with all resources of the given type that have set the given property. * * <B>Security:</B> * All users are granted. * * @param propertyDefinition the name of the propertydefinition to check. * * @return Vector with all resources. * * @throws CmsException if operation was not succesful. */ public Vector getResourcesWithPropertyDefinition(String propertyDefinition) throws CmsException { return m_driverManager.getResourcesWithPropertyDefinition(m_context, propertyDefinition); } /** * Returns a List with the complete sub tree of a given folder that have set the given property.<p> * * <B>Security:</B> * All users are granted. * * @param folder the folder to get the subresources from * @param propertyDefinition the name of the propertydefinition to check * @return List with all resources * * @throws CmsException if operation was not succesful */ public List getResourcesWithProperty(String folder, String propertyDefinition) throws CmsException { return m_driverManager.getResourcesWithProperty(m_context, addSiteRoot(folder), propertyDefinition); } /** * Returns a List with resources that have set the given property.<p> * * <B>Security:</B> * All users are granted. * * @param propertyDefinition the name of the propertydefinition to check * @return List with all resources * * @throws CmsException if operation was not succesful */ public List getResourcesWithProperty(String propertyDefinition) throws CmsException { return m_driverManager.getResourcesWithProperty(m_context, "/", propertyDefinition); } /** * Returns a Vector with all resources of the given type that have set the given property to the given value. * * <B>Security:</B> * All users are granted. * * @param propertyDefinition the name of the propertydefinition to check. * @param propertyValue the value of the property for the resource. * @param resourceType The resource type of the resource * * @return Vector with all resources. * * @throws CmsException Throws CmsException if operation was not succesful. */ public Vector getResourcesWithPropertyDefintion(String propertyDefinition, String propertyValue, int resourceType) throws CmsException { return m_driverManager.getResourcesWithPropertyDefintion(m_context, propertyDefinition, propertyValue, resourceType); } /** * Returns the initialized resource type instance for the given id.<p> * * @param resourceType the id of the resourceType to get * @return the initialized resource type instance for the given id * @throws CmsException if something goes wrong */ public I_CmsResourceType getResourceType(int resourceType) throws CmsException { return m_driverManager.getResourceType(resourceType); } /** * Returns the resource type id for the given resource type name.<p> * * @param resourceType the name of the resourceType to get the id for * @return the resource type id for the given resource type name * @throws CmsException if something goes wrong */ public int getResourceTypeId(String resourceType) throws CmsException { I_CmsResourceType type = m_driverManager.getResourceType(resourceType); if (type != null) { return type.getResourceType(); } else { return I_CmsConstants.C_UNKNOWN_ID; } } /** * Returns a Vector with all subfolders of a given folder.<p> * * @param foldername the complete path to the folder * @return all subfolders (CmsFolder Objects) for the given folder * @throws CmsException if the user has not the permissions to access or read the resource */ public List getSubFolders(String foldername) throws CmsException { return (m_driverManager.getSubFolders(m_context, addSiteRoot(foldername), false)); } /** * Returns a Vector with all subfolders of a given folder.<p> * * @param foldername the complete path to the folder * @param includeDeleted if true folders marked as deleted are also included * @return all subfolders (CmsFolder Objects) for the given folder * @throws CmsException if the user has not the permissions to access or read the resource */ public List getSubFolders(String foldername, boolean includeDeleted) throws CmsException { return (m_driverManager.getSubFolders(m_context, addSiteRoot(foldername), includeDeleted)); } /** * Get a parameter value for a task. * * @param taskid the id of the task. * @param parname the name of the parameter. * @return the parameter value. * * @throws CmsException if operation was not successful. */ public String getTaskPar(int taskid, String parname) throws CmsException { return (m_driverManager.getTaskPar(taskid, parname)); } /** * Get the template task id fo a given taskname. * * @param taskname the name of the task. * * @return the id of the task template. * * @throws CmsException if operation was not successful. */ public int getTaskType(String taskname) throws CmsException { return m_driverManager.getTaskType(taskname); } /** * Returns all users in the Cms. * * @return a Vector of all users in the Cms. * * @throws CmsException if operation was not successful. */ public Vector getUsers() throws CmsException { return (m_driverManager.getUsers(m_context)); } /** * Returns all users of the given type in the Cms. * * @param type the type of the users. * * @return vector of all users of the given type in the Cms. * * @throws CmsException if operation was not successful. */ public Vector getUsers(int type) throws CmsException { return (m_driverManager.getUsers(m_context, type)); } /** * Returns all users from a given type that start with a specified string<P/> * * @param type the type of the users. * @param namefilter The filter for the username * @return vector of all users of the given type in the Cms. * * @throws CmsException if operation was not successful. * @deprecated */ public Vector getUsers(int type, String namefilter) throws CmsException { return m_driverManager.getUsers(m_context, type, namefilter); } /** * Gets all users with a certain Lastname. * * @param Lastname the start of the users lastname * @param UserType webuser or systemuser * @param UserStatus enabled, disabled * @param wasLoggedIn was the user ever locked in? * @param nMax max number of results * * @return the users. * * @throws CmsException if operation was not successful. * @deprecated */ public Vector getUsersByLastname(String Lastname, int UserType, int UserStatus, int wasLoggedIn, int nMax) throws CmsException { return m_driverManager.getUsersByLastname(m_context, Lastname, UserType, UserStatus, wasLoggedIn, nMax); } /** * Gets all users of a group. * * @param groupname the name of the group to get all users for. * @return all users in the group. * * @throws CmsException if operation was not successful. */ public Vector getUsersOfGroup(String groupname) throws CmsException { return (m_driverManager.getUsersOfGroup(m_context, groupname)); } /** * Returns a Vector with all resources of the given type that have set the given property to the given value. * * <B>Security:</B> * All users that have read and view access are granted. * * @param propertyDefinition the name of the propertydefinition to check. * @param propertyValue the value of the property for the resource. * @param resourceType the resource type of the resource * * @return Vector with all resources. * * @throws CmsException Throws CmsException if operation was not succesful. */ public Vector getVisibleResourcesWithProperty(String propertyDefinition, String propertyValue, int resourceType) throws CmsException { return m_driverManager.getVisibleResourcesWithProperty(m_context, propertyDefinition, propertyValue, resourceType); } /** * Checks if the current user has required permissions to access a given resource. * * @param resource the resource that will be accessed * @param requiredPermissions the set of required permissions * @return true if the required permissions are satisfied * @throws CmsException if something goes wrong */ public boolean hasPermissions(CmsResource resource, CmsPermissionSet requiredPermissions) throws CmsException { return m_driverManager.hasPermissions(m_context, resource, requiredPermissions, false); } /** * Checks if the current user has required permissions to access a given resource * * @param resourceName the name of the resource that will be accessed * @param requiredPermissions the set of required permissions * @return true if the required permissions are satisfied * @throws CmsException if something goes wrong */ public boolean hasPermissions(String resourceName, CmsPermissionSet requiredPermissions) throws CmsException { CmsResource resource = readFileHeader(resourceName); return m_driverManager.hasPermissions(m_context, resource, requiredPermissions, false); } /** * Imports a import-resource (folder or zipfile) to the cms. * * @param importFile the name (absolute Path) of the import resource (zipfile or folder). * @param importPath the name (absolute Path) of the folder in which should be imported. * * @throws CmsException if operation was not successful. */ public void importFolder(String importFile, String importPath) throws CmsException { // OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP, false)); m_driverManager.clearcache(); // import the resources m_driverManager.importFolder(this, m_context, importFile, importPath); // OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP, false)); m_driverManager.clearcache(); } /** * Imports a resource to the cms.<p> * * @param resource the resource to be imported * @param content the content of the resource * @param properties the properties of the resource * @param importpath the name of the resource destinaition * @return the imported CmsResource * @throws CmsException if operation was not successful */ public CmsResource importResource(CmsResource resource, byte[] content, Map properties, String importpath) throws CmsException { return getResourceType(resource.getType()).importResource(this, resource, content, properties, importpath); } /** * Checks, if the users current group is the admin-group. * * * @return <code>true</code>, if the users current group is the admin-group; <code>false</code> otherwise. * @throws CmsException if operation was not successful. */ public boolean isAdmin() throws CmsException { return m_driverManager.isAdmin(m_context); } /** * Checks if the user has management access to the project. * * Please note: This is NOT the same as the {@link CmsObject#isProjectManager()} * check. If the user has management access to a project depends on the * project settings.<p> * * @return true if the user has management access to the project * @throws CmsException if operation was not successful. * @see #isProjectManager() */ public boolean isManagerOfProject() throws CmsException { return m_driverManager.isManagerOfProject(m_context); } /** * Checks if the user is a member of the project manager group.<p> * * Please note: This is NOT the same as the {@link CmsObject#isManagerOfProject()()} * check. If the user is a member of the project manager group, * he can create new projects.<p> * * @return true if the user is a member of the project manager group * @throws CmsException if operation was not successful. * @see #isManagerOfProject() */ public boolean isProjectManager() throws CmsException { return m_driverManager.isProjectManager(m_context); } /** * Returns the user, who has locked a given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. This methods checks, who has locked a resource. * * @param resource the resource to check. * * @return the user who has locked the resource. * * @throws CmsException if operation was not successful. */ public CmsUser lockedBy(CmsResource resource) throws CmsException { return (m_driverManager.lockedBy(m_context, resource)); } /** * Returns the user, who has locked a given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. This methods checks, who has locked a resource. * * @param resource The complete path to the resource. * * @return the user who has locked a resource. * * @throws CmsException if operation was not successful. */ public CmsUser lockedBy(String resource) throws CmsException { return (m_driverManager.lockedBy(m_context, addSiteRoot(resource))); } /** * Locks the given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. * * @param resource The complete path to the resource to lock. * * @throws CmsException if the user has not the rights to lock this resource. * It will also be thrown, if there is an existing lock. * */ public void lockResource(String resource) throws CmsException { // try to lock the resource, prevent from overwriting an existing lock lockResource(resource, false, CmsLock.C_MODE_COMMON); } /** * Locks a given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. * * @param resource the complete path to the resource to lock. * @param force if force is <code>true</code>, a existing locking will be overwritten. * * @throws CmsException if the user has not the rights to lock this resource. * It will also be thrown, if there is a existing lock and force was set to false. */ public void lockResource(String resource, boolean force) throws CmsException { lockResource(resource, force, CmsLock.C_MODE_COMMON); } /** * Locks a given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. * * @param resource the complete path to the resource to lock. * @param force if force is <code>true</code>, a existing locking will be overwritten. * @param mode flag indicating the mode (temporary or common) of a lock * * @throws CmsException if the user has not the rights to lock this resource. * It will also be thrown, if there is a existing lock and force was set to false. */ public void lockResource(String resource, boolean force, int mode) throws CmsException { getResourceType(readFileHeader(resource).getType()).lockResource(this, resource, force, mode); } /** * Changes the lock of a resource.<p> * * @param resourcename name of the resource * @throws CmsException if something goes wrong */ public void changeLock(String resourcename) throws CmsException { m_driverManager.changeLock(m_context, addSiteRoot(resourcename)); } /** * Logs a user into the Cms, if the password is correct.<p> * * @param username the name of the user * @param password the password of the user * @return the name of the logged in user * * @throws CmsSecurityException if operation was not successful */ public String loginUser(String username, String password) throws CmsSecurityException { return loginUser(username, password, m_context.getRemoteAddress()); } /** * Logs a user with a given ip address into the Cms, if the password is correct.<p> * * @param username the name of the user * @param password the password of the user * @param remoteAddress the ip address * @return the name of the logged in user * * @throws CmsSecurityException if operation was not successful */ public String loginUser(String username, String password, String remoteAddress) throws CmsSecurityException { return loginUser(username, password, remoteAddress, I_CmsConstants.C_USER_TYPE_SYSTEMUSER); } /** * Logs a user with a given type and a given ip address into the Cms, if the password is correct.<p> * * @param username the name of the user * @param password the password of the user * @param remoteAddress the ip address * @param type the user type (System or Web user) * @return the name of the logged in user * * @throws CmsSecurityException if operation was not successful */ public String loginUser(String username, String password, String remoteAddress, int type) throws CmsSecurityException { // login the user CmsUser newUser = m_driverManager.loginUser(username, password, remoteAddress, type); // set the project back to the "Online" project CmsProject newProject; try { newProject = m_driverManager.readProject(I_CmsConstants.C_PROJECT_ONLINE_ID); } catch (CmsException e) { // should not happen since the online project is always available throw new CmsSecurityException(CmsSecurityException.C_SECURITY_LOGIN_FAILED, e); } // switch the cms context to the new user and project m_context.switchUser(newUser, newProject); // init this CmsObject with the new user init(m_driverManager, m_context, m_sessionStorage); // fire a login event this.fireEvent(org.opencms.main.I_CmsEventListener.EVENT_LOGIN_USER, newUser); // return the users login name return newUser.getName(); } /** * Logs a web user into the Cms, if the password is correct. * * @param username the name of the user. * @param password the password of the user. * @return the name of the logged in user. * * @throws CmsSecurityException if operation was not successful */ public String loginWebUser(String username, String password) throws CmsSecurityException { return loginUser(username, password, m_context.getRemoteAddress(), I_CmsConstants.C_USER_TYPE_WEBUSER); } /** * Lookup and reads the user or group with the given UUID.<p> * * @param principalId the uuid of a user or group * @return the user or group with the given UUID */ public I_CmsPrincipal lookupPrincipal(CmsUUID principalId) { return m_driverManager.lookupPrincipal(principalId); } /** * Lookup and reads the user or group with the given name.<p> * * @param principalName the name of the user or group * @return the user or group with the given name */ public I_CmsPrincipal lookupPrincipal(String principalName) { return m_driverManager.lookupPrincipal(principalName); } /** * Moves a resource to the given destination. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfile. * * @throws CmsException if the user has not the rights to move this resource, * or if the file couldn't be moved. */ public void moveResource(String source, String destination) throws CmsException { getResourceType(readFileHeader(source).getType()).moveResource(this, source, destination); } /** * Moves a resource to the lost and found folder * * @param source the complete path of the sourcefile. * @return location of the moved resource * @throws CmsException if the user has not the rights to move this resource, * or if the file couldn't be moved. */ public String copyToLostAndFound(String source) throws CmsException { return getResourceType(readFileHeader(source).getType()).copyToLostAndFound(this, source, true); } /** * Publishes the current project, printing messages to a shell report.<p> * * @throws Exception if something goes wrong */ public void publishProject() throws Exception { publishProject(new CmsShellReport()); } /** * Publishes the current project.<p> * * @param report an instance of I_CmsReport to print messages * @throws CmsException if something goes wrong */ public void publishProject(I_CmsReport report) throws CmsException { publishProject(report, null, false); } /** * Direct publishes a specified resource.<p> * * @param report an instance of I_CmsReport to print messages * @param directPublishResource a CmsResource that gets directly published; or null if an entire project gets published * @param directPublishSiblings if a CmsResource that should get published directly is provided as an argument, all eventual siblings of this resource get publish too, if this flag is true * @throws CmsException if something goes wrong * @see #publishResource(String) * @see #publishResource(String, boolean, I_CmsReport) */ public void publishProject(I_CmsReport report, CmsResource directPublishResource, boolean directPublishSiblings) throws CmsException { CmsPublishList publishList = getPublishList(directPublishResource, directPublishSiblings, report); publishProject(report, publishList); } /** * Publishes the resources of a specified publish list.<p> * * @param report an instance of I_CmsReport to print messages * @param publishList a publish list * @throws CmsException if something goes wrong * @see #getPublishList(I_CmsReport) * @see #getPublishList(CmsResource, boolean, I_CmsReport) */ public void publishProject(I_CmsReport report, CmsPublishList publishList) throws CmsException { // TODO check if useful/neccessary m_driverManager.clearcache(); synchronized (m_driverManager) { try { m_driverManager.publishProject(this, m_context, publishList, report); } catch (CmsException e) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error(e); } throw e; } catch (Exception e) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error(e); } throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, e); } finally { // TODO check if useful/neccessary m_driverManager.clearcache(); // set current project to online project if the published project was temporary // and the published project is still the current project if (m_context.currentProject().getId() == m_context.currentProject().getId() && (m_context.currentProject().getType() == I_CmsConstants.C_PROJECT_TYPE_TEMPORARY)) { m_context.setCurrentProject(readProject(I_CmsConstants.C_PROJECT_ONLINE_ID)); } // fire an event that a project has been published Map eventData = (Map) new HashMap(); eventData.put("report", report); eventData.put("publishHistoryId", publishList.getPublishHistoryId().toString()); eventData.put("context", m_context); CmsEvent exportPointEvent = new CmsEvent(this, I_CmsEventListener.EVENT_PUBLISH_PROJECT, eventData, false); OpenCms.fireCmsEvent(exportPointEvent); } } } /** * Publishes a single resource.<p> * * @param resourcename the name of the resource to be published * @throws Exception if something goes wrong */ public void publishResource(String resourcename) throws Exception { publishResource(resourcename, false, new CmsShellReport()); } /** * Publishes a single resource.<p> * * @param resourcename the name of the resource to be published * @param directPublishSiblings if true, all siblings of the resource are also published * @param report the report to write the progress information to * @throws Exception if something goes wrong */ public void publishResource(String resourcename, boolean directPublishSiblings, I_CmsReport report) throws Exception { CmsResource resource = null; try { resource = readFileHeader(resourcename, true); publishProject(report, resource, directPublishSiblings); } catch (CmsException e) { throw e; } finally { OpenCms.fireCmsEvent(new CmsEvent(this, I_CmsEventListener.EVENT_PUBLISH_RESOURCE, Collections.singletonMap("resource", resource))); } } /** * Returns the absolute path of a given resource.<p> * The absolute path is the root path without the site information. * * @param resource the resource * @return the absolute path */ public String readAbsolutePath(CmsResource resource) { return readAbsolutePath(resource, false); } /** * Returns the absolute path of a given resource.<p> * The absolute path is the root path without the site information. * * @param resource the resource * @param includeDeleted include resources that are marked as deleted * @return the absolute path */ public String readAbsolutePath(CmsResource resource, boolean includeDeleted) { if (!resource.hasFullResourceName()) { try { m_driverManager.readPath(m_context, resource, includeDeleted); } catch (CmsException e) { OpenCms.getLog(this).error("Could not read absolute path for resource " + resource, e); resource.setFullResourceName(null); } } // adjust the resource path for the current site root return removeSiteRoot(resource.getRootPath()); } /** * Reads the agent of a task.<p> * * @param task the task to read the agent from * @return the agent of a task * @throws CmsException if something goes wrong */ public CmsUser readAgent(CmsTask task) throws CmsException { return (m_driverManager.readAgent(task)); } /** * Reads all file headers of a file in the OpenCms. * <br> * This method returns a vector with the history of all file headers, i.e. * the file headers of a file, independent of the project they were attached to.<br> * * The reading excludes the filecontent. * * @param filename the name of the file to be read. * * @return a Vector of file headers read from the Cms. * * @throws CmsException if operation was not successful. */ public List readAllBackupFileHeaders(String filename) throws CmsException { return (m_driverManager.readAllBackupFileHeaders(m_context, addSiteRoot(filename))); } /** * select all projectResources from an given project * * @param projectId id of the project in which the resource is used. * @return vector of all resources belonging to the given project * * @throws CmsException Throws CmsException if operation was not succesful */ public Vector readAllProjectResources(int projectId) throws CmsException { return m_driverManager.readAllProjectResources(m_context, projectId); } /** * Returns a list of all properties of a file or folder. * * @param filename the name of the resource for which the property has to be read * * @return a Vector of Strings * * @throws CmsException if operation was not succesful * @deprecated use readProperties(String) instead */ public Map readAllProperties(String filename) throws CmsException { Map result = (Map)new HashMap(); Map properties = readProperties(filename, false); if (properties != null) { result.putAll(properties); } return result; } /** * Reads all property definitions for the given resource type by id.<p> * * @param resourceType the resource type to read the property-definitions for.<p> * * @return a Vector with the property defenitions for the resource type (may be empty) * * @throws CmsException if something goes wrong */ public Vector readAllPropertydefinitions(int resourceType) throws CmsException { return m_driverManager.readAllPropertydefinitions(m_context, resourceType); } /** * Reads all property definitions for the given resource type by name.<p> * * @param resourceType the resource type to read the property-definitions for.<p> * * @return a Vector with the property defenitions for the resource type (may be empty) * * @throws CmsException if something goes wrong */ public Vector readAllPropertydefinitions(String resourceType) throws CmsException { return m_driverManager.readAllPropertydefinitions(m_context, resourceType); } /** * Reads a file from the Cms for history. * <br> * The reading includes the filecontent. * * @param filename the complete path of the file to be read. * @param tagId the tag id of the resource * * @return file the read file. * * @throws CmsException , if the user has not the rights * to read the file, or if the file couldn't be read. */ public CmsBackupResource readBackupFile(String filename, int tagId) throws CmsException { return (m_driverManager.readBackupFile(m_context, tagId, addSiteRoot(filename))); } /** * Reads a file header from the Cms for history. * <br> * The reading excludes the filecontent. * * @param filename the complete path of the file to be read. * @param tagId the version id of the resource * * @return file the read file. * * @throws CmsException , if the user has not the rights * to read the file headers, or if the file headers couldn't be read. */ public CmsResource readBackupFileHeader(String filename, int tagId) throws CmsException { return (m_driverManager.readBackupFileHeader(m_context, tagId, addSiteRoot(filename))); } /** * Reads a backup project from the Cms. * * @param tagId the tag of the backup project to be read * @return CmsBackupProject object of the requested project * @throws CmsException if operation was not successful. */ public CmsBackupProject readBackupProject(int tagId) throws CmsException { return (m_driverManager.readBackupProject(tagId)); } /** * Gets the Crontable. * * <B>Security:</B> * All users are garnted<BR/> * * @return the crontable. * @throws CmsException if something goes wrong */ public String readCronTable() throws CmsException { return m_driverManager.readCronTable(); } /** * Reads the package path of the system. * This path is used for db-export and db-import and all module packages. * * @return the package path * @throws CmsException if operation was not successful */ public String readPackagePath() throws CmsException { return m_driverManager.readPackagePath(); } /** * Reads a file from the Cms. * * @param filename the complete path to the file. * * @return file the read file. * * @throws CmsException if the user has not the rights to read this resource, * or if the file couldn't be read. */ public CmsFile readFile(String filename) throws CmsException { return m_driverManager.readFile(m_context, addSiteRoot(filename)); } /** * Reads a file from the Cms. * * @param filename the complete path to the file. * @param includeDeleted If true the deleted file will be returned. * * @return file the read file. * * @throws CmsException if the user has not the rights to read this resource, * or if the file couldn't be read. */ public CmsFile readFile(String filename, boolean includeDeleted) throws CmsException { return m_driverManager.readFile(m_context, addSiteRoot(filename), includeDeleted); } /** * Reads a file from the Cms. * * @param folder the complete path to the folder from which the file will be read. * @param filename the name of the file to be read. * * @return file the read file. * * @throws CmsException , if the user has not the rights * to read this resource, or if the file couldn't be read. */ public CmsFile readFile(String folder, String filename) throws CmsException { return (m_driverManager.readFile(m_context, addSiteRoot(folder + filename))); } /** * Gets the known file extensions (=suffixes). * * * @return a Hashtable with all known file extensions as Strings. * * @throws CmsException if operation was not successful. */ public Hashtable readFileExtensions() throws CmsException { return m_driverManager.readFileExtensions(); } /** * Reads a file header from the Cms. * <br> * The reading excludes the filecontent. * * @param filename the complete path of the file to be read. * * @return file the read file. * * @throws CmsException , if the user has not the rights * to read the file headers, or if the file headers couldn't be read. */ public CmsResource readFileHeader(String filename) throws CmsException { return (m_driverManager.readFileHeader(m_context, addSiteRoot(filename))); } /** * Reads a file header from the Cms. * <br> * The reading excludes the filecontent. * * @param filename the complete path of the file to be read * @param includeDeleted if <code>true</code>, deleted files (in offline projects) will * also be read * * @return file the read file header * * @throws CmsException if the user has not the rights * to read the file headers, or if the file headers couldn't be read */ public CmsResource readFileHeader(String filename, boolean includeDeleted) throws CmsException { return (m_driverManager.readFileHeader(m_context, addSiteRoot(filename), includeDeleted)); } /** * Reads a file header from the Cms. * <br> * The reading excludes the filecontent. * * @param filename the complete path of the file to be read. * @param projectId the id of the project where the resource should belong to * @param includeDeleted include resources that are marked as deleted * * @return file the read file. * * @throws CmsException , if the user has not the rights * to read the file headers, or if the file headers couldn't be read. */ public CmsResource readFileHeader(String filename, int projectId, boolean includeDeleted) throws CmsException { return (m_driverManager.readFileHeaderInProject(projectId, addSiteRoot(filename), includeDeleted)); } /** * Reads a file header from the Cms. * <br> * The reading excludes the filecontent. * * @param folder the complete path to the folder from which the file will be read. * @param filename the name of the file to be read. * * @return file the read file. * * @throws CmsException if the user has not the rights * to read the file header, or if the file header couldn't be read. */ public CmsResource readFileHeader(String folder, String filename) throws CmsException { return (m_driverManager.readFileHeader(m_context, addSiteRoot(folder + filename))); } /** * Reads all files from the Cms, that are of the given type.<BR/> * * @param projectId A project id for reading online or offline resources * @param resourcetype The type of the files. * * @return A Vector of files. * * @throws CmsException Throws CmsException if operation was not succesful */ public Vector readFilesByType(int projectId, int resourcetype) throws CmsException { return m_driverManager.readFilesByType(m_context, projectId, resourcetype); } /** * Reads a folder from the Cms. * * @param folderId the id of the folder to be read * @param includeDeleted Include the folder if it is marked as deleted * * @return folder the read folder * * @throws CmsException if the user does not have the permissions * to read this folder, or if the folder couldn't be read */ public CmsFolder readFolder(CmsUUID folderId, boolean includeDeleted) throws CmsException { return (m_driverManager.readFolder(m_context, folderId, includeDeleted)); } /** * Reads a folder from the Cms. * * @param folderName the name of the folder to be read * * @return The read folder * * @throws CmsException if the user does not have the permissions * to read this folder, or if the folder couldn't be read */ public CmsFolder readFolder(String folderName) throws CmsException { return (m_driverManager.readFolder(m_context, addSiteRoot(folderName))); } /** * Reads a folder from the Cms. * * @param folderName the complete path to the folder to be read * @param includeDeleted Include the folder if it is marked as deleted * * @return The read folder * * @throws CmsException If the user does not have the permissions * to read this folder, or if the folder couldn't be read */ public CmsFolder readFolder(String folderName, boolean includeDeleted) throws CmsException { return (m_driverManager.readFolder(m_context, addSiteRoot(folderName), includeDeleted)); } /** * Reads all given tasks from a user for a project. * * @param projectId the id of the project in which the tasks are defined. * @param ownerName the owner of the task. * @param taskType the type of task you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy specifies how to order the tasks. * @param sort sorting of the tasks * @return vector of given tasks for a user for a project * * @throws CmsException if operation was not successful. */ public Vector readGivenTasks(int projectId, String ownerName, int taskType, String orderBy, String sort) throws CmsException { return (m_driverManager.readGivenTasks(projectId, ownerName, taskType, orderBy, sort)); } /** * Reads the group of a project.<p> * * @param project the project to read the group from * @return the group of the given project */ public CmsGroup readGroup(CmsProject project) { return m_driverManager.readGroup(project); } /** * Reads the group (role) of a task.<p> * * @param task the task to read the group (role) from * @return the group (role) of the task * @throws CmsException if something goes wrong */ public CmsGroup readGroup(CmsTask task) throws CmsException { return m_driverManager.readGroup(task); } /** * Reads a group of the Cms based on its id.<p> * * @param groupId the id of the group to be read * @return the group that has the provided id * @throws CmsException if something goes wrong */ public CmsGroup readGroup(CmsUUID groupId) throws CmsException { return m_driverManager.readGroup(groupId); } /** * Reads a group of the Cms based on its name. * @param groupName the name of the group to be read * @return the group that has the provided name * @throws CmsException if something goes wrong */ public CmsGroup readGroup(String groupName) throws CmsException { return (m_driverManager.readGroup(groupName)); } /** * Gets the Linkchecktable. * * <B>Security:</B> * All users are granted<BR/> * * @return the linkchecktable * * @throws CmsException if something goes wrong */ public Hashtable readLinkCheckTable() throws CmsException { return m_driverManager.readLinkCheckTable(); } /** * Reads the project manager group of a project.<p> * * @param project the project * @return the managergroup of the project */ public CmsGroup readManagerGroup(CmsProject project) { return m_driverManager.readManagerGroup(project); } /** * Reads the original agent of a task from the Cms.<p> * * @param task the task to read the original agent from * @return the original agent of the task * @throws CmsException if something goes wrong */ public CmsUser readOriginalAgent(CmsTask task) throws CmsException { return m_driverManager.readOriginalAgent(task); } /** * Reads the owner of a project. * * @param project the project to read the owner from * @return the owner of the project * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsProject project) throws CmsException { return m_driverManager.readOwner(project); } /** * Reads the owner (initiator) of a task.<p> * * @param task the task to read the owner from * @return the owner of the task * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsTask task) throws CmsException { return m_driverManager.readOwner(task); } /** * Reads the owner of a task log.<p> * * @param log the task log * @return the owner of the task log * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsTaskLog log) throws CmsException { return m_driverManager.readOwner(log); } /** * Builds a list of resources for a given path.<p> * * Use this method if you want to select a resource given by it's full filename and path. * This is done by climbing down the path from the root folder using the parent-ID's and * resource names. Use this method with caution! Results are cached but reading path's * inevitably increases runtime costs. * * @param path the requested path * @param includeDeleted include resources that are marked as deleted * @return List of CmsResource's * @throws CmsException if something goes wrong */ public List readPath(String path, boolean includeDeleted) throws CmsException { return (m_driverManager.readPath(m_context, m_context.addSiteRoot(path), includeDeleted)); } /** * Reads the project in which a resource was last modified. * * @param res the resource * @return the project in which the resource was last modified * * @throws CmsException if operation was not successful. */ public CmsProject readProject(CmsResource res) throws CmsException { return m_driverManager.readProject(res.getProjectLastModified()); } /** * Reads a project of a given task from the Cms. * * @param task the task for which the project will be read. * @return the project of the task * * @throws CmsException if operation was not successful. */ public CmsProject readProject(CmsTask task) throws CmsException { return m_driverManager.readProject(task); } /** * Reads a project from the Cms. * * @param id the id of the project * @return the project with the given id * * @throws CmsException if operation was not successful. */ public CmsProject readProject(int id) throws CmsException { return m_driverManager.readProject(id); } /** * Reads a project from the Cms.<p> * * @param name the name of the project * @return the project with the given name * @throws CmsException if operation was not successful. */ public CmsProject readProject(String name) throws CmsException { return m_driverManager.readProject(name); } /** * Reads log entries for a project. * * @param projectId the id of the project for which the tasklog will be read. * @return a Vector of new TaskLog objects * @throws CmsException if operation was not successful. */ public Vector readProjectLogs(int projectId) throws CmsException { return m_driverManager.readProjectLogs(projectId); } /** * Reads all file headers of a project from the Cms. * * @param projectId the id of the project to read the file headers for. * @param filter The filter for the resources (all, new, changed, deleted, locked) * * @return a Vector (of CmsResources objects) of resources. * * @throws CmsException if something goes wrong * */ public Vector readProjectView(int projectId, String filter) throws CmsException { return m_driverManager.readProjectView(m_context, projectId, filter); } /** * Reads the property-definition for the resource type. * * @param name the name of the property-definition to read. * @param resourcetype the name of the resource type for the property-definition. * @return the property-definition. * * @throws CmsException if operation was not successful. */ public CmsPropertydefinition readPropertydefinition(String name, int resourcetype) throws CmsException { return (m_driverManager.readPropertydefinition(m_context, name, resourcetype)); } /** * Returns a list of all template resources which must be processed during a static export.<p> * * @param parameterResources flag for reading resources with parameters (1) or without (0) * @param timestamp a timestamp for reading the data from the db * @return List of template resources * @throws CmsException if something goes wrong */ public List readStaticExportResources(int parameterResources, long timestamp) throws CmsException { return m_driverManager.readStaticExportResources(m_context, parameterResources, timestamp); } /** * Returns the parameters of a resource in the table of all published template resources.<p> * @param rfsName the rfs name of the resource * @return the paramter string of the requested resource * @throws CmsException if something goes wrong */ public String readStaticExportPublishedResourceParamters(String rfsName) throws CmsException { return m_driverManager.readStaticExportPublishedResourceParamters(m_context, rfsName); } /** * Reads the task with the given id. * * @param id the id of the task to be read. * @return the task with the given id * * @throws CmsException if operation was not successful. */ public CmsTask readTask(int id) throws CmsException { return (m_driverManager.readTask(id)); } /** * Reads log entries for a task. * * @param taskid the task for which the tasklog will be read. * @return a Vector of new TaskLog objects. * @throws CmsException if operation was not successful. */ public Vector readTaskLogs(int taskid) throws CmsException { return m_driverManager.readTaskLogs(taskid); } /** * Reads all tasks for a project. * * @param projectId the id of the project in which the tasks are defined. Can be null to select all tasks. * @param tasktype the type of task you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW * @param orderBy specifies how to order the tasks. * @param sort sort order: C_SORT_ASC, C_SORT_DESC, or null. * @return vector of tasks for the project * * @throws CmsException if operation was not successful. */ public Vector readTasksForProject(int projectId, int tasktype, String orderBy, String sort) throws CmsException { return (m_driverManager.readTasksForProject(projectId, tasktype, orderBy, sort)); } /** * Reads all tasks for a role in a project. * * @param projectId the id of the Project in which the tasks are defined. * @param roleName the role who has to process the task. * @param tasktype the type of task you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy specifies how to order the tasks. * @param sort sort order C_SORT_ASC, C_SORT_DESC, or null * @return vector of tasks for the role * * @throws CmsException if operation was not successful. */ public Vector readTasksForRole(int projectId, String roleName, int tasktype, String orderBy, String sort) throws CmsException { return (m_driverManager.readTasksForRole(projectId, roleName, tasktype, orderBy, sort)); } /** * Reads all tasks for a user in a project. * * @param projectId the id of the Project in which the tasks are defined. * @param userName the user who has to process the task. * @param tasktype the type of task you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy specifies how to order the tasks. * @param sort sort order C_SORT_ASC, C_SORT_DESC, or null * @return vector of tasks for the user * * @throws CmsException if operation was not successful. */ public Vector readTasksForUser(int projectId, String userName, int tasktype, String orderBy, String sort) throws CmsException { return (m_driverManager.readTasksForUser(projectId, userName, tasktype, orderBy, sort)); } /** * Reads a user based on its id.<p> * * @param userId the id of the user to be read * @return the user with the given id * @throws CmsException if something goes wrong */ public CmsUser readUser(CmsUUID userId) throws CmsException { return m_driverManager.readUser(userId); } /** * Reads a user based on its name.<p> * * @param username the name of the user to be read * @return the user with the given name * @throws CmsException if somthing goes wrong */ public CmsUser readUser(String username) throws CmsException { return m_driverManager.readUser(username); } /** * Returns a user in the Cms. * * @param username the name of the user to be returned. * @param type the type of the user. * @return a user in the Cms. * * @throws CmsException if operation was not successful */ public CmsUser readUser(String username, int type) throws CmsException { return (m_driverManager.readUser(username, type)); } /** * Returns a user in the Cms, if the password is correct. * * @param username the name of the user to be returned. * @param password the password of the user to be returned. * @return a user in the Cms. * * @throws CmsException if operation was not successful */ public CmsUser readUser(String username, String password) throws CmsException { return (m_driverManager.readUser(username, password)); } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param username The username of the user that is to be read. * @return User * * @throws CmsException Throws CmsException if operation was not succesful */ public CmsUser readWebUser(String username) throws CmsException { return (m_driverManager.readWebUser(username)); } /** * Returns a web user object if the password for the user is correct.<p> * * <B>Security:</B> * All users are granted. * * @param username the username of the user that is to be read * @param password the password of the user that is to be read * @return a web user * * @throws CmsException if something goes wrong */ public CmsUser readWebUser(String username, String password) throws CmsException { return (m_driverManager.readWebUser(username, password)); } /** * Reactivates a task.<p> * * @param taskId the Id of the task to reactivate * * @throws CmsException if something goes wrong */ public void reaktivateTask(int taskId) throws CmsException { m_driverManager.reaktivateTask(m_context, taskId); } /** * Sets a new password if the user knows his recovery-password. * * @param username the name of the user. * @param recoveryPassword the recovery password. * @param newPassword the new password. * * @throws CmsException if operation was not successfull. */ public void recoverPassword(String username, String recoveryPassword, String newPassword) throws CmsException { m_driverManager.recoverPassword(username, recoveryPassword, newPassword); } /** * Removes the current site root prefix from the absolute path in the resource name, * i.e. adjusts the resource name for the current site root.<p> * * @param resourcename the resource name * @return the resource name adjusted for the current site root */ private String removeSiteRoot(String resourcename) { return getRequestContext().removeSiteRoot(resourcename); } /** * Removes a user from a group. * * <p> * <b>Security:</b> * Only the admin user is allowed to remove a user from a group. * * @param username the name of the user that is to be removed from the group. * @param groupname the name of the group. * @throws CmsException if operation was not successful. */ public void removeUserFromGroup(String username, String groupname) throws CmsException { m_driverManager.removeUserFromGroup(m_context, username, groupname); } /** * Renames the file to the new name. * * @param oldname the complete path to the file which will be renamed. * @param newname the new name of the file. * * @throws CmsException if the user has not the rights * to rename the file, or if the file couldn't be renamed. * * @deprecated Use renameResource instead. */ public void renameFile(String oldname, String newname) throws CmsException { renameResource(oldname, newname); } /** * Renames the resource to the new name. * * @param oldname the complete path to the file which will be renamed. * @param newname the new name of the file. * * @throws CmsException if the user has not the rights * to rename the file, or if the file couldn't be renamed. */ public void renameResource(String oldname, String newname) throws CmsException { getResourceType(readFileHeader(oldname).getType()).renameResource(this, oldname, newname); } /** * Replaces and existing resource by another file with different content * and different file type.<p> * * @param resourcename the resource to replace * @param type the type of the new resource * @param properties the properties of the new resource * @param content the content of the new resource * @throws CmsException if something goes wrong */ public void replaceResource(String resourcename, int type, Map properties, byte[] content) throws CmsException { // read the properties of the existing file Map resProps = null; try { resProps = readAllProperties(resourcename); } catch (CmsException e) { resProps = (Map)new HashMap(); } // add the properties that might have been collected during a file-upload if (properties != null) { resProps.putAll(properties); } getResourceType(readFileHeader(resourcename, true).getType()).replaceResource(this, resourcename, resProps, content, type); } /** * Restores a file in the current project with a version in the backup * * @param tagId The tag id of the resource * @param filename The name of the file to restore * * @throws CmsException Throws CmsException if operation was not succesful. */ public void restoreResource(int tagId, String filename) throws CmsException { getResourceType(readFileHeader(filename).getType()).restoreResource(this, tagId, filename); } /** * Removes an access control entry of a griven principal from a given resource.<p> * * @param resourceName name of the resource * @param principalType the type of the principal (currently group or user) * @param principalName name of the principal * @throws CmsException if something goes wrong */ public void rmacc(String resourceName, String principalType, String principalName) throws CmsException { CmsResource res = readFileHeader(resourceName); I_CmsPrincipal principal = null; if ("group".equals(principalType.toLowerCase())) { principal = readGroup(principalName); } else if ("user".equals(principalType.toLowerCase())) { principal = readUser(principalName); } m_driverManager.removeAccessControlEntry(m_context, res, principal.getId()); } /** * Returns the root-folder object. * * @return the root-folder object. * @throws CmsException if operation was not successful. */ public CmsFolder rootFolder() throws CmsException { return (readFolder(I_CmsConstants.C_ROOT)); } /** * Send a broadcast message to all currently logged in users.<p> * * This method is only allowed for administrators. * * @param message the message to send * @throws CmsException if something goes wrong */ public void sendBroadcastMessage(String message) throws CmsException { if (isAdmin()) { if (m_sessionStorage != null) { m_sessionStorage.sendBroadcastMessage(message); } } else { throw new CmsSecurityException("[" + this.getClass().getName() + "] sendBroadcastMessage()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED); } } /** * Sets the name of the current site root of the content objects system */ public void setContextToCos() { getRequestContext().setSiteRoot(I_CmsConstants.VFS_FOLDER_COS); } /** * Set a new name for a task.<p> * * @param taskId the id of the task * @param name the new name of the task * @throws CmsException if something goes wrong */ public void setName(int taskId, String name) throws CmsException { m_driverManager.setName(m_context, taskId, name); } /** * Sets a new parent-group for an already existing group in the Cms. * * @param groupName the name of the group that should be written to the Cms. * @param parentGroupName the name of the parentGroup to set, or null if the parent * group should be deleted. * @throws CmsException if operation was not successfull. */ public void setParentGroup(String groupName, String parentGroupName) throws CmsException { m_driverManager.setParentGroup(m_context, groupName, parentGroupName); } /** * Sets the password for a user. * * @param username the name of the user. * @param newPassword the new password. * * @throws CmsException if operation was not successful. */ public void setPassword(String username, String newPassword) throws CmsException { m_driverManager.setPassword(m_context, username, newPassword); } /** * Resets the password for a specified user.<p> * * @param username the name of the user * @param oldPassword the old password * @param newPassword the new password * @throws CmsException if the user data could not be read from the database */ public void setPassword(String username, String oldPassword, String newPassword) throws CmsException { m_driverManager.resetPassword(username, oldPassword, newPassword); } /** * Sets the priority of a task.<p> * * @param taskId the id of the task * @param priority the new priority value * @throws CmsException if something goes wrong */ public void setPriority(int taskId, int priority) throws CmsException { m_driverManager.setPriority(m_context, taskId, priority); } /** * Sets the recovery password for a user.<p> * * @param username the name of the user * @param oldPassword the old (current) password * @param newPassword the new recovery password * @throws CmsException if something goes wrong */ public void setRecoveryPassword(String username, String oldPassword, String newPassword) throws CmsException { m_driverManager.setRecoveryPassword(username, oldPassword, newPassword); } /** * Set a parameter for a task.<p> * * @param taskid the Id of the task * @param parname the ame of the parameter * @param parvalue the value of the parameter * @throws CmsException if something goes wrong */ public void setTaskPar(int taskid, String parname, String parvalue) throws CmsException { m_driverManager.setTaskPar(taskid, parname, parvalue); } /** * Sets the timeout of a task.<p> * * @param taskId the id of the task * @param timeout the new timeout value * @throws CmsException if something goes wrong */ public void setTimeout(int taskId, long timeout) throws CmsException { m_driverManager.setTimeout(m_context, taskId, timeout); } /** * Change the timestamp of a resource.<p> * * @param resourceName the name of the resource to change * @param timestamp timestamp the new timestamp of the changed resource * @param touchRecursive if true, touch recursively all sub-resources (only for folders) * @param user the user who is inserted as userladtmodified * @throws CmsException if something goes wrong */ public void touch(String resourceName, long timestamp, boolean touchRecursive, CmsUUID user) throws CmsException { getResourceType(readFileHeader(resourceName).getType()).touch(this, resourceName, timestamp, touchRecursive, user); } /** * Change the timestamp of a resource.<p> * * @param resourceName the name of the resource to change * @param timestamp timestamp the new timestamp of the changed resource * @param touchRecursive if true, touch recursively all sub-resources (only for folders) * @throws CmsException if something goes wrong */ public void touch(String resourceName, long timestamp, boolean touchRecursive) throws CmsException { touch(resourceName, timestamp, touchRecursive, getRequestContext().currentUser().getId()); } /** * Undeletes a resource. * * @param filename the complete path of the file. * * @throws CmsException if the file couldn't be undeleted, or if the user * has not the appropriate rights to undelete the file. */ public void undeleteResource(String filename) throws CmsException { //read the file header including deleted getResourceType(readFileHeader(filename, true).getType()).undeleteResource(this, filename); } /** * Undo changes in a file by copying the online file. * * @param filename the complete path of the file. * * @throws CmsException if the file couldn't be deleted, or if the user * has not the appropriate rights to write the file. */ public void undoChanges(String filename) throws CmsException { //read the file header including deleted getResourceType(readFileHeader(filename, true).getType()).undoChanges(this, filename); } /** * Unlocks all resources of a project. * * @param id the id of the project to be unlocked. * * @throws CmsException if operation was not successful. */ public void unlockProject(int id) throws CmsException { m_driverManager.unlockProject(m_context, id); } /** * Unlocks a resource.<p> * * @param resource the complete path to the resource to be unlocked * @param forceRecursive if true, also unlock all sub-resources (of a folder) * @throws CmsException if the user has no write permission for the resource */ public void unlockResource(String resource, boolean forceRecursive) throws CmsException { getResourceType(readFileHeader(resource, true).getType()).unlockResource(this, resource, forceRecursive); } /** * Tests, if a user is member of the given group. * * @param username the name of the user to test. * @param groupname the name of the group to test. * @return <code>true</code>, if the user is in the group; <code>else</code> false otherwise. * * @throws CmsException if operation was not successful. */ public boolean userInGroup(String username, String groupname) throws CmsException { return (m_driverManager.userInGroup(m_context, username, groupname)); } /** * Writes access control entries for a given resource * * @param resource the resource to attach the control entries to * @param acEntries a vector of access control entries * @throws CmsException if something goes wrong */ public void importAccessControlEntries(CmsResource resource, Vector acEntries) throws CmsException { m_driverManager.importAccessControlEntries(m_context, resource, acEntries); } /** * Writes the Crontable.<p> * * <B>Security:</B> * Only a administrator can do this.<p> * * @param crontable the crontable to write * @throws CmsException if something goes wrong */ public void writeCronTable(String crontable) throws CmsException { m_driverManager.writeCronTable(m_context, crontable); } /** * Writes the package for the system.<p> * * This path is used for db-export and db-import as well as module packages.<p> * * @param path the package path * @throws CmsException if operation ws not successful */ public void writePackagePath(String path) throws CmsException { m_driverManager.writePackagePath(m_context, path); } /** * Writes a file to the Cms. * * @param file the file to write. * * @throws CmsException if resourcetype is set to folder. The CmsException will also be thrown, * if the user has not the rights write the file. */ public void writeFile(CmsFile file) throws CmsException { m_driverManager.writeFile(m_context, file); } /** * Writes the file extension mappings.<p> * * <B>Security:</B> * Only the admin user is allowed to write file extensions. * * @param extensions holds extensions as keys and resourcetypes (Strings) as values * @throws CmsException if something goes wrong */ public void writeFileExtensions(Hashtable extensions) throws CmsException { m_driverManager.writeFileExtensions(m_context, extensions); } /** * Writes a file-header to the Cms. * * @param file the file to write. * * @throws CmsException if resourcetype is set to folder. The CmsException will also be thrown, * if the user has not the rights to write the file header.. */ public void writeFileHeader(CmsFile file) throws CmsException { m_driverManager.writeFileHeader(m_context, file); } /** * Writes an already existing group to the Cms. * * @param group the group that should be written to the Cms. * @throws CmsException if operation was not successful. */ public void writeGroup(CmsGroup group) throws CmsException { m_driverManager.writeGroup(m_context, group); } /** * Writes the Linkchecktable. * * <B>Security:</B> * Only a administrator can do this<BR/> * * @param linkchecktable The hashtable that contains the links that were not reachable * @throws CmsException if something goes wrong */ public void writeLinkCheckTable(Hashtable linkchecktable) throws CmsException { m_driverManager.writeLinkCheckTable(m_context, linkchecktable); } /** * Writes a couple of properties as structure values for a file or folder. * * @param resourceName the resource-name of which the Property has to be set. * @param properties a Hashtable with property-definitions and property values as Strings. * @throws CmsException if operation was not successful * @deprecated use {@link #writePropertyObjects(String, List)} instead */ public void writeProperties(String resourceName, Map properties) throws CmsException { m_driverManager.writePropertyObjects(m_context, addSiteRoot(resourceName), CmsProperty.toList(properties)); } /** * Writes a couple of Properties for a file or folder. * * @param name the resource-name of which the Property has to be set. * @param properties a Hashtable with property-definitions and property values as Strings. * @param addDefinition flag to indicate if unknown definitions should be added * @throws CmsException if operation was not successful. * @deprecated use {@link #writePropertyObjects(String, List)} instead */ public void writeProperties(String name, Map properties, boolean addDefinition) throws CmsException { m_driverManager.writePropertyObjects(m_context, addSiteRoot(name), CmsProperty.setAutoCreatePropertyDefinitions(CmsProperty.toList(properties), addDefinition)); } /** * Writes a property as a structure value for a file or folder.<p> * * @param resourceName the resource-name for which the property will be set * @param key the property-definition name * @param value the value for the property to be set * @throws CmsException if operation was not successful * @deprecated use {@link #writePropertyObject(String, CmsProperty)} instead */ public void writeProperty(String resourceName, String key, String value) throws CmsException { CmsProperty property = new CmsProperty(); property.setKey(key); property.setStructureValue(value); m_driverManager.writePropertyObject(m_context, addSiteRoot(resourceName), property); } /** * Writes a property for a file or folder. * * @param name the resource-name for which the property will be set. * @param key the property-definition name. * @param value the value for the property to be set. * @param addDefinition flag to indicate if unknown definitions should be added * @throws CmsException if operation was not successful. * @deprecated use {@link #writePropertyObject(String, CmsProperty)} instead */ public void writeProperty(String name, String key, String value, boolean addDefinition) throws CmsException { CmsProperty property = new CmsProperty(); property.setKey(key); property.setStructureValue(value); property.setAutoCreatePropertyDefinition(addDefinition); m_driverManager.writePropertyObject(m_context, addSiteRoot(name), property); } /** * Inserts an entry in the published resource table.<p> * * This is done during static export. * @param resourceName The name of the resource to be added to the static export * @param linkType the type of resource exported (0= non-paramter, 1=parameter) * @param linkParameter the parameters added to the resource * @param timestamp a timestamp for writing the data into the db * @throws CmsException if something goes wrong */ public void writeStaticExportPublishedResource(String resourceName, int linkType, String linkParameter, long timestamp) throws CmsException { m_driverManager.writeStaticExportPublishedResource(m_context, resourceName, linkType, linkParameter, timestamp); } /** * Writes a new user tasklog for a task. * * @param taskid the Id of the task. * @param comment the description for the log. * * @throws CmsException if operation was not successful. */ public void writeTaskLog(int taskid, String comment) throws CmsException { m_driverManager.writeTaskLog(m_context, taskid, comment); } /** * Writes a new user tasklog for a task. * * @param taskId the id of the task * @param comment the description for the log * @param taskType the type of the tasklog, user task types must be greater than 100 * @throws CmsException if something goes wrong */ public void writeTaskLog(int taskId, String comment, int taskType) throws CmsException { m_driverManager.writeTaskLog(m_context, taskId, comment, taskType); } /** * Updates the user information. * <p> * <b>Security:</b> * Only the admin user is allowed to update the user information. * * @param user the user to be written. * * @throws CmsException if operation was not successful. */ public void writeUser(CmsUser user) throws CmsException { m_driverManager.writeUser(m_context, user); } /** * Updates the user information of a web user. * <br> * Only a web user can be updated this way. * * @param user the user to be written. * * @throws CmsException if operation was not successful. */ public void writeWebUser(CmsUser user) throws CmsException { m_driverManager.writeWebUser(user); } /** * Gets the lock state for a specified resource.<p> * * @param resource the specified resource * @return the CmsLock object for the specified resource * @throws CmsException if somethong goes wrong */ public CmsLock getLock(CmsResource resource) throws CmsException { return m_driverManager.getLock(m_context, resource); } /** * Gets the lock state for a specified resource name.<p> * * @param resourcename the specified resource name * @return the CmsLock object for the specified resource name * @throws CmsException if somethong goes wrong */ public CmsLock getLock(String resourcename) throws CmsException { return m_driverManager.getLock(m_context, m_context.addSiteRoot(resourcename)); } /** * Proves if a specified resource is inside the current project.<p> * * @param resource the specified resource * @return true, if the resource name of the specified resource matches any of the current project's resources */ public boolean isInsideCurrentProject(CmsResource resource) { return m_driverManager.isInsideCurrentProject(m_context, resource); } /** * Returns the list of all resources that define the "view" of the given project.<p> * * @param project the project to get the project resources for * @return the list of all resources that define the "view" of the given project * @throws CmsException if something goes wrong */ public List readProjectResources(CmsProject project) throws CmsException { return m_driverManager.readProjectResources(project); } /** * Recovers a resource from the online project back to the offline project as an unchanged resource.<p> * * @param resourcename the name of the resource which is recovered * @return the recovered resource in the offline project * @throws CmsException if somethong goes wrong */ public CmsResource recoverResource(String resourcename) throws CmsException { return m_driverManager.recoverResource(m_context, m_context.addSiteRoot(resourcename)); } /** * This method checks if a new password follows the rules for * new passwords, which are defined by a Class configured in opencms.properties.<p> * * If this method throws no exception the password is valid.<p> * * @param password the new password that has to be checked * * @throws CmsSecurityException if the password is not valid */ public void validatePassword(String password) throws CmsSecurityException { m_driverManager.validatePassword(password); } /** * Reads the resources that were published in a publish task for a given publish history ID.<p> * * @param publishHistoryId unique int ID to identify each publish task in the publish history * @return a List of CmsPublishedResource objects * @throws CmsException if something goes wrong */ public List readPublishedResources(CmsUUID publishHistoryId) throws CmsException { return m_driverManager.readPublishedResources(m_context, publishHistoryId); } /** * Completes all post-publishing tasks for a "directly" published COS resource.<p> * * @param publishedBoResource the CmsPublishedResource onject representing the published COS resource * @param publishId unique int ID to identify each publish task in the publish history * @param tagId the backup tag revision */ public void postPublishBoResource(CmsPublishedResource publishedBoResource, CmsUUID publishId, int tagId) { try { m_driverManager.postPublishBoResource(m_context, publishedBoResource, publishId, tagId); } catch (CmsException e) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error("Error writing publish history entry for COS resource " + publishedBoResource.toString(), e); } } finally { Map eventData = (Map) new HashMap(); eventData.put("publishHistoryId", publishId.toString()); // a "directly" published COS resource can be handled totally equal to a published project OpenCms.fireCmsEvent(new CmsEvent(this, I_CmsEventListener.EVENT_PUBLISH_PROJECT, eventData)); } } /** * Validates the HTML links (hrefs and images) in all unpublished Cms files of the current * (offline) project, if the files resource types implement the interface * {@link org.opencms.validation.I_CmsHtmlLinkValidatable}.<p> * * Please refer to the Javadoc of the I_CmsHtmlLinkValidatable interface to see which classes * implement this interface (and so, which file types get validated by the HTML link * validator).<p> * * @param report an instance of I_CmsReport to print messages * @return a map with lists of invalid links keyed by resource names * @throws Exception if something goes wrong * @see org.opencms.validation.I_CmsHtmlLinkValidatable */ public Map validateHtmlLinks(I_CmsReport report) throws Exception { CmsPublishList publishList = m_driverManager.getPublishList(m_context, null, false, report); return m_driverManager.validateHtmlLinks(this, publishList, report); } /** * Validates the HTML links (hrefs and images) in the unpublished Cms file of the current * (offline) project, if the file's resource type implements the interface * {@link org.opencms.validation.I_CmsHtmlLinkValidatable}.<p> * * Please refer to the Javadoc of the I_CmsHtmlLinkValidatable interface to see which classes * implement this interface (and so, which file types get validated by the HTML link * validator).<p> * * @param directPublishResource the resource which will be directly published * @param directPublishSiblings true, if all eventual siblings of the direct published resource should also get published * @param report an instance of I_CmsReport to print messages * @return a map with lists of invalid links keyed by resource names * @throws Exception if something goes wrong * @see org.opencms.validation.I_CmsHtmlLinkValidatable */ public Map validateHtmlLinks(CmsResource directPublishResource, boolean directPublishSiblings, I_CmsReport report) throws Exception { CmsPublishList publishList = null; Map result = null; publishList = m_driverManager.getPublishList(m_context, directPublishResource, directPublishSiblings, report); result = m_driverManager.validateHtmlLinks(this, publishList, report); return result; } /** * Validates the HTML links (hrefs and images) in the unpublished Cms files of the specified * Cms publish list, if the files resource types implement the interface * {@link org.opencms.validation.I_CmsHtmlLinkValidatable}.<p> * * Please refer to the Javadoc of the I_CmsHtmlLinkValidatable interface to see which classes * implement this interface (and so, which file types get validated by the HTML link * validator).<p> * * @param publishList a Cms publish list * @param report an instance of I_CmsReport to print messages * @return a map with lists of invalid links keyed by resource names * @throws Exception if something goes wrong * @see org.opencms.validation.I_CmsHtmlLinkValidatable */ public Map validateHtmlLinks(CmsPublishList publishList, I_CmsReport report) throws Exception { return m_driverManager.validateHtmlLinks(this, publishList, report); } /** * Returns a publish list for the specified Cms resource to be published directly, plus * optionally it's siblings.<p> * * @param directPublishResource the resource which will be directly published * @param directPublishSiblings true, if all eventual siblings of the direct published resource should also get published * @param report an instance of I_CmsReport to print messages * @return a publish list * @throws CmsException if something goes wrong */ public CmsPublishList getPublishList(CmsResource directPublishResource, boolean directPublishSiblings, I_CmsReport report) throws CmsException { return m_driverManager.getPublishList(m_context, directPublishResource, directPublishSiblings, report); } /** * Returns a publish list with all new/changed/deleted Cms resources of the current (offline) * project that actually get published.<p> * * @param report an instance of I_CmsReport to print messages * @return a publish list * @throws Exception if something goes wrong */ public CmsPublishList getPublishList(I_CmsReport report) throws Exception { return getPublishList(null, false, report); } /** * Reads a property object from the database specified by it's key name mapped to a resource.<p> * * Returns {@link CmsProperty#getNullProperty()} if the property is not found.<p> * * @param resourceName the name of resource where the property is mapped to * @param propertyName the property key name * @param search true, if the property should be searched on all parent folders if not found on the resource * @return a CmsProperty object containing the structure and/or resource value * @throws CmsException if something goes wrong */ public CmsProperty readPropertyObject(String resourceName, String propertyName, boolean search) throws CmsException { return m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resourceName), m_context.getAdjustedSiteRoot(resourceName), propertyName, search); } /** * Reads all property objects mapped to a specified resource from the database.<p> * * Returns an empty list if no properties are found at all.<p> * * @param resourceName the name of resource where the property is mapped to * @param search true, if the properties should be searched on all parent folders if not found on the resource * @return a list of CmsProperty objects containing the structure and/or resource value * @throws CmsException if something goes wrong */ public List readPropertyObjects(String resourceName, boolean search) throws CmsException { return m_driverManager.readPropertyObjects(m_context, addSiteRoot(resourceName), m_context.getAdjustedSiteRoot(resourceName), search); } /** * Writes a property object to the database mapped to a specified resource.<p> * * @param resourceName the name of resource where the property is mapped to * @param property a CmsProperty object containing a structure and/or resource value * @throws CmsException if something goes wrong */ public void writePropertyObject(String resourceName, CmsProperty property) throws CmsException { m_driverManager.writePropertyObject(m_context, addSiteRoot(resourceName), property); } /** * Writes a list of property objects to the database mapped to a specified resource.<p> * * @param resourceName the name of resource where the property is mapped to * @param properties a list of CmsPropertys object containing a structure and/or resource value * @throws CmsException if something goes wrong */ public void writePropertyObjects(String resourceName, List properties) throws CmsException { m_driverManager.writePropertyObjects(m_context, addSiteRoot(resourceName), properties); } /** * Reads the (compound) values of all properties mapped to a specified resource.<p> * * @param resource the resource to look up the property for * @return Map of Strings representing all properties of the resource * @throws CmsException in case there where problems reading the properties * @deprecated use {@link #readPropertyObjects(String, boolean)} instead */ public Map readProperties(String resource) throws CmsException { List properties = m_driverManager.readPropertyObjects(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), false); return CmsProperty.toMap(properties); } /** * Reads the (compound) values of all properties mapped to a specified resource * with optional direcory upward cascading.<p> * * @param resource the resource to look up the property for * @param search if <code>true</code>, the properties will also be looked up on all parent folders and the results will be merged, if <code>false</code> not (ie. normal property lookup) * @return Map of Strings representing all properties of the resource * @throws CmsException in case there where problems reading the properties * @deprecated use {@link #readPropertyObjects(String, boolean)} instead */ public Map readProperties(String resource, boolean search) throws CmsException { List properties = m_driverManager.readPropertyObjects(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), search); return CmsProperty.toMap(properties); } /** * Reads the (compound) value of a property mapped to a specified resource.<p> * * @param resource the resource to look up the property for * @param property the name of the property to look up * @return the value of the property found, <code>null</code> if nothing was found * @throws CmsException in case there where problems reading the property * @see CmsProperty#getValue() * @deprecated use new Object based methods */ public String readProperty(String resource, String property) throws CmsException { CmsProperty value = m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), property, false); return value.isNullProperty() ? null : value.getValue(); } /** * Reads the (compound) value of a property mapped to a specified resource * with optional direcory upward cascading.<p> * * @param resource the resource to look up the property for * @param property the name of the property to look up * @param search if <code>true</code>, the property will be looked up on all parent folders if it is not attached to the the resource, if false not (ie. normal property lookup) * @return the value of the property found, <code>null</code> if nothing was found * @throws CmsException in case there where problems reading the property * @see CmsProperty#getValue() * @deprecated use new Object based methods */ public String readProperty(String resource, String property, boolean search) throws CmsException { CmsProperty value = m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), property, search); return value.isNullProperty() ? null : value.getValue(); } /** * Reads the (compound) value of a property mapped to a specified resource * with optional direcory upward cascading, a default value will be returned if the property * is not found on the resource (or it's parent folders in case search is set to <code>true</code>).<p> * * @param resource the resource to look up the property for * @param property the name of the property to look up * @param search if <code>true</code>, the property will be looked up on all parent folders if it is not attached to the the resource, if <code>false</code> not (ie. normal property lookup) * @param propertyDefault a default value that will be returned if the property was not found on the selected resource * @return the value of the property found, if nothing was found the value of the <code>propertyDefault</code> parameter is returned * @throws CmsException in case there where problems reading the property * @see CmsProperty#getValue() * @deprecated use new Object based methods */ public String readProperty(String resource, String property, boolean search, String propertyDefault) throws CmsException { CmsProperty value = m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), property, search); return value.isNullProperty() ? propertyDefault : value.getValue(); } }
src/org/opencms/file/CmsObject.java
/* * File : $Source: /alkacon/cvs/opencms/src/org/opencms/file/CmsObject.java,v $ * Date : $Date: 2004/04/02 16:59:28 $ * Version: $Revision: 1.24 $ * * This library is part of OpenCms - * the Open Source Content Mananagement System * * Copyright (C) 2002 - 2003 Alkacon Software (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.file; import org.opencms.db.CmsDriverManager; import org.opencms.db.CmsPublishList; import org.opencms.db.CmsPublishedResource; import org.opencms.lock.CmsLock; import org.opencms.main.CmsEvent; import org.opencms.main.CmsException; import org.opencms.main.CmsSessionInfoManager; import org.opencms.main.I_CmsConstants; import org.opencms.main.I_CmsEventListener; import org.opencms.main.OpenCms; import org.opencms.report.CmsShellReport; import org.opencms.report.I_CmsReport; import org.opencms.security.CmsAccessControlEntry; import org.opencms.security.CmsAccessControlList; import org.opencms.security.CmsPermissionSet; import org.opencms.security.CmsSecurityException; import org.opencms.security.I_CmsPrincipal; import org.opencms.util.CmsUUID; import org.opencms.workflow.CmsTask; import org.opencms.workflow.CmsTaskLog; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.commons.collections.ExtendedProperties; /** * This pivotal class provides all authorized access to the OpenCms resources.<p> * * It encapsulates user identification and permissions. * Think of it as the initialized "Shell" to access the OpenCms resources. * Every call to a method here will be checked for user permissions * according to the context the CmsObject instance was created with.<p> * * @author Alexander Kandzior ([email protected]) * @author Thomas Weckert ([email protected]) * @author Carsten Weinholz ([email protected]) * @author Andreas Zahner ([email protected]) * * @version $Revision: 1.24 $ */ public class CmsObject { /** * The request context. */ private CmsRequestContext m_context; /** * The driver manager to access the cms. */ private CmsDriverManager m_driverManager; /** * Method that can be invoked to find out all currently logged in users. */ private CmsSessionInfoManager m_sessionStorage; /** * The default constructor. */ public CmsObject() { // noop } /** * Initializes this CmsObject with the provided user context and database connection.<p> * * @param driverManager the driver manager to access the database * @param context the request context that contains the user authentification * @param sessionStorage the core session */ public void init( CmsDriverManager driverManager, CmsRequestContext context, CmsSessionInfoManager sessionStorage ) { m_sessionStorage = sessionStorage; m_driverManager = driverManager; m_context = context; } /** * Accept a task from the Cms. * * @param taskId the id of the task to accept. * * @throws CmsException if operation was not successful. */ public void acceptTask(int taskId) throws CmsException { m_driverManager.acceptTask(m_context, taskId); } /** * Checks if the user can access the project. * * @param projectId the id of the project. * @return <code>true</code>, if the user may access this project; <code>false</code> otherwise * * @throws CmsException if operation was not successful. */ public boolean accessProject(int projectId) throws CmsException { return (m_driverManager.accessProject(m_context, projectId)); } /** * Adds a file extension to the list of known file extensions. * <p> * <b>Security:</b> * Only members of the group administrators are allowed to add a file extension. * * @param extension a file extension like "html","txt" etc. * @param resTypeName name of the resource type associated with the extension. * * @throws CmsException if operation was not successful. */ public void addFileExtension(String extension, String resTypeName) throws CmsException { m_driverManager.addFileExtension(m_context, extension, resTypeName); } /** * Adds a user to the Cms by import. * <p> * <b>Security:</b> * Only members of the group administrators are allowed to add a user. * * @param id the id of the user * @param name the new name for the user. * @param password the new password for the user. * @param recoveryPassword the new password for the user. * @param description the description for the user. * @param firstname the firstname of the user. * @param lastname the lastname of the user. * @param email the email of the user. * @param flags the flags for a user (e.g. C_FLAG_ENABLED). * @param additionalInfos a Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param defaultGroup the default groupname for the user. * @param address the address of the user. * @param section the section of the user. * @param type the type of the user. * * @return a <code>CmsUser</code> object representing the added user. * * @throws CmsException if operation was not successful. */ public CmsUser addImportUser(String id, String name, String password, String recoveryPassword, String description, String firstname, String lastname, String email, int flags, Hashtable additionalInfos, String defaultGroup, String address, String section, int type) throws CmsException { return m_driverManager.addImportUser(m_context, id, name, password, recoveryPassword, description, firstname, lastname, email, flags, additionalInfos, defaultGroup, address, section, type); } /** * Returns the name of a resource with the complete site root name, * (e.g. /default/vfs/index.html) by adding the currently set site root prefix.<p> * * @param resourcename the resource name * @return the resource name including site root */ private String addSiteRoot(String resourcename) { return getRequestContext().addSiteRoot(resourcename); } /** * Adds a user to the OpenCms user table.<p> * * <b>Security:</b> * Only members of the group administrators are allowed to add a user.<p> * * @param name the new name for the user * @param password the password for the user * @param group the default groupname for the user * @param description the description for the user * @param additionalInfos a Hashtable with additional infos for the user * @return the newly created user * @throws CmsException if something goes wrong */ public CmsUser addUser(String name, String password, String group, String description, Hashtable additionalInfos) throws CmsException { return m_driverManager.addUser(m_context, name, password, group, description, additionalInfos); } /** * Adds a user to a group.<p> * * <b>Security:</b> * Only members of the group administrators are allowed to add a user to a group. * * @param username the name of the user that is to be added to the group * @param groupname the name of the group * @throws CmsException if something goes wrong */ public void addUserToGroup(String username, String groupname) throws CmsException { m_driverManager.addUserToGroup(m_context, username, groupname); } /** * Adds a web user to the OpenCms user table.<p> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms. * Moreover, a web user can be created by any user, the intention being that * a "Guest"user can create a personalized account from himself. * * @param name the name for the user * @param password the password for the user * @param group the default groupname for the user * @param description the description for the user * @param additionalInfos a Hashtable with additional infos for the user * @return the newly created user * @throws CmsException if something goes wrong */ public CmsUser addWebUser(String name, String password, String group, String description, Hashtable additionalInfos) throws CmsException { return m_driverManager.addWebUser(name, password, group, description, additionalInfos); } /** * Creates a backup of the published project.<p> * * @param projectId The id of the project in which the resource was published * @param versionId The version of the backup * @param publishDate The date of publishing * * @throws CmsException Throws CmsException if operation was not succesful */ public void backupProject(int projectId, int versionId, long publishDate) throws CmsException { CmsProject backupProject = m_driverManager.readProject(projectId); m_driverManager.backupProject(m_context, backupProject, versionId, publishDate); } /** * Changes the access control for a given resource and a given principal(user/group). * * @param resourceName name of the resource * @param principalType the type of the principal (currently group or user) * @param principalName name of the principal * @param allowedPermissions bitset of allowed permissions * @param deniedPermissions bitset of denied permissions * @param flags flags * @throws CmsException if something goes wrong */ public void chacc(String resourceName, String principalType, String principalName, int allowedPermissions, int deniedPermissions, int flags) throws CmsException { CmsResource res = readFileHeader(resourceName); CmsAccessControlEntry acEntry = null; I_CmsPrincipal principal = null; if ("group".equals(principalType.toLowerCase())) { principal = readGroup(principalName); acEntry = new CmsAccessControlEntry(res.getResourceId(), principal.getId(), allowedPermissions, deniedPermissions, flags); acEntry.setFlags(I_CmsConstants.C_ACCESSFLAGS_GROUP); } else if ("user".equals(principalType.toLowerCase())) { principal = readUser(principalName); acEntry = new CmsAccessControlEntry(res.getResourceId(), principal.getId(), allowedPermissions, deniedPermissions, flags); acEntry.setFlags(I_CmsConstants.C_ACCESSFLAGS_USER); } m_driverManager.writeAccessControlEntry(m_context, res, acEntry); } /** * Changes the access control for a given resource and a given principal(user/group). * * @param resourceName name of the resource * @param principalType the type of the principal (group or user) * @param principalName name of the principal * @param permissionString the permissions in the format ((+|-)(r|w|v|c|i))* * @throws CmsException if something goes wrong */ public void chacc(String resourceName, String principalType, String principalName, String permissionString) throws CmsException { CmsResource res = readFileHeader(resourceName); CmsAccessControlEntry acEntry = null; I_CmsPrincipal principal = null; if ("group".equals(principalType.toLowerCase())) { principal = readGroup(principalName); acEntry = new CmsAccessControlEntry(res.getResourceId(), principal.getId(), permissionString); acEntry.setFlags(I_CmsConstants.C_ACCESSFLAGS_GROUP); } else if ("user".equals(principalType.toLowerCase())) { principal = readUser(principalName); acEntry = new CmsAccessControlEntry(res.getResourceId(), principal.getId(), permissionString); acEntry.setFlags(I_CmsConstants.C_ACCESSFLAGS_USER); } m_driverManager.writeAccessControlEntry(m_context, res, acEntry); } /** * Changes the project-id of a resource to the new project * for publishing the resource directly.<p> * * @param projectId The new project-id * @param resourcename The name of the resource to change * @throws CmsException if something goes wrong */ public void changeLockedInProject(int projectId, String resourcename) throws CmsException { // must include files marked as deleted when publishing getResourceType(readFileHeader(resourcename, true).getType()).changeLockedInProject(this, projectId, resourcename); } /** * Changes the type of the user * * @param userId The id of the user to change * @param userType The new type of the user * @throws CmsException if something goes wrong */ public void changeUserType(CmsUUID userId, int userType) throws CmsException { m_driverManager.changeUserType(m_context, userId, userType); } /** * Changes the type of the user to webusertype * * @param username The name of the user to change * @param userType The new type of the user * @throws CmsException if something goes wrong */ public void changeUserType(String username, int userType) throws CmsException { m_driverManager.changeUserType(m_context, username, userType); } /** * Changes the resourcetype of a resource. * <br> * Only the resourcetype of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. * <p> * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename the complete path to the resource. * @param newType the name of the new resourcetype for this resource. * * @throws CmsException if operation was not successful. */ public void chtype(String filename, int newType) throws CmsException { getResourceType(readFileHeader(filename).getType()).chtype(this, filename, newType); } /** * Copies a file. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfolder. * * @throws CmsException if the file couldn't be copied, or the user * has not the appropriate rights to copy the file. * * @deprecated Use copyResource instead. */ public void copyFile(String source, String destination) throws CmsException { copyResource(source, destination, false, true, I_CmsConstants.C_COPY_PRESERVE_SIBLING); } /** * Copies a folder. * * @param source the complete path of the sourcefolder. * @param destination the complete path of the destinationfolder. * * @throws CmsException if the folder couldn't be copied, or if the * user has not the appropriate rights to copy the folder. * * @deprecated Use copyResource instead. */ public void copyFolder(String source, String destination) throws CmsException { copyResource(source, destination, false, false, I_CmsConstants.C_COPY_PRESERVE_SIBLING); } /** * Copies a file. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfolder. * * @throws CmsException if the file couldn't be copied, or the user * has not the appropriate rights to copy the file. */ public void copyResource(String source, String destination) throws CmsException { getResourceType(readFileHeader(source).getType()).copyResource(this, source, destination, false, true, I_CmsConstants.C_COPY_PRESERVE_SIBLING); } /** * Copies a file. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfolder. * @param keepFlags <code>true</code> if the copy should keep the source file's flags, * <code>false</code> if the copy should get the user's default flags. * @param lockCopy indicates if the copy should left locked after operation * @param copyMode mode of the copy operation, described how to handle linked resourced during copy. * Possible values are: * <ul> * <li>C_COPY_AS_NEW</li> * <li>C_COPY_AS_SIBLING</li> * <li>C_COPY_PRESERVE_SIBLING</li> * </ul> * @throws CmsException if the file couldn't be copied, or the user * has not the appropriate rights to copy the file. */ public void copyResource(String source, String destination, boolean keepFlags, boolean lockCopy, int copyMode) throws CmsException { getResourceType(readFileHeader(source).getType()).copyResource(this, source, destination, keepFlags, lockCopy, copyMode); } /** * Copies a resource from the online project to a new, specified project. * <br> * Copying a resource will copy the file header or folder into the specified * offline project and set its state to UNCHANGED. * * @param resource the name of the resource. * @throws CmsException if operation was not successful. */ public void copyResourceToProject(String resource) throws CmsException { getResourceType(readFileHeader(resource).getType()).copyResourceToProject(this, resource); } /** * Counts the locked resources in a project. * * @param id the id of the project * @return the number of locked resources in this project. * * @throws CmsException if operation was not successful. */ public int countLockedResources(int id) throws CmsException { return m_driverManager.countLockedResources(m_context, id); } /** * Counts the locked resources within a folder.<p> * * @param foldername the name of the folder * @return the number of locked resources in this folder * * @throws CmsException if operation was not successful. */ public int countLockedResources(String foldername) throws CmsException { return m_driverManager.countLockedResources(m_context, addSiteRoot(foldername)); } /** * Copies access control entries of a given resource to another resource.<p> * * @param sourceName the name of the resource of which the access control entries are copied * @param destName the name of the resource to which the access control entries are applied * @throws CmsException if something goes wrong */ public void cpacc(String sourceName, String destName) throws CmsException { CmsResource source = readFileHeader(sourceName); CmsResource dest = readFileHeader(destName); m_driverManager.copyAccessControlEntries(m_context, source, dest); } /** * Creates a new channel. * * @param parentChannel the complete path to the channel in which the new channel * will be created. * @param newChannelName the name of the new channel. * * @return folder a <code>CmsFolder</code> object representing the newly created channel. * * @throws CmsException if the channelname is not valid, or if the user has not the appropriate rights to create * a new channel. * */ public CmsFolder createChannel(String parentChannel, String newChannelName) throws CmsException { getRequestContext().saveSiteRoot(); try { setContextToCos(); Hashtable properties = new Hashtable(); int newChannelId = org.opencms.db.CmsDbUtil.nextId(I_CmsConstants.C_TABLE_CHANNELID); properties.put(I_CmsConstants.C_PROPERTY_CHANNELID, newChannelId + ""); return (CmsFolder)createResource(parentChannel, newChannelName, CmsResourceTypeFolder.C_RESOURCE_TYPE_ID, properties); } finally { getRequestContext().restoreSiteRoot(); } } /** * Creates a new file with the given content and resourcetype.<br> * * @param folder the complete path to the folder in which the file will be created. * @param filename the name of the new file. * @param contents the contents of the new file. * @param type the resourcetype of the new file. * * @return file a <code>CmsFile</code> object representing the newly created file. * * @throws CmsException if the resourcetype is set to folder. The CmsException is also thrown, if the * filename is not valid or if the user has not the appropriate rights to create a new file. * * @deprecated Use createResource instead. */ public CmsFile createFile(String folder, String filename, byte[] contents, int type) throws CmsException { return (CmsFile)createResource(folder, filename, type, null, contents); } /** * Creates a new file with the given content and resourcetype. * * @param folder the complete path to the folder in which the file will be created. * @param filename the name of the new file. * @param contents the contents of the new file. * @param type the resourcetype of the new file. * @param properties A Hashtable of properties, that should be set for this file. * The keys for this Hashtable are the names for properties, the values are * the values for the properties. * * @return file a <code>CmsFile</code> object representing the newly created file. * * @throws CmsException or if the resourcetype is set to folder. * The CmsException is also thrown, if the filename is not valid or if the user * has not the appropriate rights to create a new file. * * @deprecated Use createResource instead. */ public CmsFile createFile(String folder, String filename, byte[] contents, int type, Hashtable properties) throws CmsException { return (CmsFile)createResource(folder, filename, type, properties, contents); } /** * Creates a new folder. * * @param folder the complete path to the folder in which the new folder * will be created. * @param newFolderName the name of the new folder. * * @return folder a <code>CmsFolder</code> object representing the newly created folder. * * @throws CmsException if the foldername is not valid, or if the user has not the appropriate rights to create * a new folder. * * @deprecated Use createResource instead. */ public CmsFolder createFolder(String folder, String newFolderName) throws CmsException { return (CmsFolder)createResource(folder, newFolderName, CmsResourceTypeFolder.C_RESOURCE_TYPE_ID); } /** * Adds a new group to the Cms.<p> * * <b>Security:</b> * Only members of the group administrators are allowed to add a new group. * * @param name the name of the new group * @param description the description of the new group * @param flags the flags for the new group * @param parent the parent group * * @return a <code>CmsGroup</code> object representing the newly created group. * * @throws CmsException if operation was not successful. */ public CmsGroup createGroup(String name, String description, int flags, String parent) throws CmsException { return (m_driverManager.createGroup(m_context, name, description, flags, parent)); } /** * Adds a new group to the Cms.<p> * * <b>Security:</b> * Only members of the group administrators are allowed to add a new group. * * @param id the id of the group * @param name the name of the new group * @param description the description of the new group * @param flags the flags for the new group * @param parent the parent group * @return a <code>CmsGroup</code> object representing the newly created group. * @throws CmsException if something goes wrong */ public CmsGroup createGroup(String id, String name, String description, int flags, String parent) throws CmsException { return m_driverManager.createGroup(m_context, id, name, description, flags, parent); } /** * Creates a new project. * * @param name the name of the project to create * @param description the description for the new project * @param groupname the name of the project user group * @param managergroupname the name of the project manager group * @return the created project * @throws CmsException if something goes wrong */ public CmsProject createProject(String name, String description, String groupname, String managergroupname) throws CmsException { CmsProject newProject = m_driverManager.createProject(m_context, name, description, groupname, managergroupname, I_CmsConstants.C_PROJECT_TYPE_NORMAL); return (newProject); } /** * Creates a new project. * * @param name the name of the project to create * @param description the description for the new project * @param groupname the name of the project user group * @param managergroupname the name of the project manager group * @param projecttype the type of the project (normal or temporary) * @return the created project * @throws CmsException if operation was not successful. */ public CmsProject createProject(String name, String description, String groupname, String managergroupname, int projecttype) throws CmsException { CmsProject newProject = m_driverManager.createProject(m_context, name, description, groupname, managergroupname, projecttype); return (newProject); } /** * Creates the property-definition for a resource type. * * @param name the name of the property-definition to overwrite * @param resourcetype the name of the resource-type for the property-definition * @return the new property definition * * @throws CmsException if operation was not successful. */ public CmsPropertydefinition createPropertydefinition(String name, int resourcetype) throws CmsException { return (m_driverManager.createPropertydefinition(m_context, name, resourcetype)); } /** * Creates a new resource.<p> * * @param newResourceName name of the resource * @param type type of the resource * @param properties properties of the resource * @param contents content of the resource * @param parameter additional parameter * @return the new resource * @throws CmsException if something goes wrong */ public CmsResource createResource(String newResourceName, int type, Map properties, byte[] contents, Object parameter) throws CmsException { return getResourceType(type).createResource(this, newResourceName, properties, contents, parameter); } /** * Creates a new resource.<p> * * @param folder name of the parent folder * @param name name of the resource * @param type type of the resource * @return the new resource * @throws CmsException if something goes wrong */ public CmsResource createResource(String folder, String name, int type) throws CmsException { return createResource(folder + name, type, new HashMap(), new byte[0], null); } /** * Creates a new resource.<p> * * @param folder name of the parent folder * @param name name of the resource * @param type type of the resource * @param properties properties of the resource * @return the new resource * @throws CmsException if something goes wrong */ public CmsResource createResource(String folder, String name, int type, Map properties) throws CmsException { return createResource(folder + name, type, properties, new byte[0], null); } /** * Creates a new resource.<p> * * @param folder name of the parent folder * @param name name of the resource * @param type type of the resource * @param properties properties of the resource * @param contents content of the resource * @return the new resource * @throws CmsException if something goes wrong */ public CmsResource createResource(String folder, String name, int type, Map properties, byte[] contents) throws CmsException { return createResource(folder + name, type, properties, contents, null); } /** * Creates a new task.<p> * * <B>Security:</B> * All users can create a new task. * * @param projectid the Id of the current project task of the user * @param agentName the User who will edit the task * @param roleName a Usergroup for the task * @param taskname a Name of the task * @param tasktype the type of the task * @param taskcomment a description of the task * @param timeout the time when the task must finished * @param priority the Id for the priority of the task * @return the created task * @throws CmsException if something goes wrong */ public CmsTask createTask(int projectid, String agentName, String roleName, String taskname, String taskcomment, int tasktype, long timeout, int priority) throws CmsException { return m_driverManager.createTask(m_context.currentUser(), projectid, agentName, roleName, taskname, taskcomment, tasktype, timeout, priority); } /** * Creates a new task.<p> * * <B>Security:</B> * All users can create a new task. * * @param agentName the User who will edit the task * @param roleName a Usergroup for the task * @param taskname the name of the task * @param timeout the time when the task must finished * @param priority the Id for the priority of the task * @return the created task * @throws CmsException if something goes wrong */ public CmsTask createTask(String agentName, String roleName, String taskname, long timeout, int priority) throws CmsException { return (m_driverManager.createTask(m_context, agentName, roleName, taskname, timeout, priority)); } /** * Creates the project for the temporary workplace files.<p> * * @return the created project for the temporary workplace files * @throws CmsException if something goes wrong */ public CmsProject createTempfileProject() throws CmsException { return m_driverManager.createTempfileProject(m_context); } /** * Creates a new sibling of the target resource.<p> * * @param linkName name of the new link * @param targetName name of the target * @param linkProperties additional properties of the link resource * @return the new link resource * @throws CmsException if something goes wrong */ public CmsResource createSibling(String linkName, String targetName, Map linkProperties) throws CmsException { // TODO new property model: creating siblings does not support the new property model yet return m_driverManager.createSibling(m_context, addSiteRoot(linkName), addSiteRoot(targetName), CmsProperty.toList(linkProperties), true); } /** * Deletes all properties for a file or folder. * * @param resourcename the name of the resource for which all properties should be deleted. * * @throws CmsException if operation was not successful. */ public void deleteAllProperties(String resourcename) throws CmsException { m_driverManager.deleteAllProperties(m_context, addSiteRoot(resourcename)); } /** * Deletes the versions from the backup tables that are older then the given timestamp and/or number of remaining versions.<p> * * The number of verions always wins, i.e. if the given timestamp would delete more versions than given in the * versions parameter, the timestamp will be ignored. * Deletion will delete file header, content and properties. * * @param timestamp timestamp which defines the date after which backup resources must be deleted * @param versions the number of versions per file which should kept in the system. * @param report the report for output logging * * @throws CmsException if something goes wrong */ public void deleteBackups(long timestamp, int versions, I_CmsReport report) throws CmsException { m_driverManager.deleteBackups(m_context, timestamp, versions, report); } /** * Deletes a folder. * <br> * This is a very complex operation, because all sub-resources may be * deleted too. * * @param foldername the complete path of the folder. * * @throws CmsException if the folder couldn't be deleted, or if the user * has not the rights to delete this folder. * */ public void deleteEmptyFolder(String foldername) throws CmsException { m_driverManager.deleteFolder(m_context, addSiteRoot(foldername)); } /** * Deletes a file. * * @param filename the complete path of the file. * * @throws CmsException if the file couldn't be deleted, or if the user * has not the appropriate rights to delete the file. * * @deprecated Use deleteResource instead. */ public void deleteFile(String filename) throws CmsException { deleteResource(filename, I_CmsConstants.C_DELETE_OPTION_IGNORE_SIBLINGS); } /** * Deletes a folder. * <br> * This is a very complex operation, because all sub-resources may be * deleted too. * * @param foldername the complete path of the folder. * * @throws CmsException if the folder couldn't be deleted, or if the user * has not the rights to delete this folder. * * @deprecated Use deleteResource instead. */ public void deleteFolder(String foldername) throws CmsException { deleteResource(foldername, I_CmsConstants.C_DELETE_OPTION_IGNORE_SIBLINGS); } /** * Deletes a group. * <p> * <b>Security:</b> * Only the admin user is allowed to delete a group. * * @param delgroup the name of the group. * @throws CmsException if operation was not successful. */ public void deleteGroup(String delgroup) throws CmsException { m_driverManager.deleteGroup(m_context, delgroup); } /** * Deletes a project.<p> * * @param id the id of the project to delete. * * @throws CmsException if operation was not successful. */ public void deleteProject(int id) throws CmsException { m_driverManager.deleteProject(m_context, id); } /** * Deletes a property for a file or folder.<p> * * @param resourcename the name of a resource for which the property should be deleted * @param key the name of the property * @throws CmsException if something goes wrong * @deprecated use {@link #writePropertyObject(String, CmsProperty)} instead */ public void deleteProperty(String resourcename, String key) throws CmsException { CmsProperty property = new CmsProperty(); property.setKey(key); property.setStructureValue(CmsProperty.C_DELETE_VALUE); m_driverManager.writePropertyObject(m_context, addSiteRoot(resourcename), property); } /** * Deletes the property-definition for a resource type.<p> * * @param name the name of the property-definition to delete * @param resourcetype the name of the resource-type for the property-definition. * * @throws CmsException if something goes wrong */ public void deletePropertydefinition(String name, int resourcetype) throws CmsException { m_driverManager.deletePropertydefinition(m_context, name, resourcetype); } /** * Deletes a resource.<p> * * @param filename the filename of the resource exlucing the site root * @param deleteOption signals how VFS links pointing to this resource should be handled * @throws CmsException if the user has insufficient acces right to delete the resource * @see org.opencms.main.I_CmsConstants#C_DELETE_OPTION_DELETE_SIBLINGS * @see org.opencms.main.I_CmsConstants#C_DELETE_OPTION_IGNORE_SIBLINGS * @see org.opencms.main.I_CmsConstants#C_DELETE_OPTION_PRESERVE_SIBLINGS */ public void deleteResource(String filename, int deleteOption) throws CmsException { getResourceType(readFileHeader(filename).getType()).deleteResource(this, filename, deleteOption); } /** * Deletes an entry in the published resource table.<p> * * @param resourceName The name of the resource to be deleted in the static export * @param linkType the type of resource deleted (0= non-paramter, 1=parameter) * @param linkParameter the parameters of the resource * @throws CmsException if something goes wrong */ public void deleteStaticExportPublishedResource(String resourceName, int linkType, String linkParameter) throws CmsException { m_driverManager.deleteStaticExportPublishedResource(m_context, resourceName, linkType, linkParameter); } /** * Deletes all entries in the published resource table.<p> * * @param linkType the type of resource deleted (0= non-paramter, 1=parameter) * @throws CmsException if something goes wrong */ public void deleteAllStaticExportPublishedResources(int linkType) throws CmsException { m_driverManager.deleteAllStaticExportPublishedResources(m_context, linkType); } /** * Deletes a user from the Cms.<p> * * <b>Security:</b> * Only a admin user is allowed to delete a user. * * @param userId the Id of the user to be deleted. * * @throws CmsException if operation was not successful. */ public void deleteUser(CmsUUID userId) throws CmsException { m_driverManager.deleteUser(m_context, userId); } /** * Deletes a user from the Cms.<p> * * <b>Security:</b> * Only a admin user is allowed to delete a user. * * @param username the name of the user to be deleted. * * @throws CmsException if operation was not successful. */ public void deleteUser(String username) throws CmsException { m_driverManager.deleteUser(m_context, username); } /** * Deletes a web user from the Cms.<p> * * @param userId the id of the user to be deleted. * * @throws CmsException if operation was not successful. */ public void deleteWebUser(CmsUUID userId) throws CmsException { m_driverManager.deleteWebUser(userId); } /** * Method to encrypt the passwords.<p> * * @param value The value to encrypt. * @return The encrypted value. */ public String digest(String value) { return m_driverManager.digest(value); } /** * Changes the project id of a resource to the current project of the user.<p> * * @param resourcename the resource to change * @throws CmsException if something goes wrong */ protected void doChangeLockedInProject(String resourcename) throws CmsException { m_driverManager.changeLockedInProject(m_context, addSiteRoot(resourcename)); } /** * Changes the resourcetype of a resource. * <br> * Only the resourcetype of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. * <p> * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename the complete path to the resource. * @param newType the name of the new resourcetype for this resource. * * @throws CmsException if operation was not successful. */ protected void doChtype(String filename, int newType) throws CmsException { m_driverManager.chtype(m_context, addSiteRoot(filename), newType); } /** * Copies a file. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfolder. * @param lockCopy flag to lock the copied resource * @param copyMode mode of the copy operation, described how to handle linked resourced during copy. * Possible values are: * <ul> * <li>C_COPY_AS_NEW</li> * <li>C_COPY_AS_SIBLING</li> * <li>C_COPY_PRESERVE_SIBLING</li> * </ul> * @throws CmsException if the file couldn't be copied, or the user * has not the appropriate rights to copy the file. */ protected void doCopyFile(String source, String destination, boolean lockCopy, int copyMode) throws CmsException { m_driverManager.copyFile(m_context, addSiteRoot(source), addSiteRoot(destination), lockCopy, false, copyMode); } /** * Copies a folder. * * @param source the complete path of the sourcefolder. * @param destination the complete path of the destinationfolder. * @param lockCopy indicates if the copy of the folder should remain locked after operation * @param preserveTimestamps true if the timestamps and users of the folder should be kept * @throws CmsException if the folder couldn't be copied, or if the * user has not the appropriate rights to copy the folder. */ protected void doCopyFolder(String source, String destination, boolean lockCopy, boolean preserveTimestamps) throws CmsException { m_driverManager.copyFolder(m_context, addSiteRoot(source), addSiteRoot(destination), lockCopy, preserveTimestamps); } /** * Copies a resource from the online project to a new, specified project. * <br> * Copying a resource will copy the file header or folder into the specified * offline project and set its state to UNCHANGED. * * @param resource the name of the resource. * @throws CmsException if operation was not successful. */ protected void doCopyResourceToProject(String resource) throws CmsException { m_driverManager.copyResourceToProject(m_context, addSiteRoot(resource)); } /** * Creates a new file with the given content and resourcetype.<br> * * @param newFileName the name of the new file. * @param contents the contents of the new file. * @param type the resourcetype of the new file. * * @return file a <code>CmsFile</code> object representing the newly created file. * * @throws CmsException if the resourcetype is set to folder. The CmsException is also thrown, if the * filename is not valid or if the user has not the appropriate rights to create a new file. */ protected CmsFile doCreateFile(String newFileName, byte[] contents, String type) throws CmsException { CmsFile file = m_driverManager.createFile(m_context, addSiteRoot(newFileName), contents, type, Collections.EMPTY_LIST); return file; } /** * Creates a new file with the given content and resourcetype. * * @param newFileName the name of the new file. * @param contents the contents of the new file. * @param type the resourcetype of the new file. * @param properties A Hashtable of properties, that should be set for this file. * The keys for this Hashtable are the names for properties, the values are * the values for the properties. * * @return file a <code>CmsFile</code> object representing the newly created file. * * @throws CmsException if the wrong properties are given, or if the resourcetype is set to folder. * The CmsException is also thrown, if the filename is not valid or if the user * has not the appropriate rights to create a new file. */ protected CmsFile doCreateFile(String newFileName, byte[] contents, String type, Map properties) throws CmsException { // avoid null-pointer exceptions if (properties == null) { properties = Collections.EMPTY_MAP; } // TODO new property model: creating files does not support the new property model yet CmsFile file = m_driverManager.createFile(m_context, addSiteRoot(newFileName), contents, type, CmsProperty.toList(properties)); return file; } /** * Creates a new folder. * * @param newFolderName the name of the new folder. * @param properties A Hashtable of properties, that should be set for this folder. * The keys for this Hashtable are the names for property-definitions, the values are * the values for the properties. * * @return a <code>CmsFolder</code> object representing the newly created folder. * @throws CmsException if the foldername is not valid, or if the user has not the appropriate rights to create * a new folder. * */ protected CmsFolder doCreateFolder(String newFolderName, Map properties) throws CmsException { // TODO new property model: creating folders does not support the new property model yet CmsFolder cmsFolder = m_driverManager.createFolder(m_context, addSiteRoot(newFolderName), CmsProperty.toList(properties)); return cmsFolder; } /** * Creates a new folder. * * @param folder the complete path to the folder in which the new folder * will be created. * @param newFolderName the name of the new folder. * * @return folder a <code>CmsFolder</code> object representing the newly created folder. * * @throws CmsException if the foldername is not valid, or if the user has not the appropriate rights to create * a new folder. */ protected CmsFolder doCreateFolder(String folder, String newFolderName) throws CmsException { CmsFolder cmsFolder = m_driverManager.createFolder(m_context, addSiteRoot(folder + newFolderName + I_CmsConstants.C_FOLDER_SEPARATOR), Collections.EMPTY_LIST); return cmsFolder; } /** * Deletes a file. * * @param filename the complete path of the file * @param deleteOption flag to delete siblings as well * * @throws CmsException if the file couldn't be deleted, or if the user * has not the appropriate rights to delete the file. */ protected void doDeleteFile(String filename, int deleteOption) throws CmsException { m_driverManager.deleteFile(m_context, addSiteRoot(filename), deleteOption); } /** * Deletes a folder. * <br> * This is a very complex operation, because all sub-resources may be * deleted too. * * @param foldername the complete path of the folder. * * @throws CmsException if the folder couldn't be deleted, or if the user * has not the rights to delete this folder. */ protected void doDeleteFolder(String foldername) throws CmsException { m_driverManager.deleteFolder(m_context, addSiteRoot(foldername)); } /** * Creates a new resource.<p> * * @param resource the resource to be imported * @param content the content of the resource if it is of type file * @param properties A Hashtable of propertyinfos, that should be set for this folder * The keys for this Hashtable are the names for propertydefinitions, the values are * the values for the propertyinfos * @param destination the name of the new resource * * @return a <code>CmsFolder</code> object representing the newly created folder * @throws CmsException if the resourcename is not valid, or if the user has not the appropriate rights to create * a new resource * */ protected CmsResource doImportResource(CmsResource resource, byte content[], Map properties, String destination) throws CmsException { // TODO new property model: the import/export does not support the new property model yet CmsResource cmsResource = m_driverManager.importResource(m_context, addSiteRoot(destination), resource, content, CmsProperty.toList(properties)); return cmsResource; } /** * Locks the given resource.<p> * * @param resource the complete path to the resource * @param mode flag indicating the mode (temporary or common) of a lock * @throws CmsException if something goes wrong */ protected void doLockResource(String resource, int mode) throws CmsException { m_driverManager.lockResource(m_context, addSiteRoot(resource), mode); } /** * Moves a file to the given destination.<p> * * @param source the complete path of the sourcefile * @param destination the complete path of the destinationfile * @throws CmsException if something goes wrong */ protected void doMoveResource(String source, String destination) throws CmsException { m_driverManager.moveResource(m_context, addSiteRoot(source), addSiteRoot(destination)); } /** * Moves a resource to the lost and found folder.<p> * * @param resourcename the complete path of the sourcefile * @param copyResource true, if the resource should be copied to its destination inside the lost+found folder * @return location of the moved resource * @throws CmsException if the user does not have the rights to move this resource, * or if the file couldn't be moved */ protected String doCopyToLostAndFound(String resourcename, boolean copyResource) throws CmsException { return m_driverManager.copyToLostAndFound(m_context, addSiteRoot(resourcename), copyResource); } /** * Renames a resource.<p> * * @param oldname the complete path to the resource which will be renamed * @param newname the new name of the resource * @throws CmsException if the user has not the rights * to rename the resource, or if the file couldn't be renamed */ protected void doRenameResource(String oldname, String newname) throws CmsException { m_driverManager.renameResource(m_context, addSiteRoot(oldname), newname); } /** * Replaces an already existing resource with new resource data.<p> * * @param resName name of the resource * @param newResContent new content of the resource * @param newResType new type of the resource * @param newResProps new properties * @return the replaced resource * @throws CmsException if something goes wrong */ protected CmsResource doReplaceResource(String resName, byte[] newResContent, int newResType, Map newResProps) throws CmsException { CmsResource res = null; // TODO new property model: replacing resource does not yet support the new property model res = m_driverManager.replaceResource(m_context, addSiteRoot(resName), newResType, CmsProperty.toList(newResProps), newResContent); return res; } /** * Restores a file in the current project with a version in the backup * * @param tagId The tag id of the resource * @param filename The name of the file to restore * * @throws CmsException Throws CmsException if operation was not succesful. */ protected void doRestoreResource(int tagId, String filename) throws CmsException { m_driverManager.restoreResource(m_context, tagId, addSiteRoot(filename)); } /** * Access the driver manager underneath to change the timestamp of a resource. * * @param resourceName the name of the resource to change * @param timestamp timestamp the new timestamp of the changed resource * @param user the user who is inserted as userladtmodified * @throws CmsException if something goes wrong */ protected void doTouch(String resourceName, long timestamp, CmsUUID user) throws CmsException { m_driverManager.touch(m_context, addSiteRoot(resourceName), timestamp, user); } /** * Undeletes a file. * * @param filename the complete path of the file. * * @throws CmsException if the file couldn't be undeleted, or if the user * has not the appropriate rights to undelete the file. */ protected void doUndeleteFile(String filename) throws CmsException { m_driverManager.undeleteResource(m_context, addSiteRoot(filename)); } /** * Undeletes a folder. * <br> * This is a very complex operation, because all sub-resources may be * undeleted too. * * @param foldername the complete path of the folder. * * @throws CmsException if the folder couldn't be undeleted, or if the user * has not the rights to undelete this folder. */ protected void doUndeleteFolder(String foldername) throws CmsException { m_driverManager.undeleteResource(m_context, addSiteRoot(foldername)); } /** * Undo changes in a file. * <br> * * @param resource the complete path to the resource to be unlocked. * * @throws CmsException if the user has not the rights * to write this resource. */ protected void doUndoChanges(String resource) throws CmsException { m_driverManager.undoChanges(m_context, addSiteRoot(resource)); } /** * Unlocks a resource. * <br> * A user can unlock a resource, so other users may lock this file. * * @param resource the complete path to the resource to be unlocked. * * @throws CmsException if the user has not the rights * to unlock this resource. */ protected void doUnlockResource(String resource) throws CmsException { m_driverManager.unlockResource(m_context, addSiteRoot(resource)); } /** * Writes a resource and its properties to the VFS.<p> * * @param resourcename the name of the resource to write * @param properties the properties of the resource * @param filecontent the new filecontent of the resource * @throws CmsException if something goes wrong */ protected void doWriteResource(String resourcename, Map properties, byte[] filecontent) throws CmsException { // TODO new property model: the import/export does not support the new property model yet m_driverManager.writeResource(m_context, addSiteRoot(resourcename), CmsProperty.toList(properties), filecontent); } /** * Ends a task.<p> * * @param taskid the ID of the task to end. * * @throws CmsException if operation was not successful. */ public void endTask(int taskid) throws CmsException { m_driverManager.endTask(m_context, taskid); } /** * Tests if a resource with the given resourceId does already exist in the Database.<p> * * @param resourceId the resource id to test for * @return true if a resource with the given id was found, false otherweise * @throws CmsException if something goes wrong */ public boolean existsResourceId (CmsUUID resourceId) throws CmsException { return m_driverManager.existsResourceId(m_context, resourceId); } /** * Exports a resource. * * @param file the resource to export * @return the resource that was exported * @throws CmsException if something goes wrong */ public CmsFile exportResource(CmsFile file) throws CmsException { return getResourceType(file.getType()).exportResource(this, file); } /** * Reads all siblings that point to the resource record of a specified resource name.<p> * * @param resourcename name of a resource * @return List of siblings of the resource * @throws CmsException if something goes wrong */ public List getAllVfsLinks(String resourcename) throws CmsException { return m_driverManager.readSiblings(m_context, addSiteRoot(resourcename), true, false); } /** * Reads all siblings that point to the resource record of a specified resource name, * excluding the specified resource from the result.<p> * * @param resourcename name of a resource * @return List of siblings of the resource * @throws CmsException if something goes wrong */ public List getAllVfsSoftLinks(String resourcename) throws CmsException { return m_driverManager.readSiblings(m_context, addSiteRoot(resourcename), false, false); } /** * Fires a CmsEvent * * @param type The type of the event * @param data A data object that contains data used by the event listeners */ private void fireEvent(int type, Object data) { OpenCms.fireCmsEvent(this, type, Collections.singletonMap("data", data)); } /** * Forwards a task to a new user. * * @param taskid the id of the task which will be forwarded. * @param newRoleName the new group for the task. * @param newUserName the new user who gets the task. * * @throws CmsException if operation was not successful. */ public void forwardTask(int taskid, String newRoleName, String newUserName) throws CmsException { m_driverManager.forwardTask(m_context, taskid, newRoleName, newUserName); } /** * Returns the vector of access control entries of a resource. * * @param resourceName the name of the resource. * @return a vector of access control entries * @throws CmsException if something goes wrong */ public Vector getAccessControlEntries(String resourceName) throws CmsException { return getAccessControlEntries(resourceName, true); } /** * Returns the vector of access control entries of a resource. * * @param resourceName the name of the resource. * @param getInherited true, if inherited access control entries should be returned, too * @return a vector of access control entries * @throws CmsException if something goes wrong */ public Vector getAccessControlEntries(String resourceName, boolean getInherited) throws CmsException { CmsResource res = readFileHeader(resourceName); return m_driverManager.getAccessControlEntries(m_context, res, getInherited); } /** * Returns the access control list (summarized access control entries) of a given resource. * * @param resourceName the name of the resource * @return the access control list of the resource * @throws CmsException if something goes wrong */ public CmsAccessControlList getAccessControlList(String resourceName) throws CmsException { return getAccessControlList(resourceName, false); } /** * Returns the access control list (summarized access control entries) of a given resource. * * @param resourceName the name of the resource * @param inheritedOnly if set, the non-inherited entries are skipped * @return the access control list of the resource * @throws CmsException if something goes wrong */ public CmsAccessControlList getAccessControlList(String resourceName, boolean inheritedOnly) throws CmsException { CmsResource res = readFileHeader(resourceName); return m_driverManager.getAccessControlList(m_context, res, inheritedOnly); } /** * Returns all projects, which the current user can access. * * @return a Vector of objects of type <code>CmsProject</code>. * * @throws CmsException if operation was not successful. */ public Vector getAllAccessibleProjects() throws CmsException { return (m_driverManager.getAllAccessibleProjects(m_context)); } /** * Returns a Vector with all projects from history * * @return Vector with all projects from history. * * @throws CmsException Throws CmsException if operation was not succesful. */ public Vector getAllBackupProjects() throws CmsException { return m_driverManager.getAllBackupProjects(); } /** * Returns all projects which are owned by the current user or which are manageable * for the group of the user. * * @return a Vector of objects of type <code>CmsProject</code>. * * @throws CmsException if operation was not successful. */ public Vector getAllManageableProjects() throws CmsException { return (m_driverManager.getAllManageableProjects(m_context)); } /** * Returns a List with all initialized resource types.<p> * * @return a List with all initialized resource types */ public List getAllResourceTypes() { I_CmsResourceType resourceTypes[] = m_driverManager.getAllResourceTypes(); List result = new ArrayList(resourceTypes.length); for (int i = 0; i < resourceTypes.length; i++) { if (resourceTypes[i] != null) { result.add(resourceTypes[i]); } } return result; } /** * Get the next version id for the published backup resources * * @return int The new version id */ public int getBackupTagId() { return m_driverManager.getBackupTagId(); } /** * Returns all child groups of a group. * * @param groupname the name of the group. * @return groups a Vector of all child groups or null. * @throws CmsException if operation was not successful. */ public Vector getChild(String groupname) throws CmsException { return (m_driverManager.getChild(m_context, groupname)); } /** * Returns all child groups of a group. * <br> * This method also returns all sub-child groups of the current group. * * @param groupname the name of the group. * @return groups a Vector of all child groups or null. * @throws CmsException if operation was not successful. */ public Vector getChilds(String groupname) throws CmsException { return (m_driverManager.getChilds(m_context, groupname)); } /** * Gets the configurations of the properties-file. * @return the configurations of the properties-file. */ public ExtendedProperties getConfigurations() { return m_driverManager.getConfigurations(); } /** * Gets all groups to which a given user directly belongs. * * @param username the name of the user to get all groups for. * @return a Vector of all groups of a user. * * @throws CmsException if operation was not successful. */ public Vector getDirectGroupsOfUser(String username) throws CmsException { return (m_driverManager.getDirectGroupsOfUser(m_context, username)); } /** * Returns the generic driver objects.<p> * * @return a mapping of class names to driver objects */ public Map getDrivers() { HashMap drivers = new HashMap(); drivers.put(this.m_driverManager.getVfsDriver().getClass().getName(), this.m_driverManager.getVfsDriver()); drivers.put(this.m_driverManager.getUserDriver().getClass().getName(), this.m_driverManager.getUserDriver()); drivers.put(this.m_driverManager.getProjectDriver().getClass().getName(), this.m_driverManager.getProjectDriver()); drivers.put(this.m_driverManager.getWorkflowDriver().getClass().getName(), this.m_driverManager.getWorkflowDriver()); drivers.put(this.m_driverManager.getBackupDriver().getClass().getName(), this.m_driverManager.getBackupDriver()); return drivers; } /** * Returns a Vector with all files of a given folder. * (only the direct subfiles, not the files in subfolders) * <br> * Files of a folder can be read from an offline Project and the online Project. * * @param foldername the complete path to the folder. * * @return subfiles a Vector with all files of the given folder. * * @throws CmsException if the user has not hte appropriate rigths to access or read the resource. */ public List getFilesInFolder(String foldername) throws CmsException { return (m_driverManager.getSubFiles(m_context, addSiteRoot(foldername), false)); } /** * Returns a Vector with all files of a given folder. * <br> * Files of a folder can be read from an offline Project and the online Project. * * @param foldername the complete path to the folder. * @param includeDeleted Include if the folder is marked as deleted * * @return subfiles a Vector with all files of the given folder. * * @throws CmsException if the user has not hte appropriate rigths to access or read the resource. */ public List getFilesInFolder(String foldername, boolean includeDeleted) throws CmsException { return (m_driverManager.getSubFiles(m_context, addSiteRoot(foldername), includeDeleted)); } /** * Returns a Vector with all resource-names of the resources that have set the given property to the given value. * * @param propertyDefinition the name of the property-definition to check. * @param propertyValue the value of the property for the resource. * * @return a Vector with all names of the resources. * * @throws CmsException if operation was not successful. */ public Vector getFilesWithProperty(String propertyDefinition, String propertyValue) throws CmsException { return m_driverManager.getFilesWithProperty(m_context, propertyDefinition, propertyValue); } /** * This method can be called, to determine if the file-system was changed in the past. * <br> * A module can compare its previously stored number with the returned number. * If they differ, the file system has been changed. * * @return the number of file-system-changes. */ public long getFileSystemFolderChanges() { return (m_driverManager.getFileSystemFolderChanges()); } /** * Returns all groups in the Cms. * * @return a Vector of all groups in the Cms. * * @throws CmsException if operation was not successful */ public Vector getGroups() throws CmsException { return (m_driverManager.getGroups(m_context)); } /** * Returns the groups of a Cms user.<p> * * @param username the name of the user * @return a vector of Cms groups * @throws CmsException if operation was not succesful. */ public Vector getGroupsOfUser(String username) throws CmsException { return m_driverManager.getGroupsOfUser(m_context, username); } /** * Returns the groups of a Cms user filtered by the specified IP address.<p> * * @param username the name of the user * @param remoteAddress the IP address to filter the groups in the result vector * @return a vector of Cms groups filtered by the specified IP address * @throws CmsException if operation was not succesful. */ public Vector getGroupsOfUser(String username, String remoteAddress) throws CmsException { return m_driverManager.getGroupsOfUser(m_context, username, remoteAddress); } /** * Returns all groups with a name like the specified pattern.<p> * * @param namePattern pattern for the group name * @return a Vector of all groups with a name like the given pattern * * @throws CmsException if something goes wrong */ public Vector getGroupsLike(String namePattern) throws CmsException { return (m_driverManager.getGroupsLike(m_context, namePattern)); } /** * Checks if a user is a direct member of a group having a name like the specified pattern.<p> * * @param username the name of the user to get all groups for. * @param groupNamePattern pattern for the group name * @return <code>true</code> if the given user is a direct member of a group having a name like the specified pattern * @throws CmsException if something goes wrong */ public boolean hasDirectGroupsOfUserLike(String username, String groupNamePattern) throws CmsException { return (m_driverManager.hasDirectGroupsOfUserLike(m_context, username, groupNamePattern)); } /** * This is the port the workplace access is limited to. With the opencms.properties * the access to the workplace can be limited to a user defined port. With this * feature a firewall can block all outside requests to this port with the result * the workplace is only available in the local net segment. * @return the portnumber or -1 if no port is set. */ public int getLimitedWorkplacePort() { return m_driverManager.getLimitedWorkplacePort(); } /** * Returns a list of all currently logged in users. * This method is only allowed for administrators. * * @return a vector of users that are currently logged in * @throws CmsException if something goes wrong */ public Vector getLoggedInUsers() throws CmsException { if (isAdmin()) { if (m_sessionStorage != null) { return m_sessionStorage.getLoggedInUsers(); } else { return null; } } else { throw new CmsSecurityException("[" + this.getClass().getName() + "] getLoggedInUsers()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED); } } /** * Returns the parent group of a group. * * @param groupname the name of the group. * @return group the parent group or null. * @throws CmsException if operation was not successful. */ public CmsGroup getParent(String groupname) throws CmsException { return (m_driverManager.getParent(groupname)); } /** * Returns the set set of permissions of the current user for a given resource. * * @param resourceName the name of the resource * @return the set of the permissions of the current user * @throws CmsException if something goes wrong */ public CmsPermissionSet getPermissions(String resourceName) throws CmsException { // reading permissions is allowed even if the resource is marked as deleted CmsResource resource = readFileHeader(resourceName, true); CmsUser user = m_context.currentUser(); return m_driverManager.getPermissions(m_context, resource, user); } /** * Returns the set set of permissions of a given user for a given resource. * * @param resourceName the name of the resource * @param userName the name of the user * @return the current permissions on this resource * @throws CmsException if something goes wrong */ public CmsPermissionSet getPermissions(String resourceName, String userName) throws CmsException { CmsAccessControlList acList = getAccessControlList(resourceName); CmsUser user = readUser(userName); return acList.getPermissions(user, getGroupsOfUser(userName)); } /** * Returns the current OpenCms registry.<p> * * @return the current OpenCms registry */ public CmsRegistry getRegistry() { return m_driverManager.getRegistry(this); } /** * Returns the current request-context. * * @return the current request-context. */ public CmsRequestContext getRequestContext() { return (m_context); } /** * Returns a Vector with the sub resources for a folder.<br> * * @param folder the name of the folder to get the subresources from. * @return subfolders a Vector with resources * @throws CmsException if operation was not succesful */ public Vector getResourcesInFolder(String folder) throws CmsException { return m_driverManager.getResourcesInFolder(m_context, addSiteRoot(folder)); } /** * Returns a List with all sub resources of a given folder that have benn modified * in a given time range.<p> * * The rertuned list is sorted descending (newest resource first). * * <B>Security:</B> * All users are granted. * * @param folder the folder to get the subresources from * @param starttime the begin of the time range * @param endtime the end of the time range * @return List with all resources * * @throws CmsException if operation was not succesful */ public List getResourcesInTimeRange(String folder, long starttime, long endtime) throws CmsException { return m_driverManager.getResourcesInTimeRange(m_context, addSiteRoot(folder), starttime, endtime); } /** * Returns a Vector with all resources of the given type that have set the given property. * * <B>Security:</B> * All users are granted. * * @param propertyDefinition the name of the propertydefinition to check. * * @return Vector with all resources. * * @throws CmsException if operation was not succesful. */ public Vector getResourcesWithPropertyDefinition(String propertyDefinition) throws CmsException { return m_driverManager.getResourcesWithPropertyDefinition(m_context, propertyDefinition); } /** * Returns a List with the complete sub tree of a given folder that have set the given property.<p> * * <B>Security:</B> * All users are granted. * * @param folder the folder to get the subresources from * @param propertyDefinition the name of the propertydefinition to check * @return List with all resources * * @throws CmsException if operation was not succesful */ public List getResourcesWithProperty(String folder, String propertyDefinition) throws CmsException { return m_driverManager.getResourcesWithProperty(m_context, addSiteRoot(folder), propertyDefinition); } /** * Returns a List with resources that have set the given property.<p> * * <B>Security:</B> * All users are granted. * * @param propertyDefinition the name of the propertydefinition to check * @return List with all resources * * @throws CmsException if operation was not succesful */ public List getResourcesWithProperty(String propertyDefinition) throws CmsException { return m_driverManager.getResourcesWithProperty(m_context, "/", propertyDefinition); } /** * Returns a Vector with all resources of the given type that have set the given property to the given value. * * <B>Security:</B> * All users are granted. * * @param propertyDefinition the name of the propertydefinition to check. * @param propertyValue the value of the property for the resource. * @param resourceType The resource type of the resource * * @return Vector with all resources. * * @throws CmsException Throws CmsException if operation was not succesful. */ public Vector getResourcesWithPropertyDefintion(String propertyDefinition, String propertyValue, int resourceType) throws CmsException { return m_driverManager.getResourcesWithPropertyDefintion(m_context, propertyDefinition, propertyValue, resourceType); } /** * Returns the initialized resource type instance for the given id.<p> * * @param resourceType the id of the resourceType to get * @return the initialized resource type instance for the given id * @throws CmsException if something goes wrong */ public I_CmsResourceType getResourceType(int resourceType) throws CmsException { return m_driverManager.getResourceType(resourceType); } /** * Returns the resource type id for the given resource type name.<p> * * @param resourceType the name of the resourceType to get the id for * @return the resource type id for the given resource type name * @throws CmsException if something goes wrong */ public int getResourceTypeId(String resourceType) throws CmsException { I_CmsResourceType type = m_driverManager.getResourceType(resourceType); if (type != null) { return type.getResourceType(); } else { return I_CmsConstants.C_UNKNOWN_ID; } } /** * Returns a Vector with all subfolders of a given folder.<p> * * @param foldername the complete path to the folder * @return all subfolders (CmsFolder Objects) for the given folder * @throws CmsException if the user has not the permissions to access or read the resource */ public List getSubFolders(String foldername) throws CmsException { return (m_driverManager.getSubFolders(m_context, addSiteRoot(foldername), false)); } /** * Returns a Vector with all subfolders of a given folder.<p> * * @param foldername the complete path to the folder * @param includeDeleted if true folders marked as deleted are also included * @return all subfolders (CmsFolder Objects) for the given folder * @throws CmsException if the user has not the permissions to access or read the resource */ public List getSubFolders(String foldername, boolean includeDeleted) throws CmsException { return (m_driverManager.getSubFolders(m_context, addSiteRoot(foldername), includeDeleted)); } /** * Get a parameter value for a task. * * @param taskid the id of the task. * @param parname the name of the parameter. * @return the parameter value. * * @throws CmsException if operation was not successful. */ public String getTaskPar(int taskid, String parname) throws CmsException { return (m_driverManager.getTaskPar(taskid, parname)); } /** * Get the template task id fo a given taskname. * * @param taskname the name of the task. * * @return the id of the task template. * * @throws CmsException if operation was not successful. */ public int getTaskType(String taskname) throws CmsException { return m_driverManager.getTaskType(taskname); } /** * Returns all users in the Cms. * * @return a Vector of all users in the Cms. * * @throws CmsException if operation was not successful. */ public Vector getUsers() throws CmsException { return (m_driverManager.getUsers(m_context)); } /** * Returns all users of the given type in the Cms. * * @param type the type of the users. * * @return vector of all users of the given type in the Cms. * * @throws CmsException if operation was not successful. */ public Vector getUsers(int type) throws CmsException { return (m_driverManager.getUsers(m_context, type)); } /** * Returns all users from a given type that start with a specified string<P/> * * @param type the type of the users. * @param namefilter The filter for the username * @return vector of all users of the given type in the Cms. * * @throws CmsException if operation was not successful. * @deprecated */ public Vector getUsers(int type, String namefilter) throws CmsException { return m_driverManager.getUsers(m_context, type, namefilter); } /** * Gets all users with a certain Lastname. * * @param Lastname the start of the users lastname * @param UserType webuser or systemuser * @param UserStatus enabled, disabled * @param wasLoggedIn was the user ever locked in? * @param nMax max number of results * * @return the users. * * @throws CmsException if operation was not successful. * @deprecated */ public Vector getUsersByLastname(String Lastname, int UserType, int UserStatus, int wasLoggedIn, int nMax) throws CmsException { return m_driverManager.getUsersByLastname(m_context, Lastname, UserType, UserStatus, wasLoggedIn, nMax); } /** * Gets all users of a group. * * @param groupname the name of the group to get all users for. * @return all users in the group. * * @throws CmsException if operation was not successful. */ public Vector getUsersOfGroup(String groupname) throws CmsException { return (m_driverManager.getUsersOfGroup(m_context, groupname)); } /** * Returns a Vector with all resources of the given type that have set the given property to the given value. * * <B>Security:</B> * All users that have read and view access are granted. * * @param propertyDefinition the name of the propertydefinition to check. * @param propertyValue the value of the property for the resource. * @param resourceType the resource type of the resource * * @return Vector with all resources. * * @throws CmsException Throws CmsException if operation was not succesful. */ public Vector getVisibleResourcesWithProperty(String propertyDefinition, String propertyValue, int resourceType) throws CmsException { return m_driverManager.getVisibleResourcesWithProperty(m_context, propertyDefinition, propertyValue, resourceType); } /** * Checks if the current user has required permissions to access a given resource. * * @param resource the resource that will be accessed * @param requiredPermissions the set of required permissions * @return true if the required permissions are satisfied * @throws CmsException if something goes wrong */ public boolean hasPermissions(CmsResource resource, CmsPermissionSet requiredPermissions) throws CmsException { return m_driverManager.hasPermissions(m_context, resource, requiredPermissions, false); } /** * Checks if the current user has required permissions to access a given resource * * @param resourceName the name of the resource that will be accessed * @param requiredPermissions the set of required permissions * @return true if the required permissions are satisfied * @throws CmsException if something goes wrong */ public boolean hasPermissions(String resourceName, CmsPermissionSet requiredPermissions) throws CmsException { CmsResource resource = readFileHeader(resourceName); return m_driverManager.hasPermissions(m_context, resource, requiredPermissions, false); } /** * Imports a import-resource (folder or zipfile) to the cms. * * @param importFile the name (absolute Path) of the import resource (zipfile or folder). * @param importPath the name (absolute Path) of the folder in which should be imported. * * @throws CmsException if operation was not successful. */ public void importFolder(String importFile, String importPath) throws CmsException { // OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP, false)); m_driverManager.clearcache(); // import the resources m_driverManager.importFolder(this, m_context, importFile, importPath); // OpenCms.fireCmsEvent(new CmsEvent(new CmsObject(), I_CmsEventListener.EVENT_CLEAR_CACHES, Collections.EMPTY_MAP, false)); m_driverManager.clearcache(); } /** * Imports a resource to the cms.<p> * * @param resource the resource to be imported * @param content the content of the resource * @param properties the properties of the resource * @param importpath the name of the resource destinaition * @return the imported CmsResource * @throws CmsException if operation was not successful */ public CmsResource importResource(CmsResource resource, byte[] content, Map properties, String importpath) throws CmsException { return getResourceType(resource.getType()).importResource(this, resource, content, properties, importpath); } /** * Checks, if the users current group is the admin-group. * * * @return <code>true</code>, if the users current group is the admin-group; <code>false</code> otherwise. * @throws CmsException if operation was not successful. */ public boolean isAdmin() throws CmsException { return m_driverManager.isAdmin(m_context); } /** * Checks if the user has management access to the project. * * Please note: This is NOT the same as the {@link CmsObject#isProjectManager()} * check. If the user has management access to a project depends on the * project settings.<p> * * @return true if the user has management access to the project * @throws CmsException if operation was not successful. * @see #isProjectManager() */ public boolean isManagerOfProject() throws CmsException { return m_driverManager.isManagerOfProject(m_context); } /** * Checks if the user is a member of the project manager group.<p> * * Please note: This is NOT the same as the {@link CmsObject#isManagerOfProject()()} * check. If the user is a member of the project manager group, * he can create new projects.<p> * * @return true if the user is a member of the project manager group * @throws CmsException if operation was not successful. * @see #isManagerOfProject() */ public boolean isProjectManager() throws CmsException { return m_driverManager.isProjectManager(m_context); } /** * Returns the user, who has locked a given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. This methods checks, who has locked a resource. * * @param resource the resource to check. * * @return the user who has locked the resource. * * @throws CmsException if operation was not successful. */ public CmsUser lockedBy(CmsResource resource) throws CmsException { return (m_driverManager.lockedBy(m_context, resource)); } /** * Returns the user, who has locked a given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. This methods checks, who has locked a resource. * * @param resource The complete path to the resource. * * @return the user who has locked a resource. * * @throws CmsException if operation was not successful. */ public CmsUser lockedBy(String resource) throws CmsException { return (m_driverManager.lockedBy(m_context, addSiteRoot(resource))); } /** * Locks the given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. * * @param resource The complete path to the resource to lock. * * @throws CmsException if the user has not the rights to lock this resource. * It will also be thrown, if there is an existing lock. * */ public void lockResource(String resource) throws CmsException { // try to lock the resource, prevent from overwriting an existing lock lockResource(resource, false, CmsLock.C_MODE_COMMON); } /** * Locks a given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. * * @param resource the complete path to the resource to lock. * @param force if force is <code>true</code>, a existing locking will be overwritten. * * @throws CmsException if the user has not the rights to lock this resource. * It will also be thrown, if there is a existing lock and force was set to false. */ public void lockResource(String resource, boolean force) throws CmsException { lockResource(resource, force, CmsLock.C_MODE_COMMON); } /** * Locks a given resource. * <br> * A user can lock a resource, so he is the only one who can write this * resource. * * @param resource the complete path to the resource to lock. * @param force if force is <code>true</code>, a existing locking will be overwritten. * @param mode flag indicating the mode (temporary or common) of a lock * * @throws CmsException if the user has not the rights to lock this resource. * It will also be thrown, if there is a existing lock and force was set to false. */ public void lockResource(String resource, boolean force, int mode) throws CmsException { getResourceType(readFileHeader(resource).getType()).lockResource(this, resource, force, mode); } /** * Changes the lock of a resource.<p> * * @param resourcename name of the resource * @throws CmsException if something goes wrong */ public void changeLock(String resourcename) throws CmsException { m_driverManager.changeLock(m_context, addSiteRoot(resourcename)); } /** * Logs a user into the Cms, if the password is correct.<p> * * @param username the name of the user * @param password the password of the user * @return the name of the logged in user * * @throws CmsSecurityException if operation was not successful */ public String loginUser(String username, String password) throws CmsSecurityException { return loginUser(username, password, m_context.getRemoteAddress()); } /** * Logs a user with a given ip address into the Cms, if the password is correct.<p> * * @param username the name of the user * @param password the password of the user * @param remoteAddress the ip address * @return the name of the logged in user * * @throws CmsSecurityException if operation was not successful */ public String loginUser(String username, String password, String remoteAddress) throws CmsSecurityException { return loginUser(username, password, remoteAddress, I_CmsConstants.C_USER_TYPE_SYSTEMUSER); } /** * Logs a user with a given type and a given ip address into the Cms, if the password is correct.<p> * * @param username the name of the user * @param password the password of the user * @param remoteAddress the ip address * @param type the user type (System or Web user) * @return the name of the logged in user * * @throws CmsSecurityException if operation was not successful */ public String loginUser(String username, String password, String remoteAddress, int type) throws CmsSecurityException { // login the user CmsUser newUser = m_driverManager.loginUser(username, password, remoteAddress, type); // set the project back to the "Online" project CmsProject newProject; try { newProject = m_driverManager.readProject(I_CmsConstants.C_PROJECT_ONLINE_ID); } catch (CmsException e) { // should not happen since the online project is always available throw new CmsSecurityException(CmsSecurityException.C_SECURITY_LOGIN_FAILED, e); } // switch the cms context to the new user and project m_context.switchUser(newUser, newProject); // init this CmsObject with the new user init(m_driverManager, m_context, m_sessionStorage); // fire a login event this.fireEvent(org.opencms.main.I_CmsEventListener.EVENT_LOGIN_USER, newUser); // return the users login name return newUser.getName(); } /** * Logs a web user into the Cms, if the password is correct. * * @param username the name of the user. * @param password the password of the user. * @return the name of the logged in user. * * @throws CmsSecurityException if operation was not successful */ public String loginWebUser(String username, String password) throws CmsSecurityException { return loginUser(username, password, m_context.getRemoteAddress(), I_CmsConstants.C_USER_TYPE_WEBUSER); } /** * Lookup and reads the user or group with the given UUID.<p> * * @param principalId the uuid of a user or group * @return the user or group with the given UUID */ public I_CmsPrincipal lookupPrincipal(CmsUUID principalId) { return m_driverManager.lookupPrincipal(principalId); } /** * Lookup and reads the user or group with the given name.<p> * * @param principalName the name of the user or group * @return the user or group with the given name */ public I_CmsPrincipal lookupPrincipal(String principalName) { return m_driverManager.lookupPrincipal(principalName); } /** * Moves a resource to the given destination. * * @param source the complete path of the sourcefile. * @param destination the complete path of the destinationfile. * * @throws CmsException if the user has not the rights to move this resource, * or if the file couldn't be moved. */ public void moveResource(String source, String destination) throws CmsException { getResourceType(readFileHeader(source).getType()).moveResource(this, source, destination); } /** * Moves a resource to the lost and found folder * * @param source the complete path of the sourcefile. * @return location of the moved resource * @throws CmsException if the user has not the rights to move this resource, * or if the file couldn't be moved. */ public String copyToLostAndFound(String source) throws CmsException { return getResourceType(readFileHeader(source).getType()).copyToLostAndFound(this, source, true); } /** * Publishes the current project, printing messages to a shell report.<p> * * @throws Exception if something goes wrong */ public void publishProject() throws Exception { publishProject(new CmsShellReport()); } /** * Publishes the current project.<p> * * @param report an instance of I_CmsReport to print messages * @throws CmsException if something goes wrong */ public void publishProject(I_CmsReport report) throws CmsException { publishProject(report, null, false); } /** * Direct publishes a specified resource.<p> * * @param report an instance of I_CmsReport to print messages * @param directPublishResource a CmsResource that gets directly published; or null if an entire project gets published * @param directPublishSiblings if a CmsResource that should get published directly is provided as an argument, all eventual siblings of this resource get publish too, if this flag is true * @throws CmsException if something goes wrong * @see #publishResource(String) * @see #publishResource(String, boolean, I_CmsReport) */ public void publishProject(I_CmsReport report, CmsResource directPublishResource, boolean directPublishSiblings) throws CmsException { CmsPublishList publishList = getPublishList(directPublishResource, directPublishSiblings, report); publishProject(report, publishList); } /** * Publishes the resources of a specified publish list.<p> * * @param report an instance of I_CmsReport to print messages * @param publishList a publish list * @throws CmsException if something goes wrong * @see #getPublishList(I_CmsReport) * @see #getPublishList(CmsResource, boolean, I_CmsReport) */ public void publishProject(I_CmsReport report, CmsPublishList publishList) throws CmsException { // TODO check if useful/neccessary m_driverManager.clearcache(); synchronized (m_driverManager) { try { m_driverManager.publishProject(this, m_context, publishList, report); } catch (CmsException e) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error(e); } throw e; } catch (Exception e) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error(e); } throw new CmsException(CmsException.C_UNKNOWN_EXCEPTION, e); } finally { // TODO check if useful/neccessary m_driverManager.clearcache(); // set current project to online project if the published project was temporary // and the published project is still the current project if (m_context.currentProject().getId() == m_context.currentProject().getId() && (m_context.currentProject().getType() == I_CmsConstants.C_PROJECT_TYPE_TEMPORARY)) { m_context.setCurrentProject(readProject(I_CmsConstants.C_PROJECT_ONLINE_ID)); } // fire an event that a project has been published Map eventData = (Map) new HashMap(); eventData.put("report", report); eventData.put("publishHistoryId", publishList.getPublishHistoryId().toString()); eventData.put("context", m_context); CmsEvent exportPointEvent = new CmsEvent(this, I_CmsEventListener.EVENT_PUBLISH_PROJECT, eventData, false); OpenCms.fireCmsEvent(exportPointEvent); } } } /** * Publishes a single resource.<p> * * @param resourcename the name of the resource to be published * @throws Exception if something goes wrong */ public void publishResource(String resourcename) throws Exception { publishResource(resourcename, false, new CmsShellReport()); } /** * Publishes a single resource.<p> * * @param resourcename the name of the resource to be published * @param directPublishSiblings if true, all siblings of the resource are also published * @param report the report to write the progress information to * @throws Exception if something goes wrong */ public void publishResource(String resourcename, boolean directPublishSiblings, I_CmsReport report) throws Exception { CmsResource resource = null; try { resource = readFileHeader(resourcename, true); publishProject(report, resource, directPublishSiblings); } catch (CmsException e) { throw e; } finally { OpenCms.fireCmsEvent(new CmsEvent(this, I_CmsEventListener.EVENT_PUBLISH_RESOURCE, Collections.singletonMap("resource", resource))); } } /** * Returns the absolute path of a given resource.<p> * The absolute path is the root path without the site information. * * @param resource the resource * @return the absolute path */ public String readAbsolutePath(CmsResource resource) { return readAbsolutePath(resource, false); } /** * Returns the absolute path of a given resource.<p> * The absolute path is the root path without the site information. * * @param resource the resource * @param includeDeleted include resources that are marked as deleted * @return the absolute path */ public String readAbsolutePath(CmsResource resource, boolean includeDeleted) { if (!resource.hasFullResourceName()) { try { m_driverManager.readPath(m_context, resource, includeDeleted); } catch (CmsException e) { OpenCms.getLog(this).error("Could not read absolute path for resource " + resource, e); resource.setFullResourceName(null); } } // adjust the resource path for the current site root return removeSiteRoot(resource.getRootPath()); } /** * Reads the agent of a task.<p> * * @param task the task to read the agent from * @return the agent of a task * @throws CmsException if something goes wrong */ public CmsUser readAgent(CmsTask task) throws CmsException { return (m_driverManager.readAgent(task)); } /** * Reads all file headers of a file in the OpenCms. * <br> * This method returns a vector with the history of all file headers, i.e. * the file headers of a file, independent of the project they were attached to.<br> * * The reading excludes the filecontent. * * @param filename the name of the file to be read. * * @return a Vector of file headers read from the Cms. * * @throws CmsException if operation was not successful. */ public List readAllBackupFileHeaders(String filename) throws CmsException { return (m_driverManager.readAllBackupFileHeaders(m_context, addSiteRoot(filename))); } /** * select all projectResources from an given project * * @param projectId id of the project in which the resource is used. * @return vector of all resources belonging to the given project * * @throws CmsException Throws CmsException if operation was not succesful */ public Vector readAllProjectResources(int projectId) throws CmsException { return m_driverManager.readAllProjectResources(m_context, projectId); } /** * Returns a list of all properties of a file or folder. * * @param filename the name of the resource for which the property has to be read * * @return a Vector of Strings * * @throws CmsException if operation was not succesful * @deprecated use readProperties(String) instead */ public Map readAllProperties(String filename) throws CmsException { Map result = (Map)new HashMap(); Map properties = readProperties(filename, false); if (properties != null) { result.putAll(properties); } return result; } /** * Reads all property definitions for the given resource type by id.<p> * * @param resourceType the resource type to read the property-definitions for.<p> * * @return a Vector with the property defenitions for the resource type (may be empty) * * @throws CmsException if something goes wrong */ public Vector readAllPropertydefinitions(int resourceType) throws CmsException { return m_driverManager.readAllPropertydefinitions(m_context, resourceType); } /** * Reads all property definitions for the given resource type by name.<p> * * @param resourceType the resource type to read the property-definitions for.<p> * * @return a Vector with the property defenitions for the resource type (may be empty) * * @throws CmsException if something goes wrong */ public Vector readAllPropertydefinitions(String resourceType) throws CmsException { return m_driverManager.readAllPropertydefinitions(m_context, resourceType); } /** * Reads a file from the Cms for history. * <br> * The reading includes the filecontent. * * @param filename the complete path of the file to be read. * @param tagId the tag id of the resource * * @return file the read file. * * @throws CmsException , if the user has not the rights * to read the file, or if the file couldn't be read. */ public CmsBackupResource readBackupFile(String filename, int tagId) throws CmsException { return (m_driverManager.readBackupFile(m_context, tagId, addSiteRoot(filename))); } /** * Reads a file header from the Cms for history. * <br> * The reading excludes the filecontent. * * @param filename the complete path of the file to be read. * @param tagId the version id of the resource * * @return file the read file. * * @throws CmsException , if the user has not the rights * to read the file headers, or if the file headers couldn't be read. */ public CmsResource readBackupFileHeader(String filename, int tagId) throws CmsException { return (m_driverManager.readBackupFileHeader(m_context, tagId, addSiteRoot(filename))); } /** * Reads a backup project from the Cms. * * @param tagId the tag of the backup project to be read * @return CmsBackupProject object of the requested project * @throws CmsException if operation was not successful. */ public CmsBackupProject readBackupProject(int tagId) throws CmsException { return (m_driverManager.readBackupProject(tagId)); } /** * Gets the Crontable. * * <B>Security:</B> * All users are garnted<BR/> * * @return the crontable. * @throws CmsException if something goes wrong */ public String readCronTable() throws CmsException { return m_driverManager.readCronTable(); } /** * Reads the package path of the system. * This path is used for db-export and db-import and all module packages. * * @return the package path * @throws CmsException if operation was not successful */ public String readPackagePath() throws CmsException { return m_driverManager.readPackagePath(); } /** * Reads a file from the Cms. * * @param filename the complete path to the file. * * @return file the read file. * * @throws CmsException if the user has not the rights to read this resource, * or if the file couldn't be read. */ public CmsFile readFile(String filename) throws CmsException { return m_driverManager.readFile(m_context, addSiteRoot(filename)); } /** * Reads a file from the Cms. * * @param filename the complete path to the file. * @param includeDeleted If true the deleted file will be returned. * * @return file the read file. * * @throws CmsException if the user has not the rights to read this resource, * or if the file couldn't be read. */ public CmsFile readFile(String filename, boolean includeDeleted) throws CmsException { return m_driverManager.readFile(m_context, addSiteRoot(filename), includeDeleted); } /** * Reads a file from the Cms. * * @param folder the complete path to the folder from which the file will be read. * @param filename the name of the file to be read. * * @return file the read file. * * @throws CmsException , if the user has not the rights * to read this resource, or if the file couldn't be read. */ public CmsFile readFile(String folder, String filename) throws CmsException { return (m_driverManager.readFile(m_context, addSiteRoot(folder + filename))); } /** * Gets the known file extensions (=suffixes). * * * @return a Hashtable with all known file extensions as Strings. * * @throws CmsException if operation was not successful. */ public Hashtable readFileExtensions() throws CmsException { return m_driverManager.readFileExtensions(); } /** * Reads a file header from the Cms. * <br> * The reading excludes the filecontent. * * @param filename the complete path of the file to be read. * * @return file the read file. * * @throws CmsException , if the user has not the rights * to read the file headers, or if the file headers couldn't be read. */ public CmsResource readFileHeader(String filename) throws CmsException { return (m_driverManager.readFileHeader(m_context, addSiteRoot(filename))); } /** * Reads a file header from the Cms. * <br> * The reading excludes the filecontent. * * @param filename the complete path of the file to be read * @param includeDeleted if <code>true</code>, deleted files (in offline projects) will * also be read * * @return file the read file header * * @throws CmsException if the user has not the rights * to read the file headers, or if the file headers couldn't be read */ public CmsResource readFileHeader(String filename, boolean includeDeleted) throws CmsException { return (m_driverManager.readFileHeader(m_context, addSiteRoot(filename), includeDeleted)); } /** * Reads a file header from the Cms. * <br> * The reading excludes the filecontent. * * @param filename the complete path of the file to be read. * @param projectId the id of the project where the resource should belong to * @param includeDeleted include resources that are marked as deleted * * @return file the read file. * * @throws CmsException , if the user has not the rights * to read the file headers, or if the file headers couldn't be read. */ public CmsResource readFileHeader(String filename, int projectId, boolean includeDeleted) throws CmsException { return (m_driverManager.readFileHeaderInProject(projectId, addSiteRoot(filename), includeDeleted)); } /** * Reads a file header from the Cms. * <br> * The reading excludes the filecontent. * * @param folder the complete path to the folder from which the file will be read. * @param filename the name of the file to be read. * * @return file the read file. * * @throws CmsException if the user has not the rights * to read the file header, or if the file header couldn't be read. */ public CmsResource readFileHeader(String folder, String filename) throws CmsException { return (m_driverManager.readFileHeader(m_context, addSiteRoot(folder + filename))); } /** * Reads all files from the Cms, that are of the given type.<BR/> * * @param projectId A project id for reading online or offline resources * @param resourcetype The type of the files. * * @return A Vector of files. * * @throws CmsException Throws CmsException if operation was not succesful */ public Vector readFilesByType(int projectId, int resourcetype) throws CmsException { return m_driverManager.readFilesByType(m_context, projectId, resourcetype); } /** * Reads a folder from the Cms. * * @param folderId the id of the folder to be read * @param includeDeleted Include the folder if it is marked as deleted * * @return folder the read folder * * @throws CmsException if the user does not have the permissions * to read this folder, or if the folder couldn't be read */ public CmsFolder readFolder(CmsUUID folderId, boolean includeDeleted) throws CmsException { return (m_driverManager.readFolder(m_context, folderId, includeDeleted)); } /** * Reads a folder from the Cms. * * @param folderName the name of the folder to be read * * @return The read folder * * @throws CmsException if the user does not have the permissions * to read this folder, or if the folder couldn't be read */ public CmsFolder readFolder(String folderName) throws CmsException { return (m_driverManager.readFolder(m_context, addSiteRoot(folderName))); } /** * Reads a folder from the Cms. * * @param folderName the complete path to the folder to be read * @param includeDeleted Include the folder if it is marked as deleted * * @return The read folder * * @throws CmsException If the user does not have the permissions * to read this folder, or if the folder couldn't be read */ public CmsFolder readFolder(String folderName, boolean includeDeleted) throws CmsException { return (m_driverManager.readFolder(m_context, addSiteRoot(folderName), includeDeleted)); } /** * Reads all given tasks from a user for a project. * * @param projectId the id of the project in which the tasks are defined. * @param ownerName the owner of the task. * @param taskType the type of task you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy specifies how to order the tasks. * @param sort sorting of the tasks * @return vector of given tasks for a user for a project * * @throws CmsException if operation was not successful. */ public Vector readGivenTasks(int projectId, String ownerName, int taskType, String orderBy, String sort) throws CmsException { return (m_driverManager.readGivenTasks(projectId, ownerName, taskType, orderBy, sort)); } /** * Reads the group of a project.<p> * * @param project the project to read the group from * @return the group of the given project */ public CmsGroup readGroup(CmsProject project) { return m_driverManager.readGroup(project); } /** * Reads the group (role) of a task.<p> * * @param task the task to read the group (role) from * @return the group (role) of the task * @throws CmsException if something goes wrong */ public CmsGroup readGroup(CmsTask task) throws CmsException { return m_driverManager.readGroup(task); } /** * Reads a group of the Cms based on its id.<p> * * @param groupId the id of the group to be read * @return the group that has the provided id * @throws CmsException if something goes wrong */ public CmsGroup readGroup(CmsUUID groupId) throws CmsException { return m_driverManager.readGroup(groupId); } /** * Reads a group of the Cms based on its name. * @param groupName the name of the group to be read * @return the group that has the provided name * @throws CmsException if something goes wrong */ public CmsGroup readGroup(String groupName) throws CmsException { return (m_driverManager.readGroup(groupName)); } /** * Gets the Linkchecktable. * * <B>Security:</B> * All users are granted<BR/> * * @return the linkchecktable * * @throws CmsException if something goes wrong */ public Hashtable readLinkCheckTable() throws CmsException { return m_driverManager.readLinkCheckTable(); } /** * Reads the project manager group of a project.<p> * * @param project the project * @return the managergroup of the project */ public CmsGroup readManagerGroup(CmsProject project) { return m_driverManager.readManagerGroup(project); } /** * Reads the original agent of a task from the Cms.<p> * * @param task the task to read the original agent from * @return the original agent of the task * @throws CmsException if something goes wrong */ public CmsUser readOriginalAgent(CmsTask task) throws CmsException { return m_driverManager.readOriginalAgent(task); } /** * Reads the owner of a project. * * @param project the project to read the owner from * @return the owner of the project * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsProject project) throws CmsException { return m_driverManager.readOwner(project); } /** * Reads the owner (initiator) of a task.<p> * * @param task the task to read the owner from * @return the owner of the task * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsTask task) throws CmsException { return m_driverManager.readOwner(task); } /** * Reads the owner of a task log.<p> * * @param log the task log * @return the owner of the task log * @throws CmsException if something goes wrong */ public CmsUser readOwner(CmsTaskLog log) throws CmsException { return m_driverManager.readOwner(log); } /** * Builds a list of resources for a given path.<p> * * Use this method if you want to select a resource given by it's full filename and path. * This is done by climbing down the path from the root folder using the parent-ID's and * resource names. Use this method with caution! Results are cached but reading path's * inevitably increases runtime costs. * * @param path the requested path * @param includeDeleted include resources that are marked as deleted * @return List of CmsResource's * @throws CmsException if something goes wrong */ public List readPath(String path, boolean includeDeleted) throws CmsException { return (m_driverManager.readPath(m_context, m_context.addSiteRoot(path), includeDeleted)); } /** * Reads the project in which a resource was last modified. * * @param res the resource * @return the project in which the resource was last modified * * @throws CmsException if operation was not successful. */ public CmsProject readProject(CmsResource res) throws CmsException { return m_driverManager.readProject(res.getProjectLastModified()); } /** * Reads a project of a given task from the Cms. * * @param task the task for which the project will be read. * @return the project of the task * * @throws CmsException if operation was not successful. */ public CmsProject readProject(CmsTask task) throws CmsException { return m_driverManager.readProject(task); } /** * Reads a project from the Cms. * * @param id the id of the project * @return the project with the given id * * @throws CmsException if operation was not successful. */ public CmsProject readProject(int id) throws CmsException { return m_driverManager.readProject(id); } /** * Reads a project from the Cms.<p> * * @param name the name of the project * @return the project with the given name * @throws CmsException if operation was not successful. */ public CmsProject readProject(String name) throws CmsException { return m_driverManager.readProject(name); } /** * Reads log entries for a project. * * @param projectId the id of the project for which the tasklog will be read. * @return a Vector of new TaskLog objects * @throws CmsException if operation was not successful. */ public Vector readProjectLogs(int projectId) throws CmsException { return m_driverManager.readProjectLogs(projectId); } /** * Reads all file headers of a project from the Cms. * * @param projectId the id of the project to read the file headers for. * @param filter The filter for the resources (all, new, changed, deleted, locked) * * @return a Vector (of CmsResources objects) of resources. * * @throws CmsException if something goes wrong * */ public Vector readProjectView(int projectId, String filter) throws CmsException { return m_driverManager.readProjectView(m_context, projectId, filter); } /** * Reads the property-definition for the resource type. * * @param name the name of the property-definition to read. * @param resourcetype the name of the resource type for the property-definition. * @return the property-definition. * * @throws CmsException if operation was not successful. */ public CmsPropertydefinition readPropertydefinition(String name, int resourcetype) throws CmsException { return (m_driverManager.readPropertydefinition(m_context, name, resourcetype)); } /** * Returns a list of all template resources which must be processed during a static export.<p> * * @param parameterResources flag for reading resources with parameters (1) or without (0) * @param a timestamp for reading the data from the db * @return List of template resources * @throws CmsException if something goes wrong */ public List readStaticExportResources(int parameterResources, long timestamp) throws CmsException { return m_driverManager.readStaticExportResources(m_context, parameterResources, timestamp); } /** * Returns the parameters of a resource in the table of all published template resources.<p> * @param rfsName the rfs name of the resource * @return the paramter string of the requested resource * @throws CmsException if something goes wrong */ public String readStaticExportPublishedResourceParamters(String rfsName) throws CmsException { return m_driverManager.readStaticExportPublishedResourceParamters(m_context, rfsName); } /** * Reads the task with the given id. * * @param id the id of the task to be read. * @return the task with the given id * * @throws CmsException if operation was not successful. */ public CmsTask readTask(int id) throws CmsException { return (m_driverManager.readTask(id)); } /** * Reads log entries for a task. * * @param taskid the task for which the tasklog will be read. * @return a Vector of new TaskLog objects. * @throws CmsException if operation was not successful. */ public Vector readTaskLogs(int taskid) throws CmsException { return m_driverManager.readTaskLogs(taskid); } /** * Reads all tasks for a project. * * @param projectId the id of the project in which the tasks are defined. Can be null to select all tasks. * @param tasktype the type of task you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW * @param orderBy specifies how to order the tasks. * @param sort sort order: C_SORT_ASC, C_SORT_DESC, or null. * @return vector of tasks for the project * * @throws CmsException if operation was not successful. */ public Vector readTasksForProject(int projectId, int tasktype, String orderBy, String sort) throws CmsException { return (m_driverManager.readTasksForProject(projectId, tasktype, orderBy, sort)); } /** * Reads all tasks for a role in a project. * * @param projectId the id of the Project in which the tasks are defined. * @param roleName the role who has to process the task. * @param tasktype the type of task you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy specifies how to order the tasks. * @param sort sort order C_SORT_ASC, C_SORT_DESC, or null * @return vector of tasks for the role * * @throws CmsException if operation was not successful. */ public Vector readTasksForRole(int projectId, String roleName, int tasktype, String orderBy, String sort) throws CmsException { return (m_driverManager.readTasksForRole(projectId, roleName, tasktype, orderBy, sort)); } /** * Reads all tasks for a user in a project. * * @param projectId the id of the Project in which the tasks are defined. * @param userName the user who has to process the task. * @param tasktype the type of task you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy specifies how to order the tasks. * @param sort sort order C_SORT_ASC, C_SORT_DESC, or null * @return vector of tasks for the user * * @throws CmsException if operation was not successful. */ public Vector readTasksForUser(int projectId, String userName, int tasktype, String orderBy, String sort) throws CmsException { return (m_driverManager.readTasksForUser(projectId, userName, tasktype, orderBy, sort)); } /** * Reads a user based on its id.<p> * * @param userId the id of the user to be read * @return the user with the given id * @throws CmsException if something goes wrong */ public CmsUser readUser(CmsUUID userId) throws CmsException { return m_driverManager.readUser(userId); } /** * Reads a user based on its name.<p> * * @param username the name of the user to be read * @return the user with the given name * @throws CmsException if somthing goes wrong */ public CmsUser readUser(String username) throws CmsException { return m_driverManager.readUser(username); } /** * Returns a user in the Cms. * * @param username the name of the user to be returned. * @param type the type of the user. * @return a user in the Cms. * * @throws CmsException if operation was not successful */ public CmsUser readUser(String username, int type) throws CmsException { return (m_driverManager.readUser(username, type)); } /** * Returns a user in the Cms, if the password is correct. * * @param username the name of the user to be returned. * @param password the password of the user to be returned. * @return a user in the Cms. * * @throws CmsException if operation was not successful */ public CmsUser readUser(String username, String password) throws CmsException { return (m_driverManager.readUser(username, password)); } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param username The username of the user that is to be read. * @return User * * @throws CmsException Throws CmsException if operation was not succesful */ public CmsUser readWebUser(String username) throws CmsException { return (m_driverManager.readWebUser(username)); } /** * Returns a web user object if the password for the user is correct.<p> * * <B>Security:</B> * All users are granted. * * @param username the username of the user that is to be read * @param password the password of the user that is to be read * @return a web user * * @throws CmsException if something goes wrong */ public CmsUser readWebUser(String username, String password) throws CmsException { return (m_driverManager.readWebUser(username, password)); } /** * Reactivates a task.<p> * * @param taskId the Id of the task to reactivate * * @throws CmsException if something goes wrong */ public void reaktivateTask(int taskId) throws CmsException { m_driverManager.reaktivateTask(m_context, taskId); } /** * Sets a new password if the user knows his recovery-password. * * @param username the name of the user. * @param recoveryPassword the recovery password. * @param newPassword the new password. * * @throws CmsException if operation was not successfull. */ public void recoverPassword(String username, String recoveryPassword, String newPassword) throws CmsException { m_driverManager.recoverPassword(username, recoveryPassword, newPassword); } /** * Removes the current site root prefix from the absolute path in the resource name, * i.e. adjusts the resource name for the current site root.<p> * * @param resourcename the resource name * @return the resource name adjusted for the current site root */ private String removeSiteRoot(String resourcename) { return getRequestContext().removeSiteRoot(resourcename); } /** * Removes a user from a group. * * <p> * <b>Security:</b> * Only the admin user is allowed to remove a user from a group. * * @param username the name of the user that is to be removed from the group. * @param groupname the name of the group. * @throws CmsException if operation was not successful. */ public void removeUserFromGroup(String username, String groupname) throws CmsException { m_driverManager.removeUserFromGroup(m_context, username, groupname); } /** * Renames the file to the new name. * * @param oldname the complete path to the file which will be renamed. * @param newname the new name of the file. * * @throws CmsException if the user has not the rights * to rename the file, or if the file couldn't be renamed. * * @deprecated Use renameResource instead. */ public void renameFile(String oldname, String newname) throws CmsException { renameResource(oldname, newname); } /** * Renames the resource to the new name. * * @param oldname the complete path to the file which will be renamed. * @param newname the new name of the file. * * @throws CmsException if the user has not the rights * to rename the file, or if the file couldn't be renamed. */ public void renameResource(String oldname, String newname) throws CmsException { getResourceType(readFileHeader(oldname).getType()).renameResource(this, oldname, newname); } /** * Replaces and existing resource by another file with different content * and different file type.<p> * * @param resourcename the resource to replace * @param type the type of the new resource * @param properties the properties of the new resource * @param content the content of the new resource * @throws CmsException if something goes wrong */ public void replaceResource(String resourcename, int type, Map properties, byte[] content) throws CmsException { // read the properties of the existing file Map resProps = null; try { resProps = readAllProperties(resourcename); } catch (CmsException e) { resProps = (Map)new HashMap(); } // add the properties that might have been collected during a file-upload if (properties != null) { resProps.putAll(properties); } getResourceType(readFileHeader(resourcename, true).getType()).replaceResource(this, resourcename, resProps, content, type); } /** * Restores a file in the current project with a version in the backup * * @param tagId The tag id of the resource * @param filename The name of the file to restore * * @throws CmsException Throws CmsException if operation was not succesful. */ public void restoreResource(int tagId, String filename) throws CmsException { getResourceType(readFileHeader(filename).getType()).restoreResource(this, tagId, filename); } /** * Removes an access control entry of a griven principal from a given resource.<p> * * @param resourceName name of the resource * @param principalType the type of the principal (currently group or user) * @param principalName name of the principal * @throws CmsException if something goes wrong */ public void rmacc(String resourceName, String principalType, String principalName) throws CmsException { CmsResource res = readFileHeader(resourceName); I_CmsPrincipal principal = null; if ("group".equals(principalType.toLowerCase())) { principal = readGroup(principalName); } else if ("user".equals(principalType.toLowerCase())) { principal = readUser(principalName); } m_driverManager.removeAccessControlEntry(m_context, res, principal.getId()); } /** * Returns the root-folder object. * * @return the root-folder object. * @throws CmsException if operation was not successful. */ public CmsFolder rootFolder() throws CmsException { return (readFolder(I_CmsConstants.C_ROOT)); } /** * Send a broadcast message to all currently logged in users.<p> * * This method is only allowed for administrators. * * @param message the message to send * @throws CmsException if something goes wrong */ public void sendBroadcastMessage(String message) throws CmsException { if (isAdmin()) { if (m_sessionStorage != null) { m_sessionStorage.sendBroadcastMessage(message); } } else { throw new CmsSecurityException("[" + this.getClass().getName() + "] sendBroadcastMessage()", CmsSecurityException.C_SECURITY_ADMIN_PRIVILEGES_REQUIRED); } } /** * Sets the name of the current site root of the content objects system */ public void setContextToCos() { getRequestContext().setSiteRoot(I_CmsConstants.VFS_FOLDER_COS); } /** * Set a new name for a task.<p> * * @param taskId the id of the task * @param name the new name of the task * @throws CmsException if something goes wrong */ public void setName(int taskId, String name) throws CmsException { m_driverManager.setName(m_context, taskId, name); } /** * Sets a new parent-group for an already existing group in the Cms. * * @param groupName the name of the group that should be written to the Cms. * @param parentGroupName the name of the parentGroup to set, or null if the parent * group should be deleted. * @throws CmsException if operation was not successfull. */ public void setParentGroup(String groupName, String parentGroupName) throws CmsException { m_driverManager.setParentGroup(m_context, groupName, parentGroupName); } /** * Sets the password for a user. * * @param username the name of the user. * @param newPassword the new password. * * @throws CmsException if operation was not successful. */ public void setPassword(String username, String newPassword) throws CmsException { m_driverManager.setPassword(m_context, username, newPassword); } /** * Resets the password for a specified user.<p> * * @param username the name of the user * @param oldPassword the old password * @param newPassword the new password * @throws CmsException if the user data could not be read from the database */ public void setPassword(String username, String oldPassword, String newPassword) throws CmsException { m_driverManager.resetPassword(username, oldPassword, newPassword); } /** * Sets the priority of a task.<p> * * @param taskId the id of the task * @param priority the new priority value * @throws CmsException if something goes wrong */ public void setPriority(int taskId, int priority) throws CmsException { m_driverManager.setPriority(m_context, taskId, priority); } /** * Sets the recovery password for a user.<p> * * @param username the name of the user * @param oldPassword the old (current) password * @param newPassword the new recovery password * @throws CmsException if something goes wrong */ public void setRecoveryPassword(String username, String oldPassword, String newPassword) throws CmsException { m_driverManager.setRecoveryPassword(username, oldPassword, newPassword); } /** * Set a parameter for a task.<p> * * @param taskid the Id of the task * @param parname the ame of the parameter * @param parvalue the value of the parameter * @throws CmsException if something goes wrong */ public void setTaskPar(int taskid, String parname, String parvalue) throws CmsException { m_driverManager.setTaskPar(taskid, parname, parvalue); } /** * Sets the timeout of a task.<p> * * @param taskId the id of the task * @param timeout the new timeout value * @throws CmsException if something goes wrong */ public void setTimeout(int taskId, long timeout) throws CmsException { m_driverManager.setTimeout(m_context, taskId, timeout); } /** * Change the timestamp of a resource.<p> * * @param resourceName the name of the resource to change * @param timestamp timestamp the new timestamp of the changed resource * @param touchRecursive if true, touch recursively all sub-resources (only for folders) * @param user the user who is inserted as userladtmodified * @throws CmsException if something goes wrong */ public void touch(String resourceName, long timestamp, boolean touchRecursive, CmsUUID user) throws CmsException { getResourceType(readFileHeader(resourceName).getType()).touch(this, resourceName, timestamp, touchRecursive, user); } /** * Change the timestamp of a resource.<p> * * @param resourceName the name of the resource to change * @param timestamp timestamp the new timestamp of the changed resource * @param touchRecursive if true, touch recursively all sub-resources (only for folders) * @throws CmsException if something goes wrong */ public void touch(String resourceName, long timestamp, boolean touchRecursive) throws CmsException { touch(resourceName, timestamp, touchRecursive, getRequestContext().currentUser().getId()); } /** * Undeletes a resource. * * @param filename the complete path of the file. * * @throws CmsException if the file couldn't be undeleted, or if the user * has not the appropriate rights to undelete the file. */ public void undeleteResource(String filename) throws CmsException { //read the file header including deleted getResourceType(readFileHeader(filename, true).getType()).undeleteResource(this, filename); } /** * Undo changes in a file by copying the online file. * * @param filename the complete path of the file. * * @throws CmsException if the file couldn't be deleted, or if the user * has not the appropriate rights to write the file. */ public void undoChanges(String filename) throws CmsException { //read the file header including deleted getResourceType(readFileHeader(filename, true).getType()).undoChanges(this, filename); } /** * Unlocks all resources of a project. * * @param id the id of the project to be unlocked. * * @throws CmsException if operation was not successful. */ public void unlockProject(int id) throws CmsException { m_driverManager.unlockProject(m_context, id); } /** * Unlocks a resource.<p> * * @param resource the complete path to the resource to be unlocked * @param forceRecursive if true, also unlock all sub-resources (of a folder) * @throws CmsException if the user has no write permission for the resource */ public void unlockResource(String resource, boolean forceRecursive) throws CmsException { getResourceType(readFileHeader(resource, true).getType()).unlockResource(this, resource, forceRecursive); } /** * Tests, if a user is member of the given group. * * @param username the name of the user to test. * @param groupname the name of the group to test. * @return <code>true</code>, if the user is in the group; <code>else</code> false otherwise. * * @throws CmsException if operation was not successful. */ public boolean userInGroup(String username, String groupname) throws CmsException { return (m_driverManager.userInGroup(m_context, username, groupname)); } /** * Writes access control entries for a given resource * * @param resource the resource to attach the control entries to * @param acEntries a vector of access control entries * @throws CmsException if something goes wrong */ public void importAccessControlEntries(CmsResource resource, Vector acEntries) throws CmsException { m_driverManager.importAccessControlEntries(m_context, resource, acEntries); } /** * Writes the Crontable.<p> * * <B>Security:</B> * Only a administrator can do this.<p> * * @param crontable the crontable to write * @throws CmsException if something goes wrong */ public void writeCronTable(String crontable) throws CmsException { m_driverManager.writeCronTable(m_context, crontable); } /** * Writes the package for the system.<p> * * This path is used for db-export and db-import as well as module packages.<p> * * @param path the package path * @throws CmsException if operation ws not successful */ public void writePackagePath(String path) throws CmsException { m_driverManager.writePackagePath(m_context, path); } /** * Writes a file to the Cms. * * @param file the file to write. * * @throws CmsException if resourcetype is set to folder. The CmsException will also be thrown, * if the user has not the rights write the file. */ public void writeFile(CmsFile file) throws CmsException { m_driverManager.writeFile(m_context, file); } /** * Writes the file extension mappings.<p> * * <B>Security:</B> * Only the admin user is allowed to write file extensions. * * @param extensions holds extensions as keys and resourcetypes (Strings) as values * @throws CmsException if something goes wrong */ public void writeFileExtensions(Hashtable extensions) throws CmsException { m_driverManager.writeFileExtensions(m_context, extensions); } /** * Writes a file-header to the Cms. * * @param file the file to write. * * @throws CmsException if resourcetype is set to folder. The CmsException will also be thrown, * if the user has not the rights to write the file header.. */ public void writeFileHeader(CmsFile file) throws CmsException { m_driverManager.writeFileHeader(m_context, file); } /** * Writes an already existing group to the Cms. * * @param group the group that should be written to the Cms. * @throws CmsException if operation was not successful. */ public void writeGroup(CmsGroup group) throws CmsException { m_driverManager.writeGroup(m_context, group); } /** * Writes the Linkchecktable. * * <B>Security:</B> * Only a administrator can do this<BR/> * * @param linkchecktable The hashtable that contains the links that were not reachable * @throws CmsException if something goes wrong */ public void writeLinkCheckTable(Hashtable linkchecktable) throws CmsException { m_driverManager.writeLinkCheckTable(m_context, linkchecktable); } /** * Writes a couple of properties as structure values for a file or folder. * * @param resourceName the resource-name of which the Property has to be set. * @param properties a Hashtable with property-definitions and property values as Strings. * @throws CmsException if operation was not successful * @deprecated use {@link #writePropertyObjects(String, List)} instead */ public void writeProperties(String resourceName, Map properties) throws CmsException { m_driverManager.writePropertyObjects(m_context, addSiteRoot(resourceName), CmsProperty.toList(properties)); } /** * Writes a couple of Properties for a file or folder. * * @param name the resource-name of which the Property has to be set. * @param properties a Hashtable with property-definitions and property values as Strings. * @param addDefinition flag to indicate if unknown definitions should be added * @throws CmsException if operation was not successful. * @deprecated use {@link #writePropertyObjects(String, List)} instead */ public void writeProperties(String name, Map properties, boolean addDefinition) throws CmsException { m_driverManager.writePropertyObjects(m_context, addSiteRoot(name), CmsProperty.setAutoCreatePropertyDefinitions(CmsProperty.toList(properties), addDefinition)); } /** * Writes a property as a structure value for a file or folder.<p> * * @param resourceName the resource-name for which the property will be set * @param key the property-definition name * @param value the value for the property to be set * @throws CmsException if operation was not successful * @deprecated use {@link #writePropertyObject(String, CmsProperty)} instead */ public void writeProperty(String resourceName, String key, String value) throws CmsException { CmsProperty property = new CmsProperty(); property.setKey(key); property.setStructureValue(value); m_driverManager.writePropertyObject(m_context, addSiteRoot(resourceName), property); } /** * Writes a property for a file or folder. * * @param name the resource-name for which the property will be set. * @param key the property-definition name. * @param value the value for the property to be set. * @param addDefinition flag to indicate if unknown definitions should be added * @throws CmsException if operation was not successful. * @deprecated use {@link #writePropertyObject(String, CmsProperty)} instead */ public void writeProperty(String name, String key, String value, boolean addDefinition) throws CmsException { CmsProperty property = new CmsProperty(); property.setKey(key); property.setStructureValue(value); property.setAutoCreatePropertyDefinition(addDefinition); m_driverManager.writePropertyObject(m_context, addSiteRoot(name), property); } /** * Inserts an entry in the published resource table.<p> * * This is done during static export. * @param resourceName The name of the resource to be added to the static export * @param linkType the type of resource exported (0= non-paramter, 1=parameter) * @param linkParameter the parameters added to the resource * @param timestamp a timestamp for writing the data into the db * @throws CmsException if something goes wrong */ public void writeStaticExportPublishedResource(String resourceName, int linkType, String linkParameter, long timestamp) throws CmsException { m_driverManager.writeStaticExportPublishedResource(m_context, resourceName, linkType, linkParameter, timestamp); } /** * Writes a new user tasklog for a task. * * @param taskid the Id of the task. * @param comment the description for the log. * * @throws CmsException if operation was not successful. */ public void writeTaskLog(int taskid, String comment) throws CmsException { m_driverManager.writeTaskLog(m_context, taskid, comment); } /** * Writes a new user tasklog for a task. * * @param taskId the id of the task * @param comment the description for the log * @param taskType the type of the tasklog, user task types must be greater than 100 * @throws CmsException if something goes wrong */ public void writeTaskLog(int taskId, String comment, int taskType) throws CmsException { m_driverManager.writeTaskLog(m_context, taskId, comment, taskType); } /** * Updates the user information. * <p> * <b>Security:</b> * Only the admin user is allowed to update the user information. * * @param user the user to be written. * * @throws CmsException if operation was not successful. */ public void writeUser(CmsUser user) throws CmsException { m_driverManager.writeUser(m_context, user); } /** * Updates the user information of a web user. * <br> * Only a web user can be updated this way. * * @param user the user to be written. * * @throws CmsException if operation was not successful. */ public void writeWebUser(CmsUser user) throws CmsException { m_driverManager.writeWebUser(user); } /** * Gets the lock state for a specified resource.<p> * * @param resource the specified resource * @return the CmsLock object for the specified resource * @throws CmsException if somethong goes wrong */ public CmsLock getLock(CmsResource resource) throws CmsException { return m_driverManager.getLock(m_context, resource); } /** * Gets the lock state for a specified resource name.<p> * * @param resourcename the specified resource name * @return the CmsLock object for the specified resource name * @throws CmsException if somethong goes wrong */ public CmsLock getLock(String resourcename) throws CmsException { return m_driverManager.getLock(m_context, m_context.addSiteRoot(resourcename)); } /** * Proves if a specified resource is inside the current project.<p> * * @param resource the specified resource * @return true, if the resource name of the specified resource matches any of the current project's resources */ public boolean isInsideCurrentProject(CmsResource resource) { return m_driverManager.isInsideCurrentProject(m_context, resource); } /** * Returns the list of all resources that define the "view" of the given project.<p> * * @param project the project to get the project resources for * @return the list of all resources that define the "view" of the given project * @throws CmsException if something goes wrong */ public List readProjectResources(CmsProject project) throws CmsException { return m_driverManager.readProjectResources(project); } /** * Recovers a resource from the online project back to the offline project as an unchanged resource.<p> * * @param resourcename the name of the resource which is recovered * @return the recovered resource in the offline project * @throws CmsException if somethong goes wrong */ public CmsResource recoverResource(String resourcename) throws CmsException { return m_driverManager.recoverResource(m_context, m_context.addSiteRoot(resourcename)); } /** * This method checks if a new password follows the rules for * new passwords, which are defined by a Class configured in opencms.properties.<p> * * If this method throws no exception the password is valid.<p> * * @param password the new password that has to be checked * * @throws CmsSecurityException if the password is not valid */ public void validatePassword(String password) throws CmsSecurityException { m_driverManager.validatePassword(password); } /** * Reads the resources that were published in a publish task for a given publish history ID.<p> * * @param publishHistoryId unique int ID to identify each publish task in the publish history * @return a List of CmsPublishedResource objects * @throws CmsException if something goes wrong */ public List readPublishedResources(CmsUUID publishHistoryId) throws CmsException { return m_driverManager.readPublishedResources(m_context, publishHistoryId); } /** * Completes all post-publishing tasks for a "directly" published COS resource.<p> * * @param publishedBoResource the CmsPublishedResource onject representing the published COS resource * @param publishId unique int ID to identify each publish task in the publish history * @param tagId the backup tag revision */ public void postPublishBoResource(CmsPublishedResource publishedBoResource, CmsUUID publishId, int tagId) { try { m_driverManager.postPublishBoResource(m_context, publishedBoResource, publishId, tagId); } catch (CmsException e) { if (OpenCms.getLog(this).isErrorEnabled()) { OpenCms.getLog(this).error("Error writing publish history entry for COS resource " + publishedBoResource.toString(), e); } } finally { Map eventData = (Map) new HashMap(); eventData.put("publishHistoryId", publishId.toString()); // a "directly" published COS resource can be handled totally equal to a published project OpenCms.fireCmsEvent(new CmsEvent(this, I_CmsEventListener.EVENT_PUBLISH_PROJECT, eventData)); } } /** * Validates the HTML links (hrefs and images) in all unpublished Cms files of the current * (offline) project, if the files resource types implement the interface * {@link org.opencms.validation.I_CmsHtmlLinkValidatable}.<p> * * Please refer to the Javadoc of the I_CmsHtmlLinkValidatable interface to see which classes * implement this interface (and so, which file types get validated by the HTML link * validator).<p> * * @param report an instance of I_CmsReport to print messages * @return a map with lists of invalid links keyed by resource names * @throws Exception if something goes wrong * @see org.opencms.validation.I_CmsHtmlLinkValidatable */ public Map validateHtmlLinks(I_CmsReport report) throws Exception { CmsPublishList publishList = m_driverManager.getPublishList(m_context, null, false, report); return m_driverManager.validateHtmlLinks(this, publishList, report); } /** * Validates the HTML links (hrefs and images) in the unpublished Cms file of the current * (offline) project, if the file's resource type implements the interface * {@link org.opencms.validation.I_CmsHtmlLinkValidatable}.<p> * * Please refer to the Javadoc of the I_CmsHtmlLinkValidatable interface to see which classes * implement this interface (and so, which file types get validated by the HTML link * validator).<p> * * @param directPublishResource the resource which will be directly published * @param directPublishSiblings true, if all eventual siblings of the direct published resource should also get published * @param report an instance of I_CmsReport to print messages * @return a map with lists of invalid links keyed by resource names * @throws Exception if something goes wrong * @see org.opencms.validation.I_CmsHtmlLinkValidatable */ public Map validateHtmlLinks(CmsResource directPublishResource, boolean directPublishSiblings, I_CmsReport report) throws Exception { CmsPublishList publishList = null; Map result = null; publishList = m_driverManager.getPublishList(m_context, directPublishResource, directPublishSiblings, report); result = m_driverManager.validateHtmlLinks(this, publishList, report); return result; } /** * Validates the HTML links (hrefs and images) in the unpublished Cms files of the specified * Cms publish list, if the files resource types implement the interface * {@link org.opencms.validation.I_CmsHtmlLinkValidatable}.<p> * * Please refer to the Javadoc of the I_CmsHtmlLinkValidatable interface to see which classes * implement this interface (and so, which file types get validated by the HTML link * validator).<p> * * @param publishList a Cms publish list * @param report an instance of I_CmsReport to print messages * @return a map with lists of invalid links keyed by resource names * @throws Exception if something goes wrong * @see org.opencms.validation.I_CmsHtmlLinkValidatable */ public Map validateHtmlLinks(CmsPublishList publishList, I_CmsReport report) throws Exception { return m_driverManager.validateHtmlLinks(this, publishList, report); } /** * Returns a publish list for the specified Cms resource to be published directly, plus * optionally it's siblings.<p> * * @param directPublishResource the resource which will be directly published * @param directPublishSiblings true, if all eventual siblings of the direct published resource should also get published * @param report an instance of I_CmsReport to print messages * @return a publish list * @throws CmsException if something goes wrong */ public CmsPublishList getPublishList(CmsResource directPublishResource, boolean directPublishSiblings, I_CmsReport report) throws CmsException { return m_driverManager.getPublishList(m_context, directPublishResource, directPublishSiblings, report); } /** * Returns a publish list with all new/changed/deleted Cms resources of the current (offline) * project that actually get published.<p> * * @param report an instance of I_CmsReport to print messages * @return a publish list * @throws Exception if something goes wrong */ public CmsPublishList getPublishList(I_CmsReport report) throws Exception { return getPublishList(null, false, report); } /** * Reads a property object from the database specified by it's key name mapped to a resource.<p> * * Returns {@link CmsProperty#getNullProperty()} if the property is not found.<p> * * @param resourceName the name of resource where the property is mapped to * @param key the property key name * @param search true, if the property should be searched on all parent folders if not found on the resource * @return a CmsProperty object containing the structure and/or resource value * @throws CmsException if something goes wrong */ public CmsProperty readPropertyObject(String key, String resourceName, boolean search) throws CmsException { return m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resourceName), m_context.getAdjustedSiteRoot(resourceName), key, search); } /** * Reads all property objects mapped to a specified resource from the database.<p> * * Returns an empty list if no properties are found at all.<p> * * @param resourceName the name of resource where the property is mapped to * @param search true, if the properties should be searched on all parent folders if not found on the resource * @return a list of CmsProperty objects containing the structure and/or resource value * @throws CmsException if something goes wrong */ public List readPropertyObjects(String resourceName, boolean search) throws CmsException { return m_driverManager.readPropertyObjects(m_context, addSiteRoot(resourceName), m_context.getAdjustedSiteRoot(resourceName), search); } /** * Writes a property object to the database mapped to a specified resource.<p> * * @param resourceName the name of resource where the property is mapped to * @param property a CmsProperty object containing a structure and/or resource value * @throws CmsException if something goes wrong */ public void writePropertyObject(String resourceName, CmsProperty property) throws CmsException { m_driverManager.writePropertyObject(m_context, addSiteRoot(resourceName), property); } /** * Writes a list of property objects to the database mapped to a specified resource.<p> * * @param resourceName the name of resource where the property is mapped to * @param properties a list of CmsPropertys object containing a structure and/or resource value * @throws CmsException if something goes wrong */ public void writePropertyObjects(String resourceName, List properties) throws CmsException { m_driverManager.writePropertyObjects(m_context, addSiteRoot(resourceName), properties); } /** * Reads the (compound) values of all properties mapped to a specified resource.<p> * * @param resource the resource to look up the property for * @return Map of Strings representing all properties of the resource * @throws CmsException in case there where problems reading the properties * @deprecated use {@link #readPropertyObjects(String, boolean)} instead */ public Map readProperties(String resource) throws CmsException { List properties = m_driverManager.readPropertyObjects(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), false); return CmsProperty.toMap(properties); } /** * Reads the (compound) values of all properties mapped to a specified resource * with optional direcory upward cascading.<p> * * @param resource the resource to look up the property for * @param search if <code>true</code>, the properties will also be looked up on all parent folders and the results will be merged, if <code>false</code> not (ie. normal property lookup) * @return Map of Strings representing all properties of the resource * @throws CmsException in case there where problems reading the properties * @deprecated use {@link #readPropertyObjects(String, boolean)} instead */ public Map readProperties(String resource, boolean search) throws CmsException { List properties = m_driverManager.readPropertyObjects(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), search); return CmsProperty.toMap(properties); } /** * Reads the (compound) value of a property mapped to a specified resource.<p> * * @param resource the resource to look up the property for * @param property the name of the property to look up * @return the value of the property found, <code>null</code> if nothing was found * @throws CmsException in case there where problems reading the property * @see CmsProperty#getValue() * @deprecated use new Object base methods */ public String readProperty(String resource, String property) throws CmsException { CmsProperty value = m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), property, false); return (value != null) ? value.getValue() : null; } /** * Reads the (compound) value of a property mapped to a specified resource * with optional direcory upward cascading.<p> * * @param resource the resource to look up the property for * @param property the name of the property to look up * @param search if <code>true</code>, the property will be looked up on all parent folders if it is not attached to the the resource, if false not (ie. normal property lookup) * @return the value of the property found, <code>null</code> if nothing was found * @throws CmsException in case there where problems reading the property * @see CmsProperty#getValue() * @deprecated use new Object base methods */ public String readProperty(String resource, String property, boolean search) throws CmsException { CmsProperty value = m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), property, search); return (value != null) ? value.getValue() : null; } /** * Reads the (compound) value of a property mapped to a specified resource * with optional direcory upward cascading, a default value will be returned if the property * is not found on the resource (or it's parent folders in case search is set to <code>true</code>).<p> * * @param resource the resource to look up the property for * @param property the name of the property to look up * @param search if <code>true</code>, the property will be looked up on all parent folders if it is not attached to the the resource, if <code>false</code> not (ie. normal property lookup) * @param propertyDefault a default value that will be returned if the property was not found on the selected resource * @return the value of the property found, if nothing was found the value of the <code>propertyDefault</code> parameter is returned * @throws CmsException in case there where problems reading the property * @see CmsProperty#getValue() * @deprecated use new Object base methods */ public String readProperty(String resource, String property, boolean search, String propertyDefault) throws CmsException { CmsProperty value = m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), property, search); return (value != null) ? value.getValue() : propertyDefault; } }
Switched order of parameters in new readPropertyObject() method
src/org/opencms/file/CmsObject.java
Switched order of parameters in new readPropertyObject() method
<ide><path>rc/org/opencms/file/CmsObject.java <ide> /* <ide> * File : $Source: /alkacon/cvs/opencms/src/org/opencms/file/CmsObject.java,v $ <del> * Date : $Date: 2004/04/02 16:59:28 $ <del> * Version: $Revision: 1.24 $ <add> * Date : $Date: 2004/04/05 05:33:46 $ <add> * Version: $Revision: 1.25 $ <ide> * <ide> * This library is part of OpenCms - <ide> * the Open Source Content Mananagement System <ide> * @author Carsten Weinholz ([email protected]) <ide> * @author Andreas Zahner ([email protected]) <ide> * <del> * @version $Revision: 1.24 $ <add> * @version $Revision: 1.25 $ <ide> */ <ide> public class CmsObject { <ide> <ide> * Returns a list of all template resources which must be processed during a static export.<p> <ide> * <ide> * @param parameterResources flag for reading resources with parameters (1) or without (0) <del> * @param a timestamp for reading the data from the db <add> * @param timestamp a timestamp for reading the data from the db <ide> * @return List of template resources <ide> * @throws CmsException if something goes wrong <ide> */ <ide> * Returns {@link CmsProperty#getNullProperty()} if the property is not found.<p> <ide> * <ide> * @param resourceName the name of resource where the property is mapped to <del> * @param key the property key name <add> * @param propertyName the property key name <ide> * @param search true, if the property should be searched on all parent folders if not found on the resource <ide> * @return a CmsProperty object containing the structure and/or resource value <ide> * @throws CmsException if something goes wrong <ide> */ <del> public CmsProperty readPropertyObject(String key, String resourceName, boolean search) throws CmsException { <del> return m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resourceName), m_context.getAdjustedSiteRoot(resourceName), key, search); <add> public CmsProperty readPropertyObject(String resourceName, String propertyName, boolean search) throws CmsException { <add> return m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resourceName), m_context.getAdjustedSiteRoot(resourceName), propertyName, search); <ide> } <ide> <ide> /** <ide> * @return the value of the property found, <code>null</code> if nothing was found <ide> * @throws CmsException in case there where problems reading the property <ide> * @see CmsProperty#getValue() <del> * @deprecated use new Object base methods <add> * @deprecated use new Object based methods <ide> */ <ide> public String readProperty(String resource, String property) throws CmsException { <ide> CmsProperty value = m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), property, false); <del> return (value != null) ? value.getValue() : null; <add> return value.isNullProperty() ? null : value.getValue(); <ide> } <ide> <ide> /** <ide> * @return the value of the property found, <code>null</code> if nothing was found <ide> * @throws CmsException in case there where problems reading the property <ide> * @see CmsProperty#getValue() <del> * @deprecated use new Object base methods <add> * @deprecated use new Object based methods <ide> */ <ide> public String readProperty(String resource, String property, boolean search) throws CmsException { <ide> CmsProperty value = m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), property, search); <del> return (value != null) ? value.getValue() : null; <add> return value.isNullProperty() ? null : value.getValue(); <ide> } <ide> <ide> /** <ide> * @return the value of the property found, if nothing was found the value of the <code>propertyDefault</code> parameter is returned <ide> * @throws CmsException in case there where problems reading the property <ide> * @see CmsProperty#getValue() <del> * @deprecated use new Object base methods <add> * @deprecated use new Object based methods <ide> */ <ide> public String readProperty(String resource, String property, boolean search, String propertyDefault) throws CmsException { <ide> CmsProperty value = m_driverManager.readPropertyObject(m_context, m_context.addSiteRoot(resource), m_context.getAdjustedSiteRoot(resource), property, search); <del> return (value != null) ? value.getValue() : propertyDefault; <add> return value.isNullProperty() ? propertyDefault : value.getValue(); <ide> } <del> <ide> }
JavaScript
mit
084ddfbfef1cf9b210ad634354cf777cc77fde0c
0
yamingd/stronglink,Lacra17/stronglink,guiquanz/stronglink,Ryezhang/stronglink,Ryezhang/stronglink,shaunstanislaus/stronglink,iOSCowboy/stronglink,Lacra17/stronglink,nkatsaros/stronglink,feld/stronglink,rmoorman/stronglink,iOSCowboy/stronglink,btrask/stronglink,feld/stronglink,iOSCowboy/stronglink,btrask/stronglink,shaunstanislaus/stronglink,guiquanz/stronglink,yamingd/stronglink,rmoorman/stronglink,Ryezhang/stronglink,guiquanz/stronglink,feld/stronglink,shaunstanislaus/stronglink,rmoorman/stronglink,btrask/stronglink,yamingd/stronglink,nkatsaros/stronglink,btrask/stronglink,nkatsaros/stronglink,Lacra17/stronglink
var input = document.getElementById("input"); var output = document.getElementById("output"); var parser = new commonmark.Parser(); var renderer = new commonmark.HtmlRenderer({sourcepos: true}); renderer.softbreak = "<br>"; // commonmark.js should do this for us... function normalize(node) { var text; var run = []; var child = node.firstChild; for(;;) { if(!child || "Text" != child.type) { if(run.length > 1) { text = new commonmark.Node("Text"); text.literal = run.map(function(x) { x.unlink(); return x.literal; }).join(""); if(child) child.insertBefore(text); else node.appendChild(text); } run = []; } if(!child) break; if("Text" == child.type) { run.push(child); } else if(child.isContainer) { normalize(child); } child = child.next; } return node; } // Ported from C version in markdown.c // The output should be identical between each version function md_escape(iter) { var event, node, p, text; for(;;) { event = iter.next(); if(!event) break; if(!event.entering) continue; node = event.node; if("HtmlBlock" !== node.type) continue; p = new commonmark.Node("Paragraph"); text = new commonmark.Node("Text"); text.literal = node.literal; p.appendChild(text); node.insertBefore(p); node.unlink(); } } function md_escape_inline(iter) { var event, node, text; for(;;) { event = iter.next(); if(!event) break; if(!event.entering) continue; node = event.node; if("Html" !== node.type) continue; text = new commonmark.Node("Text"); text.literal = node.literal; node.insertBefore(text); node.unlink(); } } function md_autolink(iter) { // <http://daringfireball.net/2010/07/improved_regex_for_matching_urls> // Painstakingly ported to POSIX and then back // TODO: Get original // Pretty sure this is broken because it's capturing trailing punctuation... var linkify = /([a-z][a-z0-9_-]+:(\/{1,3}|[a-z0-9%])|www[0-9]{0,3}[.]|[a-z0-9.-]+[.][a-z]{2,4}\/)([^\s()<>]+|(([^\s()<>]+|(([^\s()<>]+)))*))+((([^\s()<>]+|(([^\s()<>]+)))*)|[^\[\]\s`!(){};:'".,<>?«»“”‘’])/; var event, node, match, str, text, link, face; for(;;) { event = iter.next(); if(!event) break; if(!event.entering) continue; node = event.node; if("Text" !== node.type) continue; str = node.literal; while((match = linkify.exec(str))) { text = new commonmark.Node("Text"); link = new commonmark.Node("Link"); face = new commonmark.Node("Text"); text.literal = str.slice(0, match.index); link.destination = str.slice(match.index, match.index+match[0].length) face.literal = link.destination; link.appendChild(face); node.insertBefore(text); node.insertBefore(link); str = str.slice(match.index+match[0].length); } if(str !== node.literal) { text = new commonmark.Node("Text"); text.literal = str; node.insertBefore(text); node.unlink(); } } } function md_block_external_images(iter) { var event, node, link, URI, text, child; for(;;) { event = iter.next(); if(!event) break; if(event.entering) continue; node = event.node; if("Image" !== node.type) continue; URI = node.destination; if(URI) { if("hash:" === URI.toLowerCase().slice(0, 5)) continue; if("data:" === URI.toLowerCase().slice(0, 5)) continue; } link = new commonmark.Node("Link"); text = new commonmark.Node("Text"); link.destination = URI; for(;;) { child = node.firstChild; if(!child) break; link.appendChild(child); } if(link.firstChild) { text.literal = " (external image)"; } else { text.literal = "(external image)"; } link.appendChild(text); node.insertBefore(link); node.unlink(); } } function md_convert_hashes(iter) { var event, node, URI, hashlink, sup_open, sup_close, face; for(;;) { event = iter.next(); if(!event) break; if(event.entering) continue; node = event.node; if("Link" !== node.type && "Image" !== node.type) continue; URI = node.destination; if(!URI) continue; if("hash:" !== URI.toLowerCase().slice(0, 5)) continue; hashlink = new commonmark.Node("Link"); hashlink.destination = URI; hashlink.title = "Hash URI (right click and choose copy link)"; sup_open = new commonmark.Node("Html"); sup_close = new commonmark.Node("Html"); face = new commonmark.Node("Text"); sup_open.literal = "<sup>["; sup_close.literal = "]</sup>"; face.literal = "#"; hashlink.appendChild(face); node.insertAfter(sup_open); sup_open.insertAfter(hashlink); hashlink.insertAfter(sup_close); iter.resumeAt(sup_close, false); node.destination = "../?q="+URI; } } var coalesce = null; input.oninput = input.onpropertychange = function() { clearTimeout(coalesce); coalesce = null; coalesce = setTimeout(function() { var node = normalize(parser.parse(input.value)); md_escape(node.walker()); md_escape_inline(node.walker()); md_autolink(node.walker()); md_block_external_images(node.walker()); md_convert_hashes(node.walker()); // TODO: Use target=_blank for links. output.innerHTML = renderer.render(node); }, 1000 * 0.5); }; var TAB = 9; input.onkeydown = function(e) { if(TAB !== e.keyCode && TAB !== e.which) return; e.preventDefault(); var t = "\t"; var s = this.selectionStart + t.length; // TODO: With long documents, this is slow and messes up scrolling. // There's gotta be a better way. // Only tested on Firefox so far... this.setRangeText(t, this.selectionStart, this.selectionEnd); this.setSelectionRange(s, s); this.oninput(); };
res/blog/static/markdown.js
var input = document.getElementById("input"); var output = document.getElementById("output"); var parser = new commonmark.Parser(); var renderer = new commonmark.HtmlRenderer({sourcepos: true}); renderer.softbreak = "<br>"; // Ported from C version in markdown.c // The output should be identical between each version function md_escape(iter) { var event, node, p, text; for(;;) { event = iter.next(); if(!event) break; if(!event.entering) continue; node = event.node; if("HtmlBlock" !== node.type) continue; p = new commonmark.Node("Paragraph"); text = new commonmark.Node("Text"); text.literal = node.literal; p.appendChild(text); node.insertBefore(p); node.unlink(); } } function md_escape_inline(iter) { var event, node, text; for(;;) { event = iter.next(); if(!event) break; if(!event.entering) continue; node = event.node; if("Html" !== node.type) continue; text = new commonmark.Node("Text"); text.literal = node.literal; node.insertBefore(text); node.unlink(); } } function md_autolink(iter) { // <http://daringfireball.net/2010/07/improved_regex_for_matching_urls> // Painstakingly ported to POSIX and then back // TODO: Get original // Pretty sure this is broken because it's capturing trailing punctuation... var linkify = /([a-z][a-z0-9_-]+:(\/{1,3}|[a-z0-9%])|www[0-9]{0,3}[.]|[a-z0-9.-]+[.][a-z]{2,4}\/)([^\s()<>]+|(([^\s()<>]+|(([^\s()<>]+)))*))+((([^\s()<>]+|(([^\s()<>]+)))*)|[^\[\]\s`!(){};:'".,<>?«»“”‘’])/; var event, node, match, str, text, link, face; for(;;) { event = iter.next(); if(!event) break; if(!event.entering) continue; node = event.node; if("Text" !== node.type) continue; str = node.literal; while((match = linkify.exec(str))) { text = new commonmark.Node("Text"); link = new commonmark.Node("Link"); face = new commonmark.Node("Text"); text.literal = str.slice(0, match.index); link.destination = str.slice(match.index, match.index+match[0].length) face.literal = link.destination; link.appendChild(face); node.insertBefore(text); node.insertBefore(link); str = str.slice(match.index+match[0].length); } if(str !== node.literal) { text = new commonmark.Node("Text"); text.literal = str; node.insertBefore(text); node.unlink(); } } } function md_block_external_images(iter) { var event, node, link, URI, text, child; for(;;) { event = iter.next(); if(!event) break; if(event.entering) continue; node = event.node; if("Image" !== node.type) continue; URI = node.destination; if(URI) { if("hash:" === URI.toLowerCase().slice(0, 5)) continue; if("data:" === URI.toLowerCase().slice(0, 5)) continue; } link = new commonmark.Node("Link"); text = new commonmark.Node("Text"); link.destination = URI; for(;;) { child = node.firstChild; if(!child) break; link.appendChild(child); } if(link.firstChild) { text.literal = " (external image)"; } else { text.literal = "(external image)"; } link.appendChild(text); node.insertBefore(link); node.unlink(); } } function md_convert_hashes(iter) { var event, node, URI, hashlink, sup_open, sup_close, face; for(;;) { event = iter.next(); if(!event) break; if(event.entering) continue; node = event.node; if("Link" !== node.type && "Image" !== node.type) continue; URI = node.destination; if(!URI) continue; if("hash:" !== URI.toLowerCase().slice(0, 5)) continue; hashlink = new commonmark.Node("Link"); hashlink.destination = URI; hashlink.title = "Hash URI (right click and choose copy link)"; sup_open = new commonmark.Node("Html"); sup_close = new commonmark.Node("Html"); face = new commonmark.Node("Text"); sup_open.literal = "<sup>["; sup_close.literal = "]</sup>"; face.literal = "#"; hashlink.appendChild(face); node.insertAfter(sup_open); sup_open.insertAfter(hashlink); hashlink.insertAfter(sup_close); iter.resumeAt(sup_close, false); node.destination = "../?q="+URI; } } var coalesce = null; input.oninput = input.onpropertychange = function() { clearTimeout(coalesce); coalesce = null; coalesce = setTimeout(function() { var node = parser.parse(input.value); md_escape(node.walker()); md_escape_inline(node.walker()); md_autolink(node.walker()); md_block_external_images(node.walker()); md_convert_hashes(node.walker()); // TODO: Use target=_blank for links. output.innerHTML = renderer.render(node); }, 1000 * 0.5); }; var TAB = 9; input.onkeydown = function(e) { if(TAB !== e.keyCode && TAB !== e.which) return; e.preventDefault(); var t = "\t"; var s = this.selectionStart + t.length; // TODO: With long documents, this is slow and messes up scrolling. // There's gotta be a better way. // Only tested on Firefox so far... this.setRangeText(t, this.selectionStart, this.selectionEnd); this.setSelectionRange(s, s); this.oninput(); };
Normalize commonmark.js output before processing. All this just to handle _ and & in links.
res/blog/static/markdown.js
Normalize commonmark.js output before processing.
<ide><path>es/blog/static/markdown.js <ide> var parser = new commonmark.Parser(); <ide> var renderer = new commonmark.HtmlRenderer({sourcepos: true}); <ide> renderer.softbreak = "<br>"; <add> <add>// commonmark.js should do this for us... <add>function normalize(node) { <add> var text; <add> var run = []; <add> var child = node.firstChild; <add> for(;;) { <add> if(!child || "Text" != child.type) { <add> if(run.length > 1) { <add> text = new commonmark.Node("Text"); <add> text.literal = run.map(function(x) { <add> x.unlink(); <add> return x.literal; <add> }).join(""); <add> if(child) child.insertBefore(text); <add> else node.appendChild(text); <add> } <add> run = []; <add> } <add> if(!child) break; <add> if("Text" == child.type) { <add> run.push(child); <add> } else if(child.isContainer) { <add> normalize(child); <add> } <add> child = child.next; <add> } <add> return node; <add>} <ide> <ide> // Ported from C version in markdown.c <ide> // The output should be identical between each version <ide> input.oninput = input.onpropertychange = function() { <ide> clearTimeout(coalesce); coalesce = null; <ide> coalesce = setTimeout(function() { <del> var node = parser.parse(input.value); <add> var node = normalize(parser.parse(input.value)); <ide> md_escape(node.walker()); <ide> md_escape_inline(node.walker()); <ide> md_autolink(node.walker());
Java
mit
200689ed11e234b22b188b9625e92d9e1f8c810a
0
fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg
package ua.com.fielden.platform.entity.meta; import static java.lang.String.format; import static ua.com.fielden.platform.reflection.PropertyTypeDeterminator.isRequiredByDefinition; import static ua.com.fielden.platform.reflection.TitlesDescsGetter.getEntityTitleAndDesc; import static ua.com.fielden.platform.reflection.TitlesDescsGetter.getTitleAndDesc; import static ua.com.fielden.platform.reflection.TitlesDescsGetter.processReqErrorMsg; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.AbstractFunctionalEntityForCollectionModification; import ua.com.fielden.platform.entity.DynamicEntityKey; import ua.com.fielden.platform.entity.annotation.CritOnly; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.exceptions.EntityDefinitionException; import ua.com.fielden.platform.entity.proxy.StrictProxyException; import ua.com.fielden.platform.entity.validation.FinalValidator; import ua.com.fielden.platform.entity.validation.IBeforeChangeEventHandler; import ua.com.fielden.platform.entity.validation.StubValidator; import ua.com.fielden.platform.entity.validation.annotation.Final; import ua.com.fielden.platform.entity.validation.annotation.ValidationAnnotation; import ua.com.fielden.platform.error.Result; import ua.com.fielden.platform.error.Warning; import ua.com.fielden.platform.reflection.Reflector; import ua.com.fielden.platform.utils.EntityUtils; /** * Implements the concept of a meta-property. * <p> * Currently it provides validation support and validation change listeners, which can be specified whenever it is necessary to handle validation state changes. * <p> * It is planned to support other meta-information such as accessibility, label etc. This information can be user dependent and retrieved from a database. * <p> * <b>Date: 2008-10-xx</b><br> * Provided support for meta property <code>editable</code>.<br> * Provided support for keeping the track of property value changes, which includes support for <code>prevValue</code>, <code>originalValue</code> and <code>valueChangeCount</code>. * <p> * <b>Date: 2008-12-11</b><br> * Implemented support for {@link Comparable}.<br> * Provided flags <code>active</code> and <code>key</code>. * <p> * <b>Date: 2008-12-22</b><br> * Implemented support for recording last invalid value.<br> * <p> * <b>Date: 2010-03-18</b><br> * Implemented support for restoring to original value with validation error cancellation.<br> * <b>Date: 2011-09-26</b><br> * Significant modification due to introduction of BCE and ACE event lifecycle. <b>Date: 2014-10-21</b><br> * Modified handling of requiredness to fully replace NotNull. Corrected type parameterization. * * @author TG Team * */ public final class MetaPropertyFull<T> extends MetaProperty<T> { private final Class<?> propertyAnnotationType; private final Map<ValidationAnnotation, Map<IBeforeChangeEventHandler<T>, Result>> validators; private final Set<Annotation> validationAnnotations = new HashSet<>(); private final IAfterChangeEventHandler<T> aceHandler; private final boolean collectional; private final boolean shouldAssignBeforeSave; /** * This property indicates whether a corresponding property was modified. This is similar to <code>dirty</code> property at the entity level. */ private boolean dirty; public static final Number ORIGINAL_VALUE_NOT_INIT_COLL = -1; /////////////////////////////////////////////////////// /// Holds an original value of the property. /////////////////////////////////////////////////////// /** * Original value is always the value retrieved from a data storage. This means that new entities, which have not been persisted yet, have original values of their properties * equal to <code>null</code> * <p> * In case of properties with default values such definition might be unintuitive at first. However, the whole notion of default property values specified as an assignment * during property field definition does not fit naturally into the proposed modelling paradigm. Any property value should be validated before being assigned. This requires * setter invocation, and should be a deliberate act enforced as part of the application logic. Enforcing validation for default values is not technically difficult, but would * introduce a maintenance hurdle for application developers, where during an evolution of the system the validation logic might change, but default values not updated * accordingly. This would lead to entity instantiation failure. * * A much preferred approach is to provide a custom entity constructor or instantiation factories in case default property values support is required, where property values * should be set via setters. The use of factories would provide additional flexibility, where default values could be governed by business logic and a place of entity * instantiation. */ private T originalValue; private T prevValue; private T lastInvalidValue; private int valueChangeCount = 0; /** * Indicates whether this property has an assigned value. * This flag is requited due to the fact that the value of null could be assigned making it impossible to identify the * fact of value assignment in light of the fact that the original property value could, and in most cases is, be <code>null</code>. */ private boolean assigned = false; /////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // The following properties are more related to UI controls rather than to actual property value modification. // // Some external to meta-property logic may define whether the value of <code>editable</code>. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// private boolean editable = true; private boolean visible = true; private boolean required = false; public final boolean isRequiredByDefinition; public final boolean isCritOnly; private final boolean calculated; private final boolean upperCase; //////////////////////////////////////////////////////////////////////////////////////////////////////// // if the value is present then a corresponding property has annotation {@link Final} // the boolean value captures the value of attribute persistentOnly private final Optional<Boolean> persistentOnlySettingForFinalAnnotation; private final PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); private final Logger logger = Logger.getLogger(this.getClass()); /** Enforced mutation happens as part of the error recovery to indicate processing of dependent properties. */ private boolean enforceMutator = false; /** * Property supports specification of the precise type. For example, property <code>key</code> in entity classes is recognised by reflection API as Comparable. Therefore, it * might be desirable to specify type more accurately. * * @param entity * @param field * @param type * @param isKey * @param isCollectional * @param propertyAnnotationType * @param calculated * @param upperCase * @param validationAnnotations * @param validators * @param aceHandler * @param dependentPropertyNames */ public MetaPropertyFull( final AbstractEntity<?> entity, final Field field, final Class<?> type, final boolean isProxy, final boolean isKey, final boolean isCollectional, final boolean shouldAssignBeforeSave, final Class<?> propertyAnnotationType, final boolean calculated, final boolean upperCase,// final Set<Annotation> validationAnnotations,// final Map<ValidationAnnotation, Map<IBeforeChangeEventHandler<T>, Result>> validators, final IAfterChangeEventHandler<T> aceHandler, final String[] dependentPropertyNames) { super(entity, field, type, isKey, isProxy, dependentPropertyNames); this.validationAnnotations.addAll(validationAnnotations); this.validators = validators; this.aceHandler = aceHandler; this.collectional = isCollectional; this.shouldAssignBeforeSave = shouldAssignBeforeSave; this.propertyAnnotationType = propertyAnnotationType; this.calculated = calculated; this.upperCase = upperCase; final Final finalAnnotation = field.getAnnotation(Final.class); persistentOnlySettingForFinalAnnotation = finalAnnotation == null ? Optional.empty() : Optional.of(finalAnnotation.persistentOnly()); this.isRequiredByDefinition = isRequiredByDefinition(field, entity.getType()); this.isCritOnly = field.isAnnotationPresent(CritOnly.class); } /** * Perform sequential validation. * * Stops validation at the first violation. This is preferred since subsequent validators may depend on success of preceding ones. * * Please note that collectional properties may have up to three mutators having different annotations. Thus, a special logic is used to ensure that only validators associated * with the mutator being processed are applied. * * @return */ @Override public synchronized final Result validate(final T newValue, final Set<Annotation> applicableValidationAnnotations, final boolean ignoreRequiredness) { setLastInvalidValue(null); if (!ignoreRequiredness && isRequired() && isNull(newValue, getValue())) { final Map<IBeforeChangeEventHandler<T>, Result> requiredHandler = getValidators().get(ValidationAnnotation.REQUIRED); if (requiredHandler == null || requiredHandler.size() > 1) { throw new IllegalArgumentException("There are no or there is more than one REQUIRED validation handler for required property!"); } final Result result = mkRequiredError(); setValidationResultNoSynch(ValidationAnnotation.REQUIRED, requiredHandler.keySet().iterator().next(), result); return result; } else { // refresh REQUIRED validation result if REQUIRED validation annotation pair exists final Map<IBeforeChangeEventHandler<T>, Result> requiredHandler = getValidators().get(ValidationAnnotation.REQUIRED); if (requiredHandler != null && requiredHandler.size() == 1) { setValidationResultNoSynch(ValidationAnnotation.REQUIRED, requiredHandler.keySet().iterator().next(), new Result(getEntity(), "Requiredness updated by successful result.")); } // process all registered validators (that have its own annotations) return processValidators(newValue, applicableValidationAnnotations); } } private Result mkRequiredError() { // obtain custom error message in case it has been provided at the domain level final String reqErrorMsg = processReqErrorMsg(name, getEntity().getType()); final Result result; if (!StringUtils.isEmpty(reqErrorMsg)) { result = Result.failure(getEntity(), reqErrorMsg); } else { final String msg = format("Required property [%s] is not specified for entity [%s].", getTitleAndDesc(name, getEntity().getType()).getKey(), getEntityTitleAndDesc(getEntity().getType()).getKey()); result = Result.failure(getEntity(), msg); } return result; } /** * Convenient method to determine if the newValue is "null" or is empty in terms of value. * * @param newValue * @param oldValue * @return */ private boolean isNull(final T newValue, final T oldValue) { // IMPORTANT : need to check NotNullValidator usage on existing logic. There is the case, when // should not to pass the validation : setRotable(null) in AdvicePosition when getRotable() == null!!! // that is why - - "&& (oldValue != null)" - - was removed!!!!! // The current condition is essential for UI binding logic. return (newValue == null) || /* && (oldValue != null) */ (newValue instanceof String && StringUtils.isBlank(newValue.toString())); } /** * Revalidates this property using {@link #getLastAttemptedValue()} value as the input for the property. Revalidation occurs only if this property has an assigned value (null * could also be an assigned value). * * @param ignoreRequiredness * when true then isRequired value is ignored during revalidation, this is currently used for re-validating dependent properties where there is no need to mark * properties as invalid only because they are empty. * @return revalidation result */ @Override public synchronized final Result revalidate(final boolean ignoreRequiredness) { // revalidation is required only is there is an assigned value if (assigned) { return validate(getLastAttemptedValue(), validationAnnotations, ignoreRequiredness); } return Result.successful(this); } /** * Processes all registered validators (that have its own annotations) by iterating over validators associated with corresponding validation annotations (va). * * @param newValue * @param applicableValidationAnnotations * @param mutatorType * @return */ private Result processValidators(final T newValue, final Set<Annotation> applicableValidationAnnotations) { // iterate over registered validations for (final ValidationAnnotation va : validators.keySet()) { // requiredness falls outside of processing logic for other validators, so simply ignore it if (va == ValidationAnnotation.REQUIRED) { continue; } final Set<Entry<IBeforeChangeEventHandler<T>, Result>> pairs = validators.get(va).entrySet(); for (final Entry<IBeforeChangeEventHandler<T>, Result> pair : pairs) { // if validator exists ...and it should... then validated and set validation result final IBeforeChangeEventHandler<T> handler = pair.getKey(); if (handler != null && isValidatorApplicable(applicableValidationAnnotations, va.getType())) { final Result result = pair.getKey().handle(this, newValue, applicableValidationAnnotations); setValidationResultNoSynch(va, handler, result); // important to call setValidationResult as it fires property change event listeners if (!result.isSuccessful()) { // 1. isCollectional() && newValue instance of Collection : previously the size of "newValue" collection was set as LastInvalidValue, but now, // if we need to update bounded component by the lastInvalidValue then we set it as a collectional value // 2. if the property is not collectional then simply set LastInvalidValue as newValue setLastInvalidValue(newValue); return result; } } else { pair.setValue(null); } } } return new Result(this, "Validated successfully."); } /** * Checks whether annotation identified by parameter <code>key</code> is amongst applicable validation annotations. * * @param applicableValidationAnnotations * @param validationAnnotationEnumValue * @return */ private boolean isValidatorApplicable(final Set<Annotation> applicableValidationAnnotations, final Class<? extends Annotation> validationAnnotationType) { for (final Annotation annotation : applicableValidationAnnotations) { if (annotation.annotationType() == validationAnnotationType) { return true; } } return false; } @Override public final Map<ValidationAnnotation, Map<IBeforeChangeEventHandler<T>, Result>> getValidators() { return validators; } @Override public final String toString() { return format(format("Meta-property for property [%s] in entity [%s] wiht validators [%s].", getName(), getEntity().getType().getName(), validators)); } /** * Sets the result for validator with index. * * @param key * -- annotation representing validator * @param validationResult */ private void setValidationResultNoSynch(final ValidationAnnotation key, final IBeforeChangeEventHandler<T> handler, final Result validationResult) { // fire validationResults change event!! if (validators.get(key) != null) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(key); final Result oldValue = annotationHandlers.get(handler);// getValue(); annotationHandlers.put(handler, validationResult); final Result firstFailure = getFirstFailure(); if (firstFailure != null) { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, firstFailure); } else { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, validationResult); } } } /** * Same as {@link #setValidationResultNoSynch(Annotation, IBeforeChangeEventHandler, Result)}, but with synchronization block. * * @param key * @param handler * @param validationResult */ @Override public synchronized final void setValidationResult(final ValidationAnnotation key, final IBeforeChangeEventHandler<T> handler, final Result validationResult) { setValidationResultNoSynch(key, handler, validationResult); } /** * Sets validation result specifically for {@link ValidationAnnotation.REQUIRED}; * * @param validationResult */ @Override public synchronized final void setRequiredValidationResult(final Result validationResult) { setValidationResultForFirtsValidator(validationResult, ValidationAnnotation.REQUIRED); } /** * Sets validation result specifically for {@link ValidationAnnotation.ENTITY_EXISTS}; * * @param validationResult */ @Override public synchronized final void setEntityExistsValidationResult(final Result validationResult) { setValidationResultForFirtsValidator(validationResult, ValidationAnnotation.ENTITY_EXISTS); } /** * Sets validation result specifically for {@link ValidationAnnotation.REQUIRED}; * * @param validationResult */ @Override public synchronized final void setDomainValidationResult(final Result validationResult) { setValidationResultForFirtsValidator(validationResult, ValidationAnnotation.DOMAIN); } /** * Sets validation result for the first of the annotation handlers designated by the validation annotation value. * * @param validationResult * @param annotationHandlers */ private void setValidationResultForFirtsValidator(final Result validationResult, final ValidationAnnotation va) { Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); if (annotationHandlers == null) { annotationHandlers = new HashMap<>(); annotationHandlers.put(StubValidator.singleton, null); validators.put(va, annotationHandlers); } final IBeforeChangeEventHandler<T> handler = annotationHandlers.keySet().iterator().next(); final Result oldValue = annotationHandlers.get(handler); annotationHandlers.put(handler, validationResult); final Result firstFailure = getFirstFailure(); if (firstFailure != null) { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, firstFailure); } else { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, validationResult); } } /** * Returns the last result of the first validator associated with {@link ValidationAnnotation} value in a synchronised manner if all validators for this annotation succeeded, * or the last result of the first failed validator. Most validation annotations are associated with a single validator. But some, such as * {@link ValidationAnnotation#BEFORE_CHANGE} may have more than one validator associated with it. * * @param va * -- validation annotation. * @return */ @Override public synchronized final Result getValidationResult(final ValidationAnnotation va) { final Result failure = getFirstFailureFor(va); return failure != null ? failure : validators.get(va).values().iterator().next(); } /** * Returns false if there is at least one unsuccessful result. Evaluation of the validation results happens in a synchronised manner. * * @return */ @Override public synchronized final boolean isValid() { final Result failure = getFirstFailure(); return failure == null; } @Override public synchronized final boolean hasWarnings() { final Result failure = getFirstWarning(); return failure != null; } /** * Returns the first warning associated with property validators. * * @return */ @Override public synchronized final Warning getFirstWarning() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final Result result : annotationHandlers.values()) { if (result != null && result.isWarning()) { return (Warning) result; } } } return null; } /** * Removes all validation warnings (not errors) from the property. */ @Override public synchronized final void clearWarnings() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final Entry<IBeforeChangeEventHandler<T>, Result> handlerAndResult : annotationHandlers.entrySet()) { if (handlerAndResult.getValue() != null && handlerAndResult.getValue().isWarning()) { annotationHandlers.put(handlerAndResult.getKey(), null); } } } } /** * This method invokes {@link #isValid()} and if its result is <code>true</code> (i.e. valid) then additional check kicks in to ensure requiredness validation. * * @return */ @Override public synchronized final boolean isValidWithRequiredCheck() { final boolean result = isValid(); if (result) { // if valid check whether it's requiredness sound final Object value = ((AbstractEntity<?>) getEntity()).get(getName()); // this is a potential alternative approach to validating requiredness for proxied properties // leaving it here for future reference // if (isRequired() && isProxy()) { // throw new StrictProxyException(format("Required property [%s] in entity [%s] is proxied and thus cannot be checked.", getName(), getEntity().getType().getName())); // } if (isRequired() && !isProxy() && (value == null || isEmpty(value))) { if (!getValidators().containsKey(ValidationAnnotation.REQUIRED)) { throw new IllegalArgumentException("There are no REQUIRED validation annotation pair for required property!"); } final Result result1 = mkRequiredError(); setValidationResultNoSynch(ValidationAnnotation.REQUIRED, StubValidator.singleton, result1); return false; } } return result; } /** * A convenient method, which ensures that only string values are tested for empty when required. This prevents accidental and redundant lazy loading when invoking * values.toString() on entity instances. * * @param value * @return */ private boolean isEmpty(final Object value) { return value instanceof String ? StringUtils.isEmpty(value.toString()) : false; } /** * Return the first failed validation result. If there is no failure then returns null. * * @return */ @Override public synchronized final Result getFirstFailure() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final Result result : annotationHandlers.values()) { if (result != null && !result.isSuccessful()) { return result; } } } return null; } /** * Returns the first failure associated with <code>annotation</code> value. * * @param annotation * @return */ private final Result getFirstFailureFor(final ValidationAnnotation annotation) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(annotation); for (final Result result : annotationHandlers.values()) { if (result != null && !result.isSuccessful()) { return result; } } return null; } /** * Returns the number of property validators. Can be zero. * * @return */ @Override public final int numberOfValidators() { return validators.size(); } /** * Registers property change listener to validationResults. This listener fires when setValidationResult(..) method invokes. * * @param propertyName * @param listener */ @Override public final synchronized void addValidationResultsChangeListener(final PropertyChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("PropertyChangeListener cannot be null."); } changeSupport.addPropertyChangeListener(VALIDATION_RESULTS_PROPERTY_NAME, listener); } /** * Removes validationResults change listener. */ @Override public synchronized final void removeValidationResultsChangeListener(final PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(VALIDATION_RESULTS_PROPERTY_NAME, listener); } /** * Registers property change listener for property <code>editable</code>. * * @param propertyName * @param listener */ @Override public final synchronized void addEditableChangeListener(final PropertyChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("PropertyChangeListener cannot be null."); } changeSupport.addPropertyChangeListener(EDITABLE_PROPERTY_NAME, listener); } /** * Removes change listener for property <code>editable</code>. */ @Override public final synchronized void removeEditableChangeListener(final PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(EDITABLE_PROPERTY_NAME, listener); } /** * Registers property change listener for property <code>required</code>. * * @param propertyName * @param listener */ @Override public final synchronized void addRequiredChangeListener(final PropertyChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("PropertyChangeListener cannot be null."); } changeSupport.addPropertyChangeListener(REQUIRED_PROPERTY_NAME, listener); } /** * Removes change listener for property <code>required</code>. */ @Override public final synchronized void removeRequiredChangeListener(final PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(REQUIRED_PROPERTY_NAME, listener); } @Override public final PropertyChangeSupport getChangeSupport() { return changeSupport; } @Override public final T getOriginalValue() { return originalValue; } /** * Sets the original value. * * <p> * VERY IMPORTANT : the method should not cause proxy initialisation!!! * * @param value -- new originalValue for the property */ @Override public final MetaPropertyFull<T> setOriginalValue(final T value) { // when original property value is set then the previous value should be the same // the previous value setter is not used deliberately since it has some logic not needed here if (isCollectional()) { // set the shallow copy of collection into originalValue to be able to perform comparison between actual value and original value of the collection originalValue = EntityUtils.copyCollectionalValue(value); // set the shallow copy of collection into prevValue to be able to perform comparison between actual value and prevValue value of the collection prevValue = EntityUtils.copyCollectionalValue(originalValue); } else { // The single property (proxied or not!!!) originalValue = value; prevValue = originalValue; } // reset value change counter resetValueChageCount(); // assigned = true; return this; } @Override public final int getValueChangeCount() { return valueChangeCount; } private void incValueChangeCount() { valueChangeCount++; } private void resetValueChageCount() { valueChangeCount = 0; } @Override public final T getPrevValue() { return prevValue; } /** * Returns the current (last successful) value of the property. * * @return */ @Override public final T getValue() { return entity.<T> get(name); } /** * A convenient method to set property value, which in turn accesses entity to set the propery. * * @param value */ @Override public final void setValue(final Object value) { entity.set(name, value); } /** * Updates the previous value for the entity property. Increments the update counter and check if the original value should be updated as well. * * @param value -- new prevValue for the property * @return */ @Override public final MetaPropertyFull<T> setPrevValue(final T value) { incValueChangeCount(); // just in case cater for correct processing of collection properties if (isCollectional()) { // set the shallow copy of collection into this.prevValue to be able to perform comparison between actual value and previous value of the collection this.prevValue = EntityUtils.copyCollectionalValue(value); } else { this.prevValue = value; } return this; } /** * Checks if the current value is changed from the original one. * * @return */ @Override public final boolean isChangedFromOriginal() { return isChangedFrom(getOriginalValue()); } /** * Checks if the current value is changed from the specified one by means of equality. <code>null</code> value is permitted. * <p> * Please, note that property accessor (aka getter) is used to get current value. If exception occurs during current value getting -- * this method returns <code>false</code> and silently ignores this exception (with some debugging logging). * * @param value * @return */ private final boolean isChangedFrom(final T value) { try { final Method getter = Reflector.obtainPropertyAccessor(entity.getClass(), getName()); final Object currValue = getter.invoke(entity); return !EntityUtils.equalsEx(currValue, value); } catch (final Exception e) { logger.debug(e.getMessage(), e); } return false; } /** * Checks if the current value is changed from the previous one. * * @return */ @Override public final boolean isChangedFromPrevious() { return isChangedFrom(getPrevValue()); } @Override public final boolean isEditable() { return editable && getEntity().isEditable().isSuccessful() && !isFinalised(); } private boolean isFinalised() { if (persistentOnlySettingForFinalAnnotation.isPresent()) { return FinalValidator.isPropertyFinalised(this, persistentOnlySettingForFinalAnnotation.get()); } return false; } @Override public final void setEditable(final boolean editable) { final boolean oldValue = this.editable; this.editable = editable; changeSupport.firePropertyChange(EDITABLE_PROPERTY_NAME, oldValue, editable); } /** * Invokes {@link IAfterChangeEventHandler#handle(MetaPropertyFull, Object)} if it has been provided. * * @param entityPropertyValue * @return */ @Override public final MetaPropertyFull<T> define(final T entityPropertyValue) { if (aceHandler != null) { aceHandler.handle(this, entityPropertyValue); } return this; } @Override public final MetaPropertyFull<T> defineForOriginalValue() { if (aceHandler != null) { aceHandler.handle(this, getOriginalValue()); } return this; } /** * Returns true if MetaProperty represents a collectional property. * * @return */ @Override public final boolean isCollectional() { return collectional; } /** * Returns a type provided as part of the annotation {@link IsProperty} when defining property. It is provided, for example, in cases where meta-property represents a * collection property -- the provided type indicates the type collection elements. * * @return */ @Override public final Class<?> getPropertyAnnotationType() { return propertyAnnotationType; } @Override public final boolean isVisible() { return visible; } @Override public final void setVisible(final boolean visible) { this.visible = visible; } @Override public final T getLastInvalidValue() { return lastInvalidValue; } @Override public final void setLastInvalidValue(final T lastInvalidValue) { this.lastInvalidValue = lastInvalidValue; } /** * A convenient method for determining whether there are validators associated a the corresponding property. * * @return */ @Override public final boolean hasValidators() { return getValidators().size() > 0; } /** * Convenient method that returns either property value (if property validation passed successfully) or {@link #getLastInvalidValue()} (if property validation idn't pass). * <p> * A special care is taken for properties with default values assigned at the field level. This method returns <code>original value</code> for properties that are valid and not * assigned. * * @return */ @Override public final T getLastAttemptedValue() { return isValid() ? (isAssigned() ? getValue() : getOriginalValue()) : getLastInvalidValue(); } @Override public final boolean isRequired() { return required; } /** * This setter change the 'required' state for metaProperty. Also it puts RequiredValidator to the list of validators if it does not exist. And if 'required' became false -> it * clears REQUIRED validation result by successful result. * * @param required */ @Override public final MetaPropertyFull<T> setRequired(final boolean required) { requirednessChangePreCondition(required); final boolean oldRequired = this.required; this.required = required; // if requirement changed from false to true, and REQUIRED validator does not exist in the list of validators -> then put REQUIRED validator to the list of validators if (required && !oldRequired && !containsRequiredValidator()) { putRequiredValidator(); } // if requirement changed from true to false, then update REQUIRED validation result to be successful if (!required && oldRequired) { if (containsRequiredValidator()) { final Result result = getValidationResult(ValidationAnnotation.REQUIRED); if (result != null && !result.isSuccessful()) { setEnforceMutator(true); try { setValue(getLastAttemptedValue()); } finally { setEnforceMutator(false); } } else { // associated a successful result with requiredness validator setValidationResultNoSynch(ValidationAnnotation.REQUIRED, StubValidator.singleton, new Result(this.getEntity(), "'Required' became false. The validation result cleared.")); } } else { throw new IllegalStateException("The metaProperty was required but RequiredValidator didn't exist."); } } changeSupport.firePropertyChange(REQUIRED_PROPERTY_NAME, oldRequired, required); return this; } /** * A helper method that ascertains the validity of requiredness change. * * @param required */ private void requirednessChangePreCondition(final boolean required) { if (required && !getEntity().isInitialising() && isProxy()) { throw new StrictProxyException(format("Property [%s] in entity [%s] is proxied and should not be made required.", getName(), getEntity().getType().getSimpleName())); } if (!required && isRequiredByDefinition && !isCritOnly && !shouldAssignBeforeSave() && !requirednessExceptionRule()) { throw new EntityDefinitionException(format("Property [%s] in entity [%s] is declared as required and cannot have this constraint relaxed.", name, getEntity().getType().getSimpleName())); } } /** * Entities of type {@link AbstractFunctionalEntityForCollectionModification} need to be able to relax requiredness for their keys. * * @return */ private boolean requirednessExceptionRule() { return AbstractEntity.KEY.equals(name) && AbstractFunctionalEntityForCollectionModification.class.isAssignableFrom(entity.getType()); } @Override public final void resetState() { setOriginalValue(entity.get(name)); setDirty(false); } @Override public final void resetValues() { setOriginalValue(entity.get(name)); } @Override public final boolean isCalculated() { return calculated; } /** * Checks if REQUIRED validator were ever put to the list of validators. * * @return */ @Override public final boolean containsRequiredValidator() { return getValidators().containsKey(ValidationAnnotation.REQUIRED); } /** * Checks if DYNAMIC validator were ever put to the list of validators. * * @return */ @Override public final boolean containsDynamicValidator() { return getValidators().containsKey(ValidationAnnotation.DYNAMIC); } /** * Creates and puts EMPTY validator related to DYNAMIC validation annotation. Validation result for DYNAMIC validator can be set only from the outside logic, for e.g. using * method MetaProperty.setValidationResult(). */ @Override public final void putDynamicValidator() { putValidator(ValidationAnnotation.DYNAMIC); } /** * Creates and puts EMPTY validator related to REQUIRED validation annotation. Validation result for REQURED validator can be set only from the outside logic, for e.g. using * method MetaProperty.setValidationResult(). */ @Override public final void putRequiredValidator() { putValidator(ValidationAnnotation.REQUIRED); } /** * Used to create and put new validator (without any validation logic!) to validators list related to <code>valAnnotation</code>. * * This method should be used ONLY for DYNAMIC, REQUIRED and all validators that cannot change its result from its own "validate" method, but only from the outside method * MetaProperty.setValidationResult(). * * @param valAnnotation */ private void putValidator(final ValidationAnnotation valAnnotation) { final Map<IBeforeChangeEventHandler<T>, Result> map = new HashMap<>(2); // optimised with 2 as default value for this map -- not to create map with unnecessary 16 elements map.put(StubValidator.singleton, null); getValidators().put(valAnnotation, map); } @Override public boolean isDirty() { return dirty || !entity.isPersisted(); } @Override public MetaPropertyFull<T> setDirty(final boolean dirty) { this.dirty = dirty; return this; } @Override public boolean isUpperCase() { return upperCase; } /** * Restores property state to original if possible, which includes setting the original value and removal of all validation errors. */ @Override public final void restoreToOriginal() { resetValidationResult(); // need to ignore composite key instance resetting if (!DynamicEntityKey.class.isAssignableFrom(type)) { try { entity.set(name, getOriginalValue()); } catch (final Exception ex) { logger.debug("Could not restore to original property " + name + "#" + entity.getType().getName() + "."); } } resetState(); } /** * Resets validation results for all validators by setting their value to <code>null</code>. */ @Override public synchronized final void resetValidationResult() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final IBeforeChangeEventHandler<T> handler : annotationHandlers.keySet()) { annotationHandlers.put(handler, null); } } } @Override public boolean isEnforceMutator() { return enforceMutator; } @Override public void setEnforceMutator(final boolean enforceMutator) { this.enforceMutator = enforceMutator; } @Override public boolean isAssigned() { return assigned; } @Override public void setAssigned(final boolean hasAssignedValue) { this.assigned = hasAssignedValue; } /** * Returns a list of validation annotations associated with this property. * * @return */ @Override public Set<Annotation> getValidationAnnotations() { return Collections.unmodifiableSet(validationAnnotations); } /** * Returns property ACE handler. * * @return */ @Override public IAfterChangeEventHandler<T> getAceHandler() { return aceHandler; } @Override public boolean shouldAssignBeforeSave() { return shouldAssignBeforeSave; } }
platform-pojo-bl/src/main/java/ua/com/fielden/platform/entity/meta/MetaPropertyFull.java
package ua.com.fielden.platform.entity.meta; import static java.lang.String.format; import static ua.com.fielden.platform.reflection.PropertyTypeDeterminator.isRequiredByDefinition; import static ua.com.fielden.platform.reflection.TitlesDescsGetter.getEntityTitleAndDesc; import static ua.com.fielden.platform.reflection.TitlesDescsGetter.getTitleAndDesc; import static ua.com.fielden.platform.reflection.TitlesDescsGetter.processReqErrorMsg; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.AbstractFunctionalEntityForCollectionModification; import ua.com.fielden.platform.entity.DynamicEntityKey; import ua.com.fielden.platform.entity.annotation.IsProperty; import ua.com.fielden.platform.entity.exceptions.EntityDefinitionException; import ua.com.fielden.platform.entity.proxy.StrictProxyException; import ua.com.fielden.platform.entity.validation.FinalValidator; import ua.com.fielden.platform.entity.validation.IBeforeChangeEventHandler; import ua.com.fielden.platform.entity.validation.StubValidator; import ua.com.fielden.platform.entity.validation.annotation.Final; import ua.com.fielden.platform.entity.validation.annotation.ValidationAnnotation; import ua.com.fielden.platform.error.Result; import ua.com.fielden.platform.error.Warning; import ua.com.fielden.platform.reflection.Reflector; import ua.com.fielden.platform.utils.EntityUtils; /** * Implements the concept of a meta-property. * <p> * Currently it provides validation support and validation change listeners, which can be specified whenever it is necessary to handle validation state changes. * <p> * It is planned to support other meta-information such as accessibility, label etc. This information can be user dependent and retrieved from a database. * <p> * <b>Date: 2008-10-xx</b><br> * Provided support for meta property <code>editable</code>.<br> * Provided support for keeping the track of property value changes, which includes support for <code>prevValue</code>, <code>originalValue</code> and <code>valueChangeCount</code>. * <p> * <b>Date: 2008-12-11</b><br> * Implemented support for {@link Comparable}.<br> * Provided flags <code>active</code> and <code>key</code>. * <p> * <b>Date: 2008-12-22</b><br> * Implemented support for recording last invalid value.<br> * <p> * <b>Date: 2010-03-18</b><br> * Implemented support for restoring to original value with validation error cancellation.<br> * <b>Date: 2011-09-26</b><br> * Significant modification due to introduction of BCE and ACE event lifecycle. <b>Date: 2014-10-21</b><br> * Modified handling of requiredness to fully replace NotNull. Corrected type parameterization. * * @author TG Team * */ public final class MetaPropertyFull<T> extends MetaProperty<T> { private final Class<?> propertyAnnotationType; private final Map<ValidationAnnotation, Map<IBeforeChangeEventHandler<T>, Result>> validators; private final Set<Annotation> validationAnnotations = new HashSet<>(); private final IAfterChangeEventHandler<T> aceHandler; private final boolean collectional; private final boolean shouldAssignBeforeSave; /** * This property indicates whether a corresponding property was modified. This is similar to <code>dirty</code> property at the entity level. */ private boolean dirty; public static final Number ORIGINAL_VALUE_NOT_INIT_COLL = -1; /////////////////////////////////////////////////////// /// Holds an original value of the property. /////////////////////////////////////////////////////// /** * Original value is always the value retrieved from a data storage. This means that new entities, which have not been persisted yet, have original values of their properties * equal to <code>null</code> * <p> * In case of properties with default values such definition might be unintuitive at first. However, the whole notion of default property values specified as an assignment * during property field definition does not fit naturally into the proposed modelling paradigm. Any property value should be validated before being assigned. This requires * setter invocation, and should be a deliberate act enforced as part of the application logic. Enforcing validation for default values is not technically difficult, but would * introduce a maintenance hurdle for application developers, where during an evolution of the system the validation logic might change, but default values not updated * accordingly. This would lead to entity instantiation failure. * * A much preferred approach is to provide a custom entity constructor or instantiation factories in case default property values support is required, where property values * should be set via setters. The use of factories would provide additional flexibility, where default values could be governed by business logic and a place of entity * instantiation. */ private T originalValue; private T prevValue; private T lastInvalidValue; private int valueChangeCount = 0; /** * Indicates whether this property has an assigned value. * This flag is requited due to the fact that the value of null could be assigned making it impossible to identify the * fact of value assignment in light of the fact that the original property value could, and in most cases is, be <code>null</code>. */ private boolean assigned = false; /////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // The following properties are more related to UI controls rather than to actual property value modification. // // Some external to meta-property logic may define whether the value of <code>editable</code>. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// private boolean editable = true; private boolean visible = true; private boolean required = false; public final boolean isRequiredByDefinition; private final boolean calculated; private final boolean upperCase; //////////////////////////////////////////////////////////////////////////////////////////////////////// // if the value is present then a corresponding property has annotation {@link Final} // the boolean value captures the value of attribute persistentOnly private final Optional<Boolean> persistentOnlySettingForFinalAnnotation; private final PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); private final Logger logger = Logger.getLogger(this.getClass()); /** Enforced mutation happens as part of the error recovery to indicate processing of dependent properties. */ private boolean enforceMutator = false; /** * Property supports specification of the precise type. For example, property <code>key</code> in entity classes is recognised by reflection API as Comparable. Therefore, it * might be desirable to specify type more accurately. * * @param entity * @param field * @param type * @param isKey * @param isCollectional * @param propertyAnnotationType * @param calculated * @param upperCase * @param validationAnnotations * @param validators * @param aceHandler * @param dependentPropertyNames */ public MetaPropertyFull( final AbstractEntity<?> entity, final Field field, final Class<?> type, final boolean isProxy, final boolean isKey, final boolean isCollectional, final boolean shouldAssignBeforeSave, final Class<?> propertyAnnotationType, final boolean calculated, final boolean upperCase,// final Set<Annotation> validationAnnotations,// final Map<ValidationAnnotation, Map<IBeforeChangeEventHandler<T>, Result>> validators, final IAfterChangeEventHandler<T> aceHandler, final String[] dependentPropertyNames) { super(entity, field, type, isKey, isProxy, dependentPropertyNames); this.validationAnnotations.addAll(validationAnnotations); this.validators = validators; this.aceHandler = aceHandler; this.collectional = isCollectional; this.shouldAssignBeforeSave = shouldAssignBeforeSave; this.propertyAnnotationType = propertyAnnotationType; this.calculated = calculated; this.upperCase = upperCase; final Final finalAnnotation = field.getAnnotation(Final.class); persistentOnlySettingForFinalAnnotation = finalAnnotation == null ? Optional.empty() : Optional.of(finalAnnotation.persistentOnly()); this.isRequiredByDefinition = isRequiredByDefinition(field, entity.getType()); } /** * Perform sequential validation. * * Stops validation at the first violation. This is preferred since subsequent validators may depend on success of preceding ones. * * Please note that collectional properties may have up to three mutators having different annotations. Thus, a special logic is used to ensure that only validators associated * with the mutator being processed are applied. * * @return */ @Override public synchronized final Result validate(final T newValue, final Set<Annotation> applicableValidationAnnotations, final boolean ignoreRequiredness) { setLastInvalidValue(null); if (!ignoreRequiredness && isRequired() && isNull(newValue, getValue())) { final Map<IBeforeChangeEventHandler<T>, Result> requiredHandler = getValidators().get(ValidationAnnotation.REQUIRED); if (requiredHandler == null || requiredHandler.size() > 1) { throw new IllegalArgumentException("There are no or there is more than one REQUIRED validation handler for required property!"); } final Result result = mkRequiredError(); setValidationResultNoSynch(ValidationAnnotation.REQUIRED, requiredHandler.keySet().iterator().next(), result); return result; } else { // refresh REQUIRED validation result if REQUIRED validation annotation pair exists final Map<IBeforeChangeEventHandler<T>, Result> requiredHandler = getValidators().get(ValidationAnnotation.REQUIRED); if (requiredHandler != null && requiredHandler.size() == 1) { setValidationResultNoSynch(ValidationAnnotation.REQUIRED, requiredHandler.keySet().iterator().next(), new Result(getEntity(), "Requiredness updated by successful result.")); } // process all registered validators (that have its own annotations) return processValidators(newValue, applicableValidationAnnotations); } } private Result mkRequiredError() { // obtain custom error message in case it has been provided at the domain level final String reqErrorMsg = processReqErrorMsg(name, getEntity().getType()); final Result result; if (!StringUtils.isEmpty(reqErrorMsg)) { result = Result.failure(getEntity(), reqErrorMsg); } else { final String msg = format("Required property [%s] is not specified for entity [%s].", getTitleAndDesc(name, getEntity().getType()).getKey(), getEntityTitleAndDesc(getEntity().getType()).getKey()); result = Result.failure(getEntity(), msg); } return result; } /** * Convenient method to determine if the newValue is "null" or is empty in terms of value. * * @param newValue * @param oldValue * @return */ private boolean isNull(final T newValue, final T oldValue) { // IMPORTANT : need to check NotNullValidator usage on existing logic. There is the case, when // should not to pass the validation : setRotable(null) in AdvicePosition when getRotable() == null!!! // that is why - - "&& (oldValue != null)" - - was removed!!!!! // The current condition is essential for UI binding logic. return (newValue == null) || /* && (oldValue != null) */ (newValue instanceof String && StringUtils.isBlank(newValue.toString())); } /** * Revalidates this property using {@link #getLastAttemptedValue()} value as the input for the property. Revalidation occurs only if this property has an assigned value (null * could also be an assigned value). * * @param ignoreRequiredness * when true then isRequired value is ignored during revalidation, this is currently used for re-validating dependent properties where there is no need to mark * properties as invalid only because they are empty. * @return revalidation result */ @Override public synchronized final Result revalidate(final boolean ignoreRequiredness) { // revalidation is required only is there is an assigned value if (assigned) { return validate(getLastAttemptedValue(), validationAnnotations, ignoreRequiredness); } return Result.successful(this); } /** * Processes all registered validators (that have its own annotations) by iterating over validators associated with corresponding validation annotations (va). * * @param newValue * @param applicableValidationAnnotations * @param mutatorType * @return */ private Result processValidators(final T newValue, final Set<Annotation> applicableValidationAnnotations) { // iterate over registered validations for (final ValidationAnnotation va : validators.keySet()) { // requiredness falls outside of processing logic for other validators, so simply ignore it if (va == ValidationAnnotation.REQUIRED) { continue; } final Set<Entry<IBeforeChangeEventHandler<T>, Result>> pairs = validators.get(va).entrySet(); for (final Entry<IBeforeChangeEventHandler<T>, Result> pair : pairs) { // if validator exists ...and it should... then validated and set validation result final IBeforeChangeEventHandler<T> handler = pair.getKey(); if (handler != null && isValidatorApplicable(applicableValidationAnnotations, va.getType())) { final Result result = pair.getKey().handle(this, newValue, applicableValidationAnnotations); setValidationResultNoSynch(va, handler, result); // important to call setValidationResult as it fires property change event listeners if (!result.isSuccessful()) { // 1. isCollectional() && newValue instance of Collection : previously the size of "newValue" collection was set as LastInvalidValue, but now, // if we need to update bounded component by the lastInvalidValue then we set it as a collectional value // 2. if the property is not collectional then simply set LastInvalidValue as newValue setLastInvalidValue(newValue); return result; } } else { pair.setValue(null); } } } return new Result(this, "Validated successfully."); } /** * Checks whether annotation identified by parameter <code>key</code> is amongst applicable validation annotations. * * @param applicableValidationAnnotations * @param validationAnnotationEnumValue * @return */ private boolean isValidatorApplicable(final Set<Annotation> applicableValidationAnnotations, final Class<? extends Annotation> validationAnnotationType) { for (final Annotation annotation : applicableValidationAnnotations) { if (annotation.annotationType() == validationAnnotationType) { return true; } } return false; } @Override public final Map<ValidationAnnotation, Map<IBeforeChangeEventHandler<T>, Result>> getValidators() { return validators; } @Override public final String toString() { return format(format("Meta-property for property [%s] in entity [%s] wiht validators [%s].", getName(), getEntity().getType().getName(), validators)); } /** * Sets the result for validator with index. * * @param key * -- annotation representing validator * @param validationResult */ private void setValidationResultNoSynch(final ValidationAnnotation key, final IBeforeChangeEventHandler<T> handler, final Result validationResult) { // fire validationResults change event!! if (validators.get(key) != null) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(key); final Result oldValue = annotationHandlers.get(handler);// getValue(); annotationHandlers.put(handler, validationResult); final Result firstFailure = getFirstFailure(); if (firstFailure != null) { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, firstFailure); } else { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, validationResult); } } } /** * Same as {@link #setValidationResultNoSynch(Annotation, IBeforeChangeEventHandler, Result)}, but with synchronization block. * * @param key * @param handler * @param validationResult */ @Override public synchronized final void setValidationResult(final ValidationAnnotation key, final IBeforeChangeEventHandler<T> handler, final Result validationResult) { setValidationResultNoSynch(key, handler, validationResult); } /** * Sets validation result specifically for {@link ValidationAnnotation.REQUIRED}; * * @param validationResult */ @Override public synchronized final void setRequiredValidationResult(final Result validationResult) { setValidationResultForFirtsValidator(validationResult, ValidationAnnotation.REQUIRED); } /** * Sets validation result specifically for {@link ValidationAnnotation.ENTITY_EXISTS}; * * @param validationResult */ @Override public synchronized final void setEntityExistsValidationResult(final Result validationResult) { setValidationResultForFirtsValidator(validationResult, ValidationAnnotation.ENTITY_EXISTS); } /** * Sets validation result specifically for {@link ValidationAnnotation.REQUIRED}; * * @param validationResult */ @Override public synchronized final void setDomainValidationResult(final Result validationResult) { setValidationResultForFirtsValidator(validationResult, ValidationAnnotation.DOMAIN); } /** * Sets validation result for the first of the annotation handlers designated by the validation annotation value. * * @param validationResult * @param annotationHandlers */ private void setValidationResultForFirtsValidator(final Result validationResult, final ValidationAnnotation va) { Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); if (annotationHandlers == null) { annotationHandlers = new HashMap<>(); annotationHandlers.put(StubValidator.singleton, null); validators.put(va, annotationHandlers); } final IBeforeChangeEventHandler<T> handler = annotationHandlers.keySet().iterator().next(); final Result oldValue = annotationHandlers.get(handler); annotationHandlers.put(handler, validationResult); final Result firstFailure = getFirstFailure(); if (firstFailure != null) { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, firstFailure); } else { changeSupport.firePropertyChange(VALIDATION_RESULTS_PROPERTY_NAME, oldValue, validationResult); } } /** * Returns the last result of the first validator associated with {@link ValidationAnnotation} value in a synchronised manner if all validators for this annotation succeeded, * or the last result of the first failed validator. Most validation annotations are associated with a single validator. But some, such as * {@link ValidationAnnotation#BEFORE_CHANGE} may have more than one validator associated with it. * * @param va * -- validation annotation. * @return */ @Override public synchronized final Result getValidationResult(final ValidationAnnotation va) { final Result failure = getFirstFailureFor(va); return failure != null ? failure : validators.get(va).values().iterator().next(); } /** * Returns false if there is at least one unsuccessful result. Evaluation of the validation results happens in a synchronised manner. * * @return */ @Override public synchronized final boolean isValid() { final Result failure = getFirstFailure(); return failure == null; } @Override public synchronized final boolean hasWarnings() { final Result failure = getFirstWarning(); return failure != null; } /** * Returns the first warning associated with property validators. * * @return */ @Override public synchronized final Warning getFirstWarning() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final Result result : annotationHandlers.values()) { if (result != null && result.isWarning()) { return (Warning) result; } } } return null; } /** * Removes all validation warnings (not errors) from the property. */ @Override public synchronized final void clearWarnings() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final Entry<IBeforeChangeEventHandler<T>, Result> handlerAndResult : annotationHandlers.entrySet()) { if (handlerAndResult.getValue() != null && handlerAndResult.getValue().isWarning()) { annotationHandlers.put(handlerAndResult.getKey(), null); } } } } /** * This method invokes {@link #isValid()} and if its result is <code>true</code> (i.e. valid) then additional check kicks in to ensure requiredness validation. * * @return */ @Override public synchronized final boolean isValidWithRequiredCheck() { final boolean result = isValid(); if (result) { // if valid check whether it's requiredness sound final Object value = ((AbstractEntity<?>) getEntity()).get(getName()); // this is a potential alternative approach to validating requiredness for proxied properties // leaving it here for future reference // if (isRequired() && isProxy()) { // throw new StrictProxyException(format("Required property [%s] in entity [%s] is proxied and thus cannot be checked.", getName(), getEntity().getType().getName())); // } if (isRequired() && !isProxy() && (value == null || isEmpty(value))) { if (!getValidators().containsKey(ValidationAnnotation.REQUIRED)) { throw new IllegalArgumentException("There are no REQUIRED validation annotation pair for required property!"); } final Result result1 = mkRequiredError(); setValidationResultNoSynch(ValidationAnnotation.REQUIRED, StubValidator.singleton, result1); return false; } } return result; } /** * A convenient method, which ensures that only string values are tested for empty when required. This prevents accidental and redundant lazy loading when invoking * values.toString() on entity instances. * * @param value * @return */ private boolean isEmpty(final Object value) { return value instanceof String ? StringUtils.isEmpty(value.toString()) : false; } /** * Return the first failed validation result. If there is no failure then returns null. * * @return */ @Override public synchronized final Result getFirstFailure() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final Result result : annotationHandlers.values()) { if (result != null && !result.isSuccessful()) { return result; } } } return null; } /** * Returns the first failure associated with <code>annotation</code> value. * * @param annotation * @return */ private final Result getFirstFailureFor(final ValidationAnnotation annotation) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(annotation); for (final Result result : annotationHandlers.values()) { if (result != null && !result.isSuccessful()) { return result; } } return null; } /** * Returns the number of property validators. Can be zero. * * @return */ @Override public final int numberOfValidators() { return validators.size(); } /** * Registers property change listener to validationResults. This listener fires when setValidationResult(..) method invokes. * * @param propertyName * @param listener */ @Override public final synchronized void addValidationResultsChangeListener(final PropertyChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("PropertyChangeListener cannot be null."); } changeSupport.addPropertyChangeListener(VALIDATION_RESULTS_PROPERTY_NAME, listener); } /** * Removes validationResults change listener. */ @Override public synchronized final void removeValidationResultsChangeListener(final PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(VALIDATION_RESULTS_PROPERTY_NAME, listener); } /** * Registers property change listener for property <code>editable</code>. * * @param propertyName * @param listener */ @Override public final synchronized void addEditableChangeListener(final PropertyChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("PropertyChangeListener cannot be null."); } changeSupport.addPropertyChangeListener(EDITABLE_PROPERTY_NAME, listener); } /** * Removes change listener for property <code>editable</code>. */ @Override public final synchronized void removeEditableChangeListener(final PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(EDITABLE_PROPERTY_NAME, listener); } /** * Registers property change listener for property <code>required</code>. * * @param propertyName * @param listener */ @Override public final synchronized void addRequiredChangeListener(final PropertyChangeListener listener) { if (listener == null) { throw new IllegalArgumentException("PropertyChangeListener cannot be null."); } changeSupport.addPropertyChangeListener(REQUIRED_PROPERTY_NAME, listener); } /** * Removes change listener for property <code>required</code>. */ @Override public final synchronized void removeRequiredChangeListener(final PropertyChangeListener listener) { changeSupport.removePropertyChangeListener(REQUIRED_PROPERTY_NAME, listener); } @Override public final PropertyChangeSupport getChangeSupport() { return changeSupport; } @Override public final T getOriginalValue() { return originalValue; } /** * Sets the original value. * * <p> * VERY IMPORTANT : the method should not cause proxy initialisation!!! * * @param value -- new originalValue for the property */ @Override public final MetaPropertyFull<T> setOriginalValue(final T value) { // when original property value is set then the previous value should be the same // the previous value setter is not used deliberately since it has some logic not needed here if (isCollectional()) { // set the shallow copy of collection into originalValue to be able to perform comparison between actual value and original value of the collection originalValue = EntityUtils.copyCollectionalValue(value); // set the shallow copy of collection into prevValue to be able to perform comparison between actual value and prevValue value of the collection prevValue = EntityUtils.copyCollectionalValue(originalValue); } else { // The single property (proxied or not!!!) originalValue = value; prevValue = originalValue; } // reset value change counter resetValueChageCount(); // assigned = true; return this; } @Override public final int getValueChangeCount() { return valueChangeCount; } private void incValueChangeCount() { valueChangeCount++; } private void resetValueChageCount() { valueChangeCount = 0; } @Override public final T getPrevValue() { return prevValue; } /** * Returns the current (last successful) value of the property. * * @return */ @Override public final T getValue() { return entity.<T> get(name); } /** * A convenient method to set property value, which in turn accesses entity to set the propery. * * @param value */ @Override public final void setValue(final Object value) { entity.set(name, value); } /** * Updates the previous value for the entity property. Increments the update counter and check if the original value should be updated as well. * * @param value -- new prevValue for the property * @return */ @Override public final MetaPropertyFull<T> setPrevValue(final T value) { incValueChangeCount(); // just in case cater for correct processing of collection properties if (isCollectional()) { // set the shallow copy of collection into this.prevValue to be able to perform comparison between actual value and previous value of the collection this.prevValue = EntityUtils.copyCollectionalValue(value); } else { this.prevValue = value; } return this; } /** * Checks if the current value is changed from the original one. * * @return */ @Override public final boolean isChangedFromOriginal() { return isChangedFrom(getOriginalValue()); } /** * Checks if the current value is changed from the specified one by means of equality. <code>null</code> value is permitted. * <p> * Please, note that property accessor (aka getter) is used to get current value. If exception occurs during current value getting -- * this method returns <code>false</code> and silently ignores this exception (with some debugging logging). * * @param value * @return */ private final boolean isChangedFrom(final T value) { try { final Method getter = Reflector.obtainPropertyAccessor(entity.getClass(), getName()); final Object currValue = getter.invoke(entity); return !EntityUtils.equalsEx(currValue, value); } catch (final Exception e) { logger.debug(e.getMessage(), e); } return false; } /** * Checks if the current value is changed from the previous one. * * @return */ @Override public final boolean isChangedFromPrevious() { return isChangedFrom(getPrevValue()); } @Override public final boolean isEditable() { return editable && getEntity().isEditable().isSuccessful() && !isFinalised(); } private boolean isFinalised() { if (persistentOnlySettingForFinalAnnotation.isPresent()) { return FinalValidator.isPropertyFinalised(this, persistentOnlySettingForFinalAnnotation.get()); } return false; } @Override public final void setEditable(final boolean editable) { final boolean oldValue = this.editable; this.editable = editable; changeSupport.firePropertyChange(EDITABLE_PROPERTY_NAME, oldValue, editable); } /** * Invokes {@link IAfterChangeEventHandler#handle(MetaPropertyFull, Object)} if it has been provided. * * @param entityPropertyValue * @return */ @Override public final MetaPropertyFull<T> define(final T entityPropertyValue) { if (aceHandler != null) { aceHandler.handle(this, entityPropertyValue); } return this; } @Override public final MetaPropertyFull<T> defineForOriginalValue() { if (aceHandler != null) { aceHandler.handle(this, getOriginalValue()); } return this; } /** * Returns true if MetaProperty represents a collectional property. * * @return */ @Override public final boolean isCollectional() { return collectional; } /** * Returns a type provided as part of the annotation {@link IsProperty} when defining property. It is provided, for example, in cases where meta-property represents a * collection property -- the provided type indicates the type collection elements. * * @return */ @Override public final Class<?> getPropertyAnnotationType() { return propertyAnnotationType; } @Override public final boolean isVisible() { return visible; } @Override public final void setVisible(final boolean visible) { this.visible = visible; } @Override public final T getLastInvalidValue() { return lastInvalidValue; } @Override public final void setLastInvalidValue(final T lastInvalidValue) { this.lastInvalidValue = lastInvalidValue; } /** * A convenient method for determining whether there are validators associated a the corresponding property. * * @return */ @Override public final boolean hasValidators() { return getValidators().size() > 0; } /** * Convenient method that returns either property value (if property validation passed successfully) or {@link #getLastInvalidValue()} (if property validation idn't pass). * <p> * A special care is taken for properties with default values assigned at the field level. This method returns <code>original value</code> for properties that are valid and not * assigned. * * @return */ @Override public final T getLastAttemptedValue() { return isValid() ? (isAssigned() ? getValue() : getOriginalValue()) : getLastInvalidValue(); } @Override public final boolean isRequired() { return required; } /** * This setter change the 'required' state for metaProperty. Also it puts RequiredValidator to the list of validators if it does not exist. And if 'required' became false -> it * clears REQUIRED validation result by successful result. * * @param required */ @Override public final MetaPropertyFull<T> setRequired(final boolean required) { requirednessChangePreCondition(required); final boolean oldRequired = this.required; this.required = required; // if requirement changed from false to true, and REQUIRED validator does not exist in the list of validators -> then put REQUIRED validator to the list of validators if (required && !oldRequired && !containsRequiredValidator()) { putRequiredValidator(); } // if requirement changed from true to false, then update REQUIRED validation result to be successful if (!required && oldRequired) { if (containsRequiredValidator()) { final Result result = getValidationResult(ValidationAnnotation.REQUIRED); if (result != null && !result.isSuccessful()) { setEnforceMutator(true); try { setValue(getLastAttemptedValue()); } finally { setEnforceMutator(false); } } else { // associated a successful result with requiredness validator setValidationResultNoSynch(ValidationAnnotation.REQUIRED, StubValidator.singleton, new Result(this.getEntity(), "'Required' became false. The validation result cleared.")); } } else { throw new IllegalStateException("The metaProperty was required but RequiredValidator didn't exist."); } } changeSupport.firePropertyChange(REQUIRED_PROPERTY_NAME, oldRequired, required); return this; } /** * A helper method that ascertains the validity of requiredness change. * * @param required */ private void requirednessChangePreCondition(final boolean required) { if (required && !getEntity().isInitialising() && isProxy()) { throw new StrictProxyException(format("Property [%s] in entity [%s] is proxied and should not be made required.", getName(), getEntity().getType().getSimpleName())); } if (!required && isRequiredByDefinition && !shouldAssignBeforeSave() && !requirednessExceptionRule()) { throw new EntityDefinitionException(format("Property [%s] in entity [%s] is declared as required and cannot have this constraint relaxed.", name, getEntity().getType().getSimpleName())); } } /** * Entities of type {@link AbstractFunctionalEntityForCollectionModification} need to be able to relax requiredness for their keys. * * @return */ private boolean requirednessExceptionRule() { return AbstractEntity.KEY.equals(name) && AbstractFunctionalEntityForCollectionModification.class.isAssignableFrom(entity.getType()); } @Override public final void resetState() { setOriginalValue(entity.get(name)); setDirty(false); } @Override public final void resetValues() { setOriginalValue(entity.get(name)); } @Override public final boolean isCalculated() { return calculated; } /** * Checks if REQUIRED validator were ever put to the list of validators. * * @return */ @Override public final boolean containsRequiredValidator() { return getValidators().containsKey(ValidationAnnotation.REQUIRED); } /** * Checks if DYNAMIC validator were ever put to the list of validators. * * @return */ @Override public final boolean containsDynamicValidator() { return getValidators().containsKey(ValidationAnnotation.DYNAMIC); } /** * Creates and puts EMPTY validator related to DYNAMIC validation annotation. Validation result for DYNAMIC validator can be set only from the outside logic, for e.g. using * method MetaProperty.setValidationResult(). */ @Override public final void putDynamicValidator() { putValidator(ValidationAnnotation.DYNAMIC); } /** * Creates and puts EMPTY validator related to REQUIRED validation annotation. Validation result for REQURED validator can be set only from the outside logic, for e.g. using * method MetaProperty.setValidationResult(). */ @Override public final void putRequiredValidator() { putValidator(ValidationAnnotation.REQUIRED); } /** * Used to create and put new validator (without any validation logic!) to validators list related to <code>valAnnotation</code>. * * This method should be used ONLY for DYNAMIC, REQUIRED and all validators that cannot change its result from its own "validate" method, but only from the outside method * MetaProperty.setValidationResult(). * * @param valAnnotation */ private void putValidator(final ValidationAnnotation valAnnotation) { final Map<IBeforeChangeEventHandler<T>, Result> map = new HashMap<>(2); // optimised with 2 as default value for this map -- not to create map with unnecessary 16 elements map.put(StubValidator.singleton, null); getValidators().put(valAnnotation, map); } @Override public boolean isDirty() { return dirty || !entity.isPersisted(); } @Override public MetaPropertyFull<T> setDirty(final boolean dirty) { this.dirty = dirty; return this; } @Override public boolean isUpperCase() { return upperCase; } /** * Restores property state to original if possible, which includes setting the original value and removal of all validation errors. */ @Override public final void restoreToOriginal() { resetValidationResult(); // need to ignore composite key instance resetting if (!DynamicEntityKey.class.isAssignableFrom(type)) { try { entity.set(name, getOriginalValue()); } catch (final Exception ex) { logger.debug("Could not restore to original property " + name + "#" + entity.getType().getName() + "."); } } resetState(); } /** * Resets validation results for all validators by setting their value to <code>null</code>. */ @Override public synchronized final void resetValidationResult() { for (final ValidationAnnotation va : validators.keySet()) { final Map<IBeforeChangeEventHandler<T>, Result> annotationHandlers = validators.get(va); for (final IBeforeChangeEventHandler<T> handler : annotationHandlers.keySet()) { annotationHandlers.put(handler, null); } } } @Override public boolean isEnforceMutator() { return enforceMutator; } @Override public void setEnforceMutator(final boolean enforceMutator) { this.enforceMutator = enforceMutator; } @Override public boolean isAssigned() { return assigned; } @Override public void setAssigned(final boolean hasAssignedValue) { this.assigned = hasAssignedValue; } /** * Returns a list of validation annotations associated with this property. * * @return */ @Override public Set<Annotation> getValidationAnnotations() { return Collections.unmodifiableSet(validationAnnotations); } /** * Returns property ACE handler. * * @return */ @Override public IAfterChangeEventHandler<T> getAceHandler() { return aceHandler; } @Override public boolean shouldAssignBeforeSave() { return shouldAssignBeforeSave; } }
#724 Adjusted the logic of 'setRquired(false)' for @CritOnly properties that are required by definition.
platform-pojo-bl/src/main/java/ua/com/fielden/platform/entity/meta/MetaPropertyFull.java
#724 Adjusted the logic of 'setRquired(false)' for @CritOnly properties that are required by definition.
<ide><path>latform-pojo-bl/src/main/java/ua/com/fielden/platform/entity/meta/MetaPropertyFull.java <ide> import ua.com.fielden.platform.entity.AbstractEntity; <ide> import ua.com.fielden.platform.entity.AbstractFunctionalEntityForCollectionModification; <ide> import ua.com.fielden.platform.entity.DynamicEntityKey; <add>import ua.com.fielden.platform.entity.annotation.CritOnly; <ide> import ua.com.fielden.platform.entity.annotation.IsProperty; <ide> import ua.com.fielden.platform.entity.exceptions.EntityDefinitionException; <ide> import ua.com.fielden.platform.entity.proxy.StrictProxyException; <ide> private boolean visible = true; <ide> private boolean required = false; <ide> public final boolean isRequiredByDefinition; <add> public final boolean isCritOnly; <ide> private final boolean calculated; <ide> private final boolean upperCase; <ide> //////////////////////////////////////////////////////////////////////////////////////////////////////// <ide> final Final finalAnnotation = field.getAnnotation(Final.class); <ide> persistentOnlySettingForFinalAnnotation = finalAnnotation == null ? Optional.empty() : Optional.of(finalAnnotation.persistentOnly()); <ide> this.isRequiredByDefinition = isRequiredByDefinition(field, entity.getType()); <add> this.isCritOnly = field.isAnnotationPresent(CritOnly.class); <ide> } <ide> <ide> /** <ide> throw new StrictProxyException(format("Property [%s] in entity [%s] is proxied and should not be made required.", getName(), getEntity().getType().getSimpleName())); <ide> } <ide> <del> if (!required && isRequiredByDefinition && !shouldAssignBeforeSave() && !requirednessExceptionRule()) { <add> if (!required && isRequiredByDefinition && !isCritOnly && !shouldAssignBeforeSave() && !requirednessExceptionRule()) { <ide> throw new EntityDefinitionException(format("Property [%s] in entity [%s] is declared as required and cannot have this constraint relaxed.", name, getEntity().getType().getSimpleName())); <ide> } <ide> }
JavaScript
mit
682cbf44c00c3def67b66204e3c185f86e2b6f0f
0
joe-sky/nornj,joe-sky/nornj
var nj = require('../src/base'), utils = require('../src/utils/utils'), compile = require('../src/compiler/compile').compile; describe('test compile string', function () { beforeAll(function () { nj.registerFilter('filter1', function (v) { return v * 2; }); nj.registerFilter('filter2', function (v, p1, p2) { //console.log(p1 + '_' + p2); return v + 5; }); nj.registerFilter('filter3', function (v) { return !!!v; }); nj.registerFilter('tagName', function (v) { return v + 'Tmp'; }); }); describe('compile string template to html', function () { it('test compile 1', function () { nj.setParamRule(); var data = { name: "<i>joe_sky1</i>", id: 100, test0: false, list: [0, 1, 2], c1: 100, sliderItem: 'sliderItem' }; //normal template var tmpl1 = ['div name1=\'../111\' class="{ c1 } c0 { \'5\':filter1 \'!\' \'10\':filter1(1) } c2" id1=666 id2=777 name="my name:{\'name\' name},id:{id},name:{name}" id=test1', ['span', 'sky:{name},{id}', '/span'], ['span1', 'joe', '/span1'], ['div id=555', ['a /'], [ ['input type=button /'], ['$unless {test0}', ['input id="test5" /'], '/$unless'] ], '/div'], '/div']; //string template by es5 var tmpl2 = '<div name1=../111>\ <span>\ <img />\ sky:{name},{ id: filter2(1, 2) }${0}\ </span>\ </div>'; //string template by es6 var tmpl3 = nj` <div name=test1> <$params> <$param {'name'}>{test0:filter1 'test1':filter2 'test2'}</$param> <$each {list}> <$param {'data-name' .}>{.:filter1 'test1' 'test2'}</$param> </$each> <$param {'data-name10'}> <$each {list}> <$if {.}> { #:filter2 } <$else /> { '100':filter1 } </$if> </$each> </$param> </$params> <br></br> test2 <span> ${tmpl2} <img /> sky:{{ 'name555' }},{ id: filter2 } ${['section', tmpl1, '/section']} <input type=button /> ${nj` <$each { list }> <slider> <{../sliderItem:tagName} checked no='{ ../sliderItem }' /> </slider> </$each> `} </span> </div>`; var tmplFn = compile(tmpl3, 'tmplEs6'), html = tmplFn(data); //console.log(JSON.stringify(nj.templates['tmplEs6'])); console.log(html); expect(html).toBeTruthy(); }); }); });
test/compileStringSpec.js
var nj = require('../src/base'), utils = require('../src/utils/utils'), compile = require('../src/compiler/compile').compile; describe('test compile string', function () { beforeAll(function () { nj.registerFilter('filter1', function (v) { return v * 2; }); nj.registerFilter('filter2', function (v, p1, p2) { //console.log(p1 + '_' + p2); return v + 5; }); nj.registerFilter('filter3', function (v) { return !!!v; }); nj.registerFilter('tagName', function (v) { return v + 'Tmp'; }); }); describe('compile string template to html', function () { it('test compile 1', function () { nj.setParamRule(); var data = { name: "<i>joe_sky1</i>", id: 100, test0: false, list: [0, 1, 2], c1: 100, sliderItem: 'sliderItem' }; //normal template var tmpl1 = ['div name1=\'../111\' class="{ c1 } c0 { \'5\':filter1 \'!\' \'10\':filter1(1) } c2" id1=666 id2=777 name="my name:{\'name\' name},id:{id},name:{name}" id=test1', ['span', 'sky:{name},{id}', '/span'], ['span1', 'joe', '/span1'], ['div id=555', ['a /'], [ ['input type=button /'], ['$unless {test0}', ['input id="test5" /'], '/$unless'] ], '/div'], '/div']; //string template by es5 var tmpl2 = '<div name1=../111>\ <span>\ <img />\ sky:{name},{ id: filter2(1, 2) }${0}\ </span>\ </div>'; //string template by es6 var tmpl3 = nj` <div name=test1> <$params> <$param {'name'}>{test0:filter1 'test1':filter2 'test2'}</$param> <$each refer="{list}"> <$param refer="{'data-name' .}">{.:filter1 'test1' 'test2'}</$param> </$each> <$param refer="{'data-name10'}"> <$each refer="{list}"> <$if refer="{.}"> { #:filter2 } <$else /> { '100':filter1 } </$if> </$each> </$param> </$params> <br></br> test2 <span> ${tmpl2} <img /> sky:{{ 'name555' }},{ id: filter2 } ${['section', tmpl1, '/section']} <input type=button /> ${nj` <$each { list }> <slider> <{../sliderItem:tagName} checked no='{ ../sliderItem }' /> </slider> </$each> `} </span> </div>`; var tmplFn = compile(tmpl3, 'tmplEs6'), html = tmplFn(data); //console.log(JSON.stringify(nj.templates['tmplEs6'])); console.log(html); expect(html).toBeTruthy(); }); }); });
Add "$params" expression
test/compileStringSpec.js
Add "$params" expression
<ide><path>est/compileStringSpec.js <ide> <div name=test1> <ide> <$params> <ide> <$param {'name'}>{test0:filter1 'test1':filter2 'test2'}</$param> <del> <$each refer="{list}"> <del> <$param refer="{'data-name' .}">{.:filter1 'test1' 'test2'}</$param> <add> <$each {list}> <add> <$param {'data-name' .}>{.:filter1 'test1' 'test2'}</$param> <ide> </$each> <del> <$param refer="{'data-name10'}"> <del> <$each refer="{list}"> <del> <$if refer="{.}"> <add> <$param {'data-name10'}> <add> <$each {list}> <add> <$if {.}> <ide> { #:filter2 } <ide> <$else /> <ide> { '100':filter1 }
Java
apache-2.0
f6a4a833411636403e9bae9b03bce3a2dae68c5b
0
peymanmortazavi/titanium_mobile,shopmium/titanium_mobile,KoketsoMabuela92/titanium_mobile,hieupham007/Titanium_Mobile,FokkeZB/titanium_mobile,rblalock/titanium_mobile,jhaynie/titanium_mobile,jhaynie/titanium_mobile,indera/titanium_mobile,openbaoz/titanium_mobile,FokkeZB/titanium_mobile,mano-mykingdom/titanium_mobile,jvkops/titanium_mobile,arnaudsj/titanium_mobile,mano-mykingdom/titanium_mobile,FokkeZB/titanium_mobile,pinnamur/titanium_mobile,peymanmortazavi/titanium_mobile,bhatfield/titanium_mobile,pec1985/titanium_mobile,falkolab/titanium_mobile,indera/titanium_mobile,KoketsoMabuela92/titanium_mobile,formalin14/titanium_mobile,sriks/titanium_mobile,AngelkPetkov/titanium_mobile,AngelkPetkov/titanium_mobile,formalin14/titanium_mobile,csg-coder/titanium_mobile,peymanmortazavi/titanium_mobile,collinprice/titanium_mobile,bhatfield/titanium_mobile,indera/titanium_mobile,KoketsoMabuela92/titanium_mobile,arnaudsj/titanium_mobile,emilyvon/titanium_mobile,collinprice/titanium_mobile,openbaoz/titanium_mobile,taoger/titanium_mobile,pinnamur/titanium_mobile,mvitr/titanium_mobile,jhaynie/titanium_mobile,bright-sparks/titanium_mobile,perdona/titanium_mobile,KoketsoMabuela92/titanium_mobile,ashcoding/titanium_mobile,KoketsoMabuela92/titanium_mobile,emilyvon/titanium_mobile,mano-mykingdom/titanium_mobile,falkolab/titanium_mobile,perdona/titanium_mobile,jvkops/titanium_mobile,emilyvon/titanium_mobile,rblalock/titanium_mobile,taoger/titanium_mobile,KangaCoders/titanium_mobile,benbahrenburg/titanium_mobile,kopiro/titanium_mobile,bhatfield/titanium_mobile,collinprice/titanium_mobile,mano-mykingdom/titanium_mobile,perdona/titanium_mobile,openbaoz/titanium_mobile,smit1625/titanium_mobile,KangaCoders/titanium_mobile,smit1625/titanium_mobile,jvkops/titanium_mobile,FokkeZB/titanium_mobile,rblalock/titanium_mobile,csg-coder/titanium_mobile,kopiro/titanium_mobile,bhatfield/titanium_mobile,kopiro/titanium_mobile,linearhub/titanium_mobile,prop/titanium_mobile,openbaoz/titanium_mobile,pec1985/titanium_mobile,mano-mykingdom/titanium_mobile,peymanmortazavi/titanium_mobile,prop/titanium_mobile,sriks/titanium_mobile,bright-sparks/titanium_mobile,AngelkPetkov/titanium_mobile,AngelkPetkov/titanium_mobile,shopmium/titanium_mobile,falkolab/titanium_mobile,arnaudsj/titanium_mobile,linearhub/titanium_mobile,collinprice/titanium_mobile,csg-coder/titanium_mobile,bright-sparks/titanium_mobile,jhaynie/titanium_mobile,emilyvon/titanium_mobile,prop/titanium_mobile,collinprice/titanium_mobile,ashcoding/titanium_mobile,cheekiatng/titanium_mobile,ashcoding/titanium_mobile,sriks/titanium_mobile,csg-coder/titanium_mobile,rblalock/titanium_mobile,peymanmortazavi/titanium_mobile,hieupham007/Titanium_Mobile,AngelkPetkov/titanium_mobile,KangaCoders/titanium_mobile,indera/titanium_mobile,arnaudsj/titanium_mobile,pec1985/titanium_mobile,hieupham007/Titanium_Mobile,perdona/titanium_mobile,peymanmortazavi/titanium_mobile,AngelkPetkov/titanium_mobile,pec1985/titanium_mobile,bhatfield/titanium_mobile,mvitr/titanium_mobile,sriks/titanium_mobile,FokkeZB/titanium_mobile,KangaCoders/titanium_mobile,jhaynie/titanium_mobile,perdona/titanium_mobile,FokkeZB/titanium_mobile,cheekiatng/titanium_mobile,hieupham007/Titanium_Mobile,cheekiatng/titanium_mobile,indera/titanium_mobile,mano-mykingdom/titanium_mobile,falkolab/titanium_mobile,formalin14/titanium_mobile,pec1985/titanium_mobile,smit1625/titanium_mobile,csg-coder/titanium_mobile,rblalock/titanium_mobile,kopiro/titanium_mobile,benbahrenburg/titanium_mobile,emilyvon/titanium_mobile,prop/titanium_mobile,jvkops/titanium_mobile,perdona/titanium_mobile,pec1985/titanium_mobile,rblalock/titanium_mobile,ashcoding/titanium_mobile,bright-sparks/titanium_mobile,rblalock/titanium_mobile,bright-sparks/titanium_mobile,linearhub/titanium_mobile,ashcoding/titanium_mobile,taoger/titanium_mobile,cheekiatng/titanium_mobile,pinnamur/titanium_mobile,taoger/titanium_mobile,cheekiatng/titanium_mobile,openbaoz/titanium_mobile,benbahrenburg/titanium_mobile,shopmium/titanium_mobile,linearhub/titanium_mobile,bhatfield/titanium_mobile,FokkeZB/titanium_mobile,falkolab/titanium_mobile,rblalock/titanium_mobile,taoger/titanium_mobile,emilyvon/titanium_mobile,kopiro/titanium_mobile,shopmium/titanium_mobile,KoketsoMabuela92/titanium_mobile,indera/titanium_mobile,pec1985/titanium_mobile,collinprice/titanium_mobile,shopmium/titanium_mobile,mano-mykingdom/titanium_mobile,hieupham007/Titanium_Mobile,mano-mykingdom/titanium_mobile,falkolab/titanium_mobile,FokkeZB/titanium_mobile,benbahrenburg/titanium_mobile,openbaoz/titanium_mobile,smit1625/titanium_mobile,bright-sparks/titanium_mobile,KangaCoders/titanium_mobile,prop/titanium_mobile,benbahrenburg/titanium_mobile,peymanmortazavi/titanium_mobile,ashcoding/titanium_mobile,shopmium/titanium_mobile,csg-coder/titanium_mobile,linearhub/titanium_mobile,cheekiatng/titanium_mobile,bhatfield/titanium_mobile,arnaudsj/titanium_mobile,bright-sparks/titanium_mobile,hieupham007/Titanium_Mobile,smit1625/titanium_mobile,formalin14/titanium_mobile,formalin14/titanium_mobile,mvitr/titanium_mobile,smit1625/titanium_mobile,formalin14/titanium_mobile,kopiro/titanium_mobile,bright-sparks/titanium_mobile,pinnamur/titanium_mobile,pec1985/titanium_mobile,emilyvon/titanium_mobile,KangaCoders/titanium_mobile,jvkops/titanium_mobile,benbahrenburg/titanium_mobile,benbahrenburg/titanium_mobile,pinnamur/titanium_mobile,AngelkPetkov/titanium_mobile,kopiro/titanium_mobile,linearhub/titanium_mobile,indera/titanium_mobile,arnaudsj/titanium_mobile,cheekiatng/titanium_mobile,prop/titanium_mobile,collinprice/titanium_mobile,jvkops/titanium_mobile,csg-coder/titanium_mobile,mvitr/titanium_mobile,ashcoding/titanium_mobile,AngelkPetkov/titanium_mobile,smit1625/titanium_mobile,csg-coder/titanium_mobile,perdona/titanium_mobile,jhaynie/titanium_mobile,mvitr/titanium_mobile,mvitr/titanium_mobile,benbahrenburg/titanium_mobile,pinnamur/titanium_mobile,pec1985/titanium_mobile,hieupham007/Titanium_Mobile,jvkops/titanium_mobile,taoger/titanium_mobile,taoger/titanium_mobile,sriks/titanium_mobile,formalin14/titanium_mobile,KangaCoders/titanium_mobile,indera/titanium_mobile,KoketsoMabuela92/titanium_mobile,ashcoding/titanium_mobile,jhaynie/titanium_mobile,kopiro/titanium_mobile,pinnamur/titanium_mobile,KoketsoMabuela92/titanium_mobile,sriks/titanium_mobile,shopmium/titanium_mobile,pinnamur/titanium_mobile,sriks/titanium_mobile,sriks/titanium_mobile,bhatfield/titanium_mobile,smit1625/titanium_mobile,openbaoz/titanium_mobile,mvitr/titanium_mobile,falkolab/titanium_mobile,peymanmortazavi/titanium_mobile,linearhub/titanium_mobile,jvkops/titanium_mobile,falkolab/titanium_mobile,prop/titanium_mobile,cheekiatng/titanium_mobile,jhaynie/titanium_mobile,linearhub/titanium_mobile,shopmium/titanium_mobile,prop/titanium_mobile,collinprice/titanium_mobile,mvitr/titanium_mobile,perdona/titanium_mobile,hieupham007/Titanium_Mobile,KangaCoders/titanium_mobile,emilyvon/titanium_mobile,taoger/titanium_mobile,pinnamur/titanium_mobile,formalin14/titanium_mobile,openbaoz/titanium_mobile
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package org.appcelerator.titanium.view; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollPropertyChange; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.KrollProxyListener; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.TiDimension; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.Log; import org.appcelerator.titanium.util.TiAnimationBuilder; import org.appcelerator.titanium.util.TiAnimationBuilder.TiMatrixAnimation; import org.appcelerator.titanium.util.TiConfig; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiCompositeLayout.LayoutParams; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; public abstract class TiUIView implements KrollProxyListener, OnFocusChangeListener { private static final String LCAT = "TiUIView"; private static final boolean DBG = TiConfig.LOGD; private static AtomicInteger idGenerator; public static final int SOFT_KEYBOARD_DEFAULT_ON_FOCUS = 0; public static final int SOFT_KEYBOARD_HIDE_ON_FOCUS = 1; public static final int SOFT_KEYBOARD_SHOW_ON_FOCUS = 2; protected View nativeView; // Native View object protected TiViewProxy proxy; protected TiViewProxy parent; protected ArrayList<TiUIView> children = new ArrayList<TiUIView>(); protected LayoutParams layoutParams; protected int zIndex; protected TiAnimationBuilder animBuilder; protected TiBackgroundDrawable background; private KrollDict lastUpEvent = new KrollDict(2); // In the case of heavy-weight windows, the "nativeView" is null, // so this holds a reference to the view which is used for touching, // i.e., the view passed to registerForTouch. private WeakReference<View> mTouchView = null; public TiUIView(TiViewProxy proxy) { if (idGenerator == null) { idGenerator = new AtomicInteger(0); } this.proxy = proxy; this.layoutParams = new TiCompositeLayout.LayoutParams(); } public void add(TiUIView child) { if (child != null) { View cv = child.getNativeView(); if (cv != null) { View nv = getNativeView(); if (nv instanceof ViewGroup) { if (cv.getParent() == null) { ((ViewGroup) nv).addView(cv, child.getLayoutParams()); } children.add(child); } } } } public void remove(TiUIView child) { if (child != null) { View cv = child.getNativeView(); if (cv != null) { View nv = getNativeView(); if (nv instanceof ViewGroup) { ((ViewGroup) nv).removeView(cv); children.remove(child); } } } } public List<TiUIView> getChildren() { return children; } public TiViewProxy getProxy() { return proxy; } public void setProxy(TiViewProxy proxy) { this.proxy = proxy; } public TiViewProxy getParent() { return parent; } public void setParent(TiViewProxy parent) { this.parent = parent; } public LayoutParams getLayoutParams() { return layoutParams; } public int getZIndex() { return zIndex; } public View getNativeView() { return nativeView; } protected void setNativeView(View view) { if (view.getId() == View.NO_ID) { view.setId(idGenerator.incrementAndGet()); } this.nativeView = view; boolean clickable = true; if (proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) { clickable = TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED)); } doSetClickable(nativeView, clickable); nativeView.setOnFocusChangeListener(this); } protected void setLayoutParams(LayoutParams layoutParams) { this.layoutParams = layoutParams; } protected void setZIndex(int index) { zIndex = index; } public void animate() { TiAnimationBuilder builder = proxy.getPendingAnimation(); if (builder != null && nativeView != null) { AnimationSet as = builder.render(proxy, nativeView); if (DBG) { Log.d(LCAT, "starting animation: "+as); } nativeView.startAnimation(as); // Clean up proxy proxy.clearAnimation(); } } public void listenerAdded(String type, int count, KrollProxy proxy) { } public void listenerRemoved(String type, int count, KrollProxy proxy){ } private boolean hasImage(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE); } private boolean hasBorder(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_RADIUS) || d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_WIDTH); } private boolean hasColorState(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR); } protected void applyTransform(Ti2DMatrix matrix) { layoutParams.optionTransform = matrix; if (animBuilder == null) { animBuilder = new TiAnimationBuilder(); } if (nativeView != null) { if (matrix != null) { TiMatrixAnimation matrixAnimation = animBuilder.createMatrixAnimation(matrix); matrixAnimation.interpolate = false; matrixAnimation.setDuration(1); matrixAnimation.setFillAfter(true); nativeView.startAnimation(matrixAnimation); } else { nativeView.clearAnimation(); } } } protected void layoutNativeView() { if (nativeView != null) { Animation a = nativeView.getAnimation(); if (a != null && a instanceof TiMatrixAnimation) { TiMatrixAnimation matrixAnimation = (TiMatrixAnimation) a; matrixAnimation.invalidateWithMatrix(nativeView); } nativeView.requestLayout(); } } public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (key.equals(TiC.PROPERTY_LEFT)) { if (newValue != null) { layoutParams.optionLeft = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_LEFT); } else { layoutParams.optionLeft = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_TOP)) { if (newValue != null) { layoutParams.optionTop = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_TOP); } else { layoutParams.optionTop = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_CENTER)) { TiConvert.updateLayoutCenter(newValue, layoutParams); layoutNativeView(); } else if (key.equals(TiC.PROPERTY_RIGHT)) { if (newValue != null) { layoutParams.optionRight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_RIGHT); } else { layoutParams.optionRight = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_BOTTOM)) { if (newValue != null) { layoutParams.optionBottom = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_BOTTOM); } else { layoutParams.optionBottom = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_SIZE)) { if (newValue instanceof KrollDict) { KrollDict d = (KrollDict)newValue; propertyChanged(TiC.PROPERTY_WIDTH, oldValue, d.get(TiC.PROPERTY_WIDTH), proxy); propertyChanged(TiC.PROPERTY_HEIGHT, oldValue, d.get(TiC.PROPERTY_HEIGHT), proxy); }else if (newValue != null){ Log.w(LCAT, "Unsupported property type ("+(newValue.getClass().getSimpleName())+") for key: " + key+". Must be an object/dictionary"); } } else if (key.equals(TiC.PROPERTY_HEIGHT)) { if (newValue != null) { if (!newValue.equals(TiC.SIZE_AUTO)) { layoutParams.optionHeight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_HEIGHT); layoutParams.autoHeight = false; } else { layoutParams.optionHeight = null; layoutParams.autoHeight = true; } } else { layoutParams.optionHeight = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_WIDTH)) { if (newValue != null) { if (!newValue.equals(TiC.SIZE_AUTO)) { layoutParams.optionWidth = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_WIDTH); layoutParams.autoWidth = false; } else { layoutParams.optionWidth = null; layoutParams.autoWidth = true; } } else { layoutParams.optionWidth = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_ZINDEX)) { if (newValue != null) { layoutParams.optionZIndex = TiConvert.toInt(TiConvert.toString(newValue)); } else { layoutParams.optionZIndex = 0; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_FOCUSABLE)) { boolean focusable = TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_FOCUSABLE)); nativeView.setFocusable(focusable); if (focusable) { registerForKeyClick(nativeView); } else { //nativeView.setOnClickListener(null); // ? mistake? I assume OnKeyListener was meant nativeView.setOnKeyListener(null); } } else if (key.equals(TiC.PROPERTY_TOUCH_ENABLED)) { doSetClickable(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_VISIBLE)) { nativeView.setVisibility(TiConvert.toBoolean(newValue) ? View.VISIBLE : View.INVISIBLE); } else if (key.equals(TiC.PROPERTY_ENABLED)) { nativeView.setEnabled(TiConvert.toBoolean(newValue)); } else if (key.startsWith(TiC.PROPERTY_BACKGROUND_PADDING)) { Log.i(LCAT, key + " not yet implemented."); } else if (key.equals(TiC.PROPERTY_OPACITY) || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX) || key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) { // Update first before querying. proxy.setProperty(key, newValue, false); KrollDict d = proxy.getProperties(); boolean hasImage = hasImage(d); boolean hasColorState = hasColorState(d); boolean hasBorder = hasBorder(d); boolean requiresCustomBackground = hasImage || hasColorState || hasBorder; if (!requiresCustomBackground) { if (background != null) { background.releaseDelegate(); background.setCallback(null); background = null; } if (d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_COLOR)) { Integer bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); if (nativeView != null){ nativeView.setBackgroundColor(bgColor); nativeView.postInvalidate(); } } else { if (key.equals(TiC.PROPERTY_OPACITY)) { setOpacity(TiConvert.toFloat(newValue)); } if (nativeView != null) { nativeView.setBackgroundDrawable(null); nativeView.postInvalidate(); } } } else { boolean newBackground = background == null; if (newBackground) { background = new TiBackgroundDrawable(); } Integer bgColor = null; if (!hasColorState) { if (d.get(TiC.PROPERTY_BACKGROUND_COLOR) != null) { bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); if (newBackground || (key.equals(TiC.PROPERTY_OPACITY) || key.equals(TiC.PROPERTY_BACKGROUND_COLOR))) { background.setBackgroundColor(bgColor); } } } if (hasImage || hasColorState) { if (newBackground || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX)) { handleBackgroundImage(d); } } if (hasBorder) { if (newBackground) { initializeBorder(d, bgColor); } else if (key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) { handleBorderProperty(key, newValue); } } applyCustomBackground(); } if (nativeView != null) { nativeView.postInvalidate(); } } else if (key.equals(TiC.PROPERTY_SOFT_KEYBOARD_ON_FOCUS)) { Log.w(LCAT, "Focus state changed to " + TiConvert.toString(newValue) + " not honored until next focus event."); } else if (key.equals(TiC.PROPERTY_TRANSFORM)) { if (nativeView != null) { applyTransform((Ti2DMatrix)newValue); } } else { if (DBG) { Log.d(LCAT, "Unhandled property key: " + key); } } } public void processProperties(KrollDict d) { if (d.containsKey(TiC.PROPERTY_LAYOUT)) { String layout = TiConvert.toString(d, TiC.PROPERTY_LAYOUT); if (nativeView instanceof TiCompositeLayout) { ((TiCompositeLayout)nativeView).setLayoutArrangement(layout); } } if (TiConvert.fillLayout(d, layoutParams)) { if (nativeView != null) { nativeView.requestLayout(); } } Integer bgColor = null; // Default background processing. // Prefer image to color. if (hasImage(d) || hasColorState(d) || hasBorder(d)) { handleBackgroundImage(d); } else if (d.containsKey(TiC.PROPERTY_BACKGROUND_COLOR)) { bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); nativeView.setBackgroundColor(bgColor); } if (d.containsKey(TiC.PROPERTY_OPACITY)) { if (nativeView != null) { setOpacity(TiConvert.toFloat(d, TiC.PROPERTY_OPACITY)); } } if (d.containsKey(TiC.PROPERTY_VISIBLE)) { nativeView.setVisibility(TiConvert.toBoolean(d, TiC.PROPERTY_VISIBLE) ? View.VISIBLE : View.INVISIBLE); } if (d.containsKey(TiC.PROPERTY_ENABLED)) { nativeView.setEnabled(TiConvert.toBoolean(d, TiC.PROPERTY_ENABLED)); } if (d.containsKey(TiC.PROPERTY_FOCUSABLE)) { boolean focusable = TiConvert.toBoolean(d, TiC.PROPERTY_FOCUSABLE); nativeView.setFocusable(focusable); if (focusable) { registerForKeyClick(nativeView); } else { //nativeView.setOnClickListener(null); // ? mistake? I assume OnKeyListener was meant nativeView.setOnKeyListener(null); } } initializeBorder(d, bgColor); if (d.containsKey(TiC.PROPERTY_TRANSFORM)) { Ti2DMatrix matrix = (Ti2DMatrix) d.get(TiC.PROPERTY_TRANSFORM); if (matrix != null) { applyTransform(matrix); } } } @Override public void propertiesChanged(List<KrollPropertyChange> changes, KrollProxy proxy) { for (KrollPropertyChange change : changes) { propertyChanged(change.getName(), change.getOldValue(), change.getNewValue(), proxy); } } private void applyCustomBackground() { applyCustomBackground(true); } private void applyCustomBackground(boolean reuseCurrentDrawable) { if (nativeView != null) { if (background == null) { background = new TiBackgroundDrawable(); Drawable currentDrawable = nativeView.getBackground(); if (currentDrawable != null) { if (reuseCurrentDrawable) { background.setBackgroundDrawable(currentDrawable); } else { nativeView.setBackgroundDrawable(null); currentDrawable.setCallback(null); if (currentDrawable instanceof TiBackgroundDrawable) { ((TiBackgroundDrawable) currentDrawable).releaseDelegate(); } } } } nativeView.setBackgroundDrawable(background); } } public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { TiUIHelper.requestSoftInputChange(proxy, v); proxy.fireEvent(TiC.EVENT_FOCUS, getFocusEventObject(hasFocus)); } else { proxy.fireEvent(TiC.EVENT_BLUR, getFocusEventObject(hasFocus)); } } protected KrollDict getFocusEventObject(boolean hasFocus) { return null; } protected InputMethodManager getIMM() { InputMethodManager imm = null; imm = (InputMethodManager) proxy.getTiContext().getTiApp().getSystemService(Context.INPUT_METHOD_SERVICE); return imm; } public void focus() { if (nativeView != null) { nativeView.requestFocus(); } } public void blur() { if (nativeView != null) { InputMethodManager imm = getIMM(); if (imm != null) { imm.hideSoftInputFromWindow(nativeView.getWindowToken(), 0); } nativeView.clearFocus(); } } public void release() { if (DBG) { Log.d(LCAT, "Releasing: " + this); } View nv = getNativeView(); if (nv != null) { if (nv instanceof ViewGroup) { ViewGroup vg = (ViewGroup) nv; if (DBG) { Log.d(LCAT, "Group has: " + vg.getChildCount()); } if (!(vg instanceof AdapterView<?>)) { vg.removeAllViews(); } } Drawable d = nv.getBackground(); if (d != null) { nv.setBackgroundDrawable(null); d.setCallback(null); if (d instanceof TiBackgroundDrawable) { ((TiBackgroundDrawable)d).releaseDelegate(); } d = null; } nativeView = null; if (proxy != null) { proxy.setModelListener(null); } } } public void show() { if (nativeView != null) { nativeView.setVisibility(View.VISIBLE); } else { if (DBG) { Log.w(LCAT, "Attempt to show null native control"); } } } public void hide() { if (nativeView != null) { nativeView.setVisibility(View.INVISIBLE); } else { if (DBG) { Log.w(LCAT, "Attempt to hide null native control"); } } } private void handleBackgroundImage(KrollDict d) { String bg = d.getString(TiC.PROPERTY_BACKGROUND_IMAGE); String bgSelected = d.getString(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE); String bgFocused = d.getString(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE); String bgDisabled = d.getString(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE); String bgColor = d.getString(TiC.PROPERTY_BACKGROUND_COLOR); String bgSelectedColor = d.getString(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR); String bgFocusedColor = d.getString(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR); String bgDisabledColor = d.getString(TiC.PROPERTY_BACKGROUND_DISABLED_COLOR); TiContext tiContext = getProxy().getTiContext(); if (bg != null) { bg = tiContext.resolveUrl(null, bg); } if (bgSelected != null) { bgSelected = tiContext.resolveUrl(null, bgSelected); } if (bgFocused != null) { bgFocused = tiContext.resolveUrl(null, bgFocused); } if (bgDisabled != null) { bgDisabled = tiContext.resolveUrl(null, bgDisabled); } if (bg != null || bgSelected != null || bgFocused != null || bgDisabled != null || bgColor != null || bgSelectedColor != null || bgFocusedColor != null || bgDisabledColor != null) { if (background == null) { applyCustomBackground(false); } Drawable bgDrawable = TiUIHelper.buildBackgroundDrawable(tiContext, bg, bgColor, bgSelected, bgSelectedColor, bgDisabled, bgDisabledColor, bgFocused, bgFocusedColor); background.setBackgroundDrawable(bgDrawable); } } private void initializeBorder(KrollDict d, Integer bgColor) { if (d.containsKey(TiC.PROPERTY_BORDER_RADIUS) || d.containsKey(TiC.PROPERTY_BORDER_COLOR) || d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { if (background == null) { applyCustomBackground(); } if (background.getBorder() == null) { background.setBorder(new TiBackgroundDrawable.Border()); } TiBackgroundDrawable.Border border = background.getBorder(); if (d.containsKey(TiC.PROPERTY_BORDER_RADIUS)) { border.setRadius(TiConvert.toFloat(d, TiC.PROPERTY_BORDER_RADIUS)); } if (d.containsKey(TiC.PROPERTY_BORDER_COLOR) || d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { if (d.containsKey(TiC.PROPERTY_BORDER_COLOR)) { border.setColor(TiConvert.toColor(d, TiC.PROPERTY_BORDER_COLOR)); } else { if (bgColor != null) { border.setColor(bgColor); } } if (d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { border.setWidth(TiConvert.toFloat(d, TiC.PROPERTY_BORDER_WIDTH)); } } //applyCustomBackground(); } } private void handleBorderProperty(String property, Object value) { if (background.getBorder() == null) { background.setBorder(new TiBackgroundDrawable.Border()); } TiBackgroundDrawable.Border border = background.getBorder(); if (property.equals(TiC.PROPERTY_BORDER_COLOR)) { border.setColor(TiConvert.toColor(value.toString())); } else if (property.equals(TiC.PROPERTY_BORDER_RADIUS)) { border.setRadius(TiConvert.toFloat(value)); } else if (property.equals(TiC.PROPERTY_BORDER_WIDTH)) { border.setWidth(TiConvert.toFloat(value)); } applyCustomBackground(); } private static HashMap<Integer, String> motionEvents = new HashMap<Integer,String>(); static { motionEvents.put(MotionEvent.ACTION_DOWN, TiC.EVENT_TOUCH_START); motionEvents.put(MotionEvent.ACTION_UP, TiC.EVENT_TOUCH_END); motionEvents.put(MotionEvent.ACTION_MOVE, TiC.EVENT_TOUCH_MOVE); motionEvents.put(MotionEvent.ACTION_CANCEL, TiC.EVENT_TOUCH_CANCEL); } private KrollDict dictFromEvent(MotionEvent e) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_X, (double)e.getX()); data.put(TiC.EVENT_PROPERTY_Y, (double)e.getY()); data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); return data; } private KrollDict dictFromEvent(KrollDict dictToCopy){ KrollDict data = new KrollDict(); if (dictToCopy.containsKey(TiC.EVENT_PROPERTY_X)){ data.put(TiC.EVENT_PROPERTY_X, dictToCopy.get(TiC.EVENT_PROPERTY_X)); } else { data.put(TiC.EVENT_PROPERTY_X, (double)0); } if (dictToCopy.containsKey(TiC.EVENT_PROPERTY_Y)){ data.put(TiC.EVENT_PROPERTY_Y, dictToCopy.get(TiC.EVENT_PROPERTY_Y)); } else { data.put(TiC.EVENT_PROPERTY_Y, (double)0); } data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); return data; } protected boolean allowRegisterForTouch() { return true; } public void registerForTouch() { if (allowRegisterForTouch()) { registerForTouch(getNativeView()); } } protected void registerForTouch(final View touchable) { if (touchable == null) { return; } mTouchView = new WeakReference<View>(touchable); final GestureDetector detector = new GestureDetector(proxy.getTiContext().getActivity(), new SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { boolean handledTap = proxy.fireEvent(TiC.EVENT_DOUBLE_TAP, dictFromEvent(e)); boolean handledClick = proxy.fireEvent(TiC.EVENT_DOUBLE_CLICK, dictFromEvent(e)); return handledTap || handledClick; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (DBG) { Log.d(LCAT, "TAP, TAP, TAP on " + proxy); } boolean handledTap = proxy.fireEvent(TiC.EVENT_SINGLE_TAP, dictFromEvent(e)); // Moved click handling to the onTouch listener, because a single tap is not the // same as a click. A single tap is a quick tap only, whereas clicks can be held // before lifting. // boolean handledClick = proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(event)); // Note: this return value is irrelevant in our case. We "want" to use it // in onTouch below, when we call detector.onTouchEvent(event); But, in fact, // onSingleTapConfirmed is *not* called in the course of onTouchEvent. It's // called via Handler in GestureDetector. <-- See its Java source. return handledTap;// || handledClick; } }); touchable.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View view, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { lastUpEvent.put(TiC.EVENT_PROPERTY_X, (double)event.getX()); lastUpEvent.put(TiC.EVENT_PROPERTY_Y, (double)event.getY()); } boolean handled = detector.onTouchEvent(event); if (!handled && motionEvents.containsKey(event.getAction())) { if (event.getAction() == MotionEvent.ACTION_UP) { Rect r = new Rect(0, 0, view.getWidth(), view.getHeight()); int actualAction = r.contains((int)event.getX(), (int)event.getY()) ? MotionEvent.ACTION_UP : MotionEvent.ACTION_CANCEL; handled = proxy.fireEvent(motionEvents.get(actualAction), dictFromEvent(event)); if (handled && actualAction == MotionEvent.ACTION_UP) { // If this listener returns true, a click event does not occur, // because part of the Android View's default ACTION_UP handling // is to call performClick() which leads to invoking the click // listener. If we return true, that won't run, so we're doing it // here instead. touchable.performClick(); } return handled; } else { handled = proxy.fireEvent(motionEvents.get(event.getAction()), dictFromEvent(event)); } } return handled; } }); // Previously, we used the single tap handling above to fire our click event. It doesn't // work: a single tap is not the same as a click. A click can be held for a while before // lifting the finger; a single-tap is only generated from a quick tap (which will also cause // a click.) We wanted to do it in single-tap handling presumably because the singletap // listener gets a MotionEvent, which gives us the information we want to provide to our // users in our click event, whereas Android's standard OnClickListener does _not_ contain // that info. However, an "up" seems to always occur before the click listener gets invoked, // so we store the last up event's x,y coordinates (see onTouch above) and use them here. // Note: AdapterView throws an exception if you try to put a click listener on it. doSetClickable(touchable); } public void setOpacity(float opacity) { setOpacity(nativeView, opacity); } protected void setOpacity(View view, float opacity) { if (view != null) { TiUIHelper.setDrawableOpacity(view.getBackground(), opacity); if (opacity == 1) { clearOpacity(view); } view.invalidate(); } } public void clearOpacity(View view) { view.getBackground().clearColorFilter(); } protected void registerForKeyClick(View clickable) { clickable.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View view, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { switch(keyCode) { case KeyEvent.KEYCODE_ENTER : case KeyEvent.KEYCODE_DPAD_CENTER : if (proxy.hasListeners(TiC.EVENT_CLICK)) { proxy.fireEvent(TiC.EVENT_CLICK, null); return true; } } } return false; } }); } public KrollDict toImage() { return TiUIHelper.viewToImage(proxy.getTiContext(), proxy.getProperties(), getNativeView()); } private View getTouchView() { if (nativeView != null) { return nativeView; } else { if (mTouchView != null) { return mTouchView.get(); } } return null; } private void doSetClickable(View view, boolean clickable) { if (view == null) { return; } if (!clickable) { view.setOnClickListener(null); // This will set clickable to true in the view, so make sure it stays here so the next line turns it off. view.setClickable(false); } else if ( ! (view instanceof AdapterView) ){ // n.b.: AdapterView throws if click listener set. // n.b.: setting onclicklistener automatically sets clickable to true. view.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(lastUpEvent)); } }); } } private void doSetClickable(boolean clickable) { doSetClickable(getTouchView(), clickable); } /* * Used just to setup the click listener if applicable. */ private void doSetClickable(View view) { if (view == null) { return; } doSetClickable(view, view.isClickable()); } /* * Used just to setup the click listener if applicable. */ private void doSetClickable() { View view = getTouchView(); if (view == null) { return; } doSetClickable(view, view.isClickable()); } }
android/titanium/src/org/appcelerator/titanium/view/TiUIView.java
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2010 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package org.appcelerator.titanium.view; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollPropertyChange; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.KrollProxyListener; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.TiContext; import org.appcelerator.titanium.TiDimension; import org.appcelerator.titanium.proxy.TiViewProxy; import org.appcelerator.titanium.util.Log; import org.appcelerator.titanium.util.TiAnimationBuilder; import org.appcelerator.titanium.util.TiAnimationBuilder.TiMatrixAnimation; import org.appcelerator.titanium.util.TiConfig; import org.appcelerator.titanium.util.TiConvert; import org.appcelerator.titanium.util.TiUIHelper; import org.appcelerator.titanium.view.TiCompositeLayout.LayoutParams; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; public abstract class TiUIView implements KrollProxyListener, OnFocusChangeListener { private static final String LCAT = "TiUIView"; private static final boolean DBG = TiConfig.LOGD; private static AtomicInteger idGenerator; public static final int SOFT_KEYBOARD_DEFAULT_ON_FOCUS = 0; public static final int SOFT_KEYBOARD_HIDE_ON_FOCUS = 1; public static final int SOFT_KEYBOARD_SHOW_ON_FOCUS = 2; protected View nativeView; // Native View object protected TiViewProxy proxy; protected TiViewProxy parent; protected ArrayList<TiUIView> children = new ArrayList<TiUIView>(); protected LayoutParams layoutParams; protected int zIndex; protected TiAnimationBuilder animBuilder; protected TiBackgroundDrawable background; public TiUIView(TiViewProxy proxy) { if (idGenerator == null) { idGenerator = new AtomicInteger(0); } this.proxy = proxy; this.layoutParams = new TiCompositeLayout.LayoutParams(); } public void add(TiUIView child) { if (child != null) { View cv = child.getNativeView(); if (cv != null) { View nv = getNativeView(); if (nv instanceof ViewGroup) { if (cv.getParent() == null) { ((ViewGroup) nv).addView(cv, child.getLayoutParams()); } children.add(child); } } } } public void remove(TiUIView child) { if (child != null) { View cv = child.getNativeView(); if (cv != null) { View nv = getNativeView(); if (nv instanceof ViewGroup) { ((ViewGroup) nv).removeView(cv); children.remove(child); } } } } public List<TiUIView> getChildren() { return children; } public TiViewProxy getProxy() { return proxy; } public void setProxy(TiViewProxy proxy) { this.proxy = proxy; } public TiViewProxy getParent() { return parent; } public void setParent(TiViewProxy parent) { this.parent = parent; } public LayoutParams getLayoutParams() { return layoutParams; } public int getZIndex() { return zIndex; } public View getNativeView() { return nativeView; } protected void setNativeView(View view) { if (view.getId() == View.NO_ID) { view.setId(idGenerator.incrementAndGet()); } this.nativeView = view; boolean clickable = true; if (proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) { clickable = TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED)); } nativeView.setClickable(clickable); nativeView.setOnFocusChangeListener(this); } protected void setLayoutParams(LayoutParams layoutParams) { this.layoutParams = layoutParams; } protected void setZIndex(int index) { zIndex = index; } public void animate() { TiAnimationBuilder builder = proxy.getPendingAnimation(); if (builder != null && nativeView != null) { AnimationSet as = builder.render(proxy, nativeView); if (DBG) { Log.d(LCAT, "starting animation: "+as); } nativeView.startAnimation(as); // Clean up proxy proxy.clearAnimation(); } } public void listenerAdded(String type, int count, KrollProxy proxy) { } public void listenerRemoved(String type, int count, KrollProxy proxy){ } private boolean hasImage(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE); } private boolean hasBorder(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_RADIUS) || d.containsKeyAndNotNull(TiC.PROPERTY_BORDER_WIDTH); } private boolean hasColorState(KrollDict d) { return d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR) || d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR); } protected void applyTransform(Ti2DMatrix matrix) { layoutParams.optionTransform = matrix; if (animBuilder == null) { animBuilder = new TiAnimationBuilder(); } if (nativeView != null) { if (matrix != null) { TiMatrixAnimation matrixAnimation = animBuilder.createMatrixAnimation(matrix); matrixAnimation.interpolate = false; matrixAnimation.setDuration(1); matrixAnimation.setFillAfter(true); nativeView.startAnimation(matrixAnimation); } else { nativeView.clearAnimation(); } } } protected void layoutNativeView() { if (nativeView != null) { Animation a = nativeView.getAnimation(); if (a != null && a instanceof TiMatrixAnimation) { TiMatrixAnimation matrixAnimation = (TiMatrixAnimation) a; matrixAnimation.invalidateWithMatrix(nativeView); } nativeView.requestLayout(); } } public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (key.equals(TiC.PROPERTY_LEFT)) { if (newValue != null) { layoutParams.optionLeft = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_LEFT); } else { layoutParams.optionLeft = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_TOP)) { if (newValue != null) { layoutParams.optionTop = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_TOP); } else { layoutParams.optionTop = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_CENTER)) { TiConvert.updateLayoutCenter(newValue, layoutParams); layoutNativeView(); } else if (key.equals(TiC.PROPERTY_RIGHT)) { if (newValue != null) { layoutParams.optionRight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_RIGHT); } else { layoutParams.optionRight = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_BOTTOM)) { if (newValue != null) { layoutParams.optionBottom = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_BOTTOM); } else { layoutParams.optionBottom = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_SIZE)) { if (newValue instanceof KrollDict) { KrollDict d = (KrollDict)newValue; propertyChanged(TiC.PROPERTY_WIDTH, oldValue, d.get(TiC.PROPERTY_WIDTH), proxy); propertyChanged(TiC.PROPERTY_HEIGHT, oldValue, d.get(TiC.PROPERTY_HEIGHT), proxy); }else if (newValue != null){ Log.w(LCAT, "Unsupported property type ("+(newValue.getClass().getSimpleName())+") for key: " + key+". Must be an object/dictionary"); } } else if (key.equals(TiC.PROPERTY_HEIGHT)) { if (newValue != null) { if (!newValue.equals(TiC.SIZE_AUTO)) { layoutParams.optionHeight = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_HEIGHT); layoutParams.autoHeight = false; } else { layoutParams.optionHeight = null; layoutParams.autoHeight = true; } } else { layoutParams.optionHeight = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_WIDTH)) { if (newValue != null) { if (!newValue.equals(TiC.SIZE_AUTO)) { layoutParams.optionWidth = TiConvert.toTiDimension(TiConvert.toString(newValue), TiDimension.TYPE_WIDTH); layoutParams.autoWidth = false; } else { layoutParams.optionWidth = null; layoutParams.autoWidth = true; } } else { layoutParams.optionWidth = null; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_ZINDEX)) { if (newValue != null) { layoutParams.optionZIndex = TiConvert.toInt(TiConvert.toString(newValue)); } else { layoutParams.optionZIndex = 0; } layoutNativeView(); } else if (key.equals(TiC.PROPERTY_FOCUSABLE)) { boolean focusable = TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_FOCUSABLE)); nativeView.setFocusable(focusable); if (focusable) { registerForKeyClick(nativeView); } else { nativeView.setOnClickListener(null); } } else if (key.equals(TiC.PROPERTY_TOUCH_ENABLED)) { nativeView.setClickable(TiConvert.toBoolean(newValue)); } else if (key.equals(TiC.PROPERTY_VISIBLE)) { nativeView.setVisibility(TiConvert.toBoolean(newValue) ? View.VISIBLE : View.INVISIBLE); } else if (key.equals(TiC.PROPERTY_ENABLED)) { nativeView.setEnabled(TiConvert.toBoolean(newValue)); } else if (key.startsWith(TiC.PROPERTY_BACKGROUND_PADDING)) { Log.i(LCAT, key + " not yet implemented."); } else if (key.equals(TiC.PROPERTY_OPACITY) || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX) || key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) { // Update first before querying. proxy.setProperty(key, newValue, false); KrollDict d = proxy.getProperties(); boolean hasImage = hasImage(d); boolean hasColorState = hasColorState(d); boolean hasBorder = hasBorder(d); boolean requiresCustomBackground = hasImage || hasColorState || hasBorder; if (!requiresCustomBackground) { if (background != null) { background.releaseDelegate(); background.setCallback(null); background = null; } if (d.containsKeyAndNotNull(TiC.PROPERTY_BACKGROUND_COLOR)) { Integer bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); if (nativeView != null){ nativeView.setBackgroundColor(bgColor); nativeView.postInvalidate(); } } else { if (key.equals(TiC.PROPERTY_OPACITY)) { setOpacity(TiConvert.toFloat(newValue)); } if (nativeView != null) { nativeView.setBackgroundDrawable(null); nativeView.postInvalidate(); } } } else { boolean newBackground = background == null; if (newBackground) { background = new TiBackgroundDrawable(); } Integer bgColor = null; if (!hasColorState) { if (d.get(TiC.PROPERTY_BACKGROUND_COLOR) != null) { bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); if (newBackground || (key.equals(TiC.PROPERTY_OPACITY) || key.equals(TiC.PROPERTY_BACKGROUND_COLOR))) { background.setBackgroundColor(bgColor); } } } if (hasImage || hasColorState) { if (newBackground || key.startsWith(TiC.PROPERTY_BACKGROUND_PREFIX)) { handleBackgroundImage(d); } } if (hasBorder) { if (newBackground) { initializeBorder(d, bgColor); } else if (key.startsWith(TiC.PROPERTY_BORDER_PREFIX)) { handleBorderProperty(key, newValue); } } applyCustomBackground(); } if (nativeView != null) { nativeView.postInvalidate(); } } else if (key.equals(TiC.PROPERTY_SOFT_KEYBOARD_ON_FOCUS)) { Log.w(LCAT, "Focus state changed to " + TiConvert.toString(newValue) + " not honored until next focus event."); } else if (key.equals(TiC.PROPERTY_TRANSFORM)) { if (nativeView != null) { applyTransform((Ti2DMatrix)newValue); } } else { if (DBG) { Log.d(LCAT, "Unhandled property key: " + key); } } } public void processProperties(KrollDict d) { if (d.containsKey(TiC.PROPERTY_LAYOUT)) { String layout = TiConvert.toString(d, TiC.PROPERTY_LAYOUT); if (nativeView instanceof TiCompositeLayout) { ((TiCompositeLayout)nativeView).setLayoutArrangement(layout); } } if (TiConvert.fillLayout(d, layoutParams)) { if (nativeView != null) { nativeView.requestLayout(); } } Integer bgColor = null; // Default background processing. // Prefer image to color. if (hasImage(d) || hasColorState(d) || hasBorder(d)) { handleBackgroundImage(d); } else if (d.containsKey(TiC.PROPERTY_BACKGROUND_COLOR)) { bgColor = TiConvert.toColor(d, TiC.PROPERTY_BACKGROUND_COLOR); nativeView.setBackgroundColor(bgColor); } if (d.containsKey(TiC.PROPERTY_OPACITY)) { if (nativeView != null) { setOpacity(TiConvert.toFloat(d, TiC.PROPERTY_OPACITY)); } } if (d.containsKey(TiC.PROPERTY_VISIBLE)) { nativeView.setVisibility(TiConvert.toBoolean(d, TiC.PROPERTY_VISIBLE) ? View.VISIBLE : View.INVISIBLE); } if (d.containsKey(TiC.PROPERTY_ENABLED)) { nativeView.setEnabled(TiConvert.toBoolean(d, TiC.PROPERTY_ENABLED)); } if (d.containsKey(TiC.PROPERTY_FOCUSABLE)) { boolean focusable = TiConvert.toBoolean(d, TiC.PROPERTY_FOCUSABLE); nativeView.setFocusable(focusable); if (focusable) { registerForKeyClick(nativeView); } else { nativeView.setOnClickListener(null); } } initializeBorder(d, bgColor); if (d.containsKey(TiC.PROPERTY_TRANSFORM)) { Ti2DMatrix matrix = (Ti2DMatrix) d.get(TiC.PROPERTY_TRANSFORM); if (matrix != null) { applyTransform(matrix); } } } @Override public void propertiesChanged(List<KrollPropertyChange> changes, KrollProxy proxy) { for (KrollPropertyChange change : changes) { propertyChanged(change.getName(), change.getOldValue(), change.getNewValue(), proxy); } } private void applyCustomBackground() { applyCustomBackground(true); } private void applyCustomBackground(boolean reuseCurrentDrawable) { if (nativeView != null) { if (background == null) { background = new TiBackgroundDrawable(); Drawable currentDrawable = nativeView.getBackground(); if (currentDrawable != null) { if (reuseCurrentDrawable) { background.setBackgroundDrawable(currentDrawable); } else { nativeView.setBackgroundDrawable(null); currentDrawable.setCallback(null); if (currentDrawable instanceof TiBackgroundDrawable) { ((TiBackgroundDrawable) currentDrawable).releaseDelegate(); } } } } nativeView.setBackgroundDrawable(background); } } public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { TiUIHelper.requestSoftInputChange(proxy, v); proxy.fireEvent(TiC.EVENT_FOCUS, getFocusEventObject(hasFocus)); } else { proxy.fireEvent(TiC.EVENT_BLUR, getFocusEventObject(hasFocus)); } } protected KrollDict getFocusEventObject(boolean hasFocus) { return null; } protected InputMethodManager getIMM() { InputMethodManager imm = null; imm = (InputMethodManager) proxy.getTiContext().getTiApp().getSystemService(Context.INPUT_METHOD_SERVICE); return imm; } public void focus() { if (nativeView != null) { nativeView.requestFocus(); } } public void blur() { if (nativeView != null) { InputMethodManager imm = getIMM(); if (imm != null) { imm.hideSoftInputFromWindow(nativeView.getWindowToken(), 0); } nativeView.clearFocus(); } } public void release() { if (DBG) { Log.d(LCAT, "Releasing: " + this); } View nv = getNativeView(); if (nv != null) { if (nv instanceof ViewGroup) { ViewGroup vg = (ViewGroup) nv; if (DBG) { Log.d(LCAT, "Group has: " + vg.getChildCount()); } if (!(vg instanceof AdapterView<?>)) { vg.removeAllViews(); } } Drawable d = nv.getBackground(); if (d != null) { nv.setBackgroundDrawable(null); d.setCallback(null); if (d instanceof TiBackgroundDrawable) { ((TiBackgroundDrawable)d).releaseDelegate(); } d = null; } nativeView = null; if (proxy != null) { proxy.setModelListener(null); } } } public void show() { if (nativeView != null) { nativeView.setVisibility(View.VISIBLE); } else { if (DBG) { Log.w(LCAT, "Attempt to show null native control"); } } } public void hide() { if (nativeView != null) { nativeView.setVisibility(View.INVISIBLE); } else { if (DBG) { Log.w(LCAT, "Attempt to hide null native control"); } } } private void handleBackgroundImage(KrollDict d) { String bg = d.getString(TiC.PROPERTY_BACKGROUND_IMAGE); String bgSelected = d.getString(TiC.PROPERTY_BACKGROUND_SELECTED_IMAGE); String bgFocused = d.getString(TiC.PROPERTY_BACKGROUND_FOCUSED_IMAGE); String bgDisabled = d.getString(TiC.PROPERTY_BACKGROUND_DISABLED_IMAGE); String bgColor = d.getString(TiC.PROPERTY_BACKGROUND_COLOR); String bgSelectedColor = d.getString(TiC.PROPERTY_BACKGROUND_SELECTED_COLOR); String bgFocusedColor = d.getString(TiC.PROPERTY_BACKGROUND_FOCUSED_COLOR); String bgDisabledColor = d.getString(TiC.PROPERTY_BACKGROUND_DISABLED_COLOR); TiContext tiContext = getProxy().getTiContext(); if (bg != null) { bg = tiContext.resolveUrl(null, bg); } if (bgSelected != null) { bgSelected = tiContext.resolveUrl(null, bgSelected); } if (bgFocused != null) { bgFocused = tiContext.resolveUrl(null, bgFocused); } if (bgDisabled != null) { bgDisabled = tiContext.resolveUrl(null, bgDisabled); } if (bg != null || bgSelected != null || bgFocused != null || bgDisabled != null || bgColor != null || bgSelectedColor != null || bgFocusedColor != null || bgDisabledColor != null) { if (background == null) { applyCustomBackground(false); } Drawable bgDrawable = TiUIHelper.buildBackgroundDrawable(tiContext, bg, bgColor, bgSelected, bgSelectedColor, bgDisabled, bgDisabledColor, bgFocused, bgFocusedColor); background.setBackgroundDrawable(bgDrawable); } } private void initializeBorder(KrollDict d, Integer bgColor) { if (d.containsKey(TiC.PROPERTY_BORDER_RADIUS) || d.containsKey(TiC.PROPERTY_BORDER_COLOR) || d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { if (background == null) { applyCustomBackground(); } if (background.getBorder() == null) { background.setBorder(new TiBackgroundDrawable.Border()); } TiBackgroundDrawable.Border border = background.getBorder(); if (d.containsKey(TiC.PROPERTY_BORDER_RADIUS)) { border.setRadius(TiConvert.toFloat(d, TiC.PROPERTY_BORDER_RADIUS)); } if (d.containsKey(TiC.PROPERTY_BORDER_COLOR) || d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { if (d.containsKey(TiC.PROPERTY_BORDER_COLOR)) { border.setColor(TiConvert.toColor(d, TiC.PROPERTY_BORDER_COLOR)); } else { if (bgColor != null) { border.setColor(bgColor); } } if (d.containsKey(TiC.PROPERTY_BORDER_WIDTH)) { border.setWidth(TiConvert.toFloat(d, TiC.PROPERTY_BORDER_WIDTH)); } } //applyCustomBackground(); } } private void handleBorderProperty(String property, Object value) { if (background.getBorder() == null) { background.setBorder(new TiBackgroundDrawable.Border()); } TiBackgroundDrawable.Border border = background.getBorder(); if (property.equals(TiC.PROPERTY_BORDER_COLOR)) { border.setColor(TiConvert.toColor(value.toString())); } else if (property.equals(TiC.PROPERTY_BORDER_RADIUS)) { border.setRadius(TiConvert.toFloat(value)); } else if (property.equals(TiC.PROPERTY_BORDER_WIDTH)) { border.setWidth(TiConvert.toFloat(value)); } applyCustomBackground(); } private static HashMap<Integer, String> motionEvents = new HashMap<Integer,String>(); static { motionEvents.put(MotionEvent.ACTION_DOWN, TiC.EVENT_TOUCH_START); motionEvents.put(MotionEvent.ACTION_UP, TiC.EVENT_TOUCH_END); motionEvents.put(MotionEvent.ACTION_MOVE, TiC.EVENT_TOUCH_MOVE); motionEvents.put(MotionEvent.ACTION_CANCEL, TiC.EVENT_TOUCH_CANCEL); } private KrollDict dictFromEvent(MotionEvent e) { KrollDict data = new KrollDict(); data.put(TiC.EVENT_PROPERTY_X, (double)e.getX()); data.put(TiC.EVENT_PROPERTY_Y, (double)e.getY()); data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); return data; } protected boolean allowRegisterForTouch() { return true; } public void registerForTouch() { if (allowRegisterForTouch()) { registerForTouch(getNativeView()); } } protected void registerForTouch(final View touchable) { if (touchable == null) { return; } final GestureDetector detector = new GestureDetector(proxy.getTiContext().getActivity(), new SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { boolean handledTap = proxy.fireEvent(TiC.EVENT_DOUBLE_TAP, dictFromEvent(e)); boolean handledClick = proxy.fireEvent(TiC.EVENT_DOUBLE_CLICK, dictFromEvent(e)); return handledTap || handledClick; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (DBG) { Log.d(LCAT, "TAP, TAP, TAP on " + proxy); } boolean handledTap = proxy.fireEvent(TiC.EVENT_SINGLE_TAP, dictFromEvent(e)); // Moved click handling to the onTouch listener, because a single tap is not the // same as a click. A single tap is a quick tap only, whereas clicks can be held // before lifting. // boolean handledClick = proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(event)); return handledTap;// || handledClick; } }); touchable.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View view, MotionEvent event) { boolean handled = detector.onTouchEvent(event); if (!handled && motionEvents.containsKey(event.getAction())) { if (event.getAction() == MotionEvent.ACTION_UP) { Rect r = new Rect(0, 0, view.getWidth(), view.getHeight()); int actualAction = r.contains((int)event.getX(), (int)event.getY()) ? MotionEvent.ACTION_UP : MotionEvent.ACTION_CANCEL; handled = proxy.fireEvent(motionEvents.get(actualAction), dictFromEvent(event)); if (handled && actualAction == MotionEvent.ACTION_UP) { // If this listener returns true, a click event does not occur, // because part of the Android View's default ACTION_UP handling // is to call performClick() which leads to invoking the click // listener. If we return true, that won't run, so we're doing it // here instead. touchable.performClick(); } return handled; } else { handled = proxy.fireEvent(motionEvents.get(event.getAction()), dictFromEvent(event)); } } return handled; } }); touchable.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { proxy.fireEvent(TiC.EVENT_CLICK, null); } }); } public void setOpacity(float opacity) { setOpacity(nativeView, opacity); } protected void setOpacity(View view, float opacity) { if (view != null) { TiUIHelper.setDrawableOpacity(view.getBackground(), opacity); if (opacity == 1) { clearOpacity(view); } view.invalidate(); } } public void clearOpacity(View view) { view.getBackground().clearColorFilter(); } protected void registerForKeyClick(View clickable) { clickable.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View view, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { switch(keyCode) { case KeyEvent.KEYCODE_ENTER : case KeyEvent.KEYCODE_DPAD_CENTER : if (proxy.hasListeners(TiC.EVENT_CLICK)) { proxy.fireEvent(TiC.EVENT_CLICK, null); return true; } } } return false; } }); } public KrollDict toImage() { return TiUIHelper.viewToImage(proxy.getTiContext(), proxy.getProperties(), getNativeView()); } }
Make sure click listener not firing if touchable has been set to false. [#2844]
android/titanium/src/org/appcelerator/titanium/view/TiUIView.java
Make sure click listener not firing if touchable has been set to false. [#2844]
<ide><path>ndroid/titanium/src/org/appcelerator/titanium/view/TiUIView.java <ide> package org.appcelerator.titanium.view; <ide> <ide> <add>import java.lang.ref.WeakReference; <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> protected TiAnimationBuilder animBuilder; <ide> protected TiBackgroundDrawable background; <ide> <add> private KrollDict lastUpEvent = new KrollDict(2); <add> // In the case of heavy-weight windows, the "nativeView" is null, <add> // so this holds a reference to the view which is used for touching, <add> // i.e., the view passed to registerForTouch. <add> private WeakReference<View> mTouchView = null; <add> <ide> public TiUIView(TiViewProxy proxy) <ide> { <ide> if (idGenerator == null) { <ide> if (proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)) { <ide> clickable = TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED)); <ide> } <del> nativeView.setClickable(clickable); <add> doSetClickable(nativeView, clickable); <ide> nativeView.setOnFocusChangeListener(this); <ide> } <ide> <ide> if (focusable) { <ide> registerForKeyClick(nativeView); <ide> } else { <del> nativeView.setOnClickListener(null); <add> //nativeView.setOnClickListener(null); // ? mistake? I assume OnKeyListener was meant <add> nativeView.setOnKeyListener(null); <ide> } <ide> } else if (key.equals(TiC.PROPERTY_TOUCH_ENABLED)) { <del> nativeView.setClickable(TiConvert.toBoolean(newValue)); <add> doSetClickable(TiConvert.toBoolean(newValue)); <ide> } else if (key.equals(TiC.PROPERTY_VISIBLE)) { <ide> nativeView.setVisibility(TiConvert.toBoolean(newValue) ? View.VISIBLE : View.INVISIBLE); <ide> } else if (key.equals(TiC.PROPERTY_ENABLED)) { <ide> if (focusable) { <ide> registerForKeyClick(nativeView); <ide> } else { <del> nativeView.setOnClickListener(null); <add> //nativeView.setOnClickListener(null); // ? mistake? I assume OnKeyListener was meant <add> nativeView.setOnKeyListener(null); <ide> } <ide> } <ide> <ide> data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); <ide> return data; <ide> } <add> private KrollDict dictFromEvent(KrollDict dictToCopy){ <add> KrollDict data = new KrollDict(); <add> if (dictToCopy.containsKey(TiC.EVENT_PROPERTY_X)){ <add> data.put(TiC.EVENT_PROPERTY_X, dictToCopy.get(TiC.EVENT_PROPERTY_X)); <add> } else { <add> data.put(TiC.EVENT_PROPERTY_X, (double)0); <add> } <add> if (dictToCopy.containsKey(TiC.EVENT_PROPERTY_Y)){ <add> data.put(TiC.EVENT_PROPERTY_Y, dictToCopy.get(TiC.EVENT_PROPERTY_Y)); <add> } else { <add> data.put(TiC.EVENT_PROPERTY_Y, (double)0); <add> } <add> data.put(TiC.EVENT_PROPERTY_SOURCE, proxy); <add> return data; <add> } <ide> <ide> protected boolean allowRegisterForTouch() <ide> { <ide> if (touchable == null) { <ide> return; <ide> } <add> mTouchView = new WeakReference<View>(touchable); <ide> final GestureDetector detector = new GestureDetector(proxy.getTiContext().getActivity(), <ide> new SimpleOnGestureListener() { <ide> @Override <ide> boolean handledClick = proxy.fireEvent(TiC.EVENT_DOUBLE_CLICK, dictFromEvent(e)); <ide> return handledTap || handledClick; <ide> } <del> <ide> @Override <ide> public boolean onSingleTapConfirmed(MotionEvent e) { <del> if (DBG) { <del> Log.d(LCAT, "TAP, TAP, TAP on " + proxy); <del> } <add> if (DBG) { Log.d(LCAT, "TAP, TAP, TAP on " + proxy); } <ide> boolean handledTap = proxy.fireEvent(TiC.EVENT_SINGLE_TAP, dictFromEvent(e)); <ide> // Moved click handling to the onTouch listener, because a single tap is not the <ide> // same as a click. A single tap is a quick tap only, whereas clicks can be held <ide> // before lifting. <ide> // boolean handledClick = proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(event)); <add> // Note: this return value is irrelevant in our case. We "want" to use it <add> // in onTouch below, when we call detector.onTouchEvent(event); But, in fact, <add> // onSingleTapConfirmed is *not* called in the course of onTouchEvent. It's <add> // called via Handler in GestureDetector. <-- See its Java source. <ide> return handledTap;// || handledClick; <ide> } <ide> }); <ide> <ide> touchable.setOnTouchListener(new OnTouchListener() { <ide> public boolean onTouch(View view, MotionEvent event) { <add> if (event.getAction() == MotionEvent.ACTION_UP) { <add> lastUpEvent.put(TiC.EVENT_PROPERTY_X, (double)event.getX()); <add> lastUpEvent.put(TiC.EVENT_PROPERTY_Y, (double)event.getY()); <add> } <ide> boolean handled = detector.onTouchEvent(event); <ide> if (!handled && motionEvents.containsKey(event.getAction())) { <ide> if (event.getAction() == MotionEvent.ACTION_UP) { <ide> return handled; <ide> } <ide> }); <del> touchable.setOnClickListener(new OnClickListener() <del> { <del> @Override <del> public void onClick(View view) <del> { <del> proxy.fireEvent(TiC.EVENT_CLICK, null); <del> } <del> }); <add> <add> // Previously, we used the single tap handling above to fire our click event. It doesn't <add> // work: a single tap is not the same as a click. A click can be held for a while before <add> // lifting the finger; a single-tap is only generated from a quick tap (which will also cause <add> // a click.) We wanted to do it in single-tap handling presumably because the singletap <add> // listener gets a MotionEvent, which gives us the information we want to provide to our <add> // users in our click event, whereas Android's standard OnClickListener does _not_ contain <add> // that info. However, an "up" seems to always occur before the click listener gets invoked, <add> // so we store the last up event's x,y coordinates (see onTouch above) and use them here. <add> // Note: AdapterView throws an exception if you try to put a click listener on it. <add> doSetClickable(touchable); <ide> <ide> } <ide> public void setOpacity(float opacity) <ide> { <ide> return TiUIHelper.viewToImage(proxy.getTiContext(), proxy.getProperties(), getNativeView()); <ide> } <add> private View getTouchView() <add> { <add> if (nativeView != null) { <add> return nativeView; <add> } else { <add> if (mTouchView != null) { <add> return mTouchView.get(); <add> } <add> } <add> return null; <add> } <add> private void doSetClickable(View view, boolean clickable) <add> { <add> if (view == null) { <add> return; <add> } <add> if (!clickable) { <add> view.setOnClickListener(null); // This will set clickable to true in the view, so make sure it stays here so the next line turns it off. <add> view.setClickable(false); <add> } else if ( ! (view instanceof AdapterView) ){ <add> // n.b.: AdapterView throws if click listener set. <add> // n.b.: setting onclicklistener automatically sets clickable to true. <add> view.setOnClickListener(new OnClickListener() <add> { <add> @Override <add> public void onClick(View view) <add> { <add> proxy.fireEvent(TiC.EVENT_CLICK, dictFromEvent(lastUpEvent)); <add> } <add> }); <add> } <add> } <add> private void doSetClickable(boolean clickable) <add> { <add> doSetClickable(getTouchView(), clickable); <add> } <add> /* <add> * Used just to setup the click listener if applicable. <add> */ <add> private void doSetClickable(View view) <add> { <add> if (view == null) { <add> return; <add> } <add> doSetClickable(view, view.isClickable()); <add> } <add> /* <add> * Used just to setup the click listener if applicable. <add> */ <add> private void doSetClickable() <add> { <add> View view = getTouchView(); <add> if (view == null) { <add> return; <add> } <add> doSetClickable(view, view.isClickable()); <add> } <ide> }
Java
mit
f4be44edd861a9531235667850d92f89b0f597ba
0
andersonlucasg3/Java.Binary
package br.com.insanitech.javabinary.storage; import android.support.annotation.NonNull; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import br.com.insanitech.javabinary.exceptions.DataInputReadException; /** * Created by anderson on 27/06/2017. */ public class DataReader extends Data { private int position = 0; private byte[] buffer; public DataReader(@NonNull byte[] buffer) { this.buffer = buffer; } public DataReader(DataWriter writer) { this(writer.outputStream.toByteArray()); } public int position() { return this.position; } @Override public int length() { return this.buffer.length; } public Byte readByte() throws DataInputReadException { byte[] bytes = new byte[1]; this.readBytes(bytes, 1); return bytes[0]; } public Short readShort() throws DataInputReadException { byte[] bytes = new byte[2]; this.readBytes(bytes, 2); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 2).order(ByteOrder.BIG_ENDIAN); return buffer.asShortBuffer().get(); } public Integer readInt() throws DataInputReadException { byte[] bytes = new byte[4]; this.readBytes(bytes, 4); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 4).order(ByteOrder.BIG_ENDIAN); return buffer.asIntBuffer().get(); } public Long readLong() throws DataInputReadException { byte[] bytes = new byte[8]; this.readBytes(bytes, 8); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 8).order(ByteOrder.BIG_ENDIAN); return buffer.asLongBuffer().get(); } public Float readFloat() throws DataInputReadException { byte[] bytes = new byte[4]; this.readBytes(bytes, 4); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 4).order(ByteOrder.BIG_ENDIAN); return buffer.asFloatBuffer().get(); } public Double readDouble() throws DataInputReadException { byte[] bytes = new byte[8]; this.readBytes(bytes, 8); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 8).order(ByteOrder.BIG_ENDIAN); return buffer.asDoubleBuffer().get(); } public void readBytes(byte[] buffer, int length) throws DataInputReadException { int available = this.buffer.length - this.position; int read = length <= available ? length : available; System.arraycopy(this.buffer, this.position, buffer, 0, read); this.position += read; if (read != length) { throw new DataInputReadException(length, read); } } public Data readData(int length) throws DataInputReadException { byte[] buffer = new byte[length]; this.readBytes(buffer, length); return new DataReader(buffer); } public String readString(int length) throws DataInputReadException { byte[] buffer = new byte[length]; this.readBytes(buffer, length); return new String(buffer, Charset.forName("UTF-8")); } public void seek(int position) { this.position = position; } }
java.binary/src/main/java/br/com/insanitech/javabinary/storage/DataReader.java
package br.com.insanitech.javabinary.storage; import android.support.annotation.NonNull; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; import br.com.insanitech.javabinary.exceptions.DataInputReadException; /** * Created by anderson on 27/06/2017. */ public class DataReader extends Data { private int position = 0; private byte[] buffer; public DataReader(@NonNull byte[] buffer) { this.buffer = buffer; } public DataReader(DataWriter writer) { this(writer.outputStream.toByteArray()); } public int position() { return this.position; } @Override public int length() throws IOException { return this.buffer.length; } public Byte readByte() throws IOException { Byte value = this.buffer[this.position]; this.position += 1; return value; } public Short readShort() throws IOException { byte[] bytes = new byte[2]; this.readBytes(bytes, 2); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 2).order(ByteOrder.BIG_ENDIAN); return buffer.asShortBuffer().get(); } public Integer readInt() throws IOException { byte[] bytes = new byte[4]; this.readBytes(bytes, 4); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 4).order(ByteOrder.BIG_ENDIAN); return buffer.asIntBuffer().get(); } public Long readLong() throws IOException { byte[] bytes = new byte[8]; this.readBytes(bytes, 8); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 8).order(ByteOrder.BIG_ENDIAN); return buffer.asLongBuffer().get(); } public Float readFloat() throws IOException { byte[] bytes = new byte[4]; this.readBytes(bytes, 4); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 4).order(ByteOrder.BIG_ENDIAN); return buffer.asFloatBuffer().get(); } public Double readDouble() throws IOException { byte[] bytes = new byte[8]; this.readBytes(bytes, 8); ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, 8).order(ByteOrder.BIG_ENDIAN); return buffer.asDoubleBuffer().get(); } public void readBytes(byte[] buffer, int length) throws IOException { int available = this.buffer.length - this.position; int read = length <= available ? length : available; System.arraycopy(this.buffer, this.position, buffer, 0, read); this.position += read; if (read != length) { throw new DataInputReadException(length, read); } } public Data readData(int length) throws IOException { byte[] buffer = new byte[length]; this.readBytes(buffer, length); return new DataReader(buffer); } public String readString(int length) throws IOException { byte[] buffer = new byte[length]; this.readBytes(buffer, length); return new String(buffer, Charset.forName("UTF-8")); } public void seek(int position) throws IOException { this.position = position; } }
Fixed implementation of DataReader class that was throwing exception in the length() method for no reason;
java.binary/src/main/java/br/com/insanitech/javabinary/storage/DataReader.java
Fixed implementation of DataReader class that was throwing exception in the length() method for no reason;
<ide><path>ava.binary/src/main/java/br/com/insanitech/javabinary/storage/DataReader.java <ide> <ide> import android.support.annotation.NonNull; <ide> <del>import java.io.IOException; <ide> import java.nio.ByteBuffer; <ide> import java.nio.ByteOrder; <ide> import java.nio.charset.Charset; <ide> } <ide> <ide> @Override <del> public int length() throws IOException { <add> public int length() { <ide> return this.buffer.length; <ide> } <ide> <del> public Byte readByte() throws IOException { <del> Byte value = this.buffer[this.position]; <del> this.position += 1; <del> return value; <add> public Byte readByte() throws DataInputReadException { <add> byte[] bytes = new byte[1]; <add> this.readBytes(bytes, 1); <add> <add> return bytes[0]; <ide> } <ide> <del> public Short readShort() throws IOException { <add> public Short readShort() throws DataInputReadException { <ide> byte[] bytes = new byte[2]; <ide> this.readBytes(bytes, 2); <ide> <ide> return buffer.asShortBuffer().get(); <ide> } <ide> <del> public Integer readInt() throws IOException { <add> public Integer readInt() throws DataInputReadException { <ide> byte[] bytes = new byte[4]; <ide> this.readBytes(bytes, 4); <ide> <ide> return buffer.asIntBuffer().get(); <ide> } <ide> <del> public Long readLong() throws IOException { <add> public Long readLong() throws DataInputReadException { <ide> byte[] bytes = new byte[8]; <ide> this.readBytes(bytes, 8); <ide> <ide> return buffer.asLongBuffer().get(); <ide> } <ide> <del> public Float readFloat() throws IOException { <add> public Float readFloat() throws DataInputReadException { <ide> byte[] bytes = new byte[4]; <ide> this.readBytes(bytes, 4); <ide> <ide> return buffer.asFloatBuffer().get(); <ide> } <ide> <del> public Double readDouble() throws IOException { <add> public Double readDouble() throws DataInputReadException { <ide> byte[] bytes = new byte[8]; <ide> this.readBytes(bytes, 8); <ide> <ide> return buffer.asDoubleBuffer().get(); <ide> } <ide> <del> public void readBytes(byte[] buffer, int length) throws IOException { <add> public void readBytes(byte[] buffer, int length) throws DataInputReadException { <ide> int available = this.buffer.length - this.position; <ide> int read = length <= available ? length : available; <ide> <ide> } <ide> } <ide> <del> public Data readData(int length) throws IOException { <add> public Data readData(int length) throws DataInputReadException { <ide> byte[] buffer = new byte[length]; <ide> this.readBytes(buffer, length); <ide> return new DataReader(buffer); <ide> } <ide> <del> public String readString(int length) throws IOException { <add> public String readString(int length) throws DataInputReadException { <ide> byte[] buffer = new byte[length]; <ide> this.readBytes(buffer, length); <ide> return new String(buffer, Charset.forName("UTF-8")); <ide> } <ide> <del> public void seek(int position) throws IOException { <add> public void seek(int position) { <ide> this.position = position; <ide> } <ide> }
Java
apache-2.0
995934d2abcad9063b35d35b2593220cd93a22ae
0
mikesamuel/code-interlingua,mikesamuel/code-interlingua
package com.mikesamuel.cil.parser; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; import com.google.common.base.Preconditions; import com.mikesamuel.cil.ast.MatchEvent; /** * State of a parse. */ public final class ParseState { /** The input to parse. */ public final Input input; /** The position of the parse cursor in the index. */ public final int index; /** The output which can be replayed for a tree builder. */ public final @Nullable Chain<MatchEvent> output; /** Cache the index after ignorable tokens like spaces and comments. */ private int indexAfterIgnorable = -1; /** A parse state at the beginning of input with no output. */ public ParseState(Input input) { this(input, 0, null); } private ParseState( Input input, int index, @Nullable Chain<? extends MatchEvent> output) { Preconditions.checkState(0 <= index && index <= input.content.length()); this.input = input; this.index = index; this.output = output != null ? Chain.<MatchEvent>copyOf(output) : null; } /** True if no unprocessed input except for ignorable tokens. */ public boolean isEmpty() { return indexAfterIgnorables() == input.content.length(); } /** * A state whose parse point is n chars forward of the specified parse * position. * @param afterIgnorable true if characters should be counted from * {@link #indexAfterIgnorables()} instead of {@link #index}. */ public ParseState advance(int n, boolean afterIgnorable) { Preconditions.checkArgument(n >= 0); int newIndex = (afterIgnorable ? this.indexAfterIgnorables() : index) + n; if (newIndex == index) { return this; } Preconditions.checkState(newIndex <= input.content.length()); return withIndex(newIndex); } /** A state like this but with the given event appended. */ public ParseState appendOutput(MatchEvent e) { return withOutput(Chain.append(output, e)); } /** * A state like this but with the given output. */ public ParseState withOutput(Chain<? extends MatchEvent> newOutput) { ParseState ps = new ParseState(input, index, newOutput); ps.indexAfterIgnorable = this.indexAfterIgnorable; return ps; } /** * A state like this but with the given input index. */ public ParseState withIndex(int newIndex) { return new ParseState(input, newIndex, output); } /** * True if the next token after any ignorable tokens has the given text. * Since this parser is scannerless, this will return true if the given text * is a prefix of the next token. */ public boolean startsWith(String text) { return input.content.regionMatches( indexAfterIgnorables(), text, 0, text.length()); } /** * A matcher for the given pattern at the index after any ignorable tokens. */ public Matcher matcherAtStart(Pattern p) { Matcher m = p.matcher(input.content); m.region(indexAfterIgnorables(), input.content.length()); m.useTransparentBounds(false); m.useAnchoringBounds(true); return m; } private static final long SPACE_BITS = (1L << ' ') | (1L << '\t') | (1L << '\f') | (1L << '\r') | (1L << '\n'); /** The index after any ignorable tokens like spaces and comments. */ public int indexAfterIgnorables() { if (this.indexAfterIgnorable < 0) { int idx; String content = input.content; int n = content.length(); ign_loop: for (idx = index; idx < n; ++idx) { char ch = content.charAt(idx); if (ch < 64) { if ((SPACE_BITS & (1L << ch)) != 0) { continue; } else if (ch == '/' && idx + 1 < n) { char ch1 = content.charAt(idx + 1); if (ch1 == '/') { int commentEnd = idx + 2; for (; commentEnd < n; ++commentEnd) { char commentChar = content.charAt(commentEnd); if (commentChar == '\r' || commentChar == '\n') { break; } } idx = commentEnd - 1; // increment above continue; } else if (ch1 == '*') { int commentEnd = idx + 2; for (; commentEnd < n; ++commentEnd) { char commentChar = content.charAt(commentEnd); if (commentChar == '*' && commentEnd + 1 < n) { if ('/' == content.charAt(commentEnd + 1)) { // Incremented past '/' by for loop. idx = commentEnd + (2 - 1); continue ign_loop; } } } break; // Unclosed comment. TODO: Should error out. } } } break; } indexAfterIgnorable = idx; } return indexAfterIgnorable; } @Override public String toString() { String content = input.content; String inputFragment; int fragmentEnd = index + 10; if (fragmentEnd >= content.length()) { inputFragment = content.substring( index, Math.min(fragmentEnd, content.length())); } else { inputFragment = content.substring(index, fragmentEnd) + "..."; } return "(ParseState index=" + index + ", input=`" + inputFragment + "`)"; } }
src/main/java/com/mikesamuel/cil/parser/ParseState.java
package com.mikesamuel.cil.parser; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; import com.google.common.base.Preconditions; import com.mikesamuel.cil.ast.MatchEvent; /** * State of a parse. */ public final class ParseState { /** The input to parse. */ public final Input input; /** The position of the parse cursor in the index. */ public final int index; /** The output which can be replayed for a tree builder. */ public final @Nullable Chain<MatchEvent> output; /** Cache the index after ignorable tokens like spaces and comments. */ private int indexAfterIgnorable = -1; /** A parse state at the beginning of input with no output. */ public ParseState(Input input) { this(input, 0, null); } private ParseState( Input input, int index, @Nullable Chain<? extends MatchEvent> output) { Preconditions.checkState(0 <= index && index <= input.content.length()); this.input = input; this.index = index; this.output = output != null ? Chain.<MatchEvent>copyOf(output) : null; } /** True if no unprocessed input except for ignorable tokens. */ public boolean isEmpty() { return indexAfterIgnorables() == input.content.length(); } /** * A state whose parse point is n chars forward of the specified parse * position. * @param afterIgnorable true if characters should be counted from * {@link #indexAfterIgnorables()} instead of {@link #index}. */ public ParseState advance(int n, boolean afterIgnorable) { Preconditions.checkArgument(n >= 0); int newIndex = (afterIgnorable ? this.indexAfterIgnorables() : index) + n; if (newIndex == index) { return this; } Preconditions.checkState(newIndex <= input.content.length()); return withIndex(newIndex); } /** A state like this but with the given event appended. */ public ParseState appendOutput(MatchEvent e) { return withOutput(Chain.append(output, e)); } /** * A state like this but with the given output. */ public ParseState withOutput(Chain<? extends MatchEvent> newOutput) { ParseState ps = new ParseState(input, index, newOutput); ps.indexAfterIgnorable = this.indexAfterIgnorable; return ps; } /** * A state like this but with the given input index. */ public ParseState withIndex(int newIndex) { return new ParseState(input, newIndex, output); } /** * True if the next token after any ignorable tokens has the given text. * Since this parser is scannerless, this will return true if the given text * is a prefix of the next token. */ public boolean startsWith(String text) { return input.content.regionMatches( indexAfterIgnorables(), text, 0, text.length()); } /** * A matcher for the given pattern at the index after any ignorable tokens. */ public Matcher matcherAtStart(Pattern p) { Matcher m = p.matcher(input.content); m.region(indexAfterIgnorables(), input.content.length()); m.useTransparentBounds(false); m.useAnchoringBounds(true); return m; } private static final long SPACE_BITS = (1L << ' ') | (1L << '\t') | (1L << '\f') | (1L << '\r') | (1L << '\n'); /** The index after any ignorable tokens like spaces and comments. */ public int indexAfterIgnorables() { if (this.indexAfterIgnorable < 0) { int idx; String content = input.content; int n = content.length(); ign_loop: for (idx = index; idx < n; ++idx) { char ch = content.charAt(idx); if (ch < 64) { if ((SPACE_BITS & (1L << ch)) != 0) { continue; } else if (ch == '/' && idx + 1 < n) { char ch1 = content.charAt(idx + 1); if (ch1 == '/') { int commentEnd = idx + 2; for (; commentEnd < n; ++commentEnd) { char commentChar = content.charAt(commentEnd); if (commentChar == '\r' || commentChar == '\n') { break; } } idx = commentEnd - 1; // increment above continue; } else if (ch1 == '*') { int commentEnd = idx + 2; for (; commentEnd < n; ++commentEnd) { char commentChar = content.charAt(commentEnd); if (commentChar == '*' && commentEnd + 1 < n) { if ('/' == content.charAt(commentEnd + 1)) { // Incremented past '/' by for loop. idx = commentEnd + (2 - 1); continue ign_loop; } } } break; // Unclosed comment. TODO: Should error out. } } } break; } indexAfterIgnorable = idx; } return indexAfterIgnorable; } }
better toString()
src/main/java/com/mikesamuel/cil/parser/ParseState.java
better toString()
<ide><path>rc/main/java/com/mikesamuel/cil/parser/ParseState.java <ide> } <ide> return indexAfterIgnorable; <ide> } <add> <add> @Override <add> public String toString() { <add> String content = input.content; <add> String inputFragment; <add> int fragmentEnd = index + 10; <add> if (fragmentEnd >= content.length()) { <add> inputFragment = content.substring( <add> index, Math.min(fragmentEnd, content.length())); <add> } else { <add> inputFragment = content.substring(index, fragmentEnd) + "..."; <add> } <add> return "(ParseState index=" + index + ", input=`" + inputFragment + "`)"; <add> } <ide> }
Java
apache-2.0
2297b25bc053f44423657218a32d621eea479c19
0
apache/mina-sshd,ieure/mina-sshd,AnyWareGroup/mina-sshd,landro/mina-sshd,apache/mina-sshd,apache/mina-sshd,lgoldstein/mina-sshd,lucastheisen/mina-sshd,avthart/mina-sshd,avthart/mina-sshd,ieure/mina-sshd,avthart/mina-sshd,lgoldstein/mina-sshd,lucastheisen/mina-sshd,cagney/mina-sshd-service,ieure/mina-sshd,apache/mina-sshd,lgoldstein/mina-sshd,fschopp/mina-sshd,lgoldstein/mina-sshd,fschopp/mina-sshd,cagney/mina-sshd-service,landro/mina-sshd,AnyWareGroup/mina-sshd,landro/mina-sshd
/* * 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.sshd.server.shell; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.sshd.server.Command; import org.apache.sshd.server.Environment; import org.apache.sshd.server.ExitCallback; /** * A shell implementation that wraps an instance of {@link InvertedShell} * as a {@link ShellFactory.Shell}. This is useful when using external * processes. * When starting the shell, this wrapper will also create a thread used * to pump the streams and also to check if the shell is alive. * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public class InvertedShellWrapper implements Command { /** default buffer size for the IO pumps. */ public static final int DEFAULT_BUFFER_SIZE = 8192; private final InvertedShell shell; private final int bufferSize; private InputStream in; private OutputStream out; private OutputStream err; private OutputStream shellIn; private InputStream shellOut; private InputStream shellErr; private ExitCallback callback; private Thread thread; public InvertedShellWrapper(InvertedShell shell) { this(shell, DEFAULT_BUFFER_SIZE); } public InvertedShellWrapper(InvertedShell shell, int bufferSize) { this.shell = shell; this.bufferSize = bufferSize; } public void setInputStream(InputStream in) { this.in = in; } public void setOutputStream(OutputStream out) { this.out = out; } public void setErrorStream(OutputStream err) { this.err = err; } public void setExitCallback(ExitCallback callback) { this.callback = callback; } public void start(Environment env) throws IOException { // TODO propagate the Environment itself and support signal sending. shell.start(env.getEnv()); shellIn = shell.getInputStream(); shellOut = shell.getOutputStream(); shellErr = shell.getErrorStream(); thread = new Thread("inverted-shell-pump") { @Override public void run() { pumpStreams(); } }; thread.start(); } public void destroy() { shell.destroy(); } protected void pumpStreams() { try { // Use a single thread to correctly sequence the output and error streams. // If any bytes are available from the output stream, send them first, then // check the error stream, or wait until more data is available. byte[] buffer = new byte[bufferSize]; for (;;) { if (!shell.isAlive()) { callback.onExit(shell.exitValue()); return; } if (pumpStream(in, shellIn, buffer)) { continue; } if (pumpStream(shellOut, out, buffer)) { continue; } if (pumpStream(shellErr, err, buffer)) { continue; } // Sleep a bit. This is not very good, as it consumes CPU, but the // input streams are not selectable for nio, and any other blocking // method would consume at least two threads Thread.sleep(1); } } catch (Exception e) { shell.destroy(); callback.onExit(shell.exitValue()); } } private boolean pumpStream(InputStream in, OutputStream out, byte[] buffer) throws IOException { if (in.available() > 0) { int len = in.read(buffer); if (len > 0) { out.write(buffer, 0, len); out.flush(); return true; } } return false; } }
sshd-core/src/main/java/org/apache/sshd/server/shell/InvertedShellWrapper.java
/* * 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.sshd.server.shell; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.sshd.server.Command; import org.apache.sshd.server.Environment; import org.apache.sshd.server.ExitCallback; /** * A shell implementation that wraps an instance of {@link InvertedShell} * as a {@link ShellFactory.Shell}. This is useful when using external * processes. * When starting the shell, this wrapper will also create a thread used * to pump the streams and also to check if the shell is alive. * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public class InvertedShellWrapper implements Command { private final InvertedShell shell; private InputStream in; private OutputStream out; private OutputStream err; private OutputStream shellIn; private InputStream shellOut; private InputStream shellErr; private ExitCallback callback; private Thread thread; public InvertedShellWrapper(InvertedShell shell) { this.shell = shell; } public void setInputStream(InputStream in) { this.in = in; } public void setOutputStream(OutputStream out) { this.out = out; } public void setErrorStream(OutputStream err) { this.err = err; } public void setExitCallback(ExitCallback callback) { this.callback = callback; } public void start(Environment env) throws IOException { // TODO propagate the Environment itself and support signal sending. shell.start(env.getEnv()); shellIn = shell.getInputStream(); shellOut = shell.getOutputStream(); shellErr = shell.getErrorStream(); thread = new Thread("inverted-shell-pump") { @Override public void run() { pumpStreams(); } }; thread.start(); } public void destroy() { shell.destroy(); } protected void pumpStreams() { try { // Use a single thread to correctly sequence the output and error streams. // If any bytes are available from the output stream, send them first, then // check the error stream, or wait until more data is available. byte[] buffer = new byte[512]; for (;;) { if (!shell.isAlive()) { callback.onExit(shell.exitValue()); return; } if (pumpStream(in, shellIn, buffer)) { continue; } if (pumpStream(shellOut, out, buffer)) { continue; } if (pumpStream(shellErr, err, buffer)) { continue; } // Sleep a bit. This is not very good, as it consumes CPU, but the // input streams are not selectable for nio, and any other blocking // method would consume at least two threads Thread.sleep(1); } } catch (Exception e) { shell.destroy(); callback.onExit(shell.exitValue()); } } private boolean pumpStream(InputStream in, OutputStream out, byte[] buffer) throws IOException { if (in.available() > 0) { int len = in.read(buffer); if (len > 0) { out.write(buffer, 0, len); out.flush(); return true; } } return false; } }
[SSHD-164] Allow the buffer size for the IO pumps to be configurable in InvertedShellWrapper git-svn-id: 35843eadeee557a5a63cf75912048491ca4c4b53@1340427 13f79535-47bb-0310-9956-ffa450edef68
sshd-core/src/main/java/org/apache/sshd/server/shell/InvertedShellWrapper.java
[SSHD-164] Allow the buffer size for the IO pumps to be configurable in InvertedShellWrapper
<ide><path>shd-core/src/main/java/org/apache/sshd/server/shell/InvertedShellWrapper.java <ide> */ <ide> public class InvertedShellWrapper implements Command { <ide> <add> /** default buffer size for the IO pumps. */ <add> public static final int DEFAULT_BUFFER_SIZE = 8192; <add> <ide> private final InvertedShell shell; <add> private final int bufferSize; <ide> private InputStream in; <ide> private OutputStream out; <ide> private OutputStream err; <ide> private Thread thread; <ide> <ide> public InvertedShellWrapper(InvertedShell shell) { <add> this(shell, DEFAULT_BUFFER_SIZE); <add> } <add> <add> public InvertedShellWrapper(InvertedShell shell, int bufferSize) { <ide> this.shell = shell; <add> this.bufferSize = bufferSize; <ide> } <ide> <ide> public void setInputStream(InputStream in) { <ide> // Use a single thread to correctly sequence the output and error streams. <ide> // If any bytes are available from the output stream, send them first, then <ide> // check the error stream, or wait until more data is available. <del> byte[] buffer = new byte[512]; <add> byte[] buffer = new byte[bufferSize]; <ide> for (;;) { <ide> if (!shell.isAlive()) { <ide> callback.onExit(shell.exitValue());
Java
apache-2.0
ecbe223558b5ba5dbe82c24031341e9a648ec7df
0
realityforge/arez,realityforge/arez,realityforge/arez
package arez.processor; import com.google.auto.common.GeneratedAnnotationSpecs; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; /** * The class that represents the parsed state of ArezComponent annotated class. */ @SuppressWarnings( "Duplicates" ) final class ComponentDescriptor { private static final Pattern OBSERVABLE_REF_PATTERN = Pattern.compile( "^get([A-Z].*)Observable$" ); private static final Pattern COMPUTED_VALUE_REF_PATTERN = Pattern.compile( "^get([A-Z].*)ComputedValue$" ); private static final Pattern OBSERVER_REF_PATTERN = Pattern.compile( "^get([A-Z].*)Observer$" ); private static final Pattern SETTER_PATTERN = Pattern.compile( "^set([A-Z].*)$" ); private static final Pattern GETTER_PATTERN = Pattern.compile( "^get([A-Z].*)$" ); private static final Pattern ID_GETTER_PATTERN = Pattern.compile( "^get([A-Z].*)Id$" ); private static final Pattern RAW_ID_GETTER_PATTERN = Pattern.compile( "^(.*)Id$" ); private static final Pattern ISSER_PATTERN = Pattern.compile( "^is([A-Z].*)$" ); private static final List<String> OBJECT_METHODS = Arrays.asList( "hashCode", "equals", "clone", "toString", "finalize", "getClass", "wait", "notifyAll", "notify" ); private static final List<String> AREZ_SPECIAL_METHODS = Arrays.asList( "observe", "dispose", "isDisposed", "getArezId" ); @Nullable private List<TypeElement> _repositoryExtensions; /** * Flag controlling whether dagger module is created for repository. */ private String _repositoryDaggerConfig = "AUTODETECT"; /** * Flag controlling whether Inject annotation is added to repository constructor. */ private String _repositoryInjectConfig = "AUTODETECT"; @Nonnull private final SourceVersion _sourceVersion; @Nonnull private final Elements _elements; @Nonnull private final Types _typeUtils; @Nonnull private final String _type; private final boolean _nameIncludesId; private final boolean _allowEmpty; private final boolean _observable; private final boolean _disposeTrackable; private final boolean _disposeOnDeactivate; private final boolean _injectClassesPresent; private final boolean _inject; private final boolean _dagger; /** * Annotation that indicates whether equals/hashCode should be implemented. See arez.annotations.ArezComponent.requireEquals() */ private final boolean _requireEquals; /** * Flag indicating whether generated component should implement arez.component.Verifiable. */ private final boolean _verify; /** * Scope annotation that is declared on component and should be transferred to injection providers. */ private final AnnotationMirror _scopeAnnotation; private final boolean _deferSchedule; private final boolean _generateToString; private boolean _idRequired; @Nonnull private final PackageElement _packageElement; @Nonnull private final TypeElement _element; @Nullable private ExecutableElement _postConstruct; @Nullable private ExecutableElement _componentId; @Nullable private ExecutableType _componentIdMethodType; @Nullable private ExecutableElement _componentRef; @Nullable private ExecutableElement _contextRef; @Nullable private ExecutableElement _componentTypeNameRef; @Nullable private ExecutableElement _componentNameRef; @Nullable private ExecutableElement _preDispose; @Nullable private ExecutableElement _postDispose; private final Map<String, CandidateMethod> _observerRefs = new LinkedHashMap<>(); private final Map<String, ObservableDescriptor> _observables = new LinkedHashMap<>(); private final Collection<ObservableDescriptor> _roObservables = Collections.unmodifiableCollection( _observables.values() ); private final Map<String, ActionDescriptor> _actions = new LinkedHashMap<>(); private final Collection<ActionDescriptor> _roActions = Collections.unmodifiableCollection( _actions.values() ); private final Map<String, ComputedDescriptor> _computeds = new LinkedHashMap<>(); private final Collection<ComputedDescriptor> _roComputeds = Collections.unmodifiableCollection( _computeds.values() ); private final Map<String, MemoizeDescriptor> _memoizes = new LinkedHashMap<>(); private final Collection<MemoizeDescriptor> _roMemoizes = Collections.unmodifiableCollection( _memoizes.values() ); private final Map<String, AutorunDescriptor> _autoruns = new LinkedHashMap<>(); private final Collection<AutorunDescriptor> _roAutoruns = Collections.unmodifiableCollection( _autoruns.values() ); private final Map<String, TrackedDescriptor> _trackeds = new LinkedHashMap<>(); private final Collection<TrackedDescriptor> _roTrackeds = Collections.unmodifiableCollection( _trackeds.values() ); private final Map<ExecutableElement, DependencyDescriptor> _dependencies = new LinkedHashMap<>(); private final Collection<DependencyDescriptor> _roDependencies = Collections.unmodifiableCollection( _dependencies.values() ); private final Map<String, ReferenceDescriptor> _references = new LinkedHashMap<>(); private final Collection<ReferenceDescriptor> _roReferences = Collections.unmodifiableCollection( _references.values() ); private final Map<String, InverseDescriptor> _inverses = new LinkedHashMap<>(); private final Collection<InverseDescriptor> _roInverses = Collections.unmodifiableCollection( _inverses.values() ); ComponentDescriptor( @Nonnull final SourceVersion sourceVersion, @Nonnull final Elements elements, @Nonnull final Types typeUtils, @Nonnull final String type, final boolean nameIncludesId, final boolean allowEmpty, final boolean observable, final boolean disposeTrackable, final boolean disposeOnDeactivate, final boolean injectClassesPresent, final boolean inject, final boolean dagger, final boolean requireEquals, final boolean verify, @Nullable final AnnotationMirror scopeAnnotation, final boolean deferSchedule, final boolean generateToString, @Nonnull final PackageElement packageElement, @Nonnull final TypeElement element ) { _sourceVersion = Objects.requireNonNull( sourceVersion ); _elements = Objects.requireNonNull( elements ); _typeUtils = Objects.requireNonNull( typeUtils ); _type = Objects.requireNonNull( type ); _nameIncludesId = nameIncludesId; _allowEmpty = allowEmpty; _observable = observable; _disposeTrackable = disposeTrackable; _disposeOnDeactivate = disposeOnDeactivate; _injectClassesPresent = injectClassesPresent; _inject = inject; _dagger = dagger; _requireEquals = requireEquals; _verify = verify; _scopeAnnotation = scopeAnnotation; _deferSchedule = deferSchedule; _generateToString = generateToString; _packageElement = Objects.requireNonNull( packageElement ); _element = Objects.requireNonNull( element ); } private boolean hasDeprecatedElements() { return isDeprecated( _postConstruct ) || isDeprecated( _componentId ) || isDeprecated( _componentRef ) || isDeprecated( _contextRef ) || isDeprecated( _componentTypeNameRef ) || isDeprecated( _componentNameRef ) || isDeprecated( _preDispose ) || isDeprecated( _postDispose ) || _roObservables.stream().anyMatch( e -> ( e.hasSetter() && isDeprecated( e.getSetter() ) ) || ( e.hasGetter() && isDeprecated( e.getGetter() ) ) ) || _roComputeds.stream().anyMatch( e -> ( e.hasComputed() && isDeprecated( e.getComputed() ) ) || isDeprecated( e.getOnActivate() ) || isDeprecated( e.getOnDeactivate() ) || isDeprecated( e.getOnStale() ) || isDeprecated( e.getOnDispose() ) ) || _observerRefs.values().stream().anyMatch( e -> isDeprecated( e.getMethod() ) ) || _roDependencies.stream().anyMatch( e -> isDeprecated( e.getMethod() ) ) || _roActions.stream().anyMatch( e -> isDeprecated( e.getAction() ) ) || _roAutoruns.stream().anyMatch( e -> isDeprecated( e.getAutorun() ) ) || _roMemoizes.stream().anyMatch( e -> isDeprecated( e.getMemoize() ) ) || _roTrackeds.stream().anyMatch( e -> ( e.hasTrackedMethod() && isDeprecated( e.getTrackedMethod() ) ) || ( e.hasOnDepsChangedMethod() && isDeprecated( e.getOnDepsChangedMethod() ) ) ); } void setIdRequired( final boolean idRequired ) { _idRequired = idRequired; } boolean isDisposeTrackable() { return _disposeTrackable; } private boolean isDeprecated( @Nullable final ExecutableElement element ) { return null != element && null != element.getAnnotation( Deprecated.class ); } @Nonnull private DeclaredType asDeclaredType() { return (DeclaredType) _element.asType(); } @Nonnull TypeElement getElement() { return _element; } @Nonnull String getType() { return _type; } @Nonnull private ReferenceDescriptor findOrCreateReference( @Nonnull final String name ) { return _references.computeIfAbsent( name, n -> new ReferenceDescriptor( this, name ) ); } @Nonnull private ObservableDescriptor findOrCreateObservable( @Nonnull final String name ) { return _observables.computeIfAbsent( name, n -> new ObservableDescriptor( this, n ) ); } @Nonnull private TrackedDescriptor findOrCreateTracked( @Nonnull final String name ) { return _trackeds.computeIfAbsent( name, n -> new TrackedDescriptor( this, n ) ); } @Nonnull private ObservableDescriptor addObservable( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_ANNOTATION_CLASSNAME, method ); final String declaredName = getAnnotationParameter( annotation, "name" ); final boolean expectSetter = getAnnotationParameter( annotation, "expectSetter" ); final boolean readOutsideTransaction = getAnnotationParameter( annotation, "readOutsideTransaction" ); final Boolean requireInitializer = isInitializerRequired( method ); final TypeMirror returnType = method.getReturnType(); final String methodName = method.getSimpleName().toString(); String name; final boolean setter; if ( TypeKind.VOID == returnType.getKind() ) { setter = true; //Should be a setter if ( 1 != method.getParameters().size() ) { throw new ArezProcessorException( "@Observable target should be a setter or getter", method ); } name = ProcessorUtil.deriveName( method, SETTER_PATTERN, declaredName ); if ( null == name ) { name = methodName; } } else { setter = false; //Must be a getter if ( 0 != method.getParameters().size() ) { throw new ArezProcessorException( "@Observable target should be a setter or getter", method ); } name = getPropertyAccessorName( method, declaredName ); } // Override name if supplied by user if ( !ProcessorUtil.isSentinelName( declaredName ) ) { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Observable target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Observable target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } checkNameUnique( name, method, Constants.OBSERVABLE_ANNOTATION_CLASSNAME ); if ( setter && !expectSetter ) { throw new ArezProcessorException( "Method annotated with @Observable is a setter but defines " + "expectSetter = false for observable named " + name, method ); } final ObservableDescriptor observable = findOrCreateObservable( name ); if ( readOutsideTransaction ) { observable.setReadOutsideTransaction( true ); } if ( !expectSetter ) { observable.setExpectSetter( false ); } if ( !observable.expectSetter() ) { if ( observable.hasSetter() ) { throw new ArezProcessorException( "Method annotated with @Observable defines expectSetter = false but a " + "setter exists named " + observable.getSetter().getSimpleName() + "for observable named " + name, method ); } } if ( setter ) { if ( observable.hasSetter() ) { throw new ArezProcessorException( "Method annotated with @Observable defines duplicate setter for " + "observable named " + name, method ); } if ( !observable.expectSetter() ) { throw new ArezProcessorException( "Method annotated with @Observable defines expectSetter = false but a " + "setter exists for observable named " + name, method ); } observable.setSetter( method, methodType ); } else { if ( observable.hasGetter() ) { throw new ArezProcessorException( "Method annotated with @Observable defines duplicate getter for " + "observable named " + name, method ); } observable.setGetter( method, methodType ); } if ( null != requireInitializer ) { if ( !method.getModifiers().contains( Modifier.ABSTRACT ) ) { throw new ArezProcessorException( "@Observable target set initializer parameter to ENABLED but " + "method is not abstract.", method ); } final Boolean existing = observable.getInitializer(); if ( null == existing ) { observable.setInitializer( requireInitializer ); } else if ( existing != requireInitializer ) { throw new ArezProcessorException( "@Observable target set initializer parameter to value that differs from " + "the paired observable method.", method ); } } return observable; } private void addObservableRef( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = methodType.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !toRawType( returnType ).toString().equals( "arez.Observable" ) ) { throw new ArezProcessorException( "Method annotated with @ObservableRef must return an instance of " + "arez.Observable", method ); } final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { name = ProcessorUtil.deriveName( method, OBSERVABLE_REF_PATTERN, declaredName ); if ( null == name ) { throw new ArezProcessorException( "Method annotated with @ObservableRef should specify name or be " + "named according to the convention get[Name]Observable", method ); } } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@ObservableRef target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@ObservableRef target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } final ObservableDescriptor observable = findOrCreateObservable( name ); if ( observable.hasRefMethod() ) { throw new ArezProcessorException( "Method annotated with @ObservableRef defines duplicate ref accessor for " + "observable named " + name, method ); } observable.setRefMethod( method, methodType ); } @Nonnull private TypeName toRawType( @Nonnull final TypeMirror type ) { final TypeName typeName = TypeName.get( type ); if ( typeName instanceof ParameterizedTypeName ) { return ( (ParameterizedTypeName) typeName ).rawType; } else { return typeName; } } private void addAction( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeWrappable( getElement(), Constants.ACTION_ANNOTATION_CLASSNAME, method ); final String name = deriveActionName( method, annotation ); checkNameUnique( name, method, Constants.ACTION_ANNOTATION_CLASSNAME ); final boolean mutation = getAnnotationParameter( annotation, "mutation" ); final boolean requireNewTransaction = getAnnotationParameter( annotation, "requireNewTransaction" ); final boolean reportParameters = getAnnotationParameter( annotation, "reportParameters" ); final boolean verifyRequired = getAnnotationParameter( annotation, "verifyRequired" ); final ActionDescriptor action = new ActionDescriptor( this, name, requireNewTransaction, mutation, verifyRequired, reportParameters, method, methodType ); _actions.put( action.getName(), action ); } @Nonnull private String deriveActionName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation ) throws ArezProcessorException { final String name = getAnnotationParameter( annotation, "name" ); if ( ProcessorUtil.isSentinelName( name ) ) { return method.getSimpleName().toString(); } else { if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Action target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Action target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } return name; } } private void addAutorun( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeWrappable( getElement(), Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotReturnAnyValue( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotBePublic( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); final String name = deriveAutorunName( method, annotation ); checkNameUnique( name, method, Constants.AUTORUN_ANNOTATION_CLASSNAME ); final boolean mutation = getAnnotationParameter( annotation, "mutation" ); final boolean observeLowerPriorityDependencies = getAnnotationParameter( annotation, "observeLowerPriorityDependencies" ); final boolean canNestActions = getAnnotationParameter( annotation, "canNestActions" ); final VariableElement priority = getAnnotationParameter( annotation, "priority" ); final AutorunDescriptor autorun = new AutorunDescriptor( this, name, mutation, priority.getSimpleName().toString(), observeLowerPriorityDependencies, canNestActions, method, methodType ); _autoruns.put( autorun.getName(), autorun ); } @Nonnull private String deriveAutorunName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation ) throws ArezProcessorException { final String name = getAnnotationParameter( annotation, "name" ); if ( ProcessorUtil.isSentinelName( name ) ) { return method.getSimpleName().toString(); } else { if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Autorun target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Autorun target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } return name; } } private void addOnDepsChanged( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String name = deriveHookName( method, TrackedDescriptor.ON_DEPS_CHANGED_PATTERN, "DepsChanged", getAnnotationParameter( annotation, "name" ) ); findOrCreateTracked( name ).setOnDepsChangedMethod( method ); } private void addTracked( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { final String name = deriveTrackedName( method, annotation ); checkNameUnique( name, method, Constants.TRACK_ANNOTATION_CLASSNAME ); final boolean mutation = getAnnotationParameter( annotation, "mutation" ); final boolean observeLowerPriorityDependencies = getAnnotationParameter( annotation, "observeLowerPriorityDependencies" ); final boolean canNestActions = getAnnotationParameter( annotation, "canNestActions" ); final VariableElement priority = getAnnotationParameter( annotation, "priority" ); final boolean reportParameters = getAnnotationParameter( annotation, "reportParameters" ); final TrackedDescriptor tracked = findOrCreateTracked( name ); tracked.setTrackedMethod( mutation, priority.getSimpleName().toString(), reportParameters, observeLowerPriorityDependencies, canNestActions, method, methodType ); } @Nonnull private String deriveTrackedName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation ) throws ArezProcessorException { final String name = getAnnotationParameter( annotation, "name" ); if ( ProcessorUtil.isSentinelName( name ) ) { return method.getSimpleName().toString(); } else { if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Track target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Track target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } return name; } } private void addObserverRef( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = method.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !returnType.toString().equals( "arez.Observer" ) ) { throw new ArezProcessorException( "Method annotated with @ObserverRef must return an instance of " + "arez.Observer", method ); } final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { name = ProcessorUtil.deriveName( method, OBSERVER_REF_PATTERN, declaredName ); if ( null == name ) { throw new ArezProcessorException( "Method annotated with @ObserverRef should specify name or be " + "named according to the convention get[Name]Observer", method ); } } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@ObserverRef target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@ObserverRef target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } if ( _observerRefs.containsKey( name ) ) { throw new ArezProcessorException( "Method annotated with @ObserverRef defines duplicate ref accessor for " + "observer named " + name, method ); } _observerRefs.put( name, new CandidateMethod( method, methodType ) ); } @Nonnull private ComputedDescriptor findOrCreateComputed( @Nonnull final String name ) { return _computeds.computeIfAbsent( name, n -> new ComputedDescriptor( this, n ) ); } private void addComputed( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType computedType ) throws ArezProcessorException { final String name = deriveComputedName( method, annotation ); checkNameUnique( name, method, Constants.COMPUTED_ANNOTATION_CLASSNAME ); final boolean keepAlive = getAnnotationParameter( annotation, "keepAlive" ); final boolean observeLowerPriorityDependencies = getAnnotationParameter( annotation, "observeLowerPriorityDependencies" ); final VariableElement priority = getAnnotationParameter( annotation, "priority" ); findOrCreateComputed( name ).setComputed( method, computedType, keepAlive, priority.getSimpleName().toString(), observeLowerPriorityDependencies ); } private void addComputedValueRef( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = methodType.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !toRawType( returnType ).toString().equals( "arez.ComputedValue" ) ) { throw new ArezProcessorException( "Method annotated with @ComputedValueRef must return an instance of " + "arez.ComputedValue", method ); } final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { name = ProcessorUtil.deriveName( method, COMPUTED_VALUE_REF_PATTERN, declaredName ); if ( null == name ) { throw new ArezProcessorException( "Method annotated with @ComputedValueRef should specify name or be " + "named according to the convention get[Name]ComputedValue", method ); } } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@ComputedValueRef target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@ComputedValueRef target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } findOrCreateComputed( name ).setRefMethod( method, methodType ); } @Nonnull private String deriveComputedName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation ) throws ArezProcessorException { final String name = getAnnotationParameter( annotation, "name" ); if ( ProcessorUtil.isSentinelName( name ) ) { return getPropertyAccessorName( method, name ); } else { if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Computed target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Computed target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } return name; } } private void addMemoize( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { final String name = deriveMemoizeName( method, annotation ); final boolean observeLowerPriorityDependencies = getAnnotationParameter( annotation, "observeLowerPriorityDependencies" ); final VariableElement priorityElement = getAnnotationParameter( annotation, "priority" ); final String priority = priorityElement.getSimpleName().toString(); checkNameUnique( name, method, Constants.MEMOIZE_ANNOTATION_CLASSNAME ); _memoizes.put( name, new MemoizeDescriptor( this, name, priority, observeLowerPriorityDependencies, method, methodType ) ); } @Nonnull private String deriveMemoizeName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation ) throws ArezProcessorException { final String name = getAnnotationParameter( annotation, "name" ); if ( ProcessorUtil.isSentinelName( name ) ) { return method.getSimpleName().toString(); } else { if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Memoize target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Memoize target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } return name; } } private void addOnActivate( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String name = deriveHookName( method, ComputedDescriptor.ON_ACTIVATE_PATTERN, "Activate", getAnnotationParameter( annotation, "name" ) ); findOrCreateComputed( name ).setOnActivate( method ); } private void addOnDeactivate( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String name = deriveHookName( method, ComputedDescriptor.ON_DEACTIVATE_PATTERN, "Deactivate", getAnnotationParameter( annotation, "name" ) ); findOrCreateComputed( name ).setOnDeactivate( method ); } private void addOnStale( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String name = deriveHookName( method, ComputedDescriptor.ON_STALE_PATTERN, "Stale", getAnnotationParameter( annotation, "name" ) ); findOrCreateComputed( name ).setOnStale( method ); } private void addOnDispose( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String name = deriveHookName( method, ComputedDescriptor.ON_DISPOSE_PATTERN, "Dispose", getAnnotationParameter( annotation, "name" ) ); findOrCreateComputed( name ).setOnDispose( method ); } @Nonnull private String deriveHookName( @Nonnull final ExecutableElement method, @Nonnull final Pattern pattern, @Nonnull final String type, @Nonnull final String name ) throws ArezProcessorException { final String value = ProcessorUtil.deriveName( method, pattern, name ); if ( null == value ) { throw new ArezProcessorException( "Unable to derive name for @On" + type + " as does not match " + "on[Name]" + type + " pattern. Please specify name.", method ); } else if ( !SourceVersion.isIdentifier( value ) ) { throw new ArezProcessorException( "@On" + type + " target specified an invalid name '" + value + "'. The " + "name must be a valid java identifier.", _element ); } else if ( SourceVersion.isKeyword( value ) ) { throw new ArezProcessorException( "@On" + type + " target specified an invalid name '" + value + "'. The " + "name must not be a java keyword.", _element ); } else { return value; } } private void setContextRef( @Nonnull final ExecutableElement method ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = method.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !returnType.toString().equals( "arez.ArezContext" ) ) { throw new ArezProcessorException( "Method annotated with @ContextRef must return an instance of " + "arez.ArezContext", method ); } if ( null != _contextRef ) { throw new ArezProcessorException( "@ContextRef target duplicates existing method named " + _contextRef.getSimpleName(), method ); } else { _contextRef = Objects.requireNonNull( method ); } } private void setComponentRef( @Nonnull final ExecutableElement method ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = method.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !returnType.toString().equals( "arez.Component" ) ) { throw new ArezProcessorException( "Method annotated with @ComponentRef must return an instance of " + "arez.Component", method ); } if ( null != _componentRef ) { throw new ArezProcessorException( "@ComponentRef target duplicates existing method named " + _componentRef.getSimpleName(), method ); } else { _componentRef = Objects.requireNonNull( method ); } } boolean hasComponentIdMethod() { return null != _componentId; } private void setComponentId( @Nonnull final ExecutableElement componentId, @Nonnull final ExecutableType componentIdMethodType ) throws ArezProcessorException { MethodChecks.mustNotBeAbstract( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); MethodChecks.mustBeFinal( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); MethodChecks.mustReturnAValue( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); if ( null != _componentId ) { throw new ArezProcessorException( "@ComponentId target duplicates existing method named " + _componentId.getSimpleName(), componentId ); } else { _componentId = Objects.requireNonNull( componentId ); _componentIdMethodType = componentIdMethodType; } } private void setComponentTypeNameRef( @Nonnull final ExecutableElement componentTypeName ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName ); MethodChecks.mustBeAbstract( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName ); MethodChecks.mustReturnAValue( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName ); final TypeMirror returnType = componentTypeName.getReturnType(); if ( !( TypeKind.DECLARED == returnType.getKind() && returnType.toString().equals( String.class.getName() ) ) ) { throw new ArezProcessorException( "@ComponentTypeNameRef target must return a String", componentTypeName ); } if ( null != _componentTypeNameRef ) { throw new ArezProcessorException( "@ComponentTypeNameRef target duplicates existing method named " + _componentTypeNameRef.getSimpleName(), componentTypeName ); } else { _componentTypeNameRef = Objects.requireNonNull( componentTypeName ); } } private void setComponentNameRef( @Nonnull final ExecutableElement componentName ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName ); MethodChecks.mustBeAbstract( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName ); MethodChecks.mustReturnAValue( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName ); if ( null != _componentNameRef ) { throw new ArezProcessorException( "@ComponentNameRef target duplicates existing method named " + _componentNameRef.getSimpleName(), componentName ); } else { _componentNameRef = Objects.requireNonNull( componentName ); } } @Nullable ExecutableElement getPostConstruct() { return _postConstruct; } void setPostConstruct( @Nonnull final ExecutableElement postConstruct ) throws ArezProcessorException { MethodChecks.mustBeLifecycleHook( getElement(), Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME, postConstruct ); if ( null != _postConstruct ) { throw new ArezProcessorException( "@PostConstruct target duplicates existing method named " + _postConstruct.getSimpleName(), postConstruct ); } else { _postConstruct = postConstruct; } } private void setPreDispose( @Nonnull final ExecutableElement preDispose ) throws ArezProcessorException { MethodChecks.mustBeLifecycleHook( getElement(), Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME, preDispose ); if ( null != _preDispose ) { throw new ArezProcessorException( "@PreDispose target duplicates existing method named " + _preDispose.getSimpleName(), preDispose ); } else { _preDispose = preDispose; } } private void setPostDispose( @Nonnull final ExecutableElement postDispose ) throws ArezProcessorException { MethodChecks.mustBeLifecycleHook( getElement(), Constants.POST_DISPOSE_ANNOTATION_CLASSNAME, postDispose ); if ( null != _postDispose ) { throw new ArezProcessorException( "@PostDispose target duplicates existing method named " + _postDispose.getSimpleName(), postDispose ); } else { _postDispose = postDispose; } } @Nonnull Collection<ObservableDescriptor> getObservables() { return _roObservables; } void validate() throws ArezProcessorException { _roObservables.forEach( ObservableDescriptor::validate ); _roComputeds.forEach( ComputedDescriptor::validate ); _roDependencies.forEach( DependencyDescriptor::validate ); _roReferences.forEach( ReferenceDescriptor::validate ); final boolean hasReactiveElements = _roObservables.isEmpty() && _roActions.isEmpty() && _roComputeds.isEmpty() && _roMemoizes.isEmpty() && _roTrackeds.isEmpty() && _roDependencies.isEmpty() && _roReferences.isEmpty() && _roInverses.isEmpty() && _roAutoruns.isEmpty(); if ( !_allowEmpty && hasReactiveElements ) { throw new ArezProcessorException( "@ArezComponent target has no methods annotated with @Action, @Computed, " + "@Memoize, @Observable, @Inverse, @Reference, @Dependency, @Track or @Autorun", _element ); } else if ( _allowEmpty && !hasReactiveElements ) { throw new ArezProcessorException( "@ArezComponent target has specified allowEmpty = true but has methods " + "annotated with @Action, @Computed, @Memoize, @Observable, @Inverse, " + "@Reference, @Dependency, @Track or @Autorun", _element ); } if ( _deferSchedule && !requiresSchedule() ) { throw new ArezProcessorException( "@ArezComponent target has specified the deferSchedule = true " + "annotation parameter but has no methods annotated with @Autorun, " + "@Dependency or @Computed(keepAlive=true)", _element ); } } private boolean requiresSchedule() { return !_roAutoruns.isEmpty() || !_roDependencies.isEmpty() || _computeds.values().stream().anyMatch( ComputedDescriptor::isKeepAlive ); } private void checkNameUnique( @Nonnull final String name, @Nonnull final ExecutableElement sourceMethod, @Nonnull final String sourceAnnotationName ) throws ArezProcessorException { final ActionDescriptor action = _actions.get( name ); if ( null != action ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.ACTION_ANNOTATION_CLASSNAME, action.getAction() ); } final ComputedDescriptor computed = _computeds.get( name ); if ( null != computed && computed.hasComputed() ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.COMPUTED_ANNOTATION_CLASSNAME, computed.getComputed() ); } final MemoizeDescriptor memoize = _memoizes.get( name ); if ( null != memoize ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.MEMOIZE_ANNOTATION_CLASSNAME, memoize.getMemoize() ); } final AutorunDescriptor autorun = _autoruns.get( name ); if ( null != autorun ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.AUTORUN_ANNOTATION_CLASSNAME, autorun.getAutorun() ); } // Track have pairs so let the caller determine whether a duplicate occurs in that scenario if ( !sourceAnnotationName.equals( Constants.TRACK_ANNOTATION_CLASSNAME ) ) { final TrackedDescriptor tracked = _trackeds.get( name ); if ( null != tracked ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.TRACK_ANNOTATION_CLASSNAME, tracked.getTrackedMethod() ); } } // Observables have pairs so let the caller determine whether a duplicate occurs in that scenario if ( !sourceAnnotationName.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) ) { final ObservableDescriptor observable = _observables.get( name ); if ( null != observable ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.OBSERVABLE_ANNOTATION_CLASSNAME, observable.getDefiner() ); } } } @Nonnull private ArezProcessorException toException( @Nonnull final String name, @Nonnull final String sourceAnnotationName, @Nonnull final ExecutableElement sourceMethod, @Nonnull final String targetAnnotationName, @Nonnull final ExecutableElement targetElement ) { return new ArezProcessorException( "Method annotated with @" + ProcessorUtil.toSimpleName( sourceAnnotationName ) + " specified name " + name + " that duplicates @" + ProcessorUtil.toSimpleName( targetAnnotationName ) + " defined by method " + targetElement.getSimpleName(), sourceMethod ); } void analyzeCandidateMethods( @Nonnull final List<ExecutableElement> methods, @Nonnull final Types typeUtils ) throws ArezProcessorException { for ( final ExecutableElement method : methods ) { final String methodName = method.getSimpleName().toString(); if ( AREZ_SPECIAL_METHODS.contains( methodName ) && method.getParameters().isEmpty() ) { throw new ArezProcessorException( "Method defined on a class annotated by @ArezComponent uses a name " + "reserved by Arez", method ); } else if ( methodName.startsWith( GeneratorUtil.FIELD_PREFIX ) || methodName.startsWith( GeneratorUtil.OBSERVABLE_DATA_FIELD_PREFIX ) || methodName.startsWith( GeneratorUtil.REFERENCE_FIELD_PREFIX ) || methodName.startsWith( GeneratorUtil.FRAMEWORK_PREFIX ) ) { throw new ArezProcessorException( "Method defined on a class annotated by @ArezComponent uses a name " + "with a prefix reserved by Arez", method ); } } final Map<String, CandidateMethod> getters = new HashMap<>(); final Map<String, CandidateMethod> setters = new HashMap<>(); final Map<String, CandidateMethod> trackeds = new HashMap<>(); final Map<String, CandidateMethod> onDepsChangeds = new HashMap<>(); for ( final ExecutableElement method : methods ) { final ExecutableType methodType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), method ); if ( !analyzeMethod( method, methodType ) ) { /* * If we get here the method was not annotated so we can try to detect if it is a * candidate arez method in case some arez annotations are implied via naming conventions. */ if ( method.getModifiers().contains( Modifier.STATIC ) ) { continue; } final CandidateMethod candidateMethod = new CandidateMethod( method, methodType ); final boolean voidReturn = method.getReturnType().getKind() == TypeKind.VOID; final int parameterCount = method.getParameters().size(); String name; if ( !method.getModifiers().contains( Modifier.FINAL ) ) { name = ProcessorUtil.deriveName( method, SETTER_PATTERN, ProcessorUtil.SENTINEL_NAME ); if ( voidReturn && 1 == parameterCount && null != name ) { setters.put( name, candidateMethod ); continue; } name = ProcessorUtil.deriveName( method, ISSER_PATTERN, ProcessorUtil.SENTINEL_NAME ); if ( !voidReturn && 0 == parameterCount && null != name ) { getters.put( name, candidateMethod ); continue; } name = ProcessorUtil.deriveName( method, GETTER_PATTERN, ProcessorUtil.SENTINEL_NAME ); if ( !voidReturn && 0 == parameterCount && null != name ) { getters.put( name, candidateMethod ); continue; } } name = ProcessorUtil.deriveName( method, TrackedDescriptor.ON_DEPS_CHANGED_PATTERN, ProcessorUtil.SENTINEL_NAME ); if ( voidReturn && 0 == parameterCount && null != name ) { onDepsChangeds.put( name, candidateMethod ); continue; } final String methodName = method.getSimpleName().toString(); if ( !OBJECT_METHODS.contains( methodName ) ) { trackeds.put( methodName, candidateMethod ); } } } linkUnAnnotatedObservables( getters, setters ); linkUnAnnotatedTracked( trackeds, onDepsChangeds ); linkObserverRefs(); linkDependencies( getters.values() ); autodetectObservableInitializers(); /* * ALl of the maps will have called remove() for all matching candidates. * Thus any left are the non-arez methods. */ ensureNoAbstractMethods( getters.values() ); ensureNoAbstractMethods( setters.values() ); ensureNoAbstractMethods( trackeds.values() ); ensureNoAbstractMethods( onDepsChangeds.values() ); } private void autodetectObservableInitializers() { for ( final ObservableDescriptor observable : getObservables() ) { if ( null == observable.getInitializer() && observable.hasGetter() ) { if ( observable.hasSetter() ) { final boolean initializer = autodetectInitializer( observable.getGetter() ) && autodetectInitializer( observable.getSetter() ); observable.setInitializer( initializer ); } else { final boolean initializer = autodetectInitializer( observable.getGetter() ); observable.setInitializer( initializer ); } } } } private void linkDependencies( @Nonnull final Collection<CandidateMethod> candidates ) { _roObservables .stream() .filter( ObservableDescriptor::hasGetter ) .filter( o -> hasDependencyAnnotation( o.getGetter() ) ) .forEach( o -> addOrUpdateDependency( o.getGetter(), o ) ); _roComputeds .stream() .filter( ComputedDescriptor::hasComputed ) .map( ComputedDescriptor::getComputed ) .filter( this::hasDependencyAnnotation ) .forEach( this::addDependency ); candidates .stream() .map( CandidateMethod::getMethod ) .filter( this::hasDependencyAnnotation ) .forEach( this::addDependency ); } private boolean hasDependencyAnnotation( @Nonnull final ExecutableElement method ) { return null != ProcessorUtil.findAnnotationByType( method, Constants.DEPENDENCY_ANNOTATION_CLASSNAME ); } private void addOrUpdateDependency( @Nonnull final ExecutableElement method, @Nonnull final ObservableDescriptor observable ) { final DependencyDescriptor dependencyDescriptor = _dependencies.computeIfAbsent( method, this::createDependencyDescriptor ); dependencyDescriptor.setObservable( observable ); } private void addReferenceId( @Nonnull final AnnotationMirror annotation, @Nonnull final ObservableDescriptor observable, @Nonnull final ExecutableElement method ) { MethodChecks.mustNotHaveAnyParameters( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); findOrCreateReference( getReferenceIdName( annotation, method ) ).setObservable( observable ); } private void addReferenceId( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) { MethodChecks.mustNotHaveAnyParameters( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); final String name = getReferenceIdName( annotation, method ); findOrCreateReference( name ).setIdMethod( method, methodType ); } @Nonnull private String getReferenceIdName( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) { final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { final String candidate = ProcessorUtil.deriveName( method, ID_GETTER_PATTERN, declaredName ); if ( null == candidate ) { final String candidate2 = ProcessorUtil.deriveName( method, RAW_ID_GETTER_PATTERN, declaredName ); if ( null == candidate2 ) { throw new ArezProcessorException( "@ReferenceId target has not specified a name and does not follow " + "the convention \"get[Name]Id\" or \"[name]Id\"", method ); } else { name = candidate2; } } else { name = candidate; } } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@ReferenceId target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@ReferenceId target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } return name; } private void addInverse( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) { MethodChecks.mustNotHaveAnyParameters( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); final String name = getInverseName( annotation, method ); final ObservableDescriptor observable = findOrCreateObservable( name ); observable.setGetter( method, methodType ); addInverse( annotation, observable, method ); } private void addInverse( @Nonnull final AnnotationMirror annotation, @Nonnull final ObservableDescriptor observable, @Nonnull final ExecutableElement method ) { MethodChecks.mustNotHaveAnyParameters( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); final String name = getInverseName( annotation, method ); final InverseDescriptor existing = _inverses.get( name ); if ( null != existing ) { throw new ArezProcessorException( "@Inverse target defines duplicate inverse for name '" + name + "'. The other inverse is " + existing.getObservable().getGetter(), method ); } else { final TypeMirror type = method.getReturnType(); final Multiplicity multiplicity; TypeElement targetType = getInverseManyTypeTarget( method ); if ( null != targetType ) { multiplicity = Multiplicity.MANY; } else { if ( !( type instanceof DeclaredType ) || null == ProcessorUtil.findAnnotationByType( ( (DeclaredType) type ).asElement(), Constants.COMPONENT_ANNOTATION_CLASSNAME ) ) { throw new ArezProcessorException( "@Inverse target expected to return a type annotated with " + Constants.COMPONENT_ANNOTATION_CLASSNAME, method ); } targetType = (TypeElement) ( (DeclaredType) type ).asElement(); if ( null != ProcessorUtil.findAnnotationByType( method, Constants.NONNULL_ANNOTATION_CLASSNAME ) ) { multiplicity = Multiplicity.ONE; } else if ( null != ProcessorUtil.findAnnotationByType( method, Constants.NULLABLE_ANNOTATION_CLASSNAME ) ) { multiplicity = Multiplicity.ZERO_OR_ONE; } else { throw new ArezProcessorException( "@Inverse target expected to be annotated with either " + Constants.NULLABLE_ANNOTATION_CLASSNAME + " or " + Constants.NONNULL_ANNOTATION_CLASSNAME, method ); } } final String referenceName = getInverseReferenceNameParameter( method ); final InverseDescriptor descriptor = new InverseDescriptor( this, observable, referenceName, multiplicity, targetType ); _inverses.put( name, descriptor ); verifyMultiplicityOfAssociatedReferenceMethod( descriptor ); } } private void verifyMultiplicityOfAssociatedReferenceMethod( @Nonnull final InverseDescriptor descriptor ) { final Multiplicity multiplicity = ProcessorUtil .getMethods( descriptor.getTargetType(), _elements, _typeUtils ) .stream() .map( m -> { final AnnotationMirror a = ProcessorUtil.findAnnotationByType( m, Constants.REFERENCE_ANNOTATION_CLASSNAME ); if ( null != a && getReferenceName( a, m ).equals( descriptor.getReferenceName() ) ) { ensureTargetTypeAligns( descriptor, m.getReturnType() ); return getReferenceInverseMultiplicity( a ); } else { return null; } } ) .filter( Objects::nonNull ) .findAny() .orElse( null ); if ( null == multiplicity ) { throw new ArezProcessorException( "@Inverse target expected to find an associated @Reference annotation with " + "a name parameter equal to '" + descriptor.getReferenceName() + "' on class " + descriptor.getTargetType().getQualifiedName() + " but is unable to " + "locate a matching method.", descriptor.getObservable().getGetter() ); } if ( descriptor.getMultiplicity() != multiplicity ) { throw new ArezProcessorException( "@Inverse target has a multiplicity of " + descriptor.getMultiplicity() + " but that associated @Reference has a multiplicity of " + multiplicity + ". The multiplicity must align.", descriptor.getObservable().getGetter() ); } } private void ensureTargetTypeAligns( @Nonnull final InverseDescriptor descriptor, @Nonnull final TypeMirror target ) { if ( !_typeUtils.isSameType( target, getElement().asType() ) ) { throw new ArezProcessorException( "@Inverse target expected to find an associated @Reference annotation with " + "a target type equal to " + descriptor.getTargetType() + " but the actual " + "target type is " + target, descriptor.getObservable().getGetter() ); } } @Nullable private TypeElement getInverseManyTypeTarget( @Nonnull final ExecutableElement method ) { final TypeName typeName = TypeName.get( method.getReturnType() ); if ( typeName instanceof ParameterizedTypeName ) { final ParameterizedTypeName type = (ParameterizedTypeName) typeName; if ( isSupportedInverseCollectionType( type.rawType.toString() ) && !type.typeArguments.isEmpty() ) { final TypeElement typeElement = _elements.getTypeElement( type.typeArguments.get( 0 ).toString() ); if ( null != ProcessorUtil.findAnnotationByType( typeElement, Constants.COMPONENT_ANNOTATION_CLASSNAME ) ) { return typeElement; } else { throw new ArezProcessorException( "@Inverse target expected to return a type annotated with " + Constants.COMPONENT_ANNOTATION_CLASSNAME, method ); } } } return null; } private boolean isSupportedInverseCollectionType( @Nonnull final String typeClassname ) { return Collection.class.getName().equals( typeClassname ) || Set.class.getName().equals( typeClassname ) || List.class.getName().equals( typeClassname ); } @Nonnull private String getInverseReferenceNameParameter( @Nonnull final ExecutableElement method ) { final String declaredName = (String) ProcessorUtil.getAnnotationValue( _elements, method, Constants.INVERSE_ANNOTATION_CLASSNAME, "referenceName" ).getValue(); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { name = ProcessorUtil.firstCharacterToLowerCase( getElement().getSimpleName().toString() ); } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Inverse target specified an invalid referenceName '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Inverse target specified an invalid referenceName '" + name + "'. The " + "name must not be a java keyword.", method ); } } return name; } @Nonnull private String getInverseName( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) { final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { final String candidate = ProcessorUtil.deriveName( method, GETTER_PATTERN, declaredName ); name = null == candidate ? method.getSimpleName().toString() : candidate; } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Inverse target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Inverse target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } return name; } private void addReference( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) { MethodChecks.mustNotHaveAnyParameters( Constants.REFERENCE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.REFERENCE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.REFERENCE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.REFERENCE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.REFERENCE_ANNOTATION_CLASSNAME, method ); final String name = getReferenceName( annotation, method ); final String linkType = getLinkType( method ); final String inverseName; final Multiplicity inverseMultiplicity; if ( hasInverse( annotation ) ) { inverseMultiplicity = getReferenceInverseMultiplicity( annotation ); inverseName = getReferenceInverseName( annotation, method, inverseMultiplicity ); final TypeMirror returnType = method.getReturnType(); if ( !( returnType instanceof DeclaredType ) || null == ProcessorUtil.findAnnotationByType( ( (DeclaredType) returnType ).asElement(), Constants.COMPONENT_ANNOTATION_CLASSNAME ) ) { throw new ArezProcessorException( "@Reference target expected to return a type annotated with " + Constants.COMPONENT_ANNOTATION_CLASSNAME + " if there is an " + "inverse reference.", method ); } } else { inverseName = null; inverseMultiplicity = null; } final ReferenceDescriptor descriptor = findOrCreateReference( name ); descriptor.setMethod( method, methodType, linkType, inverseName, inverseMultiplicity ); verifyMultiplicityOfAssociatedInverseMethod( descriptor ); } private void verifyMultiplicityOfAssociatedInverseMethod( @Nonnull final ReferenceDescriptor descriptor ) { if ( !descriptor.hasInverse() ) { return; } final TypeElement element = (TypeElement) _typeUtils.asElement( descriptor.getMethod().getReturnType() ); final Multiplicity multiplicity = ProcessorUtil .getMethods( element, _elements, _typeUtils ) .stream() .map( m -> { final AnnotationMirror a = ProcessorUtil.findAnnotationByType( m, Constants.INVERSE_ANNOTATION_CLASSNAME ); if ( null != a && getInverseName( a, m ).equals( descriptor.getInverseName() ) ) { final TypeElement target = getInverseManyTypeTarget( m ); if ( null != target ) { ensureTargetTypeAligns( descriptor, target.asType() ); return Multiplicity.MANY; } else { ensureTargetTypeAligns( descriptor, m.getReturnType() ); if ( null != ProcessorUtil.findAnnotationByType( m, Constants.NONNULL_ANNOTATION_CLASSNAME ) ) { return Multiplicity.ONE; } else { return Multiplicity.ZERO_OR_ONE; } } } else { return null; } } ) .filter( Objects::nonNull ) .findAny() .orElse( null ); if ( null == multiplicity ) { throw new ArezProcessorException( "@Reference target expected to find an associated @Inverse annotation with " + "a name parameter equal to '" + descriptor.getInverseName() + "' on class " + descriptor.getMethod().getReturnType() + " but is unable to " + "locate a matching method.", descriptor.getMethod() ); } final Multiplicity inverseMultiplicity = descriptor.getInverseMultiplicity(); if ( inverseMultiplicity != multiplicity ) { throw new ArezProcessorException( "@Reference target has an inverseMultiplicity of " + inverseMultiplicity + " but that associated @Inverse has a multiplicity of " + multiplicity + ". The multiplicity must align.", descriptor.getMethod() ); } } private void ensureTargetTypeAligns( @Nonnull final ReferenceDescriptor descriptor, @Nonnull final TypeMirror target ) { if ( !_typeUtils.isSameType( target, getElement().asType() ) ) { throw new ArezProcessorException( "@Reference target expected to find an associated @Inverse annotation with " + "a target type equal to " + getElement().getQualifiedName() + " but " + "the actual target type is " + target, descriptor.getMethod() ); } } private boolean hasInverse( @Nonnull final AnnotationMirror annotation ) { final VariableElement variableElement = ProcessorUtil.getAnnotationValue( _elements, annotation, "inverse" ); switch ( variableElement.getSimpleName().toString() ) { case "ENABLE": return true; case "DISABLE": return false; default: return null != ProcessorUtil.findAnnotationValueNoDefaults( annotation, "inverseName" ) || null != ProcessorUtil.findAnnotationValueNoDefaults( annotation, "inverseMultiplicity" ); } } @Nonnull private String getReferenceInverseName( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final Multiplicity multiplicity ) { final String declaredName = ProcessorUtil.getAnnotationValue( _elements, annotation, "inverseName" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { final String baseName = getElement().getSimpleName().toString(); return ProcessorUtil.firstCharacterToLowerCase( baseName ) + ( Multiplicity.MANY == multiplicity ? "s" : "" ); } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Reference target specified an invalid inverseName '" + name + "'. The " + "inverseName must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Reference target specified an invalid inverseName '" + name + "'. The " + "inverseName must not be a java keyword.", method ); } } return name; } @Nonnull private Multiplicity getReferenceInverseMultiplicity( @Nonnull final AnnotationMirror annotation ) { final VariableElement variableElement = ProcessorUtil.getAnnotationValue( _elements, annotation, "inverseMultiplicity" ); switch ( variableElement.getSimpleName().toString() ) { case "MANY": return Multiplicity.MANY; case "ONE": return Multiplicity.ONE; default: return Multiplicity.ZERO_OR_ONE; } } @Nonnull private String getReferenceName( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) { final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { final String candidate = ProcessorUtil.deriveName( method, GETTER_PATTERN, declaredName ); if ( null == candidate ) { name = method.getSimpleName().toString(); } else { name = candidate; } } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Reference target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Reference target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } return name; } @Nonnull private String getLinkType( @Nonnull final ExecutableElement method ) { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, method, Constants.REFERENCE_ANNOTATION_CLASSNAME, "load" ).getValue(); return injectParameter.getSimpleName().toString(); } private void addDependency( @Nonnull final ExecutableElement method ) { _dependencies.put( method, createDependencyDescriptor( method ) ); } @Nonnull private DependencyDescriptor createDependencyDescriptor( @Nonnull final ExecutableElement method ) { MethodChecks.mustNotHaveAnyParameters( Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method ); if ( TypeKind.DECLARED != method.getReturnType().getKind() ) { throw new ArezProcessorException( "@Dependency target must return a non-primitive value", method ); } final TypeElement disposeTrackable = _elements.getTypeElement( Constants.DISPOSE_TRACKABLE_CLASSNAME ); assert null != disposeTrackable; if ( !_typeUtils.isAssignable( method.getReturnType(), disposeTrackable.asType() ) ) { final TypeElement typeElement = (TypeElement) _typeUtils.asElement( method.getReturnType() ); final AnnotationMirror value = ProcessorUtil.findAnnotationByType( typeElement, Constants.COMPONENT_ANNOTATION_CLASSNAME ); if ( null == value || !ProcessorUtil.isDisposableTrackableRequired( _elements, typeElement ) ) { throw new ArezProcessorException( "@Dependency target must return an instance compatible with " + Constants.DISPOSE_TRACKABLE_CLASSNAME + " or a type annotated " + "with @ArezComponent(disposeTrackable=ENABLE)", method ); } } final boolean cascade = isActionCascade( method ); return new DependencyDescriptor( method, cascade ); } private boolean isActionCascade( @Nonnull final ExecutableElement method ) { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, method, Constants.DEPENDENCY_ANNOTATION_CLASSNAME, "action" ).getValue(); switch ( injectParameter.getSimpleName().toString() ) { case "CASCADE": return true; case "SET_NULL": default: return false; } } private void ensureNoAbstractMethods( @Nonnull final Collection<CandidateMethod> candidateMethods ) { candidateMethods .stream() .map( CandidateMethod::getMethod ) .filter( m -> m.getModifiers().contains( Modifier.ABSTRACT ) ) .forEach( m -> { throw new ArezProcessorException( "@ArezComponent target has an abstract method not implemented by " + "framework. The method is named " + m.getSimpleName(), getElement() ); } ); } private void linkObserverRefs() { for ( final Map.Entry<String, CandidateMethod> entry : _observerRefs.entrySet() ) { final String key = entry.getKey(); final CandidateMethod method = entry.getValue(); final AutorunDescriptor autorunDescriptor = _autoruns.get( key ); if ( null != autorunDescriptor ) { autorunDescriptor.setRefMethod( method.getMethod(), method.getMethodType() ); } else { final TrackedDescriptor trackedDescriptor = _trackeds.get( key ); if ( null != trackedDescriptor ) { trackedDescriptor.setRefMethod( method.getMethod(), method.getMethodType() ); } else { throw new ArezProcessorException( "@ObserverRef target defined observer named '" + key + "' but no " + "@Autorun or @Track method with that name exists", method.getMethod() ); } } } } private void linkUnAnnotatedObservables( @Nonnull final Map<String, CandidateMethod> getters, @Nonnull final Map<String, CandidateMethod> setters ) throws ArezProcessorException { for ( final ObservableDescriptor observable : _roObservables ) { if ( !observable.hasSetter() && !observable.hasGetter() ) { throw new ArezProcessorException( "@ObservableRef target unable to be associated with an Observable property", observable.getRefMethod() ); } else if ( !observable.hasSetter() && observable.expectSetter() ) { final CandidateMethod candidate = setters.remove( observable.getName() ); if ( null != candidate ) { MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_ANNOTATION_CLASSNAME, candidate.getMethod() ); observable.setSetter( candidate.getMethod(), candidate.getMethodType() ); } else if ( observable.hasGetter() ) { throw new ArezProcessorException( "@Observable target defined getter but no setter was defined and no " + "setter could be automatically determined", observable.getGetter() ); } } else if ( !observable.hasGetter() ) { final CandidateMethod candidate = getters.remove( observable.getName() ); if ( null != candidate ) { MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_ANNOTATION_CLASSNAME, candidate.getMethod() ); observable.setGetter( candidate.getMethod(), candidate.getMethodType() ); } else { throw new ArezProcessorException( "@Observable target defined setter but no getter was defined and no " + "getter could be automatically determined", observable.getSetter() ); } } } } private void linkUnAnnotatedTracked( @Nonnull final Map<String, CandidateMethod> trackeds, @Nonnull final Map<String, CandidateMethod> onDepsChangeds ) throws ArezProcessorException { for ( final TrackedDescriptor tracked : _roTrackeds ) { if ( !tracked.hasTrackedMethod() ) { final CandidateMethod candidate = trackeds.remove( tracked.getName() ); if ( null != candidate ) { tracked.setTrackedMethod( false, "NORMAL", true, false, false, candidate.getMethod(), candidate.getMethodType() ); } else { throw new ArezProcessorException( "@OnDepsChanged target has no corresponding @Track that could " + "be automatically determined", tracked.getOnDepsChangedMethod() ); } } else if ( !tracked.hasOnDepsChangedMethod() ) { final CandidateMethod candidate = onDepsChangeds.remove( tracked.getName() ); if ( null != candidate ) { tracked.setOnDepsChangedMethod( candidate.getMethod() ); } else { throw new ArezProcessorException( "@Track target has no corresponding @OnDepsChanged that could " + "be automatically determined", tracked.getTrackedMethod() ); } } } } private boolean analyzeMethod( @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { verifyNoDuplicateAnnotations( method ); final AnnotationMirror action = ProcessorUtil.findAnnotationByType( method, Constants.ACTION_ANNOTATION_CLASSNAME ); final AnnotationMirror autorun = ProcessorUtil.findAnnotationByType( method, Constants.AUTORUN_ANNOTATION_CLASSNAME ); final AnnotationMirror observable = ProcessorUtil.findAnnotationByType( method, Constants.OBSERVABLE_ANNOTATION_CLASSNAME ); final AnnotationMirror observableRef = ProcessorUtil.findAnnotationByType( method, Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror computed = ProcessorUtil.findAnnotationByType( method, Constants.COMPUTED_ANNOTATION_CLASSNAME ); final AnnotationMirror computedValueRef = ProcessorUtil.findAnnotationByType( method, Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror contextRef = ProcessorUtil.findAnnotationByType( method, Constants.CONTEXT_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror componentRef = ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror componentId = ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_ID_ANNOTATION_CLASSNAME ); final AnnotationMirror componentTypeName = ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror componentName = ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror postConstruct = ProcessorUtil.findAnnotationByType( method, Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME ); final AnnotationMirror ejbPostConstruct = ProcessorUtil.findAnnotationByType( method, Constants.EJB_POST_CONSTRUCT_ANNOTATION_CLASSNAME ); final AnnotationMirror preDispose = ProcessorUtil.findAnnotationByType( method, Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME ); final AnnotationMirror postDispose = ProcessorUtil.findAnnotationByType( method, Constants.POST_DISPOSE_ANNOTATION_CLASSNAME ); final AnnotationMirror onActivate = ProcessorUtil.findAnnotationByType( method, Constants.ON_ACTIVATE_ANNOTATION_CLASSNAME ); final AnnotationMirror onDeactivate = ProcessorUtil.findAnnotationByType( method, Constants.ON_DEACTIVATE_ANNOTATION_CLASSNAME ); final AnnotationMirror onStale = ProcessorUtil.findAnnotationByType( method, Constants.ON_STALE_ANNOTATION_CLASSNAME ); final AnnotationMirror onDispose = ProcessorUtil.findAnnotationByType( method, Constants.ON_DISPOSE_ANNOTATION_CLASSNAME ); final AnnotationMirror track = ProcessorUtil.findAnnotationByType( method, Constants.TRACK_ANNOTATION_CLASSNAME ); final AnnotationMirror onDepsChanged = ProcessorUtil.findAnnotationByType( method, Constants.ON_DEPS_CHANGED_ANNOTATION_CLASSNAME ); final AnnotationMirror observerRef = ProcessorUtil.findAnnotationByType( method, Constants.OBSERVER_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror memoize = ProcessorUtil.findAnnotationByType( method, Constants.MEMOIZE_ANNOTATION_CLASSNAME ); final AnnotationMirror dependency = ProcessorUtil.findAnnotationByType( method, Constants.DEPENDENCY_ANNOTATION_CLASSNAME ); final AnnotationMirror reference = ProcessorUtil.findAnnotationByType( method, Constants.REFERENCE_ANNOTATION_CLASSNAME ); final AnnotationMirror referenceId = ProcessorUtil.findAnnotationByType( method, Constants.REFERENCE_ID_ANNOTATION_CLASSNAME ); final AnnotationMirror inverse = ProcessorUtil.findAnnotationByType( method, Constants.INVERSE_ANNOTATION_CLASSNAME ); if ( null != observable ) { final ObservableDescriptor descriptor = addObservable( observable, method, methodType ); if ( null != referenceId ) { addReferenceId( referenceId, descriptor, method ); } if ( null != inverse ) { addInverse( inverse, descriptor, method ); } return true; } else if ( null != observableRef ) { addObservableRef( observableRef, method, methodType ); return true; } else if ( null != action ) { addAction( action, method, methodType ); return true; } else if ( null != autorun ) { addAutorun( autorun, method, methodType ); return true; } else if ( null != track ) { addTracked( track, method, methodType ); return true; } else if ( null != onDepsChanged ) { addOnDepsChanged( onDepsChanged, method ); return true; } else if ( null != observerRef ) { addObserverRef( observerRef, method, methodType ); return true; } else if ( null != contextRef ) { setContextRef( method ); return true; } else if ( null != computed ) { addComputed( computed, method, methodType ); return true; } else if ( null != computedValueRef ) { addComputedValueRef( computedValueRef, method, methodType ); return true; } else if ( null != memoize ) { addMemoize( memoize, method, methodType ); return true; } else if ( null != componentRef ) { setComponentRef( method ); return true; } else if ( null != componentId ) { setComponentId( method, methodType ); return true; } else if ( null != componentName ) { setComponentNameRef( method ); return true; } else if ( null != componentTypeName ) { setComponentTypeNameRef( method ); return true; } else if ( null != ejbPostConstruct ) { throw new ArezProcessorException( "@" + Constants.EJB_POST_CONSTRUCT_ANNOTATION_CLASSNAME + " annotation " + "not supported in components annotated with @ArezComponent, use the @" + Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME + " annotation instead.", method ); } else if ( null != postConstruct ) { setPostConstruct( method ); return true; } else if ( null != preDispose ) { setPreDispose( method ); return true; } else if ( null != postDispose ) { setPostDispose( method ); return true; } else if ( null != onActivate ) { addOnActivate( onActivate, method ); return true; } else if ( null != onDeactivate ) { addOnDeactivate( onDeactivate, method ); return true; } else if ( null != onStale ) { addOnStale( onStale, method ); return true; } else if ( null != onDispose ) { addOnDispose( onDispose, method ); return true; } else if ( null != dependency ) { addDependency( method ); return false; } else if ( null != reference ) { addReference( reference, method, methodType ); return true; } else if ( null != referenceId ) { addReferenceId( referenceId, method, methodType ); return true; } else if ( null != inverse ) { addInverse( inverse, method, methodType ); return true; } else { return false; } } @Nullable private Boolean isInitializerRequired( @Nonnull final ExecutableElement element ) { final AnnotationMirror annotation = ProcessorUtil.findAnnotationByType( element, Constants.OBSERVABLE_ANNOTATION_CLASSNAME ); final AnnotationValue injectParameter = null == annotation ? null : ProcessorUtil.findAnnotationValueNoDefaults( annotation, "initializer" ); final String value = null == injectParameter ? "AUTODETECT" : ( (VariableElement) injectParameter.getValue() ).getSimpleName().toString(); switch ( value ) { case "ENABLE": return Boolean.TRUE; case "DISABLE": return Boolean.FALSE; default: return null; } } private boolean autodetectInitializer( @Nonnull final ExecutableElement element ) { return element.getModifiers().contains( Modifier.ABSTRACT ) && ( ( // Getter element.getReturnType().getKind() != TypeKind.VOID && null != ProcessorUtil.findAnnotationByType( element, Constants.NONNULL_ANNOTATION_CLASSNAME ) ) || ( // Setter 1 == element.getParameters().size() && null != ProcessorUtil.findAnnotationByType( element.getParameters().get( 0 ), Constants.NONNULL_ANNOTATION_CLASSNAME ) ) ); } private void verifyNoDuplicateAnnotations( @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String[] annotationTypes = new String[]{ Constants.ACTION_ANNOTATION_CLASSNAME, Constants.AUTORUN_ANNOTATION_CLASSNAME, Constants.TRACK_ANNOTATION_CLASSNAME, Constants.ON_DEPS_CHANGED_ANNOTATION_CLASSNAME, Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, Constants.OBSERVABLE_ANNOTATION_CLASSNAME, Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, Constants.COMPUTED_ANNOTATION_CLASSNAME, Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, Constants.MEMOIZE_ANNOTATION_CLASSNAME, Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME, Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME, Constants.POST_DISPOSE_ANNOTATION_CLASSNAME, Constants.REFERENCE_ANNOTATION_CLASSNAME, Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, Constants.ON_ACTIVATE_ANNOTATION_CLASSNAME, Constants.ON_DEACTIVATE_ANNOTATION_CLASSNAME, Constants.ON_DISPOSE_ANNOTATION_CLASSNAME, Constants.ON_STALE_ANNOTATION_CLASSNAME, Constants.DEPENDENCY_ANNOTATION_CLASSNAME }; for ( int i = 0; i < annotationTypes.length; i++ ) { final String type1 = annotationTypes[ i ]; final Object annotation1 = ProcessorUtil.findAnnotationByType( method, type1 ); if ( null != annotation1 ) { for ( int j = i + 1; j < annotationTypes.length; j++ ) { final String type2 = annotationTypes[ j ]; final boolean observableDependency = type1.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) && type2.equals( Constants.DEPENDENCY_ANNOTATION_CLASSNAME ); final boolean observableReferenceId = type1.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) && type2.equals( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME ); if ( !observableDependency && !observableReferenceId ) { final Object annotation2 = ProcessorUtil.findAnnotationByType( method, type2 ); if ( null != annotation2 ) { final String message = "Method can not be annotated with both @" + ProcessorUtil.toSimpleName( type1 ) + " and @" + ProcessorUtil.toSimpleName( type2 ); throw new ArezProcessorException( message, method ); } } } } } } @Nonnull private String getPropertyAccessorName( @Nonnull final ExecutableElement method, @Nonnull final String specifiedName ) throws ArezProcessorException { String name = ProcessorUtil.deriveName( method, GETTER_PATTERN, specifiedName ); if ( null != name ) { return name; } if ( method.getReturnType().getKind() == TypeKind.BOOLEAN ) { name = ProcessorUtil.deriveName( method, ISSER_PATTERN, specifiedName ); if ( null != name ) { return name; } } return method.getSimpleName().toString(); } @Nonnull private String getNestedClassPrefix() { final StringBuilder name = new StringBuilder(); TypeElement t = getElement(); while ( NestingKind.TOP_LEVEL != t.getNestingKind() ) { t = (TypeElement) t.getEnclosingElement(); name.insert( 0, t.getSimpleName() + "_" ); } return name.toString(); } /** * Build the enhanced class for the component. */ @Nonnull TypeSpec buildType( @Nonnull final Types typeUtils ) throws ArezProcessorException { final TypeSpec.Builder builder = TypeSpec.classBuilder( getArezClassName() ). superclass( TypeName.get( getElement().asType() ) ). addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) ). addModifiers( Modifier.FINAL ); addOriginatingTypes( getElement(), builder ); addGeneratedAnnotation( builder ); if ( !_roComputeds.isEmpty() ) { builder.addAnnotation( AnnotationSpec.builder( SuppressWarnings.class ). addMember( "value", "$S", "unchecked" ). build() ); } final boolean publicType = ProcessorUtil.getConstructors( getElement() ). stream(). anyMatch( c -> c.getModifiers().contains( Modifier.PUBLIC ) ) && getElement().getModifiers().contains( Modifier.PUBLIC ); if ( publicType ) { builder.addModifiers( Modifier.PUBLIC ); } if ( null != _scopeAnnotation ) { final DeclaredType annotationType = _scopeAnnotation.getAnnotationType(); final TypeElement typeElement = (TypeElement) annotationType.asElement(); builder.addAnnotation( ClassName.get( typeElement ) ); } builder.addSuperinterface( GeneratorUtil.DISPOSABLE_CLASSNAME ); builder.addSuperinterface( ParameterizedTypeName.get( GeneratorUtil.IDENTIFIABLE_CLASSNAME, getIdType().box() ) ); if ( _observable ) { builder.addSuperinterface( GeneratorUtil.COMPONENT_OBSERVABLE_CLASSNAME ); } if ( _verify ) { builder.addSuperinterface( GeneratorUtil.VERIFIABLE_CLASSNAME ); } if ( _disposeTrackable ) { builder.addSuperinterface( GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME ); } if ( needsExplicitLink() ) { builder.addSuperinterface( GeneratorUtil.LINKABLE_CLASSNAME ); } buildFields( builder ); buildConstructors( builder, typeUtils ); builder.addMethod( buildContextRefMethod() ); if ( null != _componentRef ) { builder.addMethod( buildComponentRefMethod() ); } if ( !_references.isEmpty() || !_inverses.isEmpty() ) { builder.addMethod( buildLocatorRefMethod() ); } if ( null == _componentId ) { builder.addMethod( buildComponentIdMethod() ); } builder.addMethod( buildArezIdMethod() ); builder.addMethod( buildComponentNameMethod() ); final MethodSpec method = buildComponentTypeNameMethod(); if ( null != method ) { builder.addMethod( method ); } if ( _observable ) { builder.addMethod( buildInternalObserve() ); builder.addMethod( buildObserve() ); } if ( _disposeTrackable || !_roReferences.isEmpty() ) { builder.addMethod( buildInternalPreDispose() ); } if ( _disposeTrackable ) { builder.addMethod( buildNotifierAccessor() ); } builder.addMethod( buildIsDisposed() ); builder.addMethod( buildDispose() ); if ( _verify ) { builder.addMethod( buildVerify() ); } if ( needsExplicitLink() ) { builder.addMethod( buildLink() ); } _roObservables.forEach( e -> e.buildMethods( builder ) ); _roAutoruns.forEach( e -> e.buildMethods( builder ) ); _roActions.forEach( e -> e.buildMethods( builder ) ); _roComputeds.forEach( e -> e.buildMethods( builder ) ); _roMemoizes.forEach( e -> e.buildMethods( builder ) ); _roTrackeds.forEach( e -> e.buildMethods( builder ) ); _roReferences.forEach( e -> e.buildMethods( builder ) ); _roInverses.forEach( e -> e.buildMethods( builder ) ); builder.addMethod( buildHashcodeMethod() ); builder.addMethod( buildEqualsMethod() ); if ( _generateToString ) { builder.addMethod( buildToStringMethod() ); } return builder.build(); } private boolean needsExplicitLink() { return _roReferences.stream().anyMatch( r -> r.getLinkType().equals( "EXPLICIT" ) ); } @Nonnull private MethodSpec buildToStringMethod() throws ArezProcessorException { assert _generateToString; final MethodSpec.Builder method = MethodSpec.methodBuilder( "toString" ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( Override.class ). returns( TypeName.get( String.class ) ); final CodeBlock.Builder codeBlock = CodeBlock.builder(); codeBlock.beginControlFlow( "if ( $T.areNamesEnabled() )", GeneratorUtil.AREZ_CLASSNAME ); codeBlock.addStatement( "return $S + $N() + $S", "ArezComponent[", getComponentNameMethodName(), "]" ); codeBlock.nextControlFlow( "else" ); codeBlock.addStatement( "return super.toString()" ); codeBlock.endControlFlow(); method.addCode( codeBlock.build() ); return method.build(); } @Nonnull private MethodSpec buildEqualsMethod() throws ArezProcessorException { final String idMethod = getIdMethodName(); final MethodSpec.Builder method = MethodSpec.methodBuilder( "equals" ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( Override.class ). addParameter( Object.class, "o", Modifier.FINAL ). returns( TypeName.BOOLEAN ); final ClassName generatedClass = ClassName.get( getPackageName(), getArezClassName() ); final CodeBlock.Builder codeBlock = CodeBlock.builder(); codeBlock.beginControlFlow( "if ( this == o )" ); codeBlock.addStatement( "return true" ); codeBlock.nextControlFlow( "else if ( null == o || !(o instanceof $T) )", generatedClass ); codeBlock.addStatement( "return false" ); if ( null != _componentId ) { codeBlock.nextControlFlow( "else if ( $T.isDisposed( this ) != $T.isDisposed( o ) )", GeneratorUtil.DISPOSABLE_CLASSNAME, GeneratorUtil.DISPOSABLE_CLASSNAME ); codeBlock.addStatement( "return false" ); } codeBlock.nextControlFlow( "else" ); codeBlock.addStatement( "final $T that = ($T) o;", generatedClass, generatedClass ); final TypeKind kind = null != _componentId ? _componentId.getReturnType().getKind() : GeneratorUtil.DEFAULT_ID_KIND; if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR ) { codeBlock.addStatement( "return null != $N() && $N().equals( that.$N() )", idMethod, idMethod, idMethod ); } else { codeBlock.addStatement( "return $N() == that.$N()", idMethod, idMethod ); } codeBlock.endControlFlow(); if ( _requireEquals ) { method.addCode( codeBlock.build() ); } else { final CodeBlock.Builder guardBlock = CodeBlock.builder(); guardBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME ); guardBlock.add( codeBlock.build() ); guardBlock.nextControlFlow( "else" ); guardBlock.addStatement( "return super.equals( o )" ); guardBlock.endControlFlow(); method.addCode( guardBlock.build() ); } return method.build(); } @Nonnull private MethodSpec buildHashcodeMethod() throws ArezProcessorException { final String idMethod = getIdMethodName(); final MethodSpec.Builder method = MethodSpec.methodBuilder( "hashCode" ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( Override.class ). returns( TypeName.INT ); final TypeKind kind = null != _componentId ? _componentId.getReturnType().getKind() : GeneratorUtil.DEFAULT_ID_KIND; if ( _requireEquals ) { if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR ) { method.addStatement( "return null != $N() ? $N().hashCode() : $T.identityHashCode( this )", idMethod, idMethod, System.class ); } else if ( kind == TypeKind.BYTE ) { method.addStatement( "return $T.hashCode( $N() )", Byte.class, idMethod ); } else if ( kind == TypeKind.CHAR ) { method.addStatement( "return $T.hashCode( $N() )", Character.class, idMethod ); } else if ( kind == TypeKind.SHORT ) { method.addStatement( "return $T.hashCode( $N() )", Short.class, idMethod ); } else if ( kind == TypeKind.INT ) { method.addStatement( "return $T.hashCode( $N() )", Integer.class, idMethod ); } else if ( kind == TypeKind.LONG ) { method.addStatement( "return $T.hashCode( $N() )", Long.class, idMethod ); } else if ( kind == TypeKind.FLOAT ) { method.addStatement( "return $T.hashCode( $N() )", Float.class, idMethod ); } else if ( kind == TypeKind.DOUBLE ) { method.addStatement( "return $T.hashCode( $N() )", Double.class, idMethod ); } else { // So very unlikely but will cover it for completeness assert kind == TypeKind.BOOLEAN; method.addStatement( "return $T.hashCode( $N() )", Boolean.class, idMethod ); } } else { final CodeBlock.Builder guardBlock = CodeBlock.builder(); guardBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME ); if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR ) { guardBlock.addStatement( "return null != $N() ? $N().hashCode() : $T.identityHashCode( this )", idMethod, idMethod, System.class ); } else if ( kind == TypeKind.BYTE ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Byte.class, idMethod ); } else if ( kind == TypeKind.CHAR ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Character.class, idMethod ); } else if ( kind == TypeKind.SHORT ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Short.class, idMethod ); } else if ( kind == TypeKind.INT ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Integer.class, idMethod ); } else if ( kind == TypeKind.LONG ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Long.class, idMethod ); } else if ( kind == TypeKind.FLOAT ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Float.class, idMethod ); } else if ( kind == TypeKind.DOUBLE ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Double.class, idMethod ); } else { // So very unlikely but will cover it for completeness assert kind == TypeKind.BOOLEAN; guardBlock.addStatement( "return $T.hashCode( $N() )", Boolean.class, idMethod ); } guardBlock.nextControlFlow( "else" ); guardBlock.addStatement( "return super.hashCode()" ); guardBlock.endControlFlow(); method.addCode( guardBlock.build() ); } return method.build(); } @Nonnull String getComponentNameMethodName() { return null == _componentNameRef ? GeneratorUtil.NAME_METHOD_NAME : _componentNameRef.getSimpleName().toString(); } @Nonnull private MethodSpec buildContextRefMethod() throws ArezProcessorException { final String methodName = getContextMethodName(); final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ). addModifiers( Modifier.FINAL ). returns( GeneratorUtil.AREZ_CONTEXT_CLASSNAME ); GeneratorUtil.generateNotInitializedInvariant( this, method, methodName ); method.addStatement( "return $T.areZonesEnabled() ? this.$N : $T.context()", GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.CONTEXT_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME ); if ( null != _contextRef ) { method.addAnnotation( Override.class ); ProcessorUtil.copyWhitelistedAnnotations( _contextRef, method ); ProcessorUtil.copyAccessModifiers( _contextRef, method ); } return method.build(); } @Nonnull String getContextMethodName() { return null != _contextRef ? _contextRef.getSimpleName().toString() : GeneratorUtil.CONTEXT_FIELD_NAME; } @Nonnull private MethodSpec buildLocatorRefMethod() throws ArezProcessorException { final String methodName = GeneratorUtil.LOCATOR_METHOD_NAME; final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ). addModifiers( Modifier.FINAL ). returns( GeneratorUtil.LOCATOR_CLASSNAME ); GeneratorUtil.generateNotInitializedInvariant( this, method, methodName ); method.addStatement( "return $N().locator()", getContextMethodName() ); return method.build(); } @Nonnull private MethodSpec buildComponentRefMethod() throws ArezProcessorException { assert null != _componentRef; final String methodName = _componentRef.getSimpleName().toString(); final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ). addModifiers( Modifier.FINAL ). returns( GeneratorUtil.COMPONENT_CLASSNAME ); GeneratorUtil.generateNotInitializedInvariant( this, method, methodName ); GeneratorUtil.generateNotConstructedInvariant( this, method, methodName ); GeneratorUtil.generateNotCompleteInvariant( this, method, methodName ); GeneratorUtil.generateNotDisposedInvariant( this, method, methodName ); final CodeBlock.Builder block = CodeBlock.builder(); block.beginControlFlow( "if ( $T.shouldCheckInvariants() )", GeneratorUtil.AREZ_CLASSNAME ); block.addStatement( "$T.invariant( () -> $T.areNativeComponentsEnabled(), () -> \"Invoked @ComponentRef " + "method '$N' but Arez.areNativeComponentsEnabled() returned false.\" )", GeneratorUtil.GUARDS_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, methodName ); block.endControlFlow(); method.addCode( block.build() ); method.addStatement( "return this.$N", GeneratorUtil.COMPONENT_FIELD_NAME ); ProcessorUtil.copyWhitelistedAnnotations( _componentRef, method ); ProcessorUtil.copyAccessModifiers( _componentRef, method ); return method.build(); } @Nonnull private MethodSpec buildArezIdMethod() throws ArezProcessorException { return MethodSpec.methodBuilder( "getArezId" ). addAnnotation( Override.class ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addModifiers( Modifier.PUBLIC ). addModifiers( Modifier.FINAL ). returns( getIdType().box() ). addStatement( "return $N()", getIdMethodName() ).build(); } @Nonnull private MethodSpec buildComponentIdMethod() throws ArezProcessorException { assert null == _componentId; final MethodSpec.Builder method = MethodSpec.methodBuilder( GeneratorUtil.ID_FIELD_NAME ). addModifiers( Modifier.FINAL ). returns( GeneratorUtil.DEFAULT_ID_TYPE ); if ( !_idRequired ) { final CodeBlock.Builder block = CodeBlock.builder(); if ( _nameIncludesId ) { block.beginControlFlow( "if ( $T.shouldCheckInvariants() && !$T.areNamesEnabled() && !$T.areRegistriesEnabled() && !$T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME ); } else { block.beginControlFlow( "if ( $T.shouldCheckInvariants() && !$T.areRegistriesEnabled() && !$T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME ); } block.addStatement( "$T.fail( () -> \"Method invoked to access id when id not expected on component named '\" + $N() + \"'.\" )", GeneratorUtil.GUARDS_CLASSNAME, getComponentNameMethodName() ); block.endControlFlow(); method.addCode( block.build() ); } return method.addStatement( "return this.$N", GeneratorUtil.ID_FIELD_NAME ).build(); } /** * Generate the getter for component name. */ @Nonnull private MethodSpec buildComponentNameMethod() throws ArezProcessorException { final MethodSpec.Builder builder; final String methodName; if ( null == _componentNameRef ) { methodName = GeneratorUtil.NAME_METHOD_NAME; builder = MethodSpec.methodBuilder( methodName ); } else { methodName = _componentNameRef.getSimpleName().toString(); builder = MethodSpec.methodBuilder( methodName ); ProcessorUtil.copyWhitelistedAnnotations( _componentNameRef, builder ); ProcessorUtil.copyAccessModifiers( _componentNameRef, builder ); builder.addModifiers( Modifier.FINAL ); } builder.returns( TypeName.get( String.class ) ); GeneratorUtil.generateNotInitializedInvariant( this, builder, methodName ); if ( _nameIncludesId ) { builder.addStatement( "return $S + $N()", _type.isEmpty() ? "" : _type + ".", getIdMethodName() ); } else { builder.addStatement( "return $S", _type ); } return builder.build(); } @Nullable private MethodSpec buildComponentTypeNameMethod() throws ArezProcessorException { if ( null == _componentTypeNameRef ) { return null; } final MethodSpec.Builder builder = MethodSpec.methodBuilder( _componentTypeNameRef.getSimpleName().toString() ); ProcessorUtil.copyAccessModifiers( _componentTypeNameRef, builder ); builder.addModifiers( Modifier.FINAL ); builder.addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ); builder.returns( TypeName.get( String.class ) ); builder.addStatement( "return $S", _type ); return builder.build(); } @Nonnull private MethodSpec buildVerify() { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "verify" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ); GeneratorUtil.generateNotDisposedInvariant( this, builder, "verify" ); if ( !_roReferences.isEmpty() || !_roInverses.isEmpty() ) { final CodeBlock.Builder block = CodeBlock.builder(); block.beginControlFlow( "if ( $T.shouldCheckApiInvariants() && $T.isVerifyEnabled() )", GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME ); block.addStatement( "$T.apiInvariant( () -> this == $N().findById( $T.class, $N() ), () -> \"Attempted to " + "lookup self in Locator with type $T and id '\" + $N() + \"' but unable to locate " + "self. Actual value: \" + $N().findById( $T.class, $N() ) )", GeneratorUtil.GUARDS_CLASSNAME, GeneratorUtil.LOCATOR_METHOD_NAME, getElement(), getIdMethodName(), getElement(), getIdMethodName(), GeneratorUtil.LOCATOR_METHOD_NAME, getElement(), getIdMethodName() ); for ( final ReferenceDescriptor reference : _roReferences ) { block.addStatement( "this.$N = null", reference.getFieldName() ); block.addStatement( "this.$N()", reference.getLinkMethodName() ); } for ( final InverseDescriptor inverse : _roInverses ) { inverse.buildVerify( block ); } block.endControlFlow(); builder.addCode( block.build() ); } return builder.build(); } @Nonnull private MethodSpec buildLink() { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "link" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ); GeneratorUtil.generateNotDisposedInvariant( this, builder, "link" ); final List<ReferenceDescriptor> explicitReferences = _roReferences.stream().filter( r -> r.getLinkType().equals( "EXPLICIT" ) ).collect( Collectors.toList() ); for ( final ReferenceDescriptor reference : explicitReferences ) { builder.addStatement( "this.$N()", reference.getLinkMethodName() ); } return builder.build(); } /** * Generate the dispose method. */ @Nonnull private MethodSpec buildDispose() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "dispose" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ); final CodeBlock.Builder codeBlock = CodeBlock.builder(); codeBlock.beginControlFlow( "if ( !$T.isDisposingOrDisposed( this.$N ) )", GeneratorUtil.COMPONENT_STATE_CLASSNAME, GeneratorUtil.STATE_FIELD_NAME ); codeBlock.addStatement( "this.$N = $T.COMPONENT_DISPOSING", GeneratorUtil.STATE_FIELD_NAME, GeneratorUtil.COMPONENT_STATE_CLASSNAME ); final CodeBlock.Builder nativeComponentBlock = CodeBlock.builder(); nativeComponentBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME ); nativeComponentBlock.addStatement( "this.$N.dispose()", GeneratorUtil.COMPONENT_FIELD_NAME ); nativeComponentBlock.nextControlFlow( "else" ); final CodeBlock.Builder actionBlock = CodeBlock.builder(); actionBlock.beginControlFlow( "$N().safeAction( $T.areNamesEnabled() ? $N() + $S : null, true, false, () -> {", getContextMethodName(), GeneratorUtil.AREZ_CLASSNAME, getComponentNameMethodName(), ".dispose" ); if ( _disposeTrackable || !_roReferences.isEmpty() ) { actionBlock.addStatement( "this.$N()", GeneratorUtil.INTERNAL_PRE_DISPOSE_METHOD_NAME ); } else if ( null != _preDispose ) { actionBlock.addStatement( "super.$N()", _preDispose.getSimpleName() ); } if ( _observable ) { actionBlock.addStatement( "this.$N.dispose()", GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME ); } _roAutoruns.forEach( autorun -> autorun.buildDisposer( actionBlock ) ); _roTrackeds.forEach( tracked -> tracked.buildDisposer( actionBlock ) ); _roComputeds.forEach( computed -> computed.buildDisposer( actionBlock ) ); _roMemoizes.forEach( computed -> computed.buildDisposer( actionBlock ) ); _roObservables.forEach( observable -> observable.buildDisposer( actionBlock ) ); if ( null != _postDispose ) { actionBlock.addStatement( "super.$N()", _postDispose.getSimpleName() ); } actionBlock.endControlFlow( "} )" ); nativeComponentBlock.add( actionBlock.build() ); nativeComponentBlock.endControlFlow(); codeBlock.add( nativeComponentBlock.build() ); GeneratorUtil.setStateForInvariantChecking( codeBlock, "COMPONENT_DISPOSED" ); codeBlock.endControlFlow(); builder.addCode( codeBlock.build() ); return builder.build(); } /** * Generate the isDisposed method. */ @Nonnull private MethodSpec buildIsDisposed() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "isDisposed" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ). returns( TypeName.BOOLEAN ); builder.addStatement( "return $T.isDisposingOrDisposed( this.$N )", GeneratorUtil.COMPONENT_STATE_CLASSNAME, GeneratorUtil.STATE_FIELD_NAME ); return builder.build(); } /** * Generate the observe method. */ @Nonnull private MethodSpec buildInternalObserve() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( GeneratorUtil.INTERNAL_OBSERVE_METHOD_NAME ). addModifiers( Modifier.PRIVATE ). returns( TypeName.BOOLEAN ); builder.addStatement( "final boolean isNotDisposed = isNotDisposed()" ); final CodeBlock.Builder block = CodeBlock.builder(); block.beginControlFlow( "if ( isNotDisposed ) ", getContextMethodName() ); block.addStatement( "this.$N.reportObserved()", GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME ); block.endControlFlow(); builder.addCode( block.build() ); builder.addStatement( "return isNotDisposed" ); return builder.build(); } /** * Generate the observe method. */ @Nonnull private MethodSpec buildObserve() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "observe" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ). returns( TypeName.BOOLEAN ); if ( _disposeOnDeactivate ) { builder.addStatement( "return $N.get()", GeneratorUtil.DISPOSE_ON_DEACTIVATE_FIELD_NAME ); } else { builder.addStatement( "return $N()", GeneratorUtil.INTERNAL_OBSERVE_METHOD_NAME ); } return builder.build(); } /** * Generate the preDispose method. */ @Nonnull private MethodSpec buildInternalPreDispose() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( GeneratorUtil.INTERNAL_PRE_DISPOSE_METHOD_NAME ). addModifiers( Modifier.PRIVATE ); if ( null != _preDispose ) { builder.addStatement( "super.$N()", _preDispose.getSimpleName() ); } _roReferences.forEach( r -> r.buildDisposer( builder ) ); if ( _disposeTrackable ) { builder.addStatement( "$N.dispose()", GeneratorUtil.DISPOSE_NOTIFIER_FIELD_NAME ); for ( final DependencyDescriptor dependency : _roDependencies ) { final ExecutableElement method = dependency.getMethod(); final String methodName = method.getSimpleName().toString(); final boolean isNonnull = null != ProcessorUtil.findAnnotationByType( method, Constants.NONNULL_ANNOTATION_CLASSNAME ); if ( isNonnull ) { builder.addStatement( "$T.asDisposeTrackable( $N() ).getNotifier().removeOnDisposeListener( this )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, methodName ); } else { final String varName = GeneratorUtil.VARIABLE_PREFIX + methodName + "_dependency"; final boolean abstractObservables = method.getModifiers().contains( Modifier.ABSTRACT ); if ( abstractObservables ) { builder.addStatement( "final $T $N = this.$N", method.getReturnType(), varName, dependency.getObservable().getDataFieldName() ); } else { builder.addStatement( "final $T $N = super.$N()", method.getReturnType(), varName, methodName ); } final CodeBlock.Builder listenerBlock = CodeBlock.builder(); listenerBlock.beginControlFlow( "if ( null != $N )", varName ); listenerBlock.addStatement( "$T.asDisposeTrackable( $N ).getNotifier().removeOnDisposeListener( this )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, varName ); listenerBlock.endControlFlow(); builder.addCode( listenerBlock.build() ); } } } return builder.build(); } /** * Generate the observe method. */ @Nonnull private MethodSpec buildNotifierAccessor() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "getNotifier" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). returns( GeneratorUtil.DISPOSE_NOTIFIER_CLASSNAME ); builder.addStatement( "return $N", GeneratorUtil.DISPOSE_NOTIFIER_FIELD_NAME ); return builder.build(); } /** * Build the fields required to make class Observable. This involves; * <ul> * <li>the context field if there is any @Action methods.</li> * <li>the observable object for every @Observable.</li> * <li>the ComputedValue object for every @Computed method.</li> * </ul> */ private void buildFields( @Nonnull final TypeSpec.Builder builder ) { // If we don't have a method for object id but we need one then synthesize it if ( null == _componentId ) { final FieldSpec.Builder nextIdField = FieldSpec.builder( GeneratorUtil.DEFAULT_ID_TYPE, GeneratorUtil.NEXT_ID_FIELD_NAME, Modifier.VOLATILE, Modifier.STATIC, Modifier.PRIVATE ); builder.addField( nextIdField.build() ); final FieldSpec.Builder idField = FieldSpec.builder( GeneratorUtil.DEFAULT_ID_TYPE, GeneratorUtil.ID_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ); builder.addField( idField.build() ); } final FieldSpec.Builder disposableField = FieldSpec.builder( TypeName.BYTE, GeneratorUtil.STATE_FIELD_NAME, Modifier.PRIVATE ); builder.addField( disposableField.build() ); // Create the field that contains the context { final FieldSpec.Builder field = FieldSpec.builder( GeneratorUtil.AREZ_CONTEXT_CLASSNAME, GeneratorUtil.CONTEXT_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ). addAnnotation( GeneratorUtil.NULLABLE_CLASSNAME ); builder.addField( field.build() ); } //Create the field that contains the component { final FieldSpec.Builder field = FieldSpec.builder( GeneratorUtil.COMPONENT_CLASSNAME, GeneratorUtil.COMPONENT_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ); builder.addField( field.build() ); } if ( _observable ) { final ParameterizedTypeName typeName = ParameterizedTypeName.get( GeneratorUtil.OBSERVABLE_CLASSNAME, TypeName.BOOLEAN.box() ); final FieldSpec.Builder field = FieldSpec.builder( typeName, GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ); builder.addField( field.build() ); } if ( _disposeTrackable ) { final FieldSpec.Builder field = FieldSpec.builder( GeneratorUtil.DISPOSE_NOTIFIER_CLASSNAME, GeneratorUtil.DISPOSE_NOTIFIER_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ); builder.addField( field.build() ); } _roObservables.forEach( observable -> observable.buildFields( builder ) ); _roComputeds.forEach( computed -> computed.buildFields( builder ) ); _roMemoizes.forEach( e -> e.buildFields( builder ) ); _roAutoruns.forEach( autorun -> autorun.buildFields( builder ) ); _roTrackeds.forEach( tracked -> tracked.buildFields( builder ) ); _roReferences.forEach( r -> r.buildFields( builder ) ); if ( _disposeOnDeactivate ) { final FieldSpec.Builder field = FieldSpec.builder( ParameterizedTypeName.get( GeneratorUtil.COMPUTED_VALUE_CLASSNAME, TypeName.BOOLEAN.box() ), GeneratorUtil.DISPOSE_ON_DEACTIVATE_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ); builder.addField( field.build() ); } } /** * Build all constructors as they appear on the ArezComponent class. * Arez Observable fields are populated as required and parameters are passed up to superclass. */ private void buildConstructors( @Nonnull final TypeSpec.Builder builder, @Nonnull final Types typeUtils ) { final boolean requiresDeprecatedSuppress = hasDeprecatedElements(); for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( getElement() ) ) { final ExecutableType methodType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), constructor ); builder.addMethod( buildConstructor( constructor, methodType, requiresDeprecatedSuppress ) ); } } /** * Build a constructor based on the supplied constructor */ @Nonnull private MethodSpec buildConstructor( @Nonnull final ExecutableElement constructor, @Nonnull final ExecutableType constructorType, final boolean requiresDeprecatedSuppress ) { final MethodSpec.Builder builder = MethodSpec.constructorBuilder(); ProcessorUtil.copyAccessModifiers( constructor, builder ); ProcessorUtil.copyExceptions( constructorType, builder ); ProcessorUtil.copyTypeParameters( constructorType, builder ); if ( requiresDeprecatedSuppress ) { builder.addAnnotation( AnnotationSpec.builder( SuppressWarnings.class ) .addMember( "value", "$S", "deprecation" ) .build() ); } if ( _inject ) { builder.addAnnotation( GeneratorUtil.INJECT_CLASSNAME ); } final List<ObservableDescriptor> initializers = getInitializers(); final StringBuilder superCall = new StringBuilder(); superCall.append( "super(" ); final ArrayList<String> parameterNames = new ArrayList<>(); boolean firstParam = true; for ( final VariableElement element : constructor.getParameters() ) { final ParameterSpec.Builder param = ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL ); ProcessorUtil.copyWhitelistedAnnotations( element, param ); builder.addParameter( param.build() ); parameterNames.add( element.getSimpleName().toString() ); if ( !firstParam ) { superCall.append( "," ); } firstParam = false; superCall.append( "$N" ); } superCall.append( ")" ); builder.addStatement( superCall.toString(), parameterNames.toArray() ); if ( !_references.isEmpty() ) { final CodeBlock.Builder block = CodeBlock.builder(); block.beginControlFlow( "if ( $T.shouldCheckApiInvariants() )", GeneratorUtil.AREZ_CLASSNAME ); block.addStatement( "$T.apiInvariant( () -> $T.areReferencesEnabled(), () -> \"Attempted to create instance " + "of component of type '$N' that contains references but Arez.areReferencesEnabled() " + "returns false. References need to be enabled to use this component\" )", GeneratorUtil.GUARDS_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, getType() ); block.endControlFlow(); builder.addCode( block.build() ); } for ( final ObservableDescriptor observable : initializers ) { final String candidateName = observable.getName(); final String name = isNameCollision( constructor, Collections.emptyList(), candidateName ) ? GeneratorUtil.INITIALIZER_PREFIX + candidateName : candidateName; final ParameterSpec.Builder param = ParameterSpec.builder( TypeName.get( observable.getGetterType().getReturnType() ), name, Modifier.FINAL ); ProcessorUtil.copyWhitelistedAnnotations( observable.getGetter(), param ); builder.addParameter( param.build() ); final boolean isPrimitive = TypeName.get( observable.getGetterType().getReturnType() ).isPrimitive(); if ( isPrimitive ) { builder.addStatement( "this.$N = $N", observable.getDataFieldName(), name ); } else { builder.addStatement( "this.$N = $T.requireNonNull( $N )", observable.getDataFieldName(), Objects.class, name ); } } builder.addStatement( "this.$N = $T.areZonesEnabled() ? $T.context() : null", GeneratorUtil.CONTEXT_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME ); // Synthesize Id if required if ( null == _componentId ) { if ( _nameIncludesId ) { if ( _idRequired ) { builder.addStatement( "this.$N = $N++", GeneratorUtil.ID_FIELD_NAME, GeneratorUtil.NEXT_ID_FIELD_NAME ); } else { builder.addStatement( "this.$N = ( $T.areNamesEnabled() || $T.areRegistriesEnabled() || $T.areNativeComponentsEnabled() ) ? $N++ : 0", GeneratorUtil.ID_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.NEXT_ID_FIELD_NAME ); } } else { builder.addStatement( "this.$N = ( $T.areRegistriesEnabled() || $T.areNativeComponentsEnabled() ) ? $N++ : 0", GeneratorUtil.ID_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.NEXT_ID_FIELD_NAME ); } } GeneratorUtil.setStateForInvariantChecking( builder, "COMPONENT_INITIALIZED" ); // Create component representation if required { final StringBuilder sb = new StringBuilder(); final ArrayList<Object> params = new ArrayList<>(); sb.append( "this.$N = $T.areNativeComponentsEnabled() ? " + "$N().component( $S, $N(), $T.areNamesEnabled() ? $N() :" + " null" ); params.add( GeneratorUtil.COMPONENT_FIELD_NAME ); params.add( GeneratorUtil.AREZ_CLASSNAME ); params.add( getContextMethodName() ); params.add( _type ); params.add( getIdMethodName() ); params.add( GeneratorUtil.AREZ_CLASSNAME ); params.add( getComponentNameMethodName() ); if ( _disposeTrackable || null != _preDispose || null != _postDispose ) { sb.append( ", " ); if ( _disposeTrackable ) { sb.append( "() -> $N()" ); params.add( GeneratorUtil.INTERNAL_PRE_DISPOSE_METHOD_NAME ); } else if ( null != _preDispose ) { sb.append( "() -> super.$N()" ); params.add( _preDispose.getSimpleName().toString() ); } if ( null != _postDispose ) { sb.append( ", () -> super.$N()" ); params.add( _postDispose.getSimpleName().toString() ); } } sb.append( " ) : null" ); builder.addStatement( sb.toString(), params.toArray() ); } if ( _observable ) { builder.addStatement( "this.$N = $N().observable( " + "$T.areNativeComponentsEnabled() ? this.$N : null, " + "$T.areNamesEnabled() ? $N() + $S : null, " + "$T.arePropertyIntrospectorsEnabled() ? () -> this.$N >= 0 : null )", GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME, getContextMethodName(), GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.COMPONENT_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME, getComponentNameMethodName(), ".isDisposed", GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.STATE_FIELD_NAME ); } if ( _disposeTrackable ) { builder.addStatement( "this.$N = new $T()", GeneratorUtil.DISPOSE_NOTIFIER_FIELD_NAME, GeneratorUtil.DISPOSE_NOTIFIER_CLASSNAME ); } if ( _disposeOnDeactivate ) { builder.addStatement( "this.$N = $N().computedValue( " + "$T.areNativeComponentsEnabled() ? this.$N : null, " + "$T.areNamesEnabled() ? $N() + $S : null, " + "() -> $N(), null, () -> $N().scheduleDispose( this ), null, null, $T.HIGHEST )", GeneratorUtil.DISPOSE_ON_DEACTIVATE_FIELD_NAME, getContextMethodName(), GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.COMPONENT_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME, getComponentNameMethodName(), ".disposeOnDeactivate", GeneratorUtil.INTERNAL_OBSERVE_METHOD_NAME, getContextMethodName(), GeneratorUtil.PRIORITY_CLASSNAME ); } _roObservables.forEach( observable -> observable.buildInitializer( builder ) ); _roComputeds.forEach( computed -> computed.buildInitializer( builder ) ); _roMemoizes.forEach( e -> e.buildInitializer( builder ) ); _roAutoruns.forEach( autorun -> autorun.buildInitializer( builder ) ); _roTrackeds.forEach( tracked -> tracked.buildInitializer( builder ) ); _roInverses.forEach( e -> e.buildInitializer( builder ) ); for ( final DependencyDescriptor dep : _roDependencies ) { final ExecutableElement method = dep.getMethod(); final String methodName = method.getSimpleName().toString(); final boolean abstractObservables = method.getModifiers().contains( Modifier.ABSTRACT ); final boolean isNonnull = null != ProcessorUtil.findAnnotationByType( method, Constants.NONNULL_ANNOTATION_CLASSNAME ); if ( abstractObservables ) { if ( isNonnull ) { assert dep.shouldCascadeDispose(); builder.addStatement( "$T.asDisposeTrackable( $N ).getNotifier().addOnDisposeListener( this, this::dispose )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, dep.getObservable().getDataFieldName() ); } else { final String varName = GeneratorUtil.VARIABLE_PREFIX + methodName + "_dependency"; builder.addStatement( "final $T $N = this.$N", dep.getMethod().getReturnType(), varName, dep.getObservable().getDataFieldName() ); final CodeBlock.Builder listenerBlock = CodeBlock.builder(); listenerBlock.beginControlFlow( "if ( null != $N )", varName ); if ( dep.shouldCascadeDispose() ) { listenerBlock.addStatement( "$T.asDisposeTrackable( $N ).getNotifier().addOnDisposeListener( this, this::dispose )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, dep.getObservable().getDataFieldName() ); } else { listenerBlock.addStatement( "$T.asDisposeTrackable( $N ).getNotifier().addOnDisposeListener( this, () -> $N( null ) )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, dep.getObservable().getDataFieldName(), dep.getObservable().getSetter().getSimpleName().toString() ); } listenerBlock.endControlFlow(); builder.addCode( listenerBlock.build() ); } } else { if ( isNonnull ) { assert dep.shouldCascadeDispose(); builder.addStatement( "$T.asDisposeTrackable( super.$N() ).getNotifier().addOnDisposeListener( this, this::dispose )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, method.getSimpleName().toString() ); } else { final String varName = GeneratorUtil.VARIABLE_PREFIX + methodName + "_dependency"; builder.addStatement( "final $T $N = super.$N()", dep.getMethod().getReturnType(), varName, method.getSimpleName().toString() ); final CodeBlock.Builder listenerBlock = CodeBlock.builder(); listenerBlock.beginControlFlow( "if ( null != $N )", varName ); if ( dep.shouldCascadeDispose() ) { listenerBlock.addStatement( "$T.asDisposeTrackable( super.$N() ).getNotifier().addOnDisposeListener( this, this::dispose )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, method.getSimpleName() ); } else { listenerBlock.addStatement( "$T.asDisposeTrackable( super.$N() ).getNotifier().addOnDisposeListener( this, () -> $N( null ) )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, method.getSimpleName(), dep.getObservable().getSetter().getSimpleName().toString() ); } listenerBlock.endControlFlow(); builder.addCode( listenerBlock.build() ); } } } GeneratorUtil.setStateForInvariantChecking( builder, "COMPONENT_CONSTRUCTED" ); final List<ReferenceDescriptor> eagerReferences = _roReferences.stream().filter( r -> r.getLinkType().equals( "EAGER" ) ).collect( Collectors.toList() ); for ( final ReferenceDescriptor reference : eagerReferences ) { builder.addStatement( "this.$N()", reference.getLinkMethodName() ); } final ExecutableElement postConstruct = getPostConstruct(); if ( null != postConstruct ) { builder.addStatement( "super.$N()", postConstruct.getSimpleName().toString() ); } final CodeBlock.Builder componentEnabledBlock = CodeBlock.builder(); componentEnabledBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME ); componentEnabledBlock.addStatement( "this.$N.complete()", GeneratorUtil.COMPONENT_FIELD_NAME ); componentEnabledBlock.endControlFlow(); builder.addCode( componentEnabledBlock.build() ); if ( !_deferSchedule && requiresSchedule() ) { GeneratorUtil.setStateForInvariantChecking( builder, "COMPONENT_COMPLETE" ); builder.addStatement( "$N().triggerScheduler()", getContextMethodName() ); } GeneratorUtil.setStateForInvariantChecking( builder, "COMPONENT_READY" ); return builder.build(); } @Nonnull private List<ObservableDescriptor> getInitializers() { return getObservables() .stream() .filter( ObservableDescriptor::requireInitializer ) .collect( Collectors.toList() ); } private boolean isNameCollision( @Nonnull final ExecutableElement constructor, @Nonnull final List<ObservableDescriptor> initializers, @Nonnull final String name ) { return constructor.getParameters().stream().anyMatch( p -> p.getSimpleName().toString().equals( name ) ) || initializers.stream().anyMatch( o -> o.getName().equals( name ) ); } boolean shouldGenerateComponentDaggerModule() { return _dagger; } @Nonnull TypeSpec buildComponentDaggerModule() throws ArezProcessorException { assert shouldGenerateComponentDaggerModule(); final TypeSpec.Builder builder = TypeSpec.interfaceBuilder( getComponentDaggerModuleName() ). addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) ); addOriginatingTypes( getElement(), builder ); addGeneratedAnnotation( builder ); builder.addAnnotation( GeneratorUtil.DAGGER_MODULE_CLASSNAME ); builder.addModifiers( Modifier.PUBLIC ); final MethodSpec.Builder method = MethodSpec.methodBuilder( "provideComponent" ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addAnnotation( GeneratorUtil.DAGGER_PROVIDES_CLASSNAME ). addModifiers( Modifier.STATIC, Modifier.PUBLIC ). addParameter( ClassName.get( getPackageName(), getArezClassName() ), "component", Modifier.FINAL ). addStatement( "return component" ). returns( ClassName.get( getElement() ) ); if ( null != _scopeAnnotation ) { final DeclaredType annotationType = _scopeAnnotation.getAnnotationType(); final TypeElement typeElement = (TypeElement) annotationType.asElement(); method.addAnnotation( ClassName.get( typeElement ) ); } builder.addMethod( method.build() ); return builder.build(); } boolean hasRepository() { return null != _repositoryExtensions; } @SuppressWarnings( "ConstantConditions" ) void configureRepository( @Nonnull final String name, @Nonnull final List<TypeElement> extensions, @Nonnull final String repositoryInjectConfig, @Nonnull final String repositoryDaggerConfig ) { assert null != name; assert null != extensions; _repositoryInjectConfig = repositoryInjectConfig; _repositoryDaggerConfig = repositoryDaggerConfig; for ( final TypeElement extension : extensions ) { if ( ElementKind.INTERFACE != extension.getKind() ) { throw new ArezProcessorException( "Class annotated with @Repository defined an extension that is " + "not an interface. Extension: " + extension.getQualifiedName(), getElement() ); } for ( final Element enclosedElement : extension.getEnclosedElements() ) { if ( ElementKind.METHOD == enclosedElement.getKind() ) { final ExecutableElement method = (ExecutableElement) enclosedElement; if ( !method.isDefault() && !( method.getSimpleName().toString().equals( "self" ) && 0 == method.getParameters().size() ) ) { throw new ArezProcessorException( "Class annotated with @Repository defined an extension that has " + "a non default method. Extension: " + extension.getQualifiedName() + " Method: " + method, getElement() ); } } } } _repositoryExtensions = extensions; } /** * Build the enhanced class for the component. */ @Nonnull TypeSpec buildRepository( @Nonnull final Types typeUtils ) throws ArezProcessorException { assert null != _repositoryExtensions; final TypeElement element = getElement(); final ClassName arezType = ClassName.get( getPackageName(), getArezClassName() ); final TypeSpec.Builder builder = TypeSpec.classBuilder( getRepositoryName() ). addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) ); addOriginatingTypes( element, builder ); addGeneratedAnnotation( builder ); final boolean addSingletonAnnotation = "ENABLE".equals( _repositoryInjectConfig ) || ( "AUTODETECT".equals( _repositoryInjectConfig ) && _injectClassesPresent ); final AnnotationSpec.Builder arezComponent = AnnotationSpec.builder( ClassName.bestGuess( Constants.COMPONENT_ANNOTATION_CLASSNAME ) ); if ( !addSingletonAnnotation ) { arezComponent.addMember( "nameIncludesId", "false" ); } if ( !"AUTODETECT".equals( _repositoryInjectConfig ) ) { arezComponent.addMember( "inject", "$T.$N", GeneratorUtil.INJECTIBLE_CLASSNAME, _repositoryInjectConfig ); } if ( !"AUTODETECT".equals( _repositoryDaggerConfig ) ) { arezComponent.addMember( "dagger", "$T.$N", GeneratorUtil.INJECTIBLE_CLASSNAME, _repositoryDaggerConfig ); } builder.addAnnotation( arezComponent.build() ); if ( addSingletonAnnotation ) { builder.addAnnotation( GeneratorUtil.SINGLETON_CLASSNAME ); } builder.superclass( ParameterizedTypeName.get( GeneratorUtil.ABSTRACT_REPOSITORY_CLASSNAME, getIdType().box(), ClassName.get( element ), ClassName.get( getPackageName(), getRepositoryName() ) ) ); _repositoryExtensions.forEach( e -> builder.addSuperinterface( TypeName.get( e.asType() ) ) ); ProcessorUtil.copyAccessModifiers( element, builder ); builder.addModifiers( Modifier.ABSTRACT ); //Add the default access, no-args constructor builder.addMethod( MethodSpec.constructorBuilder().build() ); // Add the factory method builder.addMethod( buildFactoryMethod() ); if ( shouldRepositoryDefineCreate() ) { for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( element ) ) { final ExecutableType methodType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), constructor ); builder.addMethod( buildRepositoryCreate( constructor, methodType, arezType ) ); } } if ( shouldRepositoryDefineAttach() ) { builder.addMethod( buildRepositoryAttach() ); } if ( null != _componentId ) { builder.addMethod( buildFindByIdMethod() ); builder.addMethod( buildGetByIdMethod() ); } if ( shouldRepositoryDefineDestroy() ) { builder.addMethod( buildRepositoryDestroy() ); } if ( shouldRepositoryDefineDetach() ) { builder.addMethod( buildRepositoryDetach() ); } return builder.build(); } private void addOriginatingTypes( @Nonnull final TypeElement element, @Nonnull final TypeSpec.Builder builder ) { builder.addOriginatingElement( element ); ProcessorUtil.getSuperTypes( element ).forEach( builder::addOriginatingElement ); } @Nonnull private String getArezClassName() { return getNestedClassPrefix() + "Arez_" + getElement().getSimpleName(); } @Nonnull private String getComponentDaggerModuleName() { return getNestedClassPrefix() + getElement().getSimpleName() + "DaggerModule"; } @Nonnull private String getArezRepositoryName() { return "Arez_" + getNestedClassPrefix() + getElement().getSimpleName() + "Repository"; } @Nonnull private String getRepositoryName() { return getNestedClassPrefix() + getElement().getSimpleName() + "Repository"; } @Nonnull private MethodSpec buildRepositoryAttach() { final TypeName entityType = TypeName.get( getElement().asType() ); final MethodSpec.Builder method = MethodSpec.methodBuilder( "attach" ). addAnnotation( Override.class ). addAnnotation( AnnotationSpec.builder( GeneratorUtil.ACTION_CLASSNAME ) .addMember( "reportParameters", "false" ) .build() ). addParameter( ParameterSpec.builder( entityType, "entity", Modifier.FINAL ) .addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ) .build() ). addStatement( "super.attach( entity )" ); ProcessorUtil.copyAccessModifiers( getElement(), method ); return method.build(); } @Nonnull private MethodSpec buildRepositoryDetach() { final TypeName entityType = TypeName.get( getElement().asType() ); final MethodSpec.Builder method = MethodSpec.methodBuilder( "detach" ). addAnnotation( Override.class ). addAnnotation( AnnotationSpec.builder( GeneratorUtil.ACTION_CLASSNAME ) .addMember( "reportParameters", "false" ) .build() ). addParameter( ParameterSpec.builder( entityType, "entity", Modifier.FINAL ) .addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ) .build() ). addStatement( "super.detach( entity )" ); ProcessorUtil.copyAccessModifiers( getElement(), method ); return method.build(); } @Nonnull private MethodSpec buildRepositoryDestroy() { final TypeName entityType = TypeName.get( getElement().asType() ); final MethodSpec.Builder method = MethodSpec.methodBuilder( "destroy" ). addAnnotation( Override.class ). addAnnotation( AnnotationSpec.builder( GeneratorUtil.ACTION_CLASSNAME ) .addMember( "reportParameters", "false" ) .build() ). addParameter( ParameterSpec.builder( entityType, "entity", Modifier.FINAL ) .addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ) .build() ). addStatement( "super.destroy( entity )" ); ProcessorUtil.copyAccessModifiers( getElement(), method ); final Set<Modifier> modifiers = getElement().getModifiers(); if ( !modifiers.contains( Modifier.PUBLIC ) && !modifiers.contains( Modifier.PROTECTED ) ) { /* * The destroy method inherited from AbstractContainer is protected and the override * must be at least the same access level. */ method.addModifiers( Modifier.PROTECTED ); } return method.build(); } @Nonnull private MethodSpec buildFindByIdMethod() { assert null != _componentId; final MethodSpec.Builder method = MethodSpec.methodBuilder( "findBy" + getIdName() ). addModifiers( Modifier.FINAL ). addParameter( ParameterSpec.builder( getIdType(), "id", Modifier.FINAL ).build() ). addAnnotation( GeneratorUtil.NULLABLE_CLASSNAME ). returns( TypeName.get( getElement().asType() ) ). addStatement( "return findByArezId( id )" ); ProcessorUtil.copyAccessModifiers( getElement(), method ); return method.build(); } @Nonnull private MethodSpec buildGetByIdMethod() { final TypeName entityType = TypeName.get( getElement().asType() ); final MethodSpec.Builder method = MethodSpec.methodBuilder( "getBy" + getIdName() ). addModifiers( Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addParameter( ParameterSpec.builder( getIdType(), "id", Modifier.FINAL ).build() ). returns( entityType ). addStatement( "return getByArezId( id )" ); ProcessorUtil.copyAccessModifiers( getElement(), method ); return method.build(); } @Nonnull private MethodSpec buildFactoryMethod() { final MethodSpec.Builder method = MethodSpec.methodBuilder( "newRepository" ). addModifiers( Modifier.STATIC ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). returns( ClassName.get( getPackageName(), getRepositoryName() ) ). addStatement( "return new $T()", ClassName.get( getPackageName(), getArezRepositoryName() ) ); ProcessorUtil.copyAccessModifiers( getElement(), method ); return method.build(); } @Nonnull private MethodSpec buildRepositoryCreate( @Nonnull final ExecutableElement constructor, @Nonnull final ExecutableType methodType, @Nonnull final ClassName arezType ) { final String suffix = constructor.getParameters().stream(). map( p -> p.getSimpleName().toString() ).collect( Collectors.joining( "_" ) ); final String actionName = "create" + ( suffix.isEmpty() ? "" : "_" + suffix ); final AnnotationSpec annotationSpec = AnnotationSpec.builder( ClassName.bestGuess( Constants.ACTION_ANNOTATION_CLASSNAME ) ). addMember( "name", "$S", actionName ).build(); final MethodSpec.Builder builder = MethodSpec.methodBuilder( "create" ). addAnnotation( annotationSpec ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). returns( TypeName.get( asDeclaredType() ) ); ProcessorUtil.copyAccessModifiers( getElement(), builder ); ProcessorUtil.copyExceptions( methodType, builder ); ProcessorUtil.copyTypeParameters( methodType, builder ); final StringBuilder newCall = new StringBuilder(); newCall.append( "final $T entity = new $T(" ); final ArrayList<Object> parameters = new ArrayList<>(); parameters.add( arezType ); parameters.add( arezType ); boolean firstParam = true; for ( final VariableElement element : constructor.getParameters() ) { final ParameterSpec.Builder param = ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL ); ProcessorUtil.copyWhitelistedAnnotations( element, param ); builder.addParameter( param.build() ); parameters.add( element.getSimpleName().toString() ); if ( !firstParam ) { newCall.append( "," ); } firstParam = false; newCall.append( "$N" ); } for ( final ObservableDescriptor observable : getInitializers() ) { final String candidateName = observable.getName(); final String name = isNameCollision( constructor, Collections.emptyList(), candidateName ) ? GeneratorUtil.INITIALIZER_PREFIX + candidateName : candidateName; final ParameterSpec.Builder param = ParameterSpec.builder( TypeName.get( observable.getGetterType().getReturnType() ), name, Modifier.FINAL ); ProcessorUtil.copyWhitelistedAnnotations( observable.getGetter(), param ); builder.addParameter( param.build() ); parameters.add( name ); if ( !firstParam ) { newCall.append( "," ); } firstParam = false; newCall.append( "$N" ); } newCall.append( ")" ); builder.addStatement( newCall.toString(), parameters.toArray() ); builder.addStatement( "attach( entity )" ); builder.addStatement( "return entity" ); return builder.build(); } @Nonnull String getPackageName() { return _packageElement.getQualifiedName().toString(); } @Nonnull private String getIdMethodName() { /* * Note that it is a deliberate choice to not use getArezId() as that will box Id which for the * "normal" case involves converting a long to a Long and it was decided that the slight increase in * code size was worth the slightly reduced memory pressure. */ return null != _componentId ? _componentId.getSimpleName().toString() : GeneratorUtil.ID_FIELD_NAME; } @Nonnull private String getIdName() { assert null != _componentId; final String name = ProcessorUtil.deriveName( _componentId, GETTER_PATTERN, ProcessorUtil.SENTINEL_NAME ); if ( null != name ) { return Character.toUpperCase( name.charAt( 0 ) ) + ( name.length() > 1 ? name.substring( 1 ) : "" ); } else { return "Id"; } } @Nonnull private TypeName getIdType() { return null == _componentIdMethodType ? GeneratorUtil.DEFAULT_ID_TYPE : TypeName.get( _componentIdMethodType.getReturnType() ); } private <T> T getAnnotationParameter( @Nonnull final AnnotationMirror annotation, @Nonnull final String parameterName ) { return ProcessorUtil.getAnnotationValue( _elements, annotation, parameterName ); } private void addGeneratedAnnotation( @Nonnull final TypeSpec.Builder builder ) { GeneratedAnnotationSpecs .generatedAnnotationSpec( _elements, _sourceVersion, ArezProcessor.class ) .ifPresent( builder::addAnnotation ); } private boolean shouldRepositoryDefineCreate() { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, getElement(), Constants.REPOSITORY_ANNOTATION_CLASSNAME, "attach" ).getValue(); switch ( injectParameter.getSimpleName().toString() ) { case "CREATE_ONLY": case "CREATE_OR_ATTACH": return true; default: return false; } } private boolean shouldRepositoryDefineAttach() { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, getElement(), Constants.REPOSITORY_ANNOTATION_CLASSNAME, "attach" ).getValue(); switch ( injectParameter.getSimpleName().toString() ) { case "ATTACH_ONLY": case "CREATE_OR_ATTACH": return true; default: return false; } } private boolean shouldRepositoryDefineDestroy() { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, getElement(), Constants.REPOSITORY_ANNOTATION_CLASSNAME, "detach" ).getValue(); switch ( injectParameter.getSimpleName().toString() ) { case "DESTROY_ONLY": case "DESTROY_OR_DETACH": return true; default: return false; } } private boolean shouldRepositoryDefineDetach() { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, getElement(), Constants.REPOSITORY_ANNOTATION_CLASSNAME, "detach" ).getValue(); switch ( injectParameter.getSimpleName().toString() ) { case "DETACH_ONLY": case "DESTROY_OR_DETACH": return true; default: return false; } } }
processor/src/main/java/arez/processor/ComponentDescriptor.java
package arez.processor; import com.google.auto.common.GeneratedAnnotationSpecs; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; /** * The class that represents the parsed state of ArezComponent annotated class. */ @SuppressWarnings( "Duplicates" ) final class ComponentDescriptor { private static final Pattern OBSERVABLE_REF_PATTERN = Pattern.compile( "^get([A-Z].*)Observable$" ); private static final Pattern COMPUTED_VALUE_REF_PATTERN = Pattern.compile( "^get([A-Z].*)ComputedValue$" ); private static final Pattern OBSERVER_REF_PATTERN = Pattern.compile( "^get([A-Z].*)Observer$" ); private static final Pattern SETTER_PATTERN = Pattern.compile( "^set([A-Z].*)$" ); private static final Pattern GETTER_PATTERN = Pattern.compile( "^get([A-Z].*)$" ); private static final Pattern ID_GETTER_PATTERN = Pattern.compile( "^get([A-Z].*)Id$" ); private static final Pattern RAW_ID_GETTER_PATTERN = Pattern.compile( "^(.*)Id$" ); private static final Pattern ISSER_PATTERN = Pattern.compile( "^is([A-Z].*)$" ); private static final List<String> OBJECT_METHODS = Arrays.asList( "hashCode", "equals", "clone", "toString", "finalize", "getClass", "wait", "notifyAll", "notify" ); private static final List<String> AREZ_SPECIAL_METHODS = Arrays.asList( "observe", "dispose", "isDisposed", "getArezId" ); @Nullable private List<TypeElement> _repositoryExtensions; /** * Flag controlling whether dagger module is created for repository. */ private String _repositoryDaggerConfig = "AUTODETECT"; /** * Flag controlling whether Inject annotation is added to repository constructor. */ private String _repositoryInjectConfig = "AUTODETECT"; @Nonnull private final SourceVersion _sourceVersion; @Nonnull private final Elements _elements; @Nonnull private final Types _typeUtils; @Nonnull private final String _type; private final boolean _nameIncludesId; private final boolean _allowEmpty; private final boolean _observable; private final boolean _disposeTrackable; private final boolean _disposeOnDeactivate; private final boolean _injectClassesPresent; private final boolean _inject; private final boolean _dagger; /** * Annotation that indicates whether equals/hashCode should be implemented. See arez.annotations.ArezComponent.requireEquals() */ private final boolean _requireEquals; /** * Flag indicating whether generated component should implement arez.component.Verifiable. */ private final boolean _verify; /** * Scope annotation that is declared on component and should be transferred to injection providers. */ private final AnnotationMirror _scopeAnnotation; private final boolean _deferSchedule; private final boolean _generateToString; private boolean _idRequired; @Nonnull private final PackageElement _packageElement; @Nonnull private final TypeElement _element; @Nullable private ExecutableElement _postConstruct; @Nullable private ExecutableElement _componentId; @Nullable private ExecutableType _componentIdMethodType; @Nullable private ExecutableElement _componentRef; @Nullable private ExecutableElement _contextRef; @Nullable private ExecutableElement _componentTypeNameRef; @Nullable private ExecutableElement _componentNameRef; @Nullable private ExecutableElement _preDispose; @Nullable private ExecutableElement _postDispose; private final Map<String, CandidateMethod> _observerRefs = new LinkedHashMap<>(); private final Map<String, ObservableDescriptor> _observables = new LinkedHashMap<>(); private final Collection<ObservableDescriptor> _roObservables = Collections.unmodifiableCollection( _observables.values() ); private final Map<String, ActionDescriptor> _actions = new LinkedHashMap<>(); private final Collection<ActionDescriptor> _roActions = Collections.unmodifiableCollection( _actions.values() ); private final Map<String, ComputedDescriptor> _computeds = new LinkedHashMap<>(); private final Collection<ComputedDescriptor> _roComputeds = Collections.unmodifiableCollection( _computeds.values() ); private final Map<String, MemoizeDescriptor> _memoizes = new LinkedHashMap<>(); private final Collection<MemoizeDescriptor> _roMemoizes = Collections.unmodifiableCollection( _memoizes.values() ); private final Map<String, AutorunDescriptor> _autoruns = new LinkedHashMap<>(); private final Collection<AutorunDescriptor> _roAutoruns = Collections.unmodifiableCollection( _autoruns.values() ); private final Map<String, TrackedDescriptor> _trackeds = new LinkedHashMap<>(); private final Collection<TrackedDescriptor> _roTrackeds = Collections.unmodifiableCollection( _trackeds.values() ); private final Map<ExecutableElement, DependencyDescriptor> _dependencies = new LinkedHashMap<>(); private final Collection<DependencyDescriptor> _roDependencies = Collections.unmodifiableCollection( _dependencies.values() ); private final Map<String, ReferenceDescriptor> _references = new LinkedHashMap<>(); private final Collection<ReferenceDescriptor> _roReferences = Collections.unmodifiableCollection( _references.values() ); private final Map<String, InverseDescriptor> _inverses = new LinkedHashMap<>(); private final Collection<InverseDescriptor> _roInverses = Collections.unmodifiableCollection( _inverses.values() ); ComponentDescriptor( @Nonnull final SourceVersion sourceVersion, @Nonnull final Elements elements, @Nonnull final Types typeUtils, @Nonnull final String type, final boolean nameIncludesId, final boolean allowEmpty, final boolean observable, final boolean disposeTrackable, final boolean disposeOnDeactivate, final boolean injectClassesPresent, final boolean inject, final boolean dagger, final boolean requireEquals, final boolean verify, @Nullable final AnnotationMirror scopeAnnotation, final boolean deferSchedule, final boolean generateToString, @Nonnull final PackageElement packageElement, @Nonnull final TypeElement element ) { _sourceVersion = Objects.requireNonNull( sourceVersion ); _elements = Objects.requireNonNull( elements ); _typeUtils = Objects.requireNonNull( typeUtils ); _type = Objects.requireNonNull( type ); _nameIncludesId = nameIncludesId; _allowEmpty = allowEmpty; _observable = observable; _disposeTrackable = disposeTrackable; _disposeOnDeactivate = disposeOnDeactivate; _injectClassesPresent = injectClassesPresent; _inject = inject; _dagger = dagger; _requireEquals = requireEquals; _verify = verify; _scopeAnnotation = scopeAnnotation; _deferSchedule = deferSchedule; _generateToString = generateToString; _packageElement = Objects.requireNonNull( packageElement ); _element = Objects.requireNonNull( element ); } private boolean hasDeprecatedElements() { return isDeprecated( _postConstruct ) || isDeprecated( _componentId ) || isDeprecated( _componentRef ) || isDeprecated( _contextRef ) || isDeprecated( _componentTypeNameRef ) || isDeprecated( _componentNameRef ) || isDeprecated( _preDispose ) || isDeprecated( _postDispose ) || _roObservables.stream().anyMatch( e -> ( e.hasSetter() && isDeprecated( e.getSetter() ) ) || ( e.hasGetter() && isDeprecated( e.getGetter() ) ) ) || _roComputeds.stream().anyMatch( e -> ( e.hasComputed() && isDeprecated( e.getComputed() ) ) || isDeprecated( e.getOnActivate() ) || isDeprecated( e.getOnDeactivate() ) || isDeprecated( e.getOnStale() ) || isDeprecated( e.getOnDispose() ) ) || _observerRefs.values().stream().anyMatch( e -> isDeprecated( e.getMethod() ) ) || _roDependencies.stream().anyMatch( e -> isDeprecated( e.getMethod() ) ) || _roActions.stream().anyMatch( e -> isDeprecated( e.getAction() ) ) || _roAutoruns.stream().anyMatch( e -> isDeprecated( e.getAutorun() ) ) || _roMemoizes.stream().anyMatch( e -> isDeprecated( e.getMemoize() ) ) || _roTrackeds.stream().anyMatch( e -> ( e.hasTrackedMethod() && isDeprecated( e.getTrackedMethod() ) ) || ( e.hasOnDepsChangedMethod() && isDeprecated( e.getOnDepsChangedMethod() ) ) ); } void setIdRequired( final boolean idRequired ) { _idRequired = idRequired; } boolean isDisposeTrackable() { return _disposeTrackable; } private boolean isDeprecated( @Nullable final ExecutableElement element ) { return null != element && null != element.getAnnotation( Deprecated.class ); } @Nonnull private DeclaredType asDeclaredType() { return (DeclaredType) _element.asType(); } @Nonnull TypeElement getElement() { return _element; } @Nonnull String getType() { return _type; } @Nonnull private ReferenceDescriptor findOrCreateReference( @Nonnull final String name ) { return _references.computeIfAbsent( name, n -> new ReferenceDescriptor( this, name ) ); } @Nonnull private ObservableDescriptor findOrCreateObservable( @Nonnull final String name ) { return _observables.computeIfAbsent( name, n -> new ObservableDescriptor( this, n ) ); } @Nonnull private TrackedDescriptor findOrCreateTracked( @Nonnull final String name ) { return _trackeds.computeIfAbsent( name, n -> new TrackedDescriptor( this, n ) ); } @Nonnull private ObservableDescriptor addObservable( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_ANNOTATION_CLASSNAME, method ); final String declaredName = getAnnotationParameter( annotation, "name" ); final boolean expectSetter = getAnnotationParameter( annotation, "expectSetter" ); final boolean readOutsideTransaction = getAnnotationParameter( annotation, "readOutsideTransaction" ); final Boolean requireInitializer = isInitializerRequired( method ); final TypeMirror returnType = method.getReturnType(); final String methodName = method.getSimpleName().toString(); String name; final boolean setter; if ( TypeKind.VOID == returnType.getKind() ) { setter = true; //Should be a setter if ( 1 != method.getParameters().size() ) { throw new ArezProcessorException( "@Observable target should be a setter or getter", method ); } name = ProcessorUtil.deriveName( method, SETTER_PATTERN, declaredName ); if ( null == name ) { name = methodName; } } else { setter = false; //Must be a getter if ( 0 != method.getParameters().size() ) { throw new ArezProcessorException( "@Observable target should be a setter or getter", method ); } name = getPropertyAccessorName( method, declaredName ); } // Override name if supplied by user if ( !ProcessorUtil.isSentinelName( declaredName ) ) { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Observable target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Observable target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } checkNameUnique( name, method, Constants.OBSERVABLE_ANNOTATION_CLASSNAME ); if ( setter && !expectSetter ) { throw new ArezProcessorException( "Method annotated with @Observable is a setter but defines " + "expectSetter = false for observable named " + name, method ); } final ObservableDescriptor observable = findOrCreateObservable( name ); if ( readOutsideTransaction ) { observable.setReadOutsideTransaction( true ); } if ( !expectSetter ) { observable.setExpectSetter( false ); } if ( !observable.expectSetter() ) { if ( observable.hasSetter() ) { throw new ArezProcessorException( "Method annotated with @Observable defines expectSetter = false but a " + "setter exists named " + observable.getSetter().getSimpleName() + "for observable named " + name, method ); } } if ( setter ) { if ( observable.hasSetter() ) { throw new ArezProcessorException( "Method annotated with @Observable defines duplicate setter for " + "observable named " + name, method ); } if ( !observable.expectSetter() ) { throw new ArezProcessorException( "Method annotated with @Observable defines expectSetter = false but a " + "setter exists for observable named " + name, method ); } observable.setSetter( method, methodType ); } else { if ( observable.hasGetter() ) { throw new ArezProcessorException( "Method annotated with @Observable defines duplicate getter for " + "observable named " + name, method ); } observable.setGetter( method, methodType ); } if ( null != requireInitializer ) { if ( !method.getModifiers().contains( Modifier.ABSTRACT ) ) { throw new ArezProcessorException( "@Observable target set initializer parameter to ENABLED but " + "method is not abstract.", method ); } final Boolean existing = observable.getInitializer(); if ( null == existing ) { observable.setInitializer( requireInitializer ); } else if ( existing != requireInitializer ) { throw new ArezProcessorException( "@Observable target set initializer parameter to value that differs from " + "the paired observable method.", method ); } } return observable; } private void addObservableRef( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = methodType.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !toRawType( returnType ).toString().equals( "arez.Observable" ) ) { throw new ArezProcessorException( "Method annotated with @ObservableRef must return an instance of " + "arez.Observable", method ); } final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { name = ProcessorUtil.deriveName( method, OBSERVABLE_REF_PATTERN, declaredName ); if ( null == name ) { throw new ArezProcessorException( "Method annotated with @ObservableRef should specify name or be " + "named according to the convention get[Name]Observable", method ); } } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@ObservableRef target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@ObservableRef target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } final ObservableDescriptor observable = findOrCreateObservable( name ); if ( observable.hasRefMethod() ) { throw new ArezProcessorException( "Method annotated with @ObservableRef defines duplicate ref accessor for " + "observable named " + name, method ); } observable.setRefMethod( method, methodType ); } @Nonnull private TypeName toRawType( @Nonnull final TypeMirror type ) { final TypeName typeName = TypeName.get( type ); if ( typeName instanceof ParameterizedTypeName ) { return ( (ParameterizedTypeName) typeName ).rawType; } else { return typeName; } } private void addAction( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeWrappable( getElement(), Constants.ACTION_ANNOTATION_CLASSNAME, method ); final String name = deriveActionName( method, annotation ); checkNameUnique( name, method, Constants.ACTION_ANNOTATION_CLASSNAME ); final boolean mutation = getAnnotationParameter( annotation, "mutation" ); final boolean requireNewTransaction = getAnnotationParameter( annotation, "requireNewTransaction" ); final boolean reportParameters = getAnnotationParameter( annotation, "reportParameters" ); final boolean verifyRequired = getAnnotationParameter( annotation, "verifyRequired" ); final ActionDescriptor action = new ActionDescriptor( this, name, requireNewTransaction, mutation, verifyRequired, reportParameters, method, methodType ); _actions.put( action.getName(), action ); } @Nonnull private String deriveActionName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation ) throws ArezProcessorException { final String name = getAnnotationParameter( annotation, "name" ); if ( ProcessorUtil.isSentinelName( name ) ) { return method.getSimpleName().toString(); } else { if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Action target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Action target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } return name; } } private void addAutorun( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeWrappable( getElement(), Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotReturnAnyValue( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotBePublic( Constants.AUTORUN_ANNOTATION_CLASSNAME, method ); final String name = deriveAutorunName( method, annotation ); checkNameUnique( name, method, Constants.AUTORUN_ANNOTATION_CLASSNAME ); final boolean mutation = getAnnotationParameter( annotation, "mutation" ); final boolean observeLowerPriorityDependencies = getAnnotationParameter( annotation, "observeLowerPriorityDependencies" ); final boolean canNestActions = getAnnotationParameter( annotation, "canNestActions" ); final VariableElement priority = getAnnotationParameter( annotation, "priority" ); final AutorunDescriptor autorun = new AutorunDescriptor( this, name, mutation, priority.getSimpleName().toString(), observeLowerPriorityDependencies, canNestActions, method, methodType ); _autoruns.put( autorun.getName(), autorun ); } @Nonnull private String deriveAutorunName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation ) throws ArezProcessorException { final String name = getAnnotationParameter( annotation, "name" ); if ( ProcessorUtil.isSentinelName( name ) ) { return method.getSimpleName().toString(); } else { if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Autorun target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Autorun target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } return name; } } private void addOnDepsChanged( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String name = deriveHookName( method, TrackedDescriptor.ON_DEPS_CHANGED_PATTERN, "DepsChanged", getAnnotationParameter( annotation, "name" ) ); findOrCreateTracked( name ).setOnDepsChangedMethod( method ); } private void addTracked( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { final String name = deriveTrackedName( method, annotation ); checkNameUnique( name, method, Constants.TRACK_ANNOTATION_CLASSNAME ); final boolean mutation = getAnnotationParameter( annotation, "mutation" ); final boolean observeLowerPriorityDependencies = getAnnotationParameter( annotation, "observeLowerPriorityDependencies" ); final boolean canNestActions = getAnnotationParameter( annotation, "canNestActions" ); final VariableElement priority = getAnnotationParameter( annotation, "priority" ); final boolean reportParameters = getAnnotationParameter( annotation, "reportParameters" ); final TrackedDescriptor tracked = findOrCreateTracked( name ); tracked.setTrackedMethod( mutation, priority.getSimpleName().toString(), reportParameters, observeLowerPriorityDependencies, canNestActions, method, methodType ); } @Nonnull private String deriveTrackedName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation ) throws ArezProcessorException { final String name = getAnnotationParameter( annotation, "name" ); if ( ProcessorUtil.isSentinelName( name ) ) { return method.getSimpleName().toString(); } else { if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Track target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Track target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } return name; } } private void addObserverRef( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = method.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !returnType.toString().equals( "arez.Observer" ) ) { throw new ArezProcessorException( "Method annotated with @ObserverRef must return an instance of " + "arez.Observer", method ); } final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { name = ProcessorUtil.deriveName( method, OBSERVER_REF_PATTERN, declaredName ); if ( null == name ) { throw new ArezProcessorException( "Method annotated with @ObserverRef should specify name or be " + "named according to the convention get[Name]Observer", method ); } } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@ObserverRef target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@ObserverRef target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } if ( _observerRefs.containsKey( name ) ) { throw new ArezProcessorException( "Method annotated with @ObserverRef defines duplicate ref accessor for " + "observer named " + name, method ); } _observerRefs.put( name, new CandidateMethod( method, methodType ) ); } @Nonnull private ComputedDescriptor findOrCreateComputed( @Nonnull final String name ) { return _computeds.computeIfAbsent( name, n -> new ComputedDescriptor( this, n ) ); } private void addComputed( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType computedType ) throws ArezProcessorException { final String name = deriveComputedName( method, annotation ); checkNameUnique( name, method, Constants.COMPUTED_ANNOTATION_CLASSNAME ); final boolean keepAlive = getAnnotationParameter( annotation, "keepAlive" ); final boolean observeLowerPriorityDependencies = getAnnotationParameter( annotation, "observeLowerPriorityDependencies" ); final VariableElement priority = getAnnotationParameter( annotation, "priority" ); findOrCreateComputed( name ).setComputed( method, computedType, keepAlive, priority.getSimpleName().toString(), observeLowerPriorityDependencies ); } private void addComputedValueRef( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = methodType.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !toRawType( returnType ).toString().equals( "arez.ComputedValue" ) ) { throw new ArezProcessorException( "Method annotated with @ComputedValueRef must return an instance of " + "arez.ComputedValue", method ); } final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { name = ProcessorUtil.deriveName( method, COMPUTED_VALUE_REF_PATTERN, declaredName ); if ( null == name ) { throw new ArezProcessorException( "Method annotated with @ComputedValueRef should specify name or be " + "named according to the convention get[Name]ComputedValue", method ); } } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@ComputedValueRef target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@ComputedValueRef target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } findOrCreateComputed( name ).setRefMethod( method, methodType ); } @Nonnull private String deriveComputedName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation ) throws ArezProcessorException { final String name = getAnnotationParameter( annotation, "name" ); if ( ProcessorUtil.isSentinelName( name ) ) { return getPropertyAccessorName( method, name ); } else { if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Computed target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Computed target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } return name; } } private void addMemoize( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { final String name = deriveMemoizeName( method, annotation ); final boolean observeLowerPriorityDependencies = getAnnotationParameter( annotation, "observeLowerPriorityDependencies" ); final VariableElement priorityElement = getAnnotationParameter( annotation, "priority" ); final String priority = priorityElement.getSimpleName().toString(); checkNameUnique( name, method, Constants.MEMOIZE_ANNOTATION_CLASSNAME ); _memoizes.put( name, new MemoizeDescriptor( this, name, priority, observeLowerPriorityDependencies, method, methodType ) ); } @Nonnull private String deriveMemoizeName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation ) throws ArezProcessorException { final String name = getAnnotationParameter( annotation, "name" ); if ( ProcessorUtil.isSentinelName( name ) ) { return method.getSimpleName().toString(); } else { if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Memoize target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Memoize target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } return name; } } private void addOnActivate( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String name = deriveHookName( method, ComputedDescriptor.ON_ACTIVATE_PATTERN, "Activate", getAnnotationParameter( annotation, "name" ) ); findOrCreateComputed( name ).setOnActivate( method ); } private void addOnDeactivate( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String name = deriveHookName( method, ComputedDescriptor.ON_DEACTIVATE_PATTERN, "Deactivate", getAnnotationParameter( annotation, "name" ) ); findOrCreateComputed( name ).setOnDeactivate( method ); } private void addOnStale( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String name = deriveHookName( method, ComputedDescriptor.ON_STALE_PATTERN, "Stale", getAnnotationParameter( annotation, "name" ) ); findOrCreateComputed( name ).setOnStale( method ); } private void addOnDispose( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String name = deriveHookName( method, ComputedDescriptor.ON_DISPOSE_PATTERN, "Dispose", getAnnotationParameter( annotation, "name" ) ); findOrCreateComputed( name ).setOnDispose( method ); } @Nonnull private String deriveHookName( @Nonnull final ExecutableElement method, @Nonnull final Pattern pattern, @Nonnull final String type, @Nonnull final String name ) throws ArezProcessorException { final String value = ProcessorUtil.deriveName( method, pattern, name ); if ( null == value ) { throw new ArezProcessorException( "Unable to derive name for @On" + type + " as does not match " + "on[Name]" + type + " pattern. Please specify name.", method ); } else if ( !SourceVersion.isIdentifier( value ) ) { throw new ArezProcessorException( "@On" + type + " target specified an invalid name '" + value + "'. The " + "name must be a valid java identifier.", _element ); } else if ( SourceVersion.isKeyword( value ) ) { throw new ArezProcessorException( "@On" + type + " target specified an invalid name '" + value + "'. The " + "name must not be a java keyword.", _element ); } else { return value; } } private void setContextRef( @Nonnull final ExecutableElement method ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = method.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !returnType.toString().equals( "arez.ArezContext" ) ) { throw new ArezProcessorException( "Method annotated with @ContextRef must return an instance of " + "arez.ArezContext", method ); } if ( null != _contextRef ) { throw new ArezProcessorException( "@ContextRef target duplicates existing method named " + _contextRef.getSimpleName(), method ); } else { _contextRef = Objects.requireNonNull( method ); } } private void setComponentRef( @Nonnull final ExecutableElement method ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method ); final TypeMirror returnType = method.getReturnType(); if ( TypeKind.DECLARED != returnType.getKind() || !returnType.toString().equals( "arez.Component" ) ) { throw new ArezProcessorException( "Method annotated with @ComponentRef must return an instance of " + "arez.Component", method ); } if ( null != _componentRef ) { throw new ArezProcessorException( "@ComponentRef target duplicates existing method named " + _componentRef.getSimpleName(), method ); } else { _componentRef = Objects.requireNonNull( method ); } } boolean hasComponentIdMethod() { return null != _componentId; } private void setComponentId( @Nonnull final ExecutableElement componentId, @Nonnull final ExecutableType componentIdMethodType ) throws ArezProcessorException { MethodChecks.mustNotBeAbstract( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); MethodChecks.mustBeFinal( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); MethodChecks.mustReturnAValue( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId ); if ( null != _componentId ) { throw new ArezProcessorException( "@ComponentId target duplicates existing method named " + _componentId.getSimpleName(), componentId ); } else { _componentId = Objects.requireNonNull( componentId ); _componentIdMethodType = componentIdMethodType; } } private void setComponentTypeNameRef( @Nonnull final ExecutableElement componentTypeName ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName ); MethodChecks.mustBeAbstract( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName ); MethodChecks.mustReturnAValue( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName ); final TypeMirror returnType = componentTypeName.getReturnType(); if ( !( TypeKind.DECLARED == returnType.getKind() && returnType.toString().equals( String.class.getName() ) ) ) { throw new ArezProcessorException( "@ComponentTypeNameRef target must return a String", componentTypeName ); } if ( null != _componentTypeNameRef ) { throw new ArezProcessorException( "@ComponentTypeNameRef target duplicates existing method named " + _componentTypeNameRef.getSimpleName(), componentTypeName ); } else { _componentTypeNameRef = Objects.requireNonNull( componentTypeName ); } } private void setComponentNameRef( @Nonnull final ExecutableElement componentName ) throws ArezProcessorException { MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName ); MethodChecks.mustBeAbstract( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName ); MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName ); MethodChecks.mustReturnAValue( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName ); MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName ); if ( null != _componentNameRef ) { throw new ArezProcessorException( "@ComponentNameRef target duplicates existing method named " + _componentNameRef.getSimpleName(), componentName ); } else { _componentNameRef = Objects.requireNonNull( componentName ); } } @Nullable ExecutableElement getPostConstruct() { return _postConstruct; } void setPostConstruct( @Nonnull final ExecutableElement postConstruct ) throws ArezProcessorException { MethodChecks.mustBeLifecycleHook( getElement(), Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME, postConstruct ); if ( null != _postConstruct ) { throw new ArezProcessorException( "@PostConstruct target duplicates existing method named " + _postConstruct.getSimpleName(), postConstruct ); } else { _postConstruct = postConstruct; } } private void setPreDispose( @Nonnull final ExecutableElement preDispose ) throws ArezProcessorException { MethodChecks.mustBeLifecycleHook( getElement(), Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME, preDispose ); if ( null != _preDispose ) { throw new ArezProcessorException( "@PreDispose target duplicates existing method named " + _preDispose.getSimpleName(), preDispose ); } else { _preDispose = preDispose; } } private void setPostDispose( @Nonnull final ExecutableElement postDispose ) throws ArezProcessorException { MethodChecks.mustBeLifecycleHook( getElement(), Constants.POST_DISPOSE_ANNOTATION_CLASSNAME, postDispose ); if ( null != _postDispose ) { throw new ArezProcessorException( "@PostDispose target duplicates existing method named " + _postDispose.getSimpleName(), postDispose ); } else { _postDispose = postDispose; } } @Nonnull Collection<ObservableDescriptor> getObservables() { return _roObservables; } void validate() throws ArezProcessorException { _roObservables.forEach( ObservableDescriptor::validate ); _roComputeds.forEach( ComputedDescriptor::validate ); _roDependencies.forEach( DependencyDescriptor::validate ); _roReferences.forEach( ReferenceDescriptor::validate ); final boolean hasReactiveElements = _roObservables.isEmpty() && _roActions.isEmpty() && _roComputeds.isEmpty() && _roMemoizes.isEmpty() && _roTrackeds.isEmpty() && _roDependencies.isEmpty() && _roReferences.isEmpty() && _roInverses.isEmpty() && _roAutoruns.isEmpty(); if ( !_allowEmpty && hasReactiveElements ) { throw new ArezProcessorException( "@ArezComponent target has no methods annotated with @Action, " + "@Computed, @Memoize, @Observable, @Inverse, @Reference, @Dependency, @Track or @Autorun", _element ); } else if ( _allowEmpty && !hasReactiveElements ) { throw new ArezProcessorException( "@ArezComponent target has specified allowEmpty = true but has methods annotated with @Action, " + "@Computed, @Memoize, @Observable, @Inverse, @Reference, @Dependency, @Track or @Autorun", _element ); } if ( _deferSchedule && !requiresSchedule() ) { throw new ArezProcessorException( "@ArezComponent target has specified the deferSchedule = true " + "annotation parameter but has no methods annotated with @Autorun, " + "@Dependency or @Computed(keepAlive=true)", _element ); } } private boolean requiresSchedule() { return !_roAutoruns.isEmpty() || !_roDependencies.isEmpty() || _computeds.values().stream().anyMatch( ComputedDescriptor::isKeepAlive ); } private void checkNameUnique( @Nonnull final String name, @Nonnull final ExecutableElement sourceMethod, @Nonnull final String sourceAnnotationName ) throws ArezProcessorException { final ActionDescriptor action = _actions.get( name ); if ( null != action ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.ACTION_ANNOTATION_CLASSNAME, action.getAction() ); } final ComputedDescriptor computed = _computeds.get( name ); if ( null != computed && computed.hasComputed() ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.COMPUTED_ANNOTATION_CLASSNAME, computed.getComputed() ); } final MemoizeDescriptor memoize = _memoizes.get( name ); if ( null != memoize ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.MEMOIZE_ANNOTATION_CLASSNAME, memoize.getMemoize() ); } final AutorunDescriptor autorun = _autoruns.get( name ); if ( null != autorun ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.AUTORUN_ANNOTATION_CLASSNAME, autorun.getAutorun() ); } // Track have pairs so let the caller determine whether a duplicate occurs in that scenario if ( !sourceAnnotationName.equals( Constants.TRACK_ANNOTATION_CLASSNAME ) ) { final TrackedDescriptor tracked = _trackeds.get( name ); if ( null != tracked ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.TRACK_ANNOTATION_CLASSNAME, tracked.getTrackedMethod() ); } } // Observables have pairs so let the caller determine whether a duplicate occurs in that scenario if ( !sourceAnnotationName.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) ) { final ObservableDescriptor observable = _observables.get( name ); if ( null != observable ) { throw toException( name, sourceAnnotationName, sourceMethod, Constants.OBSERVABLE_ANNOTATION_CLASSNAME, observable.getDefiner() ); } } } @Nonnull private ArezProcessorException toException( @Nonnull final String name, @Nonnull final String sourceAnnotationName, @Nonnull final ExecutableElement sourceMethod, @Nonnull final String targetAnnotationName, @Nonnull final ExecutableElement targetElement ) { return new ArezProcessorException( "Method annotated with @" + ProcessorUtil.toSimpleName( sourceAnnotationName ) + " specified name " + name + " that duplicates @" + ProcessorUtil.toSimpleName( targetAnnotationName ) + " defined by method " + targetElement.getSimpleName(), sourceMethod ); } void analyzeCandidateMethods( @Nonnull final List<ExecutableElement> methods, @Nonnull final Types typeUtils ) throws ArezProcessorException { for ( final ExecutableElement method : methods ) { final String methodName = method.getSimpleName().toString(); if ( AREZ_SPECIAL_METHODS.contains( methodName ) && method.getParameters().isEmpty() ) { throw new ArezProcessorException( "Method defined on a class annotated by @ArezComponent uses a name " + "reserved by Arez", method ); } else if ( methodName.startsWith( GeneratorUtil.FIELD_PREFIX ) || methodName.startsWith( GeneratorUtil.OBSERVABLE_DATA_FIELD_PREFIX ) || methodName.startsWith( GeneratorUtil.REFERENCE_FIELD_PREFIX ) || methodName.startsWith( GeneratorUtil.FRAMEWORK_PREFIX ) ) { throw new ArezProcessorException( "Method defined on a class annotated by @ArezComponent uses a name " + "with a prefix reserved by Arez", method ); } } final Map<String, CandidateMethod> getters = new HashMap<>(); final Map<String, CandidateMethod> setters = new HashMap<>(); final Map<String, CandidateMethod> trackeds = new HashMap<>(); final Map<String, CandidateMethod> onDepsChangeds = new HashMap<>(); for ( final ExecutableElement method : methods ) { final ExecutableType methodType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), method ); if ( !analyzeMethod( method, methodType ) ) { /* * If we get here the method was not annotated so we can try to detect if it is a * candidate arez method in case some arez annotations are implied via naming conventions. */ if ( method.getModifiers().contains( Modifier.STATIC ) ) { continue; } final CandidateMethod candidateMethod = new CandidateMethod( method, methodType ); final boolean voidReturn = method.getReturnType().getKind() == TypeKind.VOID; final int parameterCount = method.getParameters().size(); String name; if ( !method.getModifiers().contains( Modifier.FINAL ) ) { name = ProcessorUtil.deriveName( method, SETTER_PATTERN, ProcessorUtil.SENTINEL_NAME ); if ( voidReturn && 1 == parameterCount && null != name ) { setters.put( name, candidateMethod ); continue; } name = ProcessorUtil.deriveName( method, ISSER_PATTERN, ProcessorUtil.SENTINEL_NAME ); if ( !voidReturn && 0 == parameterCount && null != name ) { getters.put( name, candidateMethod ); continue; } name = ProcessorUtil.deriveName( method, GETTER_PATTERN, ProcessorUtil.SENTINEL_NAME ); if ( !voidReturn && 0 == parameterCount && null != name ) { getters.put( name, candidateMethod ); continue; } } name = ProcessorUtil.deriveName( method, TrackedDescriptor.ON_DEPS_CHANGED_PATTERN, ProcessorUtil.SENTINEL_NAME ); if ( voidReturn && 0 == parameterCount && null != name ) { onDepsChangeds.put( name, candidateMethod ); continue; } final String methodName = method.getSimpleName().toString(); if ( !OBJECT_METHODS.contains( methodName ) ) { trackeds.put( methodName, candidateMethod ); } } } linkUnAnnotatedObservables( getters, setters ); linkUnAnnotatedTracked( trackeds, onDepsChangeds ); linkObserverRefs(); linkDependencies( getters.values() ); autodetectObservableInitializers(); /* * ALl of the maps will have called remove() for all matching candidates. * Thus any left are the non-arez methods. */ ensureNoAbstractMethods( getters.values() ); ensureNoAbstractMethods( setters.values() ); ensureNoAbstractMethods( trackeds.values() ); ensureNoAbstractMethods( onDepsChangeds.values() ); } private void autodetectObservableInitializers() { for ( final ObservableDescriptor observable : getObservables() ) { if ( null == observable.getInitializer() && observable.hasGetter() ) { if ( observable.hasSetter() ) { final boolean initializer = autodetectInitializer( observable.getGetter() ) && autodetectInitializer( observable.getSetter() ); observable.setInitializer( initializer ); } else { final boolean initializer = autodetectInitializer( observable.getGetter() ); observable.setInitializer( initializer ); } } } } private void linkDependencies( @Nonnull final Collection<CandidateMethod> candidates ) { _roObservables .stream() .filter( ObservableDescriptor::hasGetter ) .filter( o -> hasDependencyAnnotation( o.getGetter() ) ) .forEach( o -> addOrUpdateDependency( o.getGetter(), o ) ); _roComputeds .stream() .filter( ComputedDescriptor::hasComputed ) .map( ComputedDescriptor::getComputed ) .filter( this::hasDependencyAnnotation ) .forEach( this::addDependency ); candidates .stream() .map( CandidateMethod::getMethod ) .filter( this::hasDependencyAnnotation ) .forEach( this::addDependency ); } private boolean hasDependencyAnnotation( @Nonnull final ExecutableElement method ) { return null != ProcessorUtil.findAnnotationByType( method, Constants.DEPENDENCY_ANNOTATION_CLASSNAME ); } private void addOrUpdateDependency( @Nonnull final ExecutableElement method, @Nonnull final ObservableDescriptor observable ) { final DependencyDescriptor dependencyDescriptor = _dependencies.computeIfAbsent( method, this::createDependencyDescriptor ); dependencyDescriptor.setObservable( observable ); } private void addReferenceId( @Nonnull final AnnotationMirror annotation, @Nonnull final ObservableDescriptor observable, @Nonnull final ExecutableElement method ) { MethodChecks.mustNotHaveAnyParameters( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); findOrCreateReference( getReferenceIdName( annotation, method ) ).setObservable( observable ); } private void addReferenceId( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) { MethodChecks.mustNotHaveAnyParameters( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method ); final String name = getReferenceIdName( annotation, method ); findOrCreateReference( name ).setIdMethod( method, methodType ); } @Nonnull private String getReferenceIdName( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) { final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { final String candidate = ProcessorUtil.deriveName( method, ID_GETTER_PATTERN, declaredName ); if ( null == candidate ) { final String candidate2 = ProcessorUtil.deriveName( method, RAW_ID_GETTER_PATTERN, declaredName ); if ( null == candidate2 ) { throw new ArezProcessorException( "@ReferenceId target has not specified a name and does not follow " + "the convention \"get[Name]Id\" or \"[name]Id\"", method ); } else { name = candidate2; } } else { name = candidate; } } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@ReferenceId target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@ReferenceId target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } return name; } private void addInverse( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) { MethodChecks.mustNotHaveAnyParameters( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); final String name = getInverseName( annotation, method ); final ObservableDescriptor observable = findOrCreateObservable( name ); observable.setGetter( method, methodType ); addInverse( annotation, observable, method ); } private void addInverse( @Nonnull final AnnotationMirror annotation, @Nonnull final ObservableDescriptor observable, @Nonnull final ExecutableElement method ) { MethodChecks.mustNotHaveAnyParameters( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.INVERSE_ANNOTATION_CLASSNAME, method ); final String name = getInverseName( annotation, method ); final InverseDescriptor existing = _inverses.get( name ); if ( null != existing ) { throw new ArezProcessorException( "@Inverse target defines duplicate inverse for name '" + name + "'. The other inverse is " + existing.getObservable().getGetter(), method ); } else { final TypeMirror type = method.getReturnType(); final Multiplicity multiplicity; TypeElement targetType = getInverseManyTypeTarget( method ); if ( null != targetType ) { multiplicity = Multiplicity.MANY; } else { if ( !( type instanceof DeclaredType ) || null == ProcessorUtil.findAnnotationByType( ( (DeclaredType) type ).asElement(), Constants.COMPONENT_ANNOTATION_CLASSNAME ) ) { throw new ArezProcessorException( "@Inverse target expected to return a type annotated with " + Constants.COMPONENT_ANNOTATION_CLASSNAME, method ); } targetType = (TypeElement) ( (DeclaredType) type ).asElement(); if ( null != ProcessorUtil.findAnnotationByType( method, Constants.NONNULL_ANNOTATION_CLASSNAME ) ) { multiplicity = Multiplicity.ONE; } else if ( null != ProcessorUtil.findAnnotationByType( method, Constants.NULLABLE_ANNOTATION_CLASSNAME ) ) { multiplicity = Multiplicity.ZERO_OR_ONE; } else { throw new ArezProcessorException( "@Inverse target expected to be annotated with either " + Constants.NULLABLE_ANNOTATION_CLASSNAME + " or " + Constants.NONNULL_ANNOTATION_CLASSNAME, method ); } } final String referenceName = getInverseReferenceNameParameter( method ); final InverseDescriptor descriptor = new InverseDescriptor( this, observable, referenceName, multiplicity, targetType ); _inverses.put( name, descriptor ); verifyMultiplicityOfAssociatedReferenceMethod( descriptor ); } } private void verifyMultiplicityOfAssociatedReferenceMethod( @Nonnull final InverseDescriptor descriptor ) { final Multiplicity multiplicity = ProcessorUtil .getMethods( descriptor.getTargetType(), _elements, _typeUtils ) .stream() .map( m -> { final AnnotationMirror a = ProcessorUtil.findAnnotationByType( m, Constants.REFERENCE_ANNOTATION_CLASSNAME ); if ( null != a && getReferenceName( a, m ).equals( descriptor.getReferenceName() ) ) { ensureTargetTypeAligns( descriptor, m.getReturnType() ); return getReferenceInverseMultiplicity( a ); } else { return null; } } ) .filter( Objects::nonNull ) .findAny() .orElse( null ); if ( null == multiplicity ) { throw new ArezProcessorException( "@Inverse target expected to find an associated @Reference annotation with " + "a name parameter equal to '" + descriptor.getReferenceName() + "' on class " + descriptor.getTargetType().getQualifiedName() + " but is unable to " + "locate a matching method.", descriptor.getObservable().getGetter() ); } if ( descriptor.getMultiplicity() != multiplicity ) { throw new ArezProcessorException( "@Inverse target has a multiplicity of " + descriptor.getMultiplicity() + " but that associated @Reference has a multiplicity of " + multiplicity + ". The multiplicity must align.", descriptor.getObservable().getGetter() ); } } private void ensureTargetTypeAligns( @Nonnull final InverseDescriptor descriptor, @Nonnull final TypeMirror target ) { if ( !_typeUtils.isSameType( target, getElement().asType() ) ) { throw new ArezProcessorException( "@Inverse target expected to find an associated @Reference annotation with " + "a target type equal to " + descriptor.getTargetType() + " but the actual " + "target type is " + target, descriptor.getObservable().getGetter() ); } } @Nullable private TypeElement getInverseManyTypeTarget( @Nonnull final ExecutableElement method ) { final TypeName typeName = TypeName.get( method.getReturnType() ); if ( typeName instanceof ParameterizedTypeName ) { final ParameterizedTypeName type = (ParameterizedTypeName) typeName; if ( isSupportedInverseCollectionType( type.rawType.toString() ) && !type.typeArguments.isEmpty() ) { final TypeElement typeElement = _elements.getTypeElement( type.typeArguments.get( 0 ).toString() ); if ( null != ProcessorUtil.findAnnotationByType( typeElement, Constants.COMPONENT_ANNOTATION_CLASSNAME ) ) { return typeElement; } else { throw new ArezProcessorException( "@Inverse target expected to return a type annotated with " + Constants.COMPONENT_ANNOTATION_CLASSNAME, method ); } } } return null; } private boolean isSupportedInverseCollectionType( @Nonnull final String typeClassname ) { return Collection.class.getName().equals( typeClassname ) || Set.class.getName().equals( typeClassname ) || List.class.getName().equals( typeClassname ); } @Nonnull private String getInverseReferenceNameParameter( @Nonnull final ExecutableElement method ) { final String declaredName = (String) ProcessorUtil.getAnnotationValue( _elements, method, Constants.INVERSE_ANNOTATION_CLASSNAME, "referenceName" ).getValue(); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { name = ProcessorUtil.firstCharacterToLowerCase( getElement().getSimpleName().toString() ); } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Inverse target specified an invalid referenceName '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Inverse target specified an invalid referenceName '" + name + "'. The " + "name must not be a java keyword.", method ); } } return name; } @Nonnull private String getInverseName( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) { final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { final String candidate = ProcessorUtil.deriveName( method, GETTER_PATTERN, declaredName ); name = null == candidate ? method.getSimpleName().toString() : candidate; } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Inverse target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Inverse target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } return name; } private void addReference( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) { MethodChecks.mustNotHaveAnyParameters( Constants.REFERENCE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.REFERENCE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.REFERENCE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.REFERENCE_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeAbstract( Constants.REFERENCE_ANNOTATION_CLASSNAME, method ); final String name = getReferenceName( annotation, method ); final String linkType = getLinkType( method ); final String inverseName; final Multiplicity inverseMultiplicity; if ( hasInverse( annotation ) ) { inverseMultiplicity = getReferenceInverseMultiplicity( annotation ); inverseName = getReferenceInverseName( annotation, method, inverseMultiplicity ); final TypeMirror returnType = method.getReturnType(); if ( !( returnType instanceof DeclaredType ) || null == ProcessorUtil.findAnnotationByType( ( (DeclaredType) returnType ).asElement(), Constants.COMPONENT_ANNOTATION_CLASSNAME ) ) { throw new ArezProcessorException( "@Reference target expected to return a type annotated with " + Constants.COMPONENT_ANNOTATION_CLASSNAME + " if there is an " + "inverse reference.", method ); } } else { inverseName = null; inverseMultiplicity = null; } final ReferenceDescriptor descriptor = findOrCreateReference( name ); descriptor.setMethod( method, methodType, linkType, inverseName, inverseMultiplicity ); verifyMultiplicityOfAssociatedInverseMethod( descriptor ); } private void verifyMultiplicityOfAssociatedInverseMethod( @Nonnull final ReferenceDescriptor descriptor ) { if ( !descriptor.hasInverse() ) { return; } final TypeElement element = (TypeElement) _typeUtils.asElement( descriptor.getMethod().getReturnType() ); final Multiplicity multiplicity = ProcessorUtil .getMethods( element, _elements, _typeUtils ) .stream() .map( m -> { final AnnotationMirror a = ProcessorUtil.findAnnotationByType( m, Constants.INVERSE_ANNOTATION_CLASSNAME ); if ( null != a && getInverseName( a, m ).equals( descriptor.getInverseName() ) ) { final TypeElement target = getInverseManyTypeTarget( m ); if ( null != target ) { ensureTargetTypeAligns( descriptor, target.asType() ); return Multiplicity.MANY; } else { ensureTargetTypeAligns( descriptor, m.getReturnType() ); if ( null != ProcessorUtil.findAnnotationByType( m, Constants.NONNULL_ANNOTATION_CLASSNAME ) ) { return Multiplicity.ONE; } else { return Multiplicity.ZERO_OR_ONE; } } } else { return null; } } ) .filter( Objects::nonNull ) .findAny() .orElse( null ); if ( null == multiplicity ) { throw new ArezProcessorException( "@Reference target expected to find an associated @Inverse annotation with " + "a name parameter equal to '" + descriptor.getInverseName() + "' on class " + descriptor.getMethod().getReturnType() + " but is unable to " + "locate a matching method.", descriptor.getMethod() ); } final Multiplicity inverseMultiplicity = descriptor.getInverseMultiplicity(); if ( inverseMultiplicity != multiplicity ) { throw new ArezProcessorException( "@Reference target has an inverseMultiplicity of " + inverseMultiplicity + " but that associated @Inverse has a multiplicity of " + multiplicity + ". The multiplicity must align.", descriptor.getMethod() ); } } private void ensureTargetTypeAligns( @Nonnull final ReferenceDescriptor descriptor, @Nonnull final TypeMirror target ) { if ( !_typeUtils.isSameType( target, getElement().asType() ) ) { throw new ArezProcessorException( "@Reference target expected to find an associated @Inverse annotation with " + "a target type equal to " + getElement().getQualifiedName() + " but " + "the actual target type is " + target, descriptor.getMethod() ); } } private boolean hasInverse( @Nonnull final AnnotationMirror annotation ) { final VariableElement variableElement = ProcessorUtil.getAnnotationValue( _elements, annotation, "inverse" ); switch ( variableElement.getSimpleName().toString() ) { case "ENABLE": return true; case "DISABLE": return false; default: return null != ProcessorUtil.findAnnotationValueNoDefaults( annotation, "inverseName" ) || null != ProcessorUtil.findAnnotationValueNoDefaults( annotation, "inverseMultiplicity" ); } } @Nonnull private String getReferenceInverseName( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method, @Nonnull final Multiplicity multiplicity ) { final String declaredName = ProcessorUtil.getAnnotationValue( _elements, annotation, "inverseName" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { final String baseName = getElement().getSimpleName().toString(); return ProcessorUtil.firstCharacterToLowerCase( baseName ) + ( Multiplicity.MANY == multiplicity ? "s" : "" ); } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Reference target specified an invalid inverseName '" + name + "'. The " + "inverseName must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Reference target specified an invalid inverseName '" + name + "'. The " + "inverseName must not be a java keyword.", method ); } } return name; } @Nonnull private Multiplicity getReferenceInverseMultiplicity( @Nonnull final AnnotationMirror annotation ) { final VariableElement variableElement = ProcessorUtil.getAnnotationValue( _elements, annotation, "inverseMultiplicity" ); switch ( variableElement.getSimpleName().toString() ) { case "MANY": return Multiplicity.MANY; case "ONE": return Multiplicity.ONE; default: return Multiplicity.ZERO_OR_ONE; } } @Nonnull private String getReferenceName( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method ) { final String declaredName = getAnnotationParameter( annotation, "name" ); final String name; if ( ProcessorUtil.isSentinelName( declaredName ) ) { final String candidate = ProcessorUtil.deriveName( method, GETTER_PATTERN, declaredName ); if ( null == candidate ) { name = method.getSimpleName().toString(); } else { name = candidate; } } else { name = declaredName; if ( !SourceVersion.isIdentifier( name ) ) { throw new ArezProcessorException( "@Reference target specified an invalid name '" + name + "'. The " + "name must be a valid java identifier.", method ); } else if ( SourceVersion.isKeyword( name ) ) { throw new ArezProcessorException( "@Reference target specified an invalid name '" + name + "'. The " + "name must not be a java keyword.", method ); } } return name; } @Nonnull private String getLinkType( @Nonnull final ExecutableElement method ) { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, method, Constants.REFERENCE_ANNOTATION_CLASSNAME, "load" ).getValue(); return injectParameter.getSimpleName().toString(); } private void addDependency( @Nonnull final ExecutableElement method ) { _dependencies.put( method, createDependencyDescriptor( method ) ); } @Nonnull private DependencyDescriptor createDependencyDescriptor( @Nonnull final ExecutableElement method ) { MethodChecks.mustNotHaveAnyParameters( Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method ); MethodChecks.mustBeSubclassCallable( getElement(), Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method ); MethodChecks.mustNotThrowAnyExceptions( Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method ); MethodChecks.mustReturnAValue( Constants.DEPENDENCY_ANNOTATION_CLASSNAME, method ); if ( TypeKind.DECLARED != method.getReturnType().getKind() ) { throw new ArezProcessorException( "@Dependency target must return a non-primitive value", method ); } final TypeElement disposeTrackable = _elements.getTypeElement( Constants.DISPOSE_TRACKABLE_CLASSNAME ); assert null != disposeTrackable; if ( !_typeUtils.isAssignable( method.getReturnType(), disposeTrackable.asType() ) ) { final TypeElement typeElement = (TypeElement) _typeUtils.asElement( method.getReturnType() ); final AnnotationMirror value = ProcessorUtil.findAnnotationByType( typeElement, Constants.COMPONENT_ANNOTATION_CLASSNAME ); if ( null == value || !ProcessorUtil.isDisposableTrackableRequired( _elements, typeElement ) ) { throw new ArezProcessorException( "@Dependency target must return an instance compatible with " + Constants.DISPOSE_TRACKABLE_CLASSNAME + " or a type annotated " + "with @ArezComponent(disposeTrackable=ENABLE)", method ); } } final boolean cascade = isActionCascade( method ); return new DependencyDescriptor( method, cascade ); } private boolean isActionCascade( @Nonnull final ExecutableElement method ) { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, method, Constants.DEPENDENCY_ANNOTATION_CLASSNAME, "action" ).getValue(); switch ( injectParameter.getSimpleName().toString() ) { case "CASCADE": return true; case "SET_NULL": default: return false; } } private void ensureNoAbstractMethods( @Nonnull final Collection<CandidateMethod> candidateMethods ) { candidateMethods .stream() .map( CandidateMethod::getMethod ) .filter( m -> m.getModifiers().contains( Modifier.ABSTRACT ) ) .forEach( m -> { throw new ArezProcessorException( "@ArezComponent target has an abstract method not implemented by " + "framework. The method is named " + m.getSimpleName(), getElement() ); } ); } private void linkObserverRefs() { for ( final Map.Entry<String, CandidateMethod> entry : _observerRefs.entrySet() ) { final String key = entry.getKey(); final CandidateMethod method = entry.getValue(); final AutorunDescriptor autorunDescriptor = _autoruns.get( key ); if ( null != autorunDescriptor ) { autorunDescriptor.setRefMethod( method.getMethod(), method.getMethodType() ); } else { final TrackedDescriptor trackedDescriptor = _trackeds.get( key ); if ( null != trackedDescriptor ) { trackedDescriptor.setRefMethod( method.getMethod(), method.getMethodType() ); } else { throw new ArezProcessorException( "@ObserverRef target defined observer named '" + key + "' but no " + "@Autorun or @Track method with that name exists", method.getMethod() ); } } } } private void linkUnAnnotatedObservables( @Nonnull final Map<String, CandidateMethod> getters, @Nonnull final Map<String, CandidateMethod> setters ) throws ArezProcessorException { for ( final ObservableDescriptor observable : _roObservables ) { if ( !observable.hasSetter() && !observable.hasGetter() ) { throw new ArezProcessorException( "@ObservableRef target unable to be associated with an Observable property", observable.getRefMethod() ); } else if ( !observable.hasSetter() && observable.expectSetter() ) { final CandidateMethod candidate = setters.remove( observable.getName() ); if ( null != candidate ) { MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_ANNOTATION_CLASSNAME, candidate.getMethod() ); observable.setSetter( candidate.getMethod(), candidate.getMethodType() ); } else if ( observable.hasGetter() ) { throw new ArezProcessorException( "@Observable target defined getter but no setter was defined and no " + "setter could be automatically determined", observable.getGetter() ); } } else if ( !observable.hasGetter() ) { final CandidateMethod candidate = getters.remove( observable.getName() ); if ( null != candidate ) { MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_ANNOTATION_CLASSNAME, candidate.getMethod() ); observable.setGetter( candidate.getMethod(), candidate.getMethodType() ); } else { throw new ArezProcessorException( "@Observable target defined setter but no getter was defined and no " + "getter could be automatically determined", observable.getSetter() ); } } } } private void linkUnAnnotatedTracked( @Nonnull final Map<String, CandidateMethod> trackeds, @Nonnull final Map<String, CandidateMethod> onDepsChangeds ) throws ArezProcessorException { for ( final TrackedDescriptor tracked : _roTrackeds ) { if ( !tracked.hasTrackedMethod() ) { final CandidateMethod candidate = trackeds.remove( tracked.getName() ); if ( null != candidate ) { tracked.setTrackedMethod( false, "NORMAL", true, false, false, candidate.getMethod(), candidate.getMethodType() ); } else { throw new ArezProcessorException( "@OnDepsChanged target has no corresponding @Track that could " + "be automatically determined", tracked.getOnDepsChangedMethod() ); } } else if ( !tracked.hasOnDepsChangedMethod() ) { final CandidateMethod candidate = onDepsChangeds.remove( tracked.getName() ); if ( null != candidate ) { tracked.setOnDepsChangedMethod( candidate.getMethod() ); } else { throw new ArezProcessorException( "@Track target has no corresponding @OnDepsChanged that could " + "be automatically determined", tracked.getTrackedMethod() ); } } } } private boolean analyzeMethod( @Nonnull final ExecutableElement method, @Nonnull final ExecutableType methodType ) throws ArezProcessorException { verifyNoDuplicateAnnotations( method ); final AnnotationMirror action = ProcessorUtil.findAnnotationByType( method, Constants.ACTION_ANNOTATION_CLASSNAME ); final AnnotationMirror autorun = ProcessorUtil.findAnnotationByType( method, Constants.AUTORUN_ANNOTATION_CLASSNAME ); final AnnotationMirror observable = ProcessorUtil.findAnnotationByType( method, Constants.OBSERVABLE_ANNOTATION_CLASSNAME ); final AnnotationMirror observableRef = ProcessorUtil.findAnnotationByType( method, Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror computed = ProcessorUtil.findAnnotationByType( method, Constants.COMPUTED_ANNOTATION_CLASSNAME ); final AnnotationMirror computedValueRef = ProcessorUtil.findAnnotationByType( method, Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror contextRef = ProcessorUtil.findAnnotationByType( method, Constants.CONTEXT_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror componentRef = ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror componentId = ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_ID_ANNOTATION_CLASSNAME ); final AnnotationMirror componentTypeName = ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror componentName = ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror postConstruct = ProcessorUtil.findAnnotationByType( method, Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME ); final AnnotationMirror ejbPostConstruct = ProcessorUtil.findAnnotationByType( method, Constants.EJB_POST_CONSTRUCT_ANNOTATION_CLASSNAME ); final AnnotationMirror preDispose = ProcessorUtil.findAnnotationByType( method, Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME ); final AnnotationMirror postDispose = ProcessorUtil.findAnnotationByType( method, Constants.POST_DISPOSE_ANNOTATION_CLASSNAME ); final AnnotationMirror onActivate = ProcessorUtil.findAnnotationByType( method, Constants.ON_ACTIVATE_ANNOTATION_CLASSNAME ); final AnnotationMirror onDeactivate = ProcessorUtil.findAnnotationByType( method, Constants.ON_DEACTIVATE_ANNOTATION_CLASSNAME ); final AnnotationMirror onStale = ProcessorUtil.findAnnotationByType( method, Constants.ON_STALE_ANNOTATION_CLASSNAME ); final AnnotationMirror onDispose = ProcessorUtil.findAnnotationByType( method, Constants.ON_DISPOSE_ANNOTATION_CLASSNAME ); final AnnotationMirror track = ProcessorUtil.findAnnotationByType( method, Constants.TRACK_ANNOTATION_CLASSNAME ); final AnnotationMirror onDepsChanged = ProcessorUtil.findAnnotationByType( method, Constants.ON_DEPS_CHANGED_ANNOTATION_CLASSNAME ); final AnnotationMirror observerRef = ProcessorUtil.findAnnotationByType( method, Constants.OBSERVER_REF_ANNOTATION_CLASSNAME ); final AnnotationMirror memoize = ProcessorUtil.findAnnotationByType( method, Constants.MEMOIZE_ANNOTATION_CLASSNAME ); final AnnotationMirror dependency = ProcessorUtil.findAnnotationByType( method, Constants.DEPENDENCY_ANNOTATION_CLASSNAME ); final AnnotationMirror reference = ProcessorUtil.findAnnotationByType( method, Constants.REFERENCE_ANNOTATION_CLASSNAME ); final AnnotationMirror referenceId = ProcessorUtil.findAnnotationByType( method, Constants.REFERENCE_ID_ANNOTATION_CLASSNAME ); final AnnotationMirror inverse = ProcessorUtil.findAnnotationByType( method, Constants.INVERSE_ANNOTATION_CLASSNAME ); if ( null != observable ) { final ObservableDescriptor descriptor = addObservable( observable, method, methodType ); if ( null != referenceId ) { addReferenceId( referenceId, descriptor, method ); } if ( null != inverse ) { addInverse( inverse, descriptor, method ); } return true; } else if ( null != observableRef ) { addObservableRef( observableRef, method, methodType ); return true; } else if ( null != action ) { addAction( action, method, methodType ); return true; } else if ( null != autorun ) { addAutorun( autorun, method, methodType ); return true; } else if ( null != track ) { addTracked( track, method, methodType ); return true; } else if ( null != onDepsChanged ) { addOnDepsChanged( onDepsChanged, method ); return true; } else if ( null != observerRef ) { addObserverRef( observerRef, method, methodType ); return true; } else if ( null != contextRef ) { setContextRef( method ); return true; } else if ( null != computed ) { addComputed( computed, method, methodType ); return true; } else if ( null != computedValueRef ) { addComputedValueRef( computedValueRef, method, methodType ); return true; } else if ( null != memoize ) { addMemoize( memoize, method, methodType ); return true; } else if ( null != componentRef ) { setComponentRef( method ); return true; } else if ( null != componentId ) { setComponentId( method, methodType ); return true; } else if ( null != componentName ) { setComponentNameRef( method ); return true; } else if ( null != componentTypeName ) { setComponentTypeNameRef( method ); return true; } else if ( null != ejbPostConstruct ) { throw new ArezProcessorException( "@" + Constants.EJB_POST_CONSTRUCT_ANNOTATION_CLASSNAME + " annotation " + "not supported in components annotated with @ArezComponent, use the @" + Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME + " annotation instead.", method ); } else if ( null != postConstruct ) { setPostConstruct( method ); return true; } else if ( null != preDispose ) { setPreDispose( method ); return true; } else if ( null != postDispose ) { setPostDispose( method ); return true; } else if ( null != onActivate ) { addOnActivate( onActivate, method ); return true; } else if ( null != onDeactivate ) { addOnDeactivate( onDeactivate, method ); return true; } else if ( null != onStale ) { addOnStale( onStale, method ); return true; } else if ( null != onDispose ) { addOnDispose( onDispose, method ); return true; } else if ( null != dependency ) { addDependency( method ); return false; } else if ( null != reference ) { addReference( reference, method, methodType ); return true; } else if ( null != referenceId ) { addReferenceId( referenceId, method, methodType ); return true; } else if ( null != inverse ) { addInverse( inverse, method, methodType ); return true; } else { return false; } } @Nullable private Boolean isInitializerRequired( @Nonnull final ExecutableElement element ) { final AnnotationMirror annotation = ProcessorUtil.findAnnotationByType( element, Constants.OBSERVABLE_ANNOTATION_CLASSNAME ); final AnnotationValue injectParameter = null == annotation ? null : ProcessorUtil.findAnnotationValueNoDefaults( annotation, "initializer" ); final String value = null == injectParameter ? "AUTODETECT" : ( (VariableElement) injectParameter.getValue() ).getSimpleName().toString(); switch ( value ) { case "ENABLE": return Boolean.TRUE; case "DISABLE": return Boolean.FALSE; default: return null; } } private boolean autodetectInitializer( @Nonnull final ExecutableElement element ) { return element.getModifiers().contains( Modifier.ABSTRACT ) && ( ( // Getter element.getReturnType().getKind() != TypeKind.VOID && null != ProcessorUtil.findAnnotationByType( element, Constants.NONNULL_ANNOTATION_CLASSNAME ) ) || ( // Setter 1 == element.getParameters().size() && null != ProcessorUtil.findAnnotationByType( element.getParameters().get( 0 ), Constants.NONNULL_ANNOTATION_CLASSNAME ) ) ); } private void verifyNoDuplicateAnnotations( @Nonnull final ExecutableElement method ) throws ArezProcessorException { final String[] annotationTypes = new String[]{ Constants.ACTION_ANNOTATION_CLASSNAME, Constants.AUTORUN_ANNOTATION_CLASSNAME, Constants.TRACK_ANNOTATION_CLASSNAME, Constants.ON_DEPS_CHANGED_ANNOTATION_CLASSNAME, Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, Constants.OBSERVABLE_ANNOTATION_CLASSNAME, Constants.OBSERVABLE_REF_ANNOTATION_CLASSNAME, Constants.COMPUTED_ANNOTATION_CLASSNAME, Constants.COMPUTED_VALUE_REF_ANNOTATION_CLASSNAME, Constants.MEMOIZE_ANNOTATION_CLASSNAME, Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME, Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME, Constants.POST_DISPOSE_ANNOTATION_CLASSNAME, Constants.REFERENCE_ANNOTATION_CLASSNAME, Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, Constants.ON_ACTIVATE_ANNOTATION_CLASSNAME, Constants.ON_DEACTIVATE_ANNOTATION_CLASSNAME, Constants.ON_DISPOSE_ANNOTATION_CLASSNAME, Constants.ON_STALE_ANNOTATION_CLASSNAME, Constants.DEPENDENCY_ANNOTATION_CLASSNAME }; for ( int i = 0; i < annotationTypes.length; i++ ) { final String type1 = annotationTypes[ i ]; final Object annotation1 = ProcessorUtil.findAnnotationByType( method, type1 ); if ( null != annotation1 ) { for ( int j = i + 1; j < annotationTypes.length; j++ ) { final String type2 = annotationTypes[ j ]; final boolean observableDependency = type1.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) && type2.equals( Constants.DEPENDENCY_ANNOTATION_CLASSNAME ); final boolean observableReferenceId = type1.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) && type2.equals( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME ); if ( !observableDependency && !observableReferenceId ) { final Object annotation2 = ProcessorUtil.findAnnotationByType( method, type2 ); if ( null != annotation2 ) { final String message = "Method can not be annotated with both @" + ProcessorUtil.toSimpleName( type1 ) + " and @" + ProcessorUtil.toSimpleName( type2 ); throw new ArezProcessorException( message, method ); } } } } } } @Nonnull private String getPropertyAccessorName( @Nonnull final ExecutableElement method, @Nonnull final String specifiedName ) throws ArezProcessorException { String name = ProcessorUtil.deriveName( method, GETTER_PATTERN, specifiedName ); if ( null != name ) { return name; } if ( method.getReturnType().getKind() == TypeKind.BOOLEAN ) { name = ProcessorUtil.deriveName( method, ISSER_PATTERN, specifiedName ); if ( null != name ) { return name; } } return method.getSimpleName().toString(); } @Nonnull private String getNestedClassPrefix() { final StringBuilder name = new StringBuilder(); TypeElement t = getElement(); while ( NestingKind.TOP_LEVEL != t.getNestingKind() ) { t = (TypeElement) t.getEnclosingElement(); name.insert( 0, t.getSimpleName() + "_" ); } return name.toString(); } /** * Build the enhanced class for the component. */ @Nonnull TypeSpec buildType( @Nonnull final Types typeUtils ) throws ArezProcessorException { final TypeSpec.Builder builder = TypeSpec.classBuilder( getArezClassName() ). superclass( TypeName.get( getElement().asType() ) ). addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) ). addModifiers( Modifier.FINAL ); addOriginatingTypes( getElement(), builder ); addGeneratedAnnotation( builder ); if ( !_roComputeds.isEmpty() ) { builder.addAnnotation( AnnotationSpec.builder( SuppressWarnings.class ). addMember( "value", "$S", "unchecked" ). build() ); } final boolean publicType = ProcessorUtil.getConstructors( getElement() ). stream(). anyMatch( c -> c.getModifiers().contains( Modifier.PUBLIC ) ) && getElement().getModifiers().contains( Modifier.PUBLIC ); if ( publicType ) { builder.addModifiers( Modifier.PUBLIC ); } if ( null != _scopeAnnotation ) { final DeclaredType annotationType = _scopeAnnotation.getAnnotationType(); final TypeElement typeElement = (TypeElement) annotationType.asElement(); builder.addAnnotation( ClassName.get( typeElement ) ); } builder.addSuperinterface( GeneratorUtil.DISPOSABLE_CLASSNAME ); builder.addSuperinterface( ParameterizedTypeName.get( GeneratorUtil.IDENTIFIABLE_CLASSNAME, getIdType().box() ) ); if ( _observable ) { builder.addSuperinterface( GeneratorUtil.COMPONENT_OBSERVABLE_CLASSNAME ); } if ( _verify ) { builder.addSuperinterface( GeneratorUtil.VERIFIABLE_CLASSNAME ); } if ( _disposeTrackable ) { builder.addSuperinterface( GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME ); } if ( needsExplicitLink() ) { builder.addSuperinterface( GeneratorUtil.LINKABLE_CLASSNAME ); } buildFields( builder ); buildConstructors( builder, typeUtils ); builder.addMethod( buildContextRefMethod() ); if ( null != _componentRef ) { builder.addMethod( buildComponentRefMethod() ); } if ( !_references.isEmpty() || !_inverses.isEmpty() ) { builder.addMethod( buildLocatorRefMethod() ); } if ( null == _componentId ) { builder.addMethod( buildComponentIdMethod() ); } builder.addMethod( buildArezIdMethod() ); builder.addMethod( buildComponentNameMethod() ); final MethodSpec method = buildComponentTypeNameMethod(); if ( null != method ) { builder.addMethod( method ); } if ( _observable ) { builder.addMethod( buildInternalObserve() ); builder.addMethod( buildObserve() ); } if ( _disposeTrackable || !_roReferences.isEmpty() ) { builder.addMethod( buildInternalPreDispose() ); } if ( _disposeTrackable ) { builder.addMethod( buildNotifierAccessor() ); } builder.addMethod( buildIsDisposed() ); builder.addMethod( buildDispose() ); if ( _verify ) { builder.addMethod( buildVerify() ); } if ( needsExplicitLink() ) { builder.addMethod( buildLink() ); } _roObservables.forEach( e -> e.buildMethods( builder ) ); _roAutoruns.forEach( e -> e.buildMethods( builder ) ); _roActions.forEach( e -> e.buildMethods( builder ) ); _roComputeds.forEach( e -> e.buildMethods( builder ) ); _roMemoizes.forEach( e -> e.buildMethods( builder ) ); _roTrackeds.forEach( e -> e.buildMethods( builder ) ); _roReferences.forEach( e -> e.buildMethods( builder ) ); _roInverses.forEach( e -> e.buildMethods( builder ) ); builder.addMethod( buildHashcodeMethod() ); builder.addMethod( buildEqualsMethod() ); if ( _generateToString ) { builder.addMethod( buildToStringMethod() ); } return builder.build(); } private boolean needsExplicitLink() { return _roReferences.stream().anyMatch( r -> r.getLinkType().equals( "EXPLICIT" ) ); } @Nonnull private MethodSpec buildToStringMethod() throws ArezProcessorException { assert _generateToString; final MethodSpec.Builder method = MethodSpec.methodBuilder( "toString" ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( Override.class ). returns( TypeName.get( String.class ) ); final CodeBlock.Builder codeBlock = CodeBlock.builder(); codeBlock.beginControlFlow( "if ( $T.areNamesEnabled() )", GeneratorUtil.AREZ_CLASSNAME ); codeBlock.addStatement( "return $S + $N() + $S", "ArezComponent[", getComponentNameMethodName(), "]" ); codeBlock.nextControlFlow( "else" ); codeBlock.addStatement( "return super.toString()" ); codeBlock.endControlFlow(); method.addCode( codeBlock.build() ); return method.build(); } @Nonnull private MethodSpec buildEqualsMethod() throws ArezProcessorException { final String idMethod = getIdMethodName(); final MethodSpec.Builder method = MethodSpec.methodBuilder( "equals" ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( Override.class ). addParameter( Object.class, "o", Modifier.FINAL ). returns( TypeName.BOOLEAN ); final ClassName generatedClass = ClassName.get( getPackageName(), getArezClassName() ); final CodeBlock.Builder codeBlock = CodeBlock.builder(); codeBlock.beginControlFlow( "if ( this == o )" ); codeBlock.addStatement( "return true" ); codeBlock.nextControlFlow( "else if ( null == o || !(o instanceof $T) )", generatedClass ); codeBlock.addStatement( "return false" ); if ( null != _componentId ) { codeBlock.nextControlFlow( "else if ( $T.isDisposed( this ) != $T.isDisposed( o ) )", GeneratorUtil.DISPOSABLE_CLASSNAME, GeneratorUtil.DISPOSABLE_CLASSNAME ); codeBlock.addStatement( "return false" ); } codeBlock.nextControlFlow( "else" ); codeBlock.addStatement( "final $T that = ($T) o;", generatedClass, generatedClass ); final TypeKind kind = null != _componentId ? _componentId.getReturnType().getKind() : GeneratorUtil.DEFAULT_ID_KIND; if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR ) { codeBlock.addStatement( "return null != $N() && $N().equals( that.$N() )", idMethod, idMethod, idMethod ); } else { codeBlock.addStatement( "return $N() == that.$N()", idMethod, idMethod ); } codeBlock.endControlFlow(); if ( _requireEquals ) { method.addCode( codeBlock.build() ); } else { final CodeBlock.Builder guardBlock = CodeBlock.builder(); guardBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME ); guardBlock.add( codeBlock.build() ); guardBlock.nextControlFlow( "else" ); guardBlock.addStatement( "return super.equals( o )" ); guardBlock.endControlFlow(); method.addCode( guardBlock.build() ); } return method.build(); } @Nonnull private MethodSpec buildHashcodeMethod() throws ArezProcessorException { final String idMethod = getIdMethodName(); final MethodSpec.Builder method = MethodSpec.methodBuilder( "hashCode" ). addModifiers( Modifier.PUBLIC, Modifier.FINAL ). addAnnotation( Override.class ). returns( TypeName.INT ); final TypeKind kind = null != _componentId ? _componentId.getReturnType().getKind() : GeneratorUtil.DEFAULT_ID_KIND; if ( _requireEquals ) { if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR ) { method.addStatement( "return null != $N() ? $N().hashCode() : $T.identityHashCode( this )", idMethod, idMethod, System.class ); } else if ( kind == TypeKind.BYTE ) { method.addStatement( "return $T.hashCode( $N() )", Byte.class, idMethod ); } else if ( kind == TypeKind.CHAR ) { method.addStatement( "return $T.hashCode( $N() )", Character.class, idMethod ); } else if ( kind == TypeKind.SHORT ) { method.addStatement( "return $T.hashCode( $N() )", Short.class, idMethod ); } else if ( kind == TypeKind.INT ) { method.addStatement( "return $T.hashCode( $N() )", Integer.class, idMethod ); } else if ( kind == TypeKind.LONG ) { method.addStatement( "return $T.hashCode( $N() )", Long.class, idMethod ); } else if ( kind == TypeKind.FLOAT ) { method.addStatement( "return $T.hashCode( $N() )", Float.class, idMethod ); } else if ( kind == TypeKind.DOUBLE ) { method.addStatement( "return $T.hashCode( $N() )", Double.class, idMethod ); } else { // So very unlikely but will cover it for completeness assert kind == TypeKind.BOOLEAN; method.addStatement( "return $T.hashCode( $N() )", Boolean.class, idMethod ); } } else { final CodeBlock.Builder guardBlock = CodeBlock.builder(); guardBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME ); if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR ) { guardBlock.addStatement( "return null != $N() ? $N().hashCode() : $T.identityHashCode( this )", idMethod, idMethod, System.class ); } else if ( kind == TypeKind.BYTE ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Byte.class, idMethod ); } else if ( kind == TypeKind.CHAR ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Character.class, idMethod ); } else if ( kind == TypeKind.SHORT ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Short.class, idMethod ); } else if ( kind == TypeKind.INT ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Integer.class, idMethod ); } else if ( kind == TypeKind.LONG ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Long.class, idMethod ); } else if ( kind == TypeKind.FLOAT ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Float.class, idMethod ); } else if ( kind == TypeKind.DOUBLE ) { guardBlock.addStatement( "return $T.hashCode( $N() )", Double.class, idMethod ); } else { // So very unlikely but will cover it for completeness assert kind == TypeKind.BOOLEAN; guardBlock.addStatement( "return $T.hashCode( $N() )", Boolean.class, idMethod ); } guardBlock.nextControlFlow( "else" ); guardBlock.addStatement( "return super.hashCode()" ); guardBlock.endControlFlow(); method.addCode( guardBlock.build() ); } return method.build(); } @Nonnull String getComponentNameMethodName() { return null == _componentNameRef ? GeneratorUtil.NAME_METHOD_NAME : _componentNameRef.getSimpleName().toString(); } @Nonnull private MethodSpec buildContextRefMethod() throws ArezProcessorException { final String methodName = getContextMethodName(); final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ). addModifiers( Modifier.FINAL ). returns( GeneratorUtil.AREZ_CONTEXT_CLASSNAME ); GeneratorUtil.generateNotInitializedInvariant( this, method, methodName ); method.addStatement( "return $T.areZonesEnabled() ? this.$N : $T.context()", GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.CONTEXT_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME ); if ( null != _contextRef ) { method.addAnnotation( Override.class ); ProcessorUtil.copyWhitelistedAnnotations( _contextRef, method ); ProcessorUtil.copyAccessModifiers( _contextRef, method ); } return method.build(); } @Nonnull String getContextMethodName() { return null != _contextRef ? _contextRef.getSimpleName().toString() : GeneratorUtil.CONTEXT_FIELD_NAME; } @Nonnull private MethodSpec buildLocatorRefMethod() throws ArezProcessorException { final String methodName = GeneratorUtil.LOCATOR_METHOD_NAME; final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ). addModifiers( Modifier.FINAL ). returns( GeneratorUtil.LOCATOR_CLASSNAME ); GeneratorUtil.generateNotInitializedInvariant( this, method, methodName ); method.addStatement( "return $N().locator()", getContextMethodName() ); return method.build(); } @Nonnull private MethodSpec buildComponentRefMethod() throws ArezProcessorException { assert null != _componentRef; final String methodName = _componentRef.getSimpleName().toString(); final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ). addModifiers( Modifier.FINAL ). returns( GeneratorUtil.COMPONENT_CLASSNAME ); GeneratorUtil.generateNotInitializedInvariant( this, method, methodName ); GeneratorUtil.generateNotConstructedInvariant( this, method, methodName ); GeneratorUtil.generateNotCompleteInvariant( this, method, methodName ); GeneratorUtil.generateNotDisposedInvariant( this, method, methodName ); final CodeBlock.Builder block = CodeBlock.builder(); block.beginControlFlow( "if ( $T.shouldCheckInvariants() )", GeneratorUtil.AREZ_CLASSNAME ); block.addStatement( "$T.invariant( () -> $T.areNativeComponentsEnabled(), () -> \"Invoked @ComponentRef " + "method '$N' but Arez.areNativeComponentsEnabled() returned false.\" )", GeneratorUtil.GUARDS_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, methodName ); block.endControlFlow(); method.addCode( block.build() ); method.addStatement( "return this.$N", GeneratorUtil.COMPONENT_FIELD_NAME ); ProcessorUtil.copyWhitelistedAnnotations( _componentRef, method ); ProcessorUtil.copyAccessModifiers( _componentRef, method ); return method.build(); } @Nonnull private MethodSpec buildArezIdMethod() throws ArezProcessorException { return MethodSpec.methodBuilder( "getArezId" ). addAnnotation( Override.class ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addModifiers( Modifier.PUBLIC ). addModifiers( Modifier.FINAL ). returns( getIdType().box() ). addStatement( "return $N()", getIdMethodName() ).build(); } @Nonnull private MethodSpec buildComponentIdMethod() throws ArezProcessorException { assert null == _componentId; final MethodSpec.Builder method = MethodSpec.methodBuilder( GeneratorUtil.ID_FIELD_NAME ). addModifiers( Modifier.FINAL ). returns( GeneratorUtil.DEFAULT_ID_TYPE ); if ( !_idRequired ) { final CodeBlock.Builder block = CodeBlock.builder(); if ( _nameIncludesId ) { block.beginControlFlow( "if ( $T.shouldCheckInvariants() && !$T.areNamesEnabled() && !$T.areRegistriesEnabled() && !$T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME ); } else { block.beginControlFlow( "if ( $T.shouldCheckInvariants() && !$T.areRegistriesEnabled() && !$T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME ); } block.addStatement( "$T.fail( () -> \"Method invoked to access id when id not expected on component named '\" + $N() + \"'.\" )", GeneratorUtil.GUARDS_CLASSNAME, getComponentNameMethodName() ); block.endControlFlow(); method.addCode( block.build() ); } return method.addStatement( "return this.$N", GeneratorUtil.ID_FIELD_NAME ).build(); } /** * Generate the getter for component name. */ @Nonnull private MethodSpec buildComponentNameMethod() throws ArezProcessorException { final MethodSpec.Builder builder; final String methodName; if ( null == _componentNameRef ) { methodName = GeneratorUtil.NAME_METHOD_NAME; builder = MethodSpec.methodBuilder( methodName ); } else { methodName = _componentNameRef.getSimpleName().toString(); builder = MethodSpec.methodBuilder( methodName ); ProcessorUtil.copyWhitelistedAnnotations( _componentNameRef, builder ); ProcessorUtil.copyAccessModifiers( _componentNameRef, builder ); builder.addModifiers( Modifier.FINAL ); } builder.returns( TypeName.get( String.class ) ); GeneratorUtil.generateNotInitializedInvariant( this, builder, methodName ); if ( _nameIncludesId ) { builder.addStatement( "return $S + $N()", _type.isEmpty() ? "" : _type + ".", getIdMethodName() ); } else { builder.addStatement( "return $S", _type ); } return builder.build(); } @Nullable private MethodSpec buildComponentTypeNameMethod() throws ArezProcessorException { if ( null == _componentTypeNameRef ) { return null; } final MethodSpec.Builder builder = MethodSpec.methodBuilder( _componentTypeNameRef.getSimpleName().toString() ); ProcessorUtil.copyAccessModifiers( _componentTypeNameRef, builder ); builder.addModifiers( Modifier.FINAL ); builder.addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ); builder.returns( TypeName.get( String.class ) ); builder.addStatement( "return $S", _type ); return builder.build(); } @Nonnull private MethodSpec buildVerify() { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "verify" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ); GeneratorUtil.generateNotDisposedInvariant( this, builder, "verify" ); if ( !_roReferences.isEmpty() || !_roInverses.isEmpty() ) { final CodeBlock.Builder block = CodeBlock.builder(); block.beginControlFlow( "if ( $T.shouldCheckApiInvariants() && $T.isVerifyEnabled() )", GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME ); block.addStatement( "$T.apiInvariant( () -> this == $N().findById( $T.class, $N() ), () -> \"Attempted to " + "lookup self in Locator with type $T and id '\" + $N() + \"' but unable to locate " + "self. Actual value: \" + $N().findById( $T.class, $N() ) )", GeneratorUtil.GUARDS_CLASSNAME, GeneratorUtil.LOCATOR_METHOD_NAME, getElement(), getIdMethodName(), getElement(), getIdMethodName(), GeneratorUtil.LOCATOR_METHOD_NAME, getElement(), getIdMethodName() ); for ( final ReferenceDescriptor reference : _roReferences ) { block.addStatement( "this.$N = null", reference.getFieldName() ); block.addStatement( "this.$N()", reference.getLinkMethodName() ); } for ( final InverseDescriptor inverse : _roInverses ) { inverse.buildVerify( block ); } block.endControlFlow(); builder.addCode( block.build() ); } return builder.build(); } @Nonnull private MethodSpec buildLink() { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "link" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ); GeneratorUtil.generateNotDisposedInvariant( this, builder, "link" ); final List<ReferenceDescriptor> explicitReferences = _roReferences.stream().filter( r -> r.getLinkType().equals( "EXPLICIT" ) ).collect( Collectors.toList() ); for ( final ReferenceDescriptor reference : explicitReferences ) { builder.addStatement( "this.$N()", reference.getLinkMethodName() ); } return builder.build(); } /** * Generate the dispose method. */ @Nonnull private MethodSpec buildDispose() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "dispose" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ); final CodeBlock.Builder codeBlock = CodeBlock.builder(); codeBlock.beginControlFlow( "if ( !$T.isDisposingOrDisposed( this.$N ) )", GeneratorUtil.COMPONENT_STATE_CLASSNAME, GeneratorUtil.STATE_FIELD_NAME ); codeBlock.addStatement( "this.$N = $T.COMPONENT_DISPOSING", GeneratorUtil.STATE_FIELD_NAME, GeneratorUtil.COMPONENT_STATE_CLASSNAME ); final CodeBlock.Builder nativeComponentBlock = CodeBlock.builder(); nativeComponentBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME ); nativeComponentBlock.addStatement( "this.$N.dispose()", GeneratorUtil.COMPONENT_FIELD_NAME ); nativeComponentBlock.nextControlFlow( "else" ); final CodeBlock.Builder actionBlock = CodeBlock.builder(); actionBlock.beginControlFlow( "$N().safeAction( $T.areNamesEnabled() ? $N() + $S : null, true, false, () -> {", getContextMethodName(), GeneratorUtil.AREZ_CLASSNAME, getComponentNameMethodName(), ".dispose" ); if ( _disposeTrackable || !_roReferences.isEmpty() ) { actionBlock.addStatement( "this.$N()", GeneratorUtil.INTERNAL_PRE_DISPOSE_METHOD_NAME ); } else if ( null != _preDispose ) { actionBlock.addStatement( "super.$N()", _preDispose.getSimpleName() ); } if ( _observable ) { actionBlock.addStatement( "this.$N.dispose()", GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME ); } _roAutoruns.forEach( autorun -> autorun.buildDisposer( actionBlock ) ); _roTrackeds.forEach( tracked -> tracked.buildDisposer( actionBlock ) ); _roComputeds.forEach( computed -> computed.buildDisposer( actionBlock ) ); _roMemoizes.forEach( computed -> computed.buildDisposer( actionBlock ) ); _roObservables.forEach( observable -> observable.buildDisposer( actionBlock ) ); if ( null != _postDispose ) { actionBlock.addStatement( "super.$N()", _postDispose.getSimpleName() ); } actionBlock.endControlFlow( "} )" ); nativeComponentBlock.add( actionBlock.build() ); nativeComponentBlock.endControlFlow(); codeBlock.add( nativeComponentBlock.build() ); GeneratorUtil.setStateForInvariantChecking( codeBlock, "COMPONENT_DISPOSED" ); codeBlock.endControlFlow(); builder.addCode( codeBlock.build() ); return builder.build(); } /** * Generate the isDisposed method. */ @Nonnull private MethodSpec buildIsDisposed() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "isDisposed" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ). returns( TypeName.BOOLEAN ); builder.addStatement( "return $T.isDisposingOrDisposed( this.$N )", GeneratorUtil.COMPONENT_STATE_CLASSNAME, GeneratorUtil.STATE_FIELD_NAME ); return builder.build(); } /** * Generate the observe method. */ @Nonnull private MethodSpec buildInternalObserve() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( GeneratorUtil.INTERNAL_OBSERVE_METHOD_NAME ). addModifiers( Modifier.PRIVATE ). returns( TypeName.BOOLEAN ); builder.addStatement( "final boolean isNotDisposed = isNotDisposed()" ); final CodeBlock.Builder block = CodeBlock.builder(); block.beginControlFlow( "if ( isNotDisposed ) ", getContextMethodName() ); block.addStatement( "this.$N.reportObserved()", GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME ); block.endControlFlow(); builder.addCode( block.build() ); builder.addStatement( "return isNotDisposed" ); return builder.build(); } /** * Generate the observe method. */ @Nonnull private MethodSpec buildObserve() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "observe" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ). returns( TypeName.BOOLEAN ); if ( _disposeOnDeactivate ) { builder.addStatement( "return $N.get()", GeneratorUtil.DISPOSE_ON_DEACTIVATE_FIELD_NAME ); } else { builder.addStatement( "return $N()", GeneratorUtil.INTERNAL_OBSERVE_METHOD_NAME ); } return builder.build(); } /** * Generate the preDispose method. */ @Nonnull private MethodSpec buildInternalPreDispose() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( GeneratorUtil.INTERNAL_PRE_DISPOSE_METHOD_NAME ). addModifiers( Modifier.PRIVATE ); if ( null != _preDispose ) { builder.addStatement( "super.$N()", _preDispose.getSimpleName() ); } _roReferences.forEach( r -> r.buildDisposer( builder ) ); if ( _disposeTrackable ) { builder.addStatement( "$N.dispose()", GeneratorUtil.DISPOSE_NOTIFIER_FIELD_NAME ); for ( final DependencyDescriptor dependency : _roDependencies ) { final ExecutableElement method = dependency.getMethod(); final String methodName = method.getSimpleName().toString(); final boolean isNonnull = null != ProcessorUtil.findAnnotationByType( method, Constants.NONNULL_ANNOTATION_CLASSNAME ); if ( isNonnull ) { builder.addStatement( "$T.asDisposeTrackable( $N() ).getNotifier().removeOnDisposeListener( this )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, methodName ); } else { final String varName = GeneratorUtil.VARIABLE_PREFIX + methodName + "_dependency"; final boolean abstractObservables = method.getModifiers().contains( Modifier.ABSTRACT ); if ( abstractObservables ) { builder.addStatement( "final $T $N = this.$N", method.getReturnType(), varName, dependency.getObservable().getDataFieldName() ); } else { builder.addStatement( "final $T $N = super.$N()", method.getReturnType(), varName, methodName ); } final CodeBlock.Builder listenerBlock = CodeBlock.builder(); listenerBlock.beginControlFlow( "if ( null != $N )", varName ); listenerBlock.addStatement( "$T.asDisposeTrackable( $N ).getNotifier().removeOnDisposeListener( this )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, varName ); listenerBlock.endControlFlow(); builder.addCode( listenerBlock.build() ); } } } return builder.build(); } /** * Generate the observe method. */ @Nonnull private MethodSpec buildNotifierAccessor() throws ArezProcessorException { final MethodSpec.Builder builder = MethodSpec.methodBuilder( "getNotifier" ). addModifiers( Modifier.PUBLIC ). addAnnotation( Override.class ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). returns( GeneratorUtil.DISPOSE_NOTIFIER_CLASSNAME ); builder.addStatement( "return $N", GeneratorUtil.DISPOSE_NOTIFIER_FIELD_NAME ); return builder.build(); } /** * Build the fields required to make class Observable. This involves; * <ul> * <li>the context field if there is any @Action methods.</li> * <li>the observable object for every @Observable.</li> * <li>the ComputedValue object for every @Computed method.</li> * </ul> */ private void buildFields( @Nonnull final TypeSpec.Builder builder ) { // If we don't have a method for object id but we need one then synthesize it if ( null == _componentId ) { final FieldSpec.Builder nextIdField = FieldSpec.builder( GeneratorUtil.DEFAULT_ID_TYPE, GeneratorUtil.NEXT_ID_FIELD_NAME, Modifier.VOLATILE, Modifier.STATIC, Modifier.PRIVATE ); builder.addField( nextIdField.build() ); final FieldSpec.Builder idField = FieldSpec.builder( GeneratorUtil.DEFAULT_ID_TYPE, GeneratorUtil.ID_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ); builder.addField( idField.build() ); } final FieldSpec.Builder disposableField = FieldSpec.builder( TypeName.BYTE, GeneratorUtil.STATE_FIELD_NAME, Modifier.PRIVATE ); builder.addField( disposableField.build() ); // Create the field that contains the context { final FieldSpec.Builder field = FieldSpec.builder( GeneratorUtil.AREZ_CONTEXT_CLASSNAME, GeneratorUtil.CONTEXT_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ). addAnnotation( GeneratorUtil.NULLABLE_CLASSNAME ); builder.addField( field.build() ); } //Create the field that contains the component { final FieldSpec.Builder field = FieldSpec.builder( GeneratorUtil.COMPONENT_CLASSNAME, GeneratorUtil.COMPONENT_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ); builder.addField( field.build() ); } if ( _observable ) { final ParameterizedTypeName typeName = ParameterizedTypeName.get( GeneratorUtil.OBSERVABLE_CLASSNAME, TypeName.BOOLEAN.box() ); final FieldSpec.Builder field = FieldSpec.builder( typeName, GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ); builder.addField( field.build() ); } if ( _disposeTrackable ) { final FieldSpec.Builder field = FieldSpec.builder( GeneratorUtil.DISPOSE_NOTIFIER_CLASSNAME, GeneratorUtil.DISPOSE_NOTIFIER_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ); builder.addField( field.build() ); } _roObservables.forEach( observable -> observable.buildFields( builder ) ); _roComputeds.forEach( computed -> computed.buildFields( builder ) ); _roMemoizes.forEach( e -> e.buildFields( builder ) ); _roAutoruns.forEach( autorun -> autorun.buildFields( builder ) ); _roTrackeds.forEach( tracked -> tracked.buildFields( builder ) ); _roReferences.forEach( r -> r.buildFields( builder ) ); if ( _disposeOnDeactivate ) { final FieldSpec.Builder field = FieldSpec.builder( ParameterizedTypeName.get( GeneratorUtil.COMPUTED_VALUE_CLASSNAME, TypeName.BOOLEAN.box() ), GeneratorUtil.DISPOSE_ON_DEACTIVATE_FIELD_NAME, Modifier.FINAL, Modifier.PRIVATE ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ); builder.addField( field.build() ); } } /** * Build all constructors as they appear on the ArezComponent class. * Arez Observable fields are populated as required and parameters are passed up to superclass. */ private void buildConstructors( @Nonnull final TypeSpec.Builder builder, @Nonnull final Types typeUtils ) { final boolean requiresDeprecatedSuppress = hasDeprecatedElements(); for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( getElement() ) ) { final ExecutableType methodType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), constructor ); builder.addMethod( buildConstructor( constructor, methodType, requiresDeprecatedSuppress ) ); } } /** * Build a constructor based on the supplied constructor */ @Nonnull private MethodSpec buildConstructor( @Nonnull final ExecutableElement constructor, @Nonnull final ExecutableType constructorType, final boolean requiresDeprecatedSuppress ) { final MethodSpec.Builder builder = MethodSpec.constructorBuilder(); ProcessorUtil.copyAccessModifiers( constructor, builder ); ProcessorUtil.copyExceptions( constructorType, builder ); ProcessorUtil.copyTypeParameters( constructorType, builder ); if ( requiresDeprecatedSuppress ) { builder.addAnnotation( AnnotationSpec.builder( SuppressWarnings.class ) .addMember( "value", "$S", "deprecation" ) .build() ); } if ( _inject ) { builder.addAnnotation( GeneratorUtil.INJECT_CLASSNAME ); } final List<ObservableDescriptor> initializers = getInitializers(); final StringBuilder superCall = new StringBuilder(); superCall.append( "super(" ); final ArrayList<String> parameterNames = new ArrayList<>(); boolean firstParam = true; for ( final VariableElement element : constructor.getParameters() ) { final ParameterSpec.Builder param = ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL ); ProcessorUtil.copyWhitelistedAnnotations( element, param ); builder.addParameter( param.build() ); parameterNames.add( element.getSimpleName().toString() ); if ( !firstParam ) { superCall.append( "," ); } firstParam = false; superCall.append( "$N" ); } superCall.append( ")" ); builder.addStatement( superCall.toString(), parameterNames.toArray() ); if ( !_references.isEmpty() ) { final CodeBlock.Builder block = CodeBlock.builder(); block.beginControlFlow( "if ( $T.shouldCheckApiInvariants() )", GeneratorUtil.AREZ_CLASSNAME ); block.addStatement( "$T.apiInvariant( () -> $T.areReferencesEnabled(), () -> \"Attempted to create instance " + "of component of type '$N' that contains references but Arez.areReferencesEnabled() " + "returns false. References need to be enabled to use this component\" )", GeneratorUtil.GUARDS_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, getType() ); block.endControlFlow(); builder.addCode( block.build() ); } for ( final ObservableDescriptor observable : initializers ) { final String candidateName = observable.getName(); final String name = isNameCollision( constructor, Collections.emptyList(), candidateName ) ? GeneratorUtil.INITIALIZER_PREFIX + candidateName : candidateName; final ParameterSpec.Builder param = ParameterSpec.builder( TypeName.get( observable.getGetterType().getReturnType() ), name, Modifier.FINAL ); ProcessorUtil.copyWhitelistedAnnotations( observable.getGetter(), param ); builder.addParameter( param.build() ); final boolean isPrimitive = TypeName.get( observable.getGetterType().getReturnType() ).isPrimitive(); if ( isPrimitive ) { builder.addStatement( "this.$N = $N", observable.getDataFieldName(), name ); } else { builder.addStatement( "this.$N = $T.requireNonNull( $N )", observable.getDataFieldName(), Objects.class, name ); } } builder.addStatement( "this.$N = $T.areZonesEnabled() ? $T.context() : null", GeneratorUtil.CONTEXT_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME ); // Synthesize Id if required if ( null == _componentId ) { if ( _nameIncludesId ) { if ( _idRequired ) { builder.addStatement( "this.$N = $N++", GeneratorUtil.ID_FIELD_NAME, GeneratorUtil.NEXT_ID_FIELD_NAME ); } else { builder.addStatement( "this.$N = ( $T.areNamesEnabled() || $T.areRegistriesEnabled() || $T.areNativeComponentsEnabled() ) ? $N++ : 0", GeneratorUtil.ID_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.NEXT_ID_FIELD_NAME ); } } else { builder.addStatement( "this.$N = ( $T.areRegistriesEnabled() || $T.areNativeComponentsEnabled() ) ? $N++ : 0", GeneratorUtil.ID_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.NEXT_ID_FIELD_NAME ); } } GeneratorUtil.setStateForInvariantChecking( builder, "COMPONENT_INITIALIZED" ); // Create component representation if required { final StringBuilder sb = new StringBuilder(); final ArrayList<Object> params = new ArrayList<>(); sb.append( "this.$N = $T.areNativeComponentsEnabled() ? " + "$N().component( $S, $N(), $T.areNamesEnabled() ? $N() :" + " null" ); params.add( GeneratorUtil.COMPONENT_FIELD_NAME ); params.add( GeneratorUtil.AREZ_CLASSNAME ); params.add( getContextMethodName() ); params.add( _type ); params.add( getIdMethodName() ); params.add( GeneratorUtil.AREZ_CLASSNAME ); params.add( getComponentNameMethodName() ); if ( _disposeTrackable || null != _preDispose || null != _postDispose ) { sb.append( ", " ); if ( _disposeTrackable ) { sb.append( "() -> $N()" ); params.add( GeneratorUtil.INTERNAL_PRE_DISPOSE_METHOD_NAME ); } else if ( null != _preDispose ) { sb.append( "() -> super.$N()" ); params.add( _preDispose.getSimpleName().toString() ); } if ( null != _postDispose ) { sb.append( ", () -> super.$N()" ); params.add( _postDispose.getSimpleName().toString() ); } } sb.append( " ) : null" ); builder.addStatement( sb.toString(), params.toArray() ); } if ( _observable ) { builder.addStatement( "this.$N = $N().observable( " + "$T.areNativeComponentsEnabled() ? this.$N : null, " + "$T.areNamesEnabled() ? $N() + $S : null, " + "$T.arePropertyIntrospectorsEnabled() ? () -> this.$N >= 0 : null )", GeneratorUtil.DISPOSED_OBSERVABLE_FIELD_NAME, getContextMethodName(), GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.COMPONENT_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME, getComponentNameMethodName(), ".isDisposed", GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.STATE_FIELD_NAME ); } if ( _disposeTrackable ) { builder.addStatement( "this.$N = new $T()", GeneratorUtil.DISPOSE_NOTIFIER_FIELD_NAME, GeneratorUtil.DISPOSE_NOTIFIER_CLASSNAME ); } if ( _disposeOnDeactivate ) { builder.addStatement( "this.$N = $N().computedValue( " + "$T.areNativeComponentsEnabled() ? this.$N : null, " + "$T.areNamesEnabled() ? $N() + $S : null, " + "() -> $N(), null, () -> $N().scheduleDispose( this ), null, null, $T.HIGHEST )", GeneratorUtil.DISPOSE_ON_DEACTIVATE_FIELD_NAME, getContextMethodName(), GeneratorUtil.AREZ_CLASSNAME, GeneratorUtil.COMPONENT_FIELD_NAME, GeneratorUtil.AREZ_CLASSNAME, getComponentNameMethodName(), ".disposeOnDeactivate", GeneratorUtil.INTERNAL_OBSERVE_METHOD_NAME, getContextMethodName(), GeneratorUtil.PRIORITY_CLASSNAME ); } _roObservables.forEach( observable -> observable.buildInitializer( builder ) ); _roComputeds.forEach( computed -> computed.buildInitializer( builder ) ); _roMemoizes.forEach( e -> e.buildInitializer( builder ) ); _roAutoruns.forEach( autorun -> autorun.buildInitializer( builder ) ); _roTrackeds.forEach( tracked -> tracked.buildInitializer( builder ) ); _roInverses.forEach( e -> e.buildInitializer( builder ) ); for ( final DependencyDescriptor dep : _roDependencies ) { final ExecutableElement method = dep.getMethod(); final String methodName = method.getSimpleName().toString(); final boolean abstractObservables = method.getModifiers().contains( Modifier.ABSTRACT ); final boolean isNonnull = null != ProcessorUtil.findAnnotationByType( method, Constants.NONNULL_ANNOTATION_CLASSNAME ); if ( abstractObservables ) { if ( isNonnull ) { assert dep.shouldCascadeDispose(); builder.addStatement( "$T.asDisposeTrackable( $N ).getNotifier().addOnDisposeListener( this, this::dispose )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, dep.getObservable().getDataFieldName() ); } else { final String varName = GeneratorUtil.VARIABLE_PREFIX + methodName + "_dependency"; builder.addStatement( "final $T $N = this.$N", dep.getMethod().getReturnType(), varName, dep.getObservable().getDataFieldName() ); final CodeBlock.Builder listenerBlock = CodeBlock.builder(); listenerBlock.beginControlFlow( "if ( null != $N )", varName ); if ( dep.shouldCascadeDispose() ) { listenerBlock.addStatement( "$T.asDisposeTrackable( $N ).getNotifier().addOnDisposeListener( this, this::dispose )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, dep.getObservable().getDataFieldName() ); } else { listenerBlock.addStatement( "$T.asDisposeTrackable( $N ).getNotifier().addOnDisposeListener( this, () -> $N( null ) )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, dep.getObservable().getDataFieldName(), dep.getObservable().getSetter().getSimpleName().toString() ); } listenerBlock.endControlFlow(); builder.addCode( listenerBlock.build() ); } } else { if ( isNonnull ) { assert dep.shouldCascadeDispose(); builder.addStatement( "$T.asDisposeTrackable( super.$N() ).getNotifier().addOnDisposeListener( this, this::dispose )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, method.getSimpleName().toString() ); } else { final String varName = GeneratorUtil.VARIABLE_PREFIX + methodName + "_dependency"; builder.addStatement( "final $T $N = super.$N()", dep.getMethod().getReturnType(), varName, method.getSimpleName().toString() ); final CodeBlock.Builder listenerBlock = CodeBlock.builder(); listenerBlock.beginControlFlow( "if ( null != $N )", varName ); if ( dep.shouldCascadeDispose() ) { listenerBlock.addStatement( "$T.asDisposeTrackable( super.$N() ).getNotifier().addOnDisposeListener( this, this::dispose )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, method.getSimpleName() ); } else { listenerBlock.addStatement( "$T.asDisposeTrackable( super.$N() ).getNotifier().addOnDisposeListener( this, () -> $N( null ) )", GeneratorUtil.DISPOSE_TRACKABLE_CLASSNAME, method.getSimpleName(), dep.getObservable().getSetter().getSimpleName().toString() ); } listenerBlock.endControlFlow(); builder.addCode( listenerBlock.build() ); } } } GeneratorUtil.setStateForInvariantChecking( builder, "COMPONENT_CONSTRUCTED" ); final List<ReferenceDescriptor> eagerReferences = _roReferences.stream().filter( r -> r.getLinkType().equals( "EAGER" ) ).collect( Collectors.toList() ); for ( final ReferenceDescriptor reference : eagerReferences ) { builder.addStatement( "this.$N()", reference.getLinkMethodName() ); } final ExecutableElement postConstruct = getPostConstruct(); if ( null != postConstruct ) { builder.addStatement( "super.$N()", postConstruct.getSimpleName().toString() ); } final CodeBlock.Builder componentEnabledBlock = CodeBlock.builder(); componentEnabledBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", GeneratorUtil.AREZ_CLASSNAME ); componentEnabledBlock.addStatement( "this.$N.complete()", GeneratorUtil.COMPONENT_FIELD_NAME ); componentEnabledBlock.endControlFlow(); builder.addCode( componentEnabledBlock.build() ); if ( !_deferSchedule && requiresSchedule() ) { GeneratorUtil.setStateForInvariantChecking( builder, "COMPONENT_COMPLETE" ); builder.addStatement( "$N().triggerScheduler()", getContextMethodName() ); } GeneratorUtil.setStateForInvariantChecking( builder, "COMPONENT_READY" ); return builder.build(); } @Nonnull private List<ObservableDescriptor> getInitializers() { return getObservables() .stream() .filter( ObservableDescriptor::requireInitializer ) .collect( Collectors.toList() ); } private boolean isNameCollision( @Nonnull final ExecutableElement constructor, @Nonnull final List<ObservableDescriptor> initializers, @Nonnull final String name ) { return constructor.getParameters().stream().anyMatch( p -> p.getSimpleName().toString().equals( name ) ) || initializers.stream().anyMatch( o -> o.getName().equals( name ) ); } boolean shouldGenerateComponentDaggerModule() { return _dagger; } @Nonnull TypeSpec buildComponentDaggerModule() throws ArezProcessorException { assert shouldGenerateComponentDaggerModule(); final TypeSpec.Builder builder = TypeSpec.interfaceBuilder( getComponentDaggerModuleName() ). addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) ); addOriginatingTypes( getElement(), builder ); addGeneratedAnnotation( builder ); builder.addAnnotation( GeneratorUtil.DAGGER_MODULE_CLASSNAME ); builder.addModifiers( Modifier.PUBLIC ); final MethodSpec.Builder method = MethodSpec.methodBuilder( "provideComponent" ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addAnnotation( GeneratorUtil.DAGGER_PROVIDES_CLASSNAME ). addModifiers( Modifier.STATIC, Modifier.PUBLIC ). addParameter( ClassName.get( getPackageName(), getArezClassName() ), "component", Modifier.FINAL ). addStatement( "return component" ). returns( ClassName.get( getElement() ) ); if ( null != _scopeAnnotation ) { final DeclaredType annotationType = _scopeAnnotation.getAnnotationType(); final TypeElement typeElement = (TypeElement) annotationType.asElement(); method.addAnnotation( ClassName.get( typeElement ) ); } builder.addMethod( method.build() ); return builder.build(); } boolean hasRepository() { return null != _repositoryExtensions; } @SuppressWarnings( "ConstantConditions" ) void configureRepository( @Nonnull final String name, @Nonnull final List<TypeElement> extensions, @Nonnull final String repositoryInjectConfig, @Nonnull final String repositoryDaggerConfig ) { assert null != name; assert null != extensions; _repositoryInjectConfig = repositoryInjectConfig; _repositoryDaggerConfig = repositoryDaggerConfig; for ( final TypeElement extension : extensions ) { if ( ElementKind.INTERFACE != extension.getKind() ) { throw new ArezProcessorException( "Class annotated with @Repository defined an extension that is " + "not an interface. Extension: " + extension.getQualifiedName(), getElement() ); } for ( final Element enclosedElement : extension.getEnclosedElements() ) { if ( ElementKind.METHOD == enclosedElement.getKind() ) { final ExecutableElement method = (ExecutableElement) enclosedElement; if ( !method.isDefault() && !( method.getSimpleName().toString().equals( "self" ) && 0 == method.getParameters().size() ) ) { throw new ArezProcessorException( "Class annotated with @Repository defined an extension that has " + "a non default method. Extension: " + extension.getQualifiedName() + " Method: " + method, getElement() ); } } } } _repositoryExtensions = extensions; } /** * Build the enhanced class for the component. */ @Nonnull TypeSpec buildRepository( @Nonnull final Types typeUtils ) throws ArezProcessorException { assert null != _repositoryExtensions; final TypeElement element = getElement(); final ClassName arezType = ClassName.get( getPackageName(), getArezClassName() ); final TypeSpec.Builder builder = TypeSpec.classBuilder( getRepositoryName() ). addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) ); addOriginatingTypes( element, builder ); addGeneratedAnnotation( builder ); final boolean addSingletonAnnotation = "ENABLE".equals( _repositoryInjectConfig ) || ( "AUTODETECT".equals( _repositoryInjectConfig ) && _injectClassesPresent ); final AnnotationSpec.Builder arezComponent = AnnotationSpec.builder( ClassName.bestGuess( Constants.COMPONENT_ANNOTATION_CLASSNAME ) ); if ( !addSingletonAnnotation ) { arezComponent.addMember( "nameIncludesId", "false" ); } if ( !"AUTODETECT".equals( _repositoryInjectConfig ) ) { arezComponent.addMember( "inject", "$T.$N", GeneratorUtil.INJECTIBLE_CLASSNAME, _repositoryInjectConfig ); } if ( !"AUTODETECT".equals( _repositoryDaggerConfig ) ) { arezComponent.addMember( "dagger", "$T.$N", GeneratorUtil.INJECTIBLE_CLASSNAME, _repositoryDaggerConfig ); } builder.addAnnotation( arezComponent.build() ); if ( addSingletonAnnotation ) { builder.addAnnotation( GeneratorUtil.SINGLETON_CLASSNAME ); } builder.superclass( ParameterizedTypeName.get( GeneratorUtil.ABSTRACT_REPOSITORY_CLASSNAME, getIdType().box(), ClassName.get( element ), ClassName.get( getPackageName(), getRepositoryName() ) ) ); _repositoryExtensions.forEach( e -> builder.addSuperinterface( TypeName.get( e.asType() ) ) ); ProcessorUtil.copyAccessModifiers( element, builder ); builder.addModifiers( Modifier.ABSTRACT ); //Add the default access, no-args constructor builder.addMethod( MethodSpec.constructorBuilder().build() ); // Add the factory method builder.addMethod( buildFactoryMethod() ); if ( shouldRepositoryDefineCreate() ) { for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( element ) ) { final ExecutableType methodType = (ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), constructor ); builder.addMethod( buildRepositoryCreate( constructor, methodType, arezType ) ); } } if ( shouldRepositoryDefineAttach() ) { builder.addMethod( buildRepositoryAttach() ); } if ( null != _componentId ) { builder.addMethod( buildFindByIdMethod() ); builder.addMethod( buildGetByIdMethod() ); } if ( shouldRepositoryDefineDestroy() ) { builder.addMethod( buildRepositoryDestroy() ); } if ( shouldRepositoryDefineDetach() ) { builder.addMethod( buildRepositoryDetach() ); } return builder.build(); } private void addOriginatingTypes( @Nonnull final TypeElement element, @Nonnull final TypeSpec.Builder builder ) { builder.addOriginatingElement( element ); ProcessorUtil.getSuperTypes( element ).forEach( builder::addOriginatingElement ); } @Nonnull private String getArezClassName() { return getNestedClassPrefix() + "Arez_" + getElement().getSimpleName(); } @Nonnull private String getComponentDaggerModuleName() { return getNestedClassPrefix() + getElement().getSimpleName() + "DaggerModule"; } @Nonnull private String getArezRepositoryName() { return "Arez_" + getNestedClassPrefix() + getElement().getSimpleName() + "Repository"; } @Nonnull private String getRepositoryName() { return getNestedClassPrefix() + getElement().getSimpleName() + "Repository"; } @Nonnull private MethodSpec buildRepositoryAttach() { final TypeName entityType = TypeName.get( getElement().asType() ); final MethodSpec.Builder method = MethodSpec.methodBuilder( "attach" ). addAnnotation( Override.class ). addAnnotation( AnnotationSpec.builder( GeneratorUtil.ACTION_CLASSNAME ) .addMember( "reportParameters", "false" ) .build() ). addParameter( ParameterSpec.builder( entityType, "entity", Modifier.FINAL ) .addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ) .build() ). addStatement( "super.attach( entity )" ); ProcessorUtil.copyAccessModifiers( getElement(), method ); return method.build(); } @Nonnull private MethodSpec buildRepositoryDetach() { final TypeName entityType = TypeName.get( getElement().asType() ); final MethodSpec.Builder method = MethodSpec.methodBuilder( "detach" ). addAnnotation( Override.class ). addAnnotation( AnnotationSpec.builder( GeneratorUtil.ACTION_CLASSNAME ) .addMember( "reportParameters", "false" ) .build() ). addParameter( ParameterSpec.builder( entityType, "entity", Modifier.FINAL ) .addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ) .build() ). addStatement( "super.detach( entity )" ); ProcessorUtil.copyAccessModifiers( getElement(), method ); return method.build(); } @Nonnull private MethodSpec buildRepositoryDestroy() { final TypeName entityType = TypeName.get( getElement().asType() ); final MethodSpec.Builder method = MethodSpec.methodBuilder( "destroy" ). addAnnotation( Override.class ). addAnnotation( AnnotationSpec.builder( GeneratorUtil.ACTION_CLASSNAME ) .addMember( "reportParameters", "false" ) .build() ). addParameter( ParameterSpec.builder( entityType, "entity", Modifier.FINAL ) .addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ) .build() ). addStatement( "super.destroy( entity )" ); ProcessorUtil.copyAccessModifiers( getElement(), method ); final Set<Modifier> modifiers = getElement().getModifiers(); if ( !modifiers.contains( Modifier.PUBLIC ) && !modifiers.contains( Modifier.PROTECTED ) ) { /* * The destroy method inherited from AbstractContainer is protected and the override * must be at least the same access level. */ method.addModifiers( Modifier.PROTECTED ); } return method.build(); } @Nonnull private MethodSpec buildFindByIdMethod() { assert null != _componentId; final MethodSpec.Builder method = MethodSpec.methodBuilder( "findBy" + getIdName() ). addModifiers( Modifier.FINAL ). addParameter( ParameterSpec.builder( getIdType(), "id", Modifier.FINAL ).build() ). addAnnotation( GeneratorUtil.NULLABLE_CLASSNAME ). returns( TypeName.get( getElement().asType() ) ). addStatement( "return findByArezId( id )" ); ProcessorUtil.copyAccessModifiers( getElement(), method ); return method.build(); } @Nonnull private MethodSpec buildGetByIdMethod() { final TypeName entityType = TypeName.get( getElement().asType() ); final MethodSpec.Builder method = MethodSpec.methodBuilder( "getBy" + getIdName() ). addModifiers( Modifier.FINAL ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). addParameter( ParameterSpec.builder( getIdType(), "id", Modifier.FINAL ).build() ). returns( entityType ). addStatement( "return getByArezId( id )" ); ProcessorUtil.copyAccessModifiers( getElement(), method ); return method.build(); } @Nonnull private MethodSpec buildFactoryMethod() { final MethodSpec.Builder method = MethodSpec.methodBuilder( "newRepository" ). addModifiers( Modifier.STATIC ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). returns( ClassName.get( getPackageName(), getRepositoryName() ) ). addStatement( "return new $T()", ClassName.get( getPackageName(), getArezRepositoryName() ) ); ProcessorUtil.copyAccessModifiers( getElement(), method ); return method.build(); } @Nonnull private MethodSpec buildRepositoryCreate( @Nonnull final ExecutableElement constructor, @Nonnull final ExecutableType methodType, @Nonnull final ClassName arezType ) { final String suffix = constructor.getParameters().stream(). map( p -> p.getSimpleName().toString() ).collect( Collectors.joining( "_" ) ); final String actionName = "create" + ( suffix.isEmpty() ? "" : "_" + suffix ); final AnnotationSpec annotationSpec = AnnotationSpec.builder( ClassName.bestGuess( Constants.ACTION_ANNOTATION_CLASSNAME ) ). addMember( "name", "$S", actionName ).build(); final MethodSpec.Builder builder = MethodSpec.methodBuilder( "create" ). addAnnotation( annotationSpec ). addAnnotation( GeneratorUtil.NONNULL_CLASSNAME ). returns( TypeName.get( asDeclaredType() ) ); ProcessorUtil.copyAccessModifiers( getElement(), builder ); ProcessorUtil.copyExceptions( methodType, builder ); ProcessorUtil.copyTypeParameters( methodType, builder ); final StringBuilder newCall = new StringBuilder(); newCall.append( "final $T entity = new $T(" ); final ArrayList<Object> parameters = new ArrayList<>(); parameters.add( arezType ); parameters.add( arezType ); boolean firstParam = true; for ( final VariableElement element : constructor.getParameters() ) { final ParameterSpec.Builder param = ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL ); ProcessorUtil.copyWhitelistedAnnotations( element, param ); builder.addParameter( param.build() ); parameters.add( element.getSimpleName().toString() ); if ( !firstParam ) { newCall.append( "," ); } firstParam = false; newCall.append( "$N" ); } for ( final ObservableDescriptor observable : getInitializers() ) { final String candidateName = observable.getName(); final String name = isNameCollision( constructor, Collections.emptyList(), candidateName ) ? GeneratorUtil.INITIALIZER_PREFIX + candidateName : candidateName; final ParameterSpec.Builder param = ParameterSpec.builder( TypeName.get( observable.getGetterType().getReturnType() ), name, Modifier.FINAL ); ProcessorUtil.copyWhitelistedAnnotations( observable.getGetter(), param ); builder.addParameter( param.build() ); parameters.add( name ); if ( !firstParam ) { newCall.append( "," ); } firstParam = false; newCall.append( "$N" ); } newCall.append( ")" ); builder.addStatement( newCall.toString(), parameters.toArray() ); builder.addStatement( "attach( entity )" ); builder.addStatement( "return entity" ); return builder.build(); } @Nonnull String getPackageName() { return _packageElement.getQualifiedName().toString(); } @Nonnull private String getIdMethodName() { /* * Note that it is a deliberate choice to not use getArezId() as that will box Id which for the * "normal" case involves converting a long to a Long and it was decided that the slight increase in * code size was worth the slightly reduced memory pressure. */ return null != _componentId ? _componentId.getSimpleName().toString() : GeneratorUtil.ID_FIELD_NAME; } @Nonnull private String getIdName() { assert null != _componentId; final String name = ProcessorUtil.deriveName( _componentId, GETTER_PATTERN, ProcessorUtil.SENTINEL_NAME ); if ( null != name ) { return Character.toUpperCase( name.charAt( 0 ) ) + ( name.length() > 1 ? name.substring( 1 ) : "" ); } else { return "Id"; } } @Nonnull private TypeName getIdType() { return null == _componentIdMethodType ? GeneratorUtil.DEFAULT_ID_TYPE : TypeName.get( _componentIdMethodType.getReturnType() ); } private <T> T getAnnotationParameter( @Nonnull final AnnotationMirror annotation, @Nonnull final String parameterName ) { return ProcessorUtil.getAnnotationValue( _elements, annotation, parameterName ); } private void addGeneratedAnnotation( @Nonnull final TypeSpec.Builder builder ) { GeneratedAnnotationSpecs .generatedAnnotationSpec( _elements, _sourceVersion, ArezProcessor.class ) .ifPresent( builder::addAnnotation ); } private boolean shouldRepositoryDefineCreate() { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, getElement(), Constants.REPOSITORY_ANNOTATION_CLASSNAME, "attach" ).getValue(); switch ( injectParameter.getSimpleName().toString() ) { case "CREATE_ONLY": case "CREATE_OR_ATTACH": return true; default: return false; } } private boolean shouldRepositoryDefineAttach() { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, getElement(), Constants.REPOSITORY_ANNOTATION_CLASSNAME, "attach" ).getValue(); switch ( injectParameter.getSimpleName().toString() ) { case "ATTACH_ONLY": case "CREATE_OR_ATTACH": return true; default: return false; } } private boolean shouldRepositoryDefineDestroy() { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, getElement(), Constants.REPOSITORY_ANNOTATION_CLASSNAME, "detach" ).getValue(); switch ( injectParameter.getSimpleName().toString() ) { case "DESTROY_ONLY": case "DESTROY_OR_DETACH": return true; default: return false; } } private boolean shouldRepositoryDefineDetach() { final VariableElement injectParameter = (VariableElement) ProcessorUtil.getAnnotationValue( _elements, getElement(), Constants.REPOSITORY_ANNOTATION_CLASSNAME, "detach" ).getValue(); switch ( injectParameter.getSimpleName().toString() ) { case "DETACH_ONLY": case "DESTROY_OR_DETACH": return true; default: return false; } } }
Whitespace
processor/src/main/java/arez/processor/ComponentDescriptor.java
Whitespace
<ide><path>rocessor/src/main/java/arez/processor/ComponentDescriptor.java <ide> <ide> if ( !_allowEmpty && hasReactiveElements ) <ide> { <del> throw new ArezProcessorException( "@ArezComponent target has no methods annotated with @Action, " + <del> "@Computed, @Memoize, @Observable, @Inverse, @Reference, @Dependency, @Track or @Autorun", <add> throw new ArezProcessorException( "@ArezComponent target has no methods annotated with @Action, @Computed, " + <add> "@Memoize, @Observable, @Inverse, @Reference, @Dependency, @Track or @Autorun", <ide> _element ); <ide> } <ide> else if ( _allowEmpty && !hasReactiveElements ) <ide> { <del> throw new ArezProcessorException( "@ArezComponent target has specified allowEmpty = true but has methods annotated with @Action, " + <del> "@Computed, @Memoize, @Observable, @Inverse, @Reference, @Dependency, @Track or @Autorun", <del> _element ); <add> throw new ArezProcessorException( "@ArezComponent target has specified allowEmpty = true but has methods " + <add> "annotated with @Action, @Computed, @Memoize, @Observable, @Inverse, " + <add> "@Reference, @Dependency, @Track or @Autorun", _element ); <ide> } <ide> <ide> if ( _deferSchedule && !requiresSchedule() )
Java
apache-2.0
ade90b458c8b883a8beee992119b88c8435441bd
0
blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,gradle/gradle
/* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.tasks.compile; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.gradle.api.InvalidUserDataException; import org.gradle.api.JavaVersion; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.FileCollection; import org.gradle.api.file.FileTree; import org.gradle.api.file.ProjectLayout; import org.gradle.api.internal.FeaturePreviews; import org.gradle.api.internal.file.FileOperations; import org.gradle.api.internal.file.FileTreeInternal; import org.gradle.api.internal.file.temp.TemporaryFileProvider; import org.gradle.api.internal.tasks.compile.CleaningJavaCompiler; import org.gradle.api.internal.tasks.compile.CompilationSourceDirs; import org.gradle.api.internal.tasks.compile.CompilerForkUtils; import org.gradle.api.internal.tasks.compile.DefaultGroovyJavaJointCompileSpec; import org.gradle.api.internal.tasks.compile.DefaultGroovyJavaJointCompileSpecFactory; import org.gradle.api.internal.tasks.compile.GroovyCompilerFactory; import org.gradle.api.internal.tasks.compile.GroovyJavaJointCompileSpec; import org.gradle.api.internal.tasks.compile.HasCompileOptions; import org.gradle.api.internal.tasks.compile.MinimalGroovyCompileOptions; import org.gradle.api.internal.tasks.compile.MinimalJavaCompilerDaemonForkOptions; import org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilerFactory; import org.gradle.api.internal.tasks.compile.incremental.recomp.GroovyRecompilationSpecProvider; import org.gradle.api.internal.tasks.compile.incremental.recomp.RecompilationSpecProvider; import org.gradle.api.model.ObjectFactory; import org.gradle.api.model.ReplacedBy; import org.gradle.api.provider.Property; import org.gradle.api.tasks.CacheableTask; import org.gradle.api.tasks.Classpath; import org.gradle.api.tasks.CompileClasspath; import org.gradle.api.tasks.IgnoreEmptyDirectories; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.Nested; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.PathSensitivity; import org.gradle.api.tasks.SkipWhenEmpty; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.WorkResult; import org.gradle.internal.file.Deleter; import org.gradle.internal.jvm.Jvm; import org.gradle.internal.jvm.inspection.JvmMetadataDetector; import org.gradle.jvm.toolchain.JavaInstallationMetadata; import org.gradle.jvm.toolchain.JavaLauncher; import org.gradle.language.base.internal.compile.Compiler; import org.gradle.util.internal.GFileUtils; import org.gradle.util.internal.IncubationLogger; import org.gradle.work.Incremental; import org.gradle.work.InputChanges; import javax.annotation.Nullable; import javax.inject.Inject; import java.io.File; import java.util.List; import java.util.concurrent.Callable; import static com.google.common.base.Preconditions.checkState; import static org.gradle.api.internal.FeaturePreviews.Feature.GROOVY_COMPILATION_AVOIDANCE; /** * Compiles Groovy source files, and optionally, Java source files. */ @CacheableTask public class GroovyCompile extends AbstractCompile implements HasCompileOptions { private FileCollection groovyClasspath; private final ConfigurableFileCollection astTransformationClasspath; private final CompileOptions compileOptions; private final GroovyCompileOptions groovyCompileOptions = new GroovyCompileOptions(); private final FileCollection stableSources = getProject().files((Callable<FileTree>) this::getSource); private final Property<JavaLauncher> javaLauncher; private File previousCompilationDataFile; public GroovyCompile() { ObjectFactory objectFactory = getObjectFactory(); CompileOptions compileOptions = objectFactory.newInstance(CompileOptions.class); compileOptions.setIncremental(false); this.compileOptions = compileOptions; this.javaLauncher = objectFactory.property(JavaLauncher.class); this.astTransformationClasspath = objectFactory.fileCollection(); if (!experimentalCompilationAvoidanceEnabled()) { this.astTransformationClasspath.from((Callable<FileCollection>) this::getClasspath); } CompilerForkUtils.doNotCacheIfForkingViaExecutable(compileOptions, getOutputs()); } @Override @CompileClasspath @Incremental public FileCollection getClasspath() { // Note that @CompileClasspath here is an approximation and must be fixed before de-incubating getAstTransformationClasspath() // See https://github.com/gradle/gradle/pull/9513 return super.getClasspath(); } /** * The classpath containing AST transformations and their dependencies. * * @since 5.6 */ @Classpath public ConfigurableFileCollection getAstTransformationClasspath() { return astTransformationClasspath; } private boolean experimentalCompilationAvoidanceEnabled() { return getFeaturePreviews().isFeatureEnabled(GROOVY_COMPILATION_AVOIDANCE); } @TaskAction protected void compile(InputChanges inputChanges) { checkGroovyClasspathIsNonEmpty(); warnIfCompileAvoidanceEnabled(); GroovyJavaJointCompileSpec spec = createSpec(); WorkResult result = getCompiler(spec, inputChanges).execute(spec); setDidWork(result.getDidWork()); } /** * The previous compilation analysis. Internal use only. * * @since 7.1 */ @OutputFile protected File getPreviousCompilationData() { if (previousCompilationDataFile == null) { previousCompilationDataFile = new File(getTemporaryDirWithoutCreating(), "previous-compilation-data.bin"); } return previousCompilationDataFile; } private void warnIfCompileAvoidanceEnabled() { if (experimentalCompilationAvoidanceEnabled()) { IncubationLogger.incubatingFeatureUsed("Groovy compilation avoidance"); } } private Compiler<GroovyJavaJointCompileSpec> getCompiler(GroovyJavaJointCompileSpec spec, InputChanges inputChanges) { GroovyCompilerFactory groovyCompilerFactory = getGroovyCompilerFactory(); Compiler<GroovyJavaJointCompileSpec> delegatingCompiler = groovyCompilerFactory.newCompiler(spec); CleaningJavaCompiler<GroovyJavaJointCompileSpec> cleaningGroovyCompiler = new CleaningJavaCompiler<>(delegatingCompiler, getOutputs(), getDeleter()); if (spec.incrementalCompilationEnabled()) { IncrementalCompilerFactory factory = getIncrementalCompilerFactory(); return factory.makeIncremental( cleaningGroovyCompiler, getStableSources().getAsFileTree(), createRecompilationSpecProvider(inputChanges) ); } else { return cleaningGroovyCompiler; } } @Inject protected GroovyCompilerFactory getGroovyCompilerFactory() { throw new UnsupportedOperationException(); } private RecompilationSpecProvider createRecompilationSpecProvider(InputChanges inputChanges) { FileCollection stableSources = getStableSources(); return new GroovyRecompilationSpecProvider( getDeleter(), getServices().get(FileOperations.class), stableSources.getAsFileTree(), inputChanges.isIncremental(), () -> inputChanges.getFileChanges(stableSources).iterator() ); } /** * The sources for incremental change detection. * * @since 5.6 */ @SkipWhenEmpty @IgnoreEmptyDirectories @PathSensitive(PathSensitivity.RELATIVE) // Java source files are supported, too. Therefore we should care about the relative path. @InputFiles protected FileCollection getStableSources() { return stableSources; } /** * Injects and returns an instance of {@link IncrementalCompilerFactory}. * * @since 5.6 */ @Inject protected IncrementalCompilerFactory getIncrementalCompilerFactory() { throw new UnsupportedOperationException(); } @Inject protected Deleter getDeleter() { throw new UnsupportedOperationException("Decorator takes care of injection"); } @Inject protected ProjectLayout getProjectLayout() { throw new UnsupportedOperationException(); } @Inject protected ObjectFactory getObjectFactory() { throw new UnsupportedOperationException(); } private FileCollection determineGroovyCompileClasspath() { if (experimentalCompilationAvoidanceEnabled()) { return astTransformationClasspath.plus(getClasspath()); } else { return getClasspath(); } } private static void validateIncrementalCompilationOptions(List<File> sourceRoots, boolean annotationProcessingConfigured) { if (sourceRoots.isEmpty()) { throw new InvalidUserDataException("Unable to infer source roots. Incremental Groovy compilation requires the source roots. Change the configuration of your sources or disable incremental Groovy compilation."); } if (annotationProcessingConfigured) { throw new InvalidUserDataException("Enabling incremental compilation and configuring Java annotation processors for Groovy compilation is not allowed. Disable incremental Groovy compilation or remove the Java annotation processor configuration."); } } @Nullable private JavaInstallationMetadata getToolchain() { return javaLauncher.map(JavaLauncher::getMetadata).getOrNull(); } private GroovyJavaJointCompileSpec createSpec() { validateConfiguration(); DefaultGroovyJavaJointCompileSpec spec = new DefaultGroovyJavaJointCompileSpecFactory(compileOptions, getToolchain()).create(); assert spec != null; FileTreeInternal stableSourcesAsFileTree = (FileTreeInternal) getStableSources().getAsFileTree(); List<File> sourceRoots = CompilationSourceDirs.inferSourceRoots(stableSourcesAsFileTree); spec.setSourcesRoots(sourceRoots); spec.setSourceFiles(stableSourcesAsFileTree); spec.setDestinationDir(getDestinationDirectory().getAsFile().get()); spec.setWorkingDir(getProjectLayout().getProjectDirectory().getAsFile()); spec.setTempDir(getTemporaryDir()); spec.setCompileClasspath(ImmutableList.copyOf(determineGroovyCompileClasspath())); configureCompatibilityOptions(spec); spec.setAnnotationProcessorPath(Lists.newArrayList(compileOptions.getAnnotationProcessorPath() == null ? getProjectLayout().files() : compileOptions.getAnnotationProcessorPath())); spec.setGroovyClasspath(Lists.newArrayList(getGroovyClasspath())); spec.setCompileOptions(compileOptions); spec.setGroovyCompileOptions(new MinimalGroovyCompileOptions(groovyCompileOptions)); spec.getCompileOptions().setSupportsCompilerApi(true); if (getOptions().isIncremental()) { validateIncrementalCompilationOptions(sourceRoots, spec.annotationProcessingConfigured()); spec.getCompileOptions().setPreviousCompilationDataFile(getPreviousCompilationData()); } if (spec.getGroovyCompileOptions().getStubDir() == null) { File dir = new File(getTemporaryDir(), "groovy-java-stubs"); GFileUtils.mkdirs(dir); spec.getGroovyCompileOptions().setStubDir(dir); } configureExecutable(spec.getCompileOptions().getForkOptions()); return spec; } private void configureCompatibilityOptions(DefaultGroovyJavaJointCompileSpec spec) { JavaInstallationMetadata toolchain = getToolchain(); if (toolchain != null) { boolean isSourceOrTargetConfigured = false; if (super.getSourceCompatibility() != null) { spec.setSourceCompatibility(getSourceCompatibility()); isSourceOrTargetConfigured = true; } if (super.getTargetCompatibility() != null) { spec.setTargetCompatibility(getTargetCompatibility()); isSourceOrTargetConfigured = true; } if (!isSourceOrTargetConfigured) { String languageVersion = toolchain.getLanguageVersion().toString(); spec.setSourceCompatibility(languageVersion); spec.setTargetCompatibility(languageVersion); } } else { spec.setSourceCompatibility(getSourceCompatibility()); spec.setTargetCompatibility(getTargetCompatibility()); } } private void configureExecutable(MinimalJavaCompilerDaemonForkOptions forkOptions) { if (javaLauncher.isPresent()) { forkOptions.setExecutable(javaLauncher.get().getExecutablePath().getAsFile().getAbsolutePath()); } else { forkOptions.setExecutable(Jvm.current().getJavaExecutable().getAbsolutePath()); } } private void validateConfiguration() { if (javaLauncher.isPresent()) { checkState(getOptions().getForkOptions().getJavaHome() == null, "Must not use `javaHome` property on `ForkOptions` together with `javaLauncher` property"); checkState(getOptions().getForkOptions().getExecutable() == null, "Must not use `executable` property on `ForkOptions` together with `javaLauncher` property"); } } private void checkGroovyClasspathIsNonEmpty() { if (getGroovyClasspath().isEmpty()) { throw new InvalidUserDataException("'" + getName() + ".groovyClasspath' must not be empty. If a Groovy compile dependency is provided, " + "the 'groovy-base' plugin will attempt to configure 'groovyClasspath' automatically. Alternatively, you may configure 'groovyClasspath' explicitly."); } } /** * We need to track the Java version of the JVM the Groovy compiler is running on, since the Groovy compiler produces different results depending on it. * * This should be replaced by a property on the Groovy toolchain as soon as we model these. * * @since 4.0 */ @Input protected String getGroovyCompilerJvmVersion() { if (javaLauncher.isPresent()) { return javaLauncher.get().getMetadata().getLanguageVersion().toString(); } final File customHome = getOptions().getForkOptions().getJavaHome(); if (customHome != null) { return getServices().get(JvmMetadataDetector.class).getMetadata(customHome).getLanguageVersion().getMajorVersion(); } return JavaVersion.current().getMajorVersion(); } /** * {@inheritDoc} */ @Override @ReplacedBy("stableSources") public FileTree getSource() { return super.getSource(); } /** * Gets the options for the Groovy compilation. To set specific options for the nested Java compilation, use {@link * #getOptions()}. * * @return The Groovy compile options. Never returns null. */ @Nested public GroovyCompileOptions getGroovyOptions() { return groovyCompileOptions; } /** * Returns the options for Java compilation. * * @return The Java compile options. Never returns null. */ @Nested public CompileOptions getOptions() { return compileOptions; } /** * Returns the classpath containing the version of Groovy to use for compilation. * * @return The classpath. */ @Classpath public FileCollection getGroovyClasspath() { return groovyClasspath; } /** * Sets the classpath containing the version of Groovy to use for compilation. * * @param groovyClasspath The classpath. Must not be null. */ public void setGroovyClasspath(FileCollection groovyClasspath) { this.groovyClasspath = groovyClasspath; } /** * The toolchain {@link JavaLauncher} to use for executing the Groovy compiler. * * @return the java launcher property * @since 6.8 */ @Nested @Optional public Property<JavaLauncher> getJavaLauncher() { return javaLauncher; } @Inject protected FeaturePreviews getFeaturePreviews() { throw new UnsupportedOperationException(); } private File getTemporaryDirWithoutCreating() { // Do not create the temporary folder, since that causes problems. return getServices().get(TemporaryFileProvider.class).newTemporaryFile(getName()); } }
subprojects/language-groovy/src/main/java/org/gradle/api/tasks/compile/GroovyCompile.java
/* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.tasks.compile; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.gradle.api.InvalidUserDataException; import org.gradle.api.JavaVersion; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.FileCollection; import org.gradle.api.file.FileTree; import org.gradle.api.file.ProjectLayout; import org.gradle.api.internal.FeaturePreviews; import org.gradle.api.internal.file.FileOperations; import org.gradle.api.internal.file.FileTreeInternal; import org.gradle.api.internal.file.temp.TemporaryFileProvider; import org.gradle.api.internal.tasks.compile.CleaningJavaCompiler; import org.gradle.api.internal.tasks.compile.CompilationSourceDirs; import org.gradle.api.internal.tasks.compile.CompilerForkUtils; import org.gradle.api.internal.tasks.compile.DefaultGroovyJavaJointCompileSpec; import org.gradle.api.internal.tasks.compile.DefaultGroovyJavaJointCompileSpecFactory; import org.gradle.api.internal.tasks.compile.GroovyCompilerFactory; import org.gradle.api.internal.tasks.compile.GroovyJavaJointCompileSpec; import org.gradle.api.internal.tasks.compile.HasCompileOptions; import org.gradle.api.internal.tasks.compile.MinimalGroovyCompileOptions; import org.gradle.api.internal.tasks.compile.MinimalJavaCompilerDaemonForkOptions; import org.gradle.api.internal.tasks.compile.incremental.IncrementalCompilerFactory; import org.gradle.api.internal.tasks.compile.incremental.recomp.GroovyRecompilationSpecProvider; import org.gradle.api.internal.tasks.compile.incremental.recomp.RecompilationSpecProvider; import org.gradle.api.model.ObjectFactory; import org.gradle.api.model.ReplacedBy; import org.gradle.api.provider.Property; import org.gradle.api.tasks.CacheableTask; import org.gradle.api.tasks.Classpath; import org.gradle.api.tasks.CompileClasspath; import org.gradle.api.tasks.IgnoreEmptyDirectories; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputFiles; import org.gradle.api.tasks.Nested; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.OutputFile; import org.gradle.api.tasks.PathSensitive; import org.gradle.api.tasks.PathSensitivity; import org.gradle.api.tasks.SkipWhenEmpty; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.WorkResult; import org.gradle.internal.file.Deleter; import org.gradle.internal.jvm.Jvm; import org.gradle.internal.jvm.inspection.JvmMetadataDetector; import org.gradle.jvm.toolchain.JavaInstallationMetadata; import org.gradle.jvm.toolchain.JavaLauncher; import org.gradle.language.base.internal.compile.Compiler; import org.gradle.util.internal.GFileUtils; import org.gradle.util.internal.IncubationLogger; import org.gradle.work.Incremental; import org.gradle.work.InputChanges; import javax.annotation.Nullable; import javax.inject.Inject; import java.io.File; import java.util.List; import java.util.concurrent.Callable; import static com.google.common.base.Preconditions.checkState; import static org.gradle.api.internal.FeaturePreviews.Feature.GROOVY_COMPILATION_AVOIDANCE; /** * Compiles Groovy source files, and optionally, Java source files. */ @CacheableTask public class GroovyCompile extends AbstractCompile implements HasCompileOptions { private FileCollection groovyClasspath; private final ConfigurableFileCollection astTransformationClasspath; private final CompileOptions compileOptions; private final GroovyCompileOptions groovyCompileOptions = new GroovyCompileOptions(); private final FileCollection stableSources = getProject().files((Callable<FileTree>) this::getSource); private final Property<JavaLauncher> javaLauncher; private File previousCompilationDataFile; public GroovyCompile() { ObjectFactory objectFactory = getObjectFactory(); CompileOptions compileOptions = objectFactory.newInstance(CompileOptions.class); compileOptions.setIncremental(false); this.compileOptions = compileOptions; this.astTransformationClasspath = objectFactory.fileCollection(); this.javaLauncher = objectFactory.property(JavaLauncher.class); if (!experimentalCompilationAvoidanceEnabled()) { this.astTransformationClasspath.from((Callable<FileCollection>) this::getClasspath); } CompilerForkUtils.doNotCacheIfForkingViaExecutable(compileOptions, getOutputs()); } @Override @CompileClasspath @Incremental public FileCollection getClasspath() { // Note that @CompileClasspath here is an approximation and must be fixed before de-incubating getAstTransformationClasspath() // See https://github.com/gradle/gradle/pull/9513 return super.getClasspath(); } /** * The classpath containing AST transformations and their dependencies. * * @since 5.6 */ @Classpath public ConfigurableFileCollection getAstTransformationClasspath() { return astTransformationClasspath; } private boolean experimentalCompilationAvoidanceEnabled() { return getFeaturePreviews().isFeatureEnabled(GROOVY_COMPILATION_AVOIDANCE); } @TaskAction protected void compile(InputChanges inputChanges) { checkGroovyClasspathIsNonEmpty(); warnIfCompileAvoidanceEnabled(); GroovyJavaJointCompileSpec spec = createSpec(); WorkResult result = getCompiler(spec, inputChanges).execute(spec); setDidWork(result.getDidWork()); } /** * The previous compilation analysis. Internal use only. * * @since 7.1 */ @OutputFile protected File getPreviousCompilationData() { if (previousCompilationDataFile == null) { previousCompilationDataFile = new File(getTemporaryDirWithoutCreating(), "previous-compilation-data.bin"); } return previousCompilationDataFile; } private void warnIfCompileAvoidanceEnabled() { if (experimentalCompilationAvoidanceEnabled()) { IncubationLogger.incubatingFeatureUsed("Groovy compilation avoidance"); } } private Compiler<GroovyJavaJointCompileSpec> getCompiler(GroovyJavaJointCompileSpec spec, InputChanges inputChanges) { GroovyCompilerFactory groovyCompilerFactory = getGroovyCompilerFactory(); Compiler<GroovyJavaJointCompileSpec> delegatingCompiler = groovyCompilerFactory.newCompiler(spec); CleaningJavaCompiler<GroovyJavaJointCompileSpec> cleaningGroovyCompiler = new CleaningJavaCompiler<>(delegatingCompiler, getOutputs(), getDeleter()); if (spec.incrementalCompilationEnabled()) { IncrementalCompilerFactory factory = getIncrementalCompilerFactory(); return factory.makeIncremental( cleaningGroovyCompiler, getStableSources().getAsFileTree(), createRecompilationSpecProvider(inputChanges) ); } else { return cleaningGroovyCompiler; } } @Inject protected GroovyCompilerFactory getGroovyCompilerFactory() { throw new UnsupportedOperationException(); } private RecompilationSpecProvider createRecompilationSpecProvider(InputChanges inputChanges) { FileCollection stableSources = getStableSources(); return new GroovyRecompilationSpecProvider( getDeleter(), getServices().get(FileOperations.class), stableSources.getAsFileTree(), inputChanges.isIncremental(), () -> inputChanges.getFileChanges(stableSources).iterator() ); } /** * The sources for incremental change detection. * * @since 5.6 */ @SkipWhenEmpty @IgnoreEmptyDirectories @PathSensitive(PathSensitivity.RELATIVE) // Java source files are supported, too. Therefore we should care about the relative path. @InputFiles protected FileCollection getStableSources() { return stableSources; } /** * Injects and returns an instance of {@link IncrementalCompilerFactory}. * * @since 5.6 */ @Inject protected IncrementalCompilerFactory getIncrementalCompilerFactory() { throw new UnsupportedOperationException(); } @Inject protected Deleter getDeleter() { throw new UnsupportedOperationException("Decorator takes care of injection"); } @Inject protected ProjectLayout getProjectLayout() { throw new UnsupportedOperationException(); } @Inject protected ObjectFactory getObjectFactory() { throw new UnsupportedOperationException(); } private FileCollection determineGroovyCompileClasspath() { if (experimentalCompilationAvoidanceEnabled()) { return astTransformationClasspath.plus(getClasspath()); } else { return getClasspath(); } } private static void validateIncrementalCompilationOptions(List<File> sourceRoots, boolean annotationProcessingConfigured) { if (sourceRoots.isEmpty()) { throw new InvalidUserDataException("Unable to infer source roots. Incremental Groovy compilation requires the source roots. Change the configuration of your sources or disable incremental Groovy compilation."); } if (annotationProcessingConfigured) { throw new InvalidUserDataException("Enabling incremental compilation and configuring Java annotation processors for Groovy compilation is not allowed. Disable incremental Groovy compilation or remove the Java annotation processor configuration."); } } @Nullable private JavaInstallationMetadata getToolchain() { return javaLauncher.map(JavaLauncher::getMetadata).getOrNull(); } private GroovyJavaJointCompileSpec createSpec() { validateConfiguration(); DefaultGroovyJavaJointCompileSpec spec = new DefaultGroovyJavaJointCompileSpecFactory(compileOptions, getToolchain()).create(); assert spec != null; FileTreeInternal stableSourcesAsFileTree = (FileTreeInternal) getStableSources().getAsFileTree(); List<File> sourceRoots = CompilationSourceDirs.inferSourceRoots(stableSourcesAsFileTree); spec.setSourcesRoots(sourceRoots); spec.setSourceFiles(stableSourcesAsFileTree); spec.setDestinationDir(getDestinationDirectory().getAsFile().get()); spec.setWorkingDir(getProjectLayout().getProjectDirectory().getAsFile()); spec.setTempDir(getTemporaryDir()); spec.setCompileClasspath(ImmutableList.copyOf(determineGroovyCompileClasspath())); configureCompatibilityOptions(spec); spec.setAnnotationProcessorPath(Lists.newArrayList(compileOptions.getAnnotationProcessorPath() == null ? getProjectLayout().files() : compileOptions.getAnnotationProcessorPath())); spec.setGroovyClasspath(Lists.newArrayList(getGroovyClasspath())); spec.setCompileOptions(compileOptions); spec.setGroovyCompileOptions(new MinimalGroovyCompileOptions(groovyCompileOptions)); spec.getCompileOptions().setSupportsCompilerApi(true); if (getOptions().isIncremental()) { validateIncrementalCompilationOptions(sourceRoots, spec.annotationProcessingConfigured()); spec.getCompileOptions().setPreviousCompilationDataFile(getPreviousCompilationData()); } if (spec.getGroovyCompileOptions().getStubDir() == null) { File dir = new File(getTemporaryDir(), "groovy-java-stubs"); GFileUtils.mkdirs(dir); spec.getGroovyCompileOptions().setStubDir(dir); } configureExecutable(spec.getCompileOptions().getForkOptions()); return spec; } private void configureCompatibilityOptions(DefaultGroovyJavaJointCompileSpec spec) { JavaInstallationMetadata toolchain = getToolchain(); if (toolchain != null) { boolean isSourceOrTargetConfigured = false; if (super.getSourceCompatibility() != null) { spec.setSourceCompatibility(getSourceCompatibility()); isSourceOrTargetConfigured = true; } if (super.getTargetCompatibility() != null) { spec.setTargetCompatibility(getTargetCompatibility()); isSourceOrTargetConfigured = true; } if (!isSourceOrTargetConfigured) { String languageVersion = toolchain.getLanguageVersion().toString(); spec.setSourceCompatibility(languageVersion); spec.setTargetCompatibility(languageVersion); } } else { spec.setSourceCompatibility(getSourceCompatibility()); spec.setTargetCompatibility(getTargetCompatibility()); } } private void configureExecutable(MinimalJavaCompilerDaemonForkOptions forkOptions) { if (javaLauncher.isPresent()) { forkOptions.setExecutable(javaLauncher.get().getExecutablePath().getAsFile().getAbsolutePath()); } else { forkOptions.setExecutable(Jvm.current().getJavaExecutable().getAbsolutePath()); } } private void validateConfiguration() { if (javaLauncher.isPresent()) { checkState(getOptions().getForkOptions().getJavaHome() == null, "Must not use `javaHome` property on `ForkOptions` together with `javaLauncher` property"); checkState(getOptions().getForkOptions().getExecutable() == null, "Must not use `executable` property on `ForkOptions` together with `javaLauncher` property"); } } private void checkGroovyClasspathIsNonEmpty() { if (getGroovyClasspath().isEmpty()) { throw new InvalidUserDataException("'" + getName() + ".groovyClasspath' must not be empty. If a Groovy compile dependency is provided, " + "the 'groovy-base' plugin will attempt to configure 'groovyClasspath' automatically. Alternatively, you may configure 'groovyClasspath' explicitly."); } } /** * We need to track the Java version of the JVM the Groovy compiler is running on, since the Groovy compiler produces different results depending on it. * * This should be replaced by a property on the Groovy toolchain as soon as we model these. * * @since 4.0 */ @Input protected String getGroovyCompilerJvmVersion() { if (javaLauncher.isPresent()) { return javaLauncher.get().getMetadata().getLanguageVersion().toString(); } final File customHome = getOptions().getForkOptions().getJavaHome(); if(customHome != null) { return getServices().get(JvmMetadataDetector.class).getMetadata(customHome).getLanguageVersion().getMajorVersion(); } return JavaVersion.current().getMajorVersion(); } /** * {@inheritDoc} */ @Override @ReplacedBy("stableSources") public FileTree getSource() { return super.getSource(); } /** * Gets the options for the Groovy compilation. To set specific options for the nested Java compilation, use {@link * #getOptions()}. * * @return The Groovy compile options. Never returns null. */ @Nested public GroovyCompileOptions getGroovyOptions() { return groovyCompileOptions; } /** * Returns the options for Java compilation. * * @return The Java compile options. Never returns null. */ @Nested public CompileOptions getOptions() { return compileOptions; } /** * Returns the classpath containing the version of Groovy to use for compilation. * * @return The classpath. */ @Classpath public FileCollection getGroovyClasspath() { return groovyClasspath; } /** * Sets the classpath containing the version of Groovy to use for compilation. * * @param groovyClasspath The classpath. Must not be null. */ public void setGroovyClasspath(FileCollection groovyClasspath) { this.groovyClasspath = groovyClasspath; } /** * The toolchain {@link JavaLauncher} to use for executing the Groovy compiler. * * @return the java launcher property * @since 6.8 */ @Nested @Optional public Property<JavaLauncher> getJavaLauncher() { return javaLauncher; } @Inject protected FeaturePreviews getFeaturePreviews() { throw new UnsupportedOperationException(); } private File getTemporaryDirWithoutCreating() { // Do not create the temporary folder, since that causes problems. return getServices().get(TemporaryFileProvider.class).newTemporaryFile(getName()); } }
Format `GroovyCompile`
subprojects/language-groovy/src/main/java/org/gradle/api/tasks/compile/GroovyCompile.java
Format `GroovyCompile`
<ide><path>ubprojects/language-groovy/src/main/java/org/gradle/api/tasks/compile/GroovyCompile.java <ide> CompileOptions compileOptions = objectFactory.newInstance(CompileOptions.class); <ide> compileOptions.setIncremental(false); <ide> this.compileOptions = compileOptions; <add> this.javaLauncher = objectFactory.property(JavaLauncher.class); <ide> this.astTransformationClasspath = objectFactory.fileCollection(); <del> this.javaLauncher = objectFactory.property(JavaLauncher.class); <ide> if (!experimentalCompilationAvoidanceEnabled()) { <ide> this.astTransformationClasspath.from((Callable<FileCollection>) this::getClasspath); <ide> } <ide> return javaLauncher.get().getMetadata().getLanguageVersion().toString(); <ide> } <ide> final File customHome = getOptions().getForkOptions().getJavaHome(); <del> if(customHome != null) { <add> if (customHome != null) { <ide> return getServices().get(JvmMetadataDetector.class).getMetadata(customHome).getLanguageVersion().getMajorVersion(); <ide> } <ide> return JavaVersion.current().getMajorVersion();
Java
mit
error: pathspec 'cc-dq/execute-cc/src/main/java/vn/ducquoc/cc/execute/cme/timeconversion/Solution.java' did not match any file(s) known to git
6095be2b92fc6c1c7ca924598c13d795bee5bb6c
1
ducquoc/dq-protected,ducquoc/dq-protected
package vn.ducquoc.cc.execute.cme.timeconversion; import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; import java.util.stream.*;/* Java 8 */ /** * CME - <b>Contact My Email</b>: [email protected] * <br></br> * FYI, (2018) just copied from HackerRank: //hackerrank.com/challenges/time-conversion * //hackerrank.com/challenges/birthday-cake-candles * //hackerrank.com/challenges/staircase * <p></p> * Access https://www.compilejava.net/ and paste there like a pro! ( > 90% will be NPE not compatible HackerRank) * * @see //github.com/ducquoc/fresher-training/blob/master/hackerrank-java-examples/src/main/java/vn/ducquoc/hr/warmup10/Solution.java * @see //github.com/ducquoc/fresher-training/blob/master/hackerrank-java-examples/src/test/java/vn/ducquoc/hr/warmup10/SolutionTest.java */ @SuppressWarnings("unused") public class Solution { /* * Complete the timeConversion function below. */ static String timeConversion(String s) { /* * Write your code here. */ String timeText = s;//07:05:45PM -> 19:05:45 String hourText = timeText.substring(0, 2); if (timeText.endsWith("AM")) { if ("12".equals(hourText)) { hourText = "00"; } } else { // PM if (!"12".equals(hourText)) { hourText = String.valueOf(12 + Integer.valueOf(hourText)); } } timeText = hourText + timeText.substring(2, timeText.length() - 2); return timeText; } private static final Scanner scan = new Scanner(System.in); public static void main(String[] args) throws IOException {//stupid copy & paste might not work outside HR //BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));//compatible old HackerRank String s = scan.nextLine(); String result = timeConversion(s); bw.write(result); bw.newLine(); bw.close(); } }
cc-dq/execute-cc/src/main/java/vn/ducquoc/cc/execute/cme/timeconversion/Solution.java
copied //hackerrank.com/challenges/time-conversion to compilejava.net and met NPE, stupid copy "spiral" --> who will fix? Contact My Email
cc-dq/execute-cc/src/main/java/vn/ducquoc/cc/execute/cme/timeconversion/Solution.java
copied //hackerrank.com/challenges/time-conversion to compilejava.net and met NPE, stupid copy "spiral" --> who will fix? Contact My Email
<ide><path>c-dq/execute-cc/src/main/java/vn/ducquoc/cc/execute/cme/timeconversion/Solution.java <add>package vn.ducquoc.cc.execute.cme.timeconversion; <add> <add>import java.io.*; <add>import java.math.*; <add>import java.text.*; <add>import java.util.*; <add>import java.util.regex.*; <add>import java.util.stream.*;/* Java 8 */ <add> <add>/** <add> * CME - <b>Contact My Email</b>: [email protected] <add> * <br></br> <add> * FYI, (2018) just copied from HackerRank: //hackerrank.com/challenges/time-conversion <add> * //hackerrank.com/challenges/birthday-cake-candles <add> * //hackerrank.com/challenges/staircase <add> * <p></p> <add> * Access https://www.compilejava.net/ and paste there like a pro! ( > 90% will be NPE not compatible HackerRank) <add> * <add> * @see //github.com/ducquoc/fresher-training/blob/master/hackerrank-java-examples/src/main/java/vn/ducquoc/hr/warmup10/Solution.java <add> * @see //github.com/ducquoc/fresher-training/blob/master/hackerrank-java-examples/src/test/java/vn/ducquoc/hr/warmup10/SolutionTest.java <add> */ <add>@SuppressWarnings("unused") <add>public class Solution { <add> <add> /* <add> * Complete the timeConversion function below. <add> */ <add> static String timeConversion(String s) { <add> /* <add> * Write your code here. <add> */ <add> String timeText = s;//07:05:45PM -> 19:05:45 <add> String hourText = timeText.substring(0, 2); <add> if (timeText.endsWith("AM")) { <add> if ("12".equals(hourText)) { <add> hourText = "00"; <add> } <add> } else { // PM <add> if (!"12".equals(hourText)) { <add> hourText = String.valueOf(12 + Integer.valueOf(hourText)); <add> } <add> } <add> timeText = hourText + timeText.substring(2, timeText.length() - 2); <add> return timeText; <add> } <add> <add> private static final Scanner scan = new Scanner(System.in); <add> <add> public static void main(String[] args) throws IOException {//stupid copy & paste might not work outside HR <add> //BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); <add> BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));//compatible old HackerRank <add> <add> String s = scan.nextLine(); <add> <add> String result = timeConversion(s); <add> <add> bw.write(result); <add> bw.newLine(); <add> <add> bw.close(); <add> } <add> <add>}
JavaScript
mit
623fc99820ddc1eda9b8750738be412c909588cb
0
Denverus/soccer-stat,Denverus/soccer-stat
var express = require('express'); var gameTool = require('./game'); var statTool = require('./stat'); var app = express(); app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); // views is directory for all template files app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); var nav = [ { title: 'Home', icon: 'home', url: '/' }, { title: 'Games', icon: 'cd', url: '/games' }, { title: 'All players', icon: 'user', url: '/players' }, { title: 'Scorers', icon: 'record', url: '/scorers' }, { title: 'Assists', icon: 'thumbs-up', url: '/assists' }, { title: 'Goal + Pass', icon: 'star', url: '/glas' }, { title: 'Winners', icon: 'asterisk', url: '/winners' }, { title: 'Captains', icon: 'king', url: '/captains' } ]; getNavFor = function(url) { for(var i = 0; i < nav.length; i++) { if (nav[i].url == url) { nav[i].active = true; } else { nav[i].active = false; } } return nav; }; app.get('/', function (request, response) { gameTool.loadIndexPageData(function (data) { console.log('Index page data ', data); response.render('pages/index', { lastGame: data.lastGame, games: data.gameList, scorers: data.scorers, assists: data.assists, glas: data.glas, winners: data.winners, captains: data.captains, nav: getNavFor('/') }); }); }); app.get('/api/1.0/index', function (request, response) { gameTool.loadGamesPageData(function (games) { var data = { lastGame: data.lastGame, games: data.gameList, scorers: data.scorers, assists: data.assists, glas: data.glas, winners: data.winners, captains: data.captains }; console.log('Games list ', data); response.end( JSON.stringify(data)); }); }); app.get('/games', function (request, response) { gameTool.loadGamesPageData(function (games) { console.log('Games list ', games); response.render('pages/games', { games: games, nav: getNavFor('/games') }); }); }); app.get('/api/1.0/games', function (request, response) { gameTool.loadGamesPageData(function (games) { console.log('Games list ', games); response.end( JSON.stringify(games)); }); }); app.get('/game/:gameId', function (request, response) { gameTool.loadOneGamePageData(request.params.gameId, function (data) { console.log('Single game ', data); response.render('pages/single_game', { game: data.game, gameStat: data.gameStat, nav: getNavFor('') }); }); }); app.get('/api/1.0/game/:gameId', function (request, response) { gameTool.loadOneGamePageData(request.params.gameId, function (data) { console.log('Single game ', data); var data = { game: data.game, gameStat: data.gameStat, nav: getNavFor('') }; response.end( JSON.stringify(data)); }); }); app.get('/players', function (request, response) { gameTool.loadPlayersPageData('name', function (players) { console.log('Player list ', players); response.render('pages/players', { players: players, nav: getNavFor('/players') }); }); }); app.get('/api/1.0/players', function (request, response) { gameTool.loadPlayersPageData('name', function (players) { console.log('Player list ', players); var data = { players: players, nav: getNavFor('/players') }; response.end( JSON.stringify(data)); }); }); app.get('/scorers', function (request, response) { gameTool.loadPlayersPageData('goal', function (players) { console.log('Player list ', players); response.render('pages/scorers', { scorers: players, nav: getNavFor('/scorers') }); }); }); app.get('/api/1.0/scorers', function (request, response) { gameTool.loadPlayersPageData('goal', function (players) { console.log('Player list ', players); var data = { scorers: players, nav: getNavFor('/scorers') }; response.end( JSON.stringify(data)); }); }); app.get('/assists', function (request, response) { gameTool.loadPlayersPageData('assist', function (players) { console.log('Player list ', players); response.render('pages/assists', { assists: players, nav: getNavFor('/assists') }); }); }); app.get('/api/1.0/assists', function (request, response) { gameTool.loadPlayersPageData('assist', function (players) { console.log('Player list ', players); var data = { assists: players, nav: getNavFor('/assists') }; response.end( JSON.stringify(data)); }); }); app.get('/glas', function (request, response) { gameTool.loadPlayersPageData('glas', function (players) { console.log('Player list ', players); response.render('pages/glas', { glas: players, nav: getNavFor('/glas') }); }); }); app.get('/api/1.0/glas', function (request, response) { gameTool.loadPlayersPageData('glas', function (players) { console.log('Player list ', players); var data = { glas: players, nav: getNavFor('/glas') }; response.end( JSON.stringify(data)); }); }); app.get('/player/:playerId', function (request, response) { gameTool.loadPlayerProfilePageData(request.params.playerId, function (player) { console.log('Player profile ', player); response.render('pages/player', { player: player, nav: getNavFor('') }); }); }); app.get('/api/1.0/player/:playerId', function (request, response) { gameTool.loadPlayerProfilePageData(request.params.playerId, function (player) { console.log('Player profile ', player); var data = { player: player, nav: getNavFor('') }; response.end( JSON.stringify(data)); }); }); app.get('/winners', function (request, response) { gameTool.loadWinnersPageData('point', function (winners) { console.log('Winners', winners); response.render('pages/winners', { winners: winners, nav: getNavFor('/winners') }); }); }); app.get('/api/1.0/winners', function (request, response) { gameTool.loadWinnersPageData('point', function (winners) { console.log('Winners', winners); var data = { winners: winners, nav: getNavFor('/winners') }; response.end( JSON.stringify(data)); }); }); app.get('/captains', function (request, response) { gameTool.loadCaptainsPageData('point', function (captains) { console.log('Captains', captains); response.render('pages/captains', { captains: captains, nav: getNavFor('/captains') }); }); }); app.get('/api/1.0/captains', function (request, response) { gameTool.loadCaptainsPageData('point', function (captains) { console.log('Captains', captains); var data = { captains: captains, nav: getNavFor('/captains') }; response.end( JSON.stringify(data)); }); }); app.get('/trinity/:size', function (request, response) { gameTool.loadTrinityPageData(request.params.size, 'point', function (trinity) { console.log('Trinity', trinity); response.render('pages/trinity', { trinity: trinity, nav: getNavFor('') }); }); }); app.get('/api/1.0/trinity/:size', function (request, response) { gameTool.loadTrinityPageData(request.params.size, 'point', function (trinity) { console.log('Trinity', trinity); var data = { trinity: trinity, nav: getNavFor('') }; response.end( JSON.stringify(data)); }); }); app.get('/test', function (request, response) { response.render('pages/response'); }); app.listen(app.get('port'), function () { console.log('Node app is running on port', app.get('port')); }); var config = { apiKey: "AIzaSyDH8qA0uF6b8AfNeaB7oz_T57_y7PXurqo", authDomain: "russian-soccer.firebaseapp.com", databaseURL: "https://russian-soccer.firebaseio.com", storageBucket: "russian-soccer.appspot.com", messagingSenderId: "476867980667" };
index.js
var express = require('express'); var gameTool = require('./game'); var statTool = require('./stat'); var app = express(); app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); // views is directory for all template files app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); var nav = [ { title: 'Home', icon: 'home', url: '/' }, { title: 'Games', icon: 'cd', url: '/games' }, { title: 'All players', icon: 'user', url: '/players' }, { title: 'Scorers', icon: 'record', url: '/scorers' }, { title: 'Assists', icon: 'thumbs-up', url: '/assists' }, { title: 'Goal + Pass', icon: 'star', url: '/glas' }, { title: 'Winners', icon: 'asterisk', url: '/winners' }, { title: 'Captains', icon: 'king', url: '/captains' } ]; getNavFor = function(url) { for(var i = 0; i < nav.length; i++) { if (nav[i].url == url) { nav[i].active = true; } else { nav[i].active = false; } } return nav; }; app.get('/', function (request, response) { gameTool.loadIndexPageData(function (data) { console.log('Index page data ', data); response.render('pages/index', { lastGame: data.lastGame, games: data.gameList, scorers: data.scorers, assists: data.assists, glas: data.glas, winners: data.winners, captains: data.captains, nav: getNavFor('/') }); }); }); app.get('/games', function (request, response) { gameTool.loadGamesPageData(function (games) { console.log('Games list ', games); response.render('pages/games', { games: games, nav: getNavFor('/games') }); }); }); app.get('/api/1.0/games', function (request, response) { gameTool.loadGamesPageData(function (games) { console.log('Games list ', games); var data = { games: games, nav: getNavFor('/games') }; response.end( JSON.stringify(data)); }); }); app.get('/game/:gameId', function (request, response) { gameTool.loadOneGamePageData(request.params.gameId, function (data) { console.log('Single game ', data); response.render('pages/single_game', { game: data.game, gameStat: data.gameStat, nav: getNavFor('') }); }); }); app.get('/api/1.0/game/:gameId', function (request, response) { gameTool.loadOneGamePageData(request.params.gameId, function (data) { console.log('Single game ', data); var data = { game: data.game, gameStat: data.gameStat, nav: getNavFor('') }; response.end( JSON.stringify(data)); }); }); app.get('/players', function (request, response) { gameTool.loadPlayersPageData('name', function (players) { console.log('Player list ', players); response.render('pages/players', { players: players, nav: getNavFor('/players') }); }); }); app.get('/api/1.0/players', function (request, response) { gameTool.loadPlayersPageData('name', function (players) { console.log('Player list ', players); var data = { players: players, nav: getNavFor('/players') }; response.end( JSON.stringify(data)); }); }); app.get('/scorers', function (request, response) { gameTool.loadPlayersPageData('goal', function (players) { console.log('Player list ', players); response.render('pages/scorers', { scorers: players, nav: getNavFor('/scorers') }); }); }); app.get('/api/1.0/scorers', function (request, response) { gameTool.loadPlayersPageData('goal', function (players) { console.log('Player list ', players); var data = { scorers: players, nav: getNavFor('/scorers') }; response.end( JSON.stringify(data)); }); }); app.get('/assists', function (request, response) { gameTool.loadPlayersPageData('assist', function (players) { console.log('Player list ', players); response.render('pages/assists', { assists: players, nav: getNavFor('/assists') }); }); }); app.get('/api/1.0/assists', function (request, response) { gameTool.loadPlayersPageData('assist', function (players) { console.log('Player list ', players); var data = { assists: players, nav: getNavFor('/assists') }; response.end( JSON.stringify(data)); }); }); app.get('/glas', function (request, response) { gameTool.loadPlayersPageData('glas', function (players) { console.log('Player list ', players); response.render('pages/glas', { glas: players, nav: getNavFor('/glas') }); }); }); app.get('/api/1.0/glas', function (request, response) { gameTool.loadPlayersPageData('glas', function (players) { console.log('Player list ', players); var data = { glas: players, nav: getNavFor('/glas') }; response.end( JSON.stringify(data)); }); }); app.get('/player/:playerId', function (request, response) { gameTool.loadPlayerProfilePageData(request.params.playerId, function (player) { console.log('Player profile ', player); response.render('pages/player', { player: player, nav: getNavFor('') }); }); }); app.get('/api/1.0/player/:playerId', function (request, response) { gameTool.loadPlayerProfilePageData(request.params.playerId, function (player) { console.log('Player profile ', player); var data = { player: player, nav: getNavFor('') }; response.end( JSON.stringify(data)); }); }); app.get('/winners', function (request, response) { gameTool.loadWinnersPageData('point', function (winners) { console.log('Winners', winners); response.render('pages/winners', { winners: winners, nav: getNavFor('/winners') }); }); }); app.get('/api/1.0/winners', function (request, response) { gameTool.loadWinnersPageData('point', function (winners) { console.log('Winners', winners); var data = { winners: winners, nav: getNavFor('/winners') }; response.end( JSON.stringify(data)); }); }); app.get('/captains', function (request, response) { gameTool.loadCaptainsPageData('point', function (captains) { console.log('Captains', captains); response.render('pages/captains', { captains: captains, nav: getNavFor('/captains') }); }); }); app.get('/api/1.0/captains', function (request, response) { gameTool.loadCaptainsPageData('point', function (captains) { console.log('Captains', captains); var data = { captains: captains, nav: getNavFor('/captains') }; response.end( JSON.stringify(data)); }); }); app.get('/trinity/:size', function (request, response) { gameTool.loadTrinityPageData(request.params.size, 'point', function (trinity) { console.log('Trinity', trinity); response.render('pages/trinity', { trinity: trinity, nav: getNavFor('') }); }); }); app.get('/api/1.0/trinity/:size', function (request, response) { gameTool.loadTrinityPageData(request.params.size, 'point', function (trinity) { console.log('Trinity', trinity); var data = { trinity: trinity, nav: getNavFor('') }; response.end( JSON.stringify(data)); }); }); app.get('/test', function (request, response) { response.render('pages/response'); }); app.listen(app.get('port'), function () { console.log('Node app is running on port', app.get('port')); }); var config = { apiKey: "AIzaSyDH8qA0uF6b8AfNeaB7oz_T57_y7PXurqo", authDomain: "russian-soccer.firebaseapp.com", databaseURL: "https://russian-soccer.firebaseio.com", storageBucket: "russian-soccer.appspot.com", messagingSenderId: "476867980667" };
Fixed Rest API for /games and added /index
index.js
Fixed Rest API for /games and added /index
<ide><path>ndex.js <ide> }); <ide> }); <ide> <add>app.get('/api/1.0/index', function (request, response) { <add> gameTool.loadGamesPageData(function (games) { <add> var data = { <add> lastGame: data.lastGame, <add> games: data.gameList, <add> scorers: data.scorers, <add> assists: data.assists, <add> glas: data.glas, <add> winners: data.winners, <add> captains: data.captains <add> }; <add> console.log('Games list ', data); <add> response.end( JSON.stringify(data)); <add> }); <add>}); <add> <ide> app.get('/games', function (request, response) { <ide> gameTool.loadGamesPageData(function (games) { <ide> console.log('Games list ', games); <ide> app.get('/api/1.0/games', function (request, response) { <ide> gameTool.loadGamesPageData(function (games) { <ide> console.log('Games list ', games); <del> var data = { <del> games: games, <del> nav: getNavFor('/games') <del> }; <del> response.end( JSON.stringify(data)); <add> response.end( JSON.stringify(games)); <ide> }); <ide> }); <ide>
Java
apache-2.0
3a15b761024211f0cb0d992a5701abf590cd800d
0
nla/bamboo,nla/bamboo,nla/bamboo,nla/bamboo
package bamboo.task; import com.google.common.net.InternetDomainName; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.stream.JsonWriter; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.parser.PdfTextExtractor; import de.l3s.boilerpipe.BoilerpipeProcessingException; import de.l3s.boilerpipe.document.TextDocument; import de.l3s.boilerpipe.extractors.DefaultExtractor; import de.l3s.boilerpipe.sax.BoilerpipeSAXInput; import org.apache.commons.io.input.BoundedInputStream; import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.apache.tika.Tika; import org.apache.tika.config.TikaConfig; import org.apache.tika.exception.TikaException; import org.apache.tika.fork.ForkParser; import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.TikaCoreProperties; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.sax.BodyContentHandler; import org.apache.tika.sax.Link; import org.apache.tika.sax.LinkContentHandler; import org.apache.tika.sax.TeeContentHandler; import org.archive.io.ArchiveReader; import org.archive.io.ArchiveReaderFactory; import org.archive.io.ArchiveRecord; import org.archive.io.ArchiveRecordHeader; import org.archive.util.Base32; import org.netpreserve.urlcanon.Canonicalizer; import org.netpreserve.urlcanon.ParsedUrl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.*; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TextExtractor { private static final Logger log = LoggerFactory.getLogger(TextExtractor.class); static final int pdfDiskOffloadThreshold = 32 * 1024 * 1024; static final int maxDocSize = 0x100000; static final long timeLimitMillis = 5000; private boolean boilingEnabled = false; private boolean usePdfBox = false; private boolean useTika = false; public static final Pattern PANDORA_REGEX = Pattern.compile("http://pandora.nla.gov.au/pan/[0-9]+/[0-9-]+/([^/.]+\\.[^/]+/.*)"); private final Parser parser; public TextExtractor() { try { TikaConfig config = new TikaConfig(getClass().getResource("tika.xml")); ForkParser parser = new ForkParser(getClass().getClassLoader(), new AutoDetectParser(config)); parser.setJavaCommand(Arrays.asList("java", "-Xmx512m")); if (System.getenv("TIKA_POOL_SIZE") != null) { parser.setPoolSize(Integer.parseInt(System.getenv("TIKA_POOL_SIZE"))); } this.parser = parser; } catch (Exception e) { throw new RuntimeException("Error configuring tika via tika.xml", e); } } public static void setUrls(Document doc, String url) throws TextExtractionException { String deliveryUrl = url; Matcher m = PANDORA_REGEX.matcher(url); if (m.matches()) { // TODO: consult url.map String hackedOffUrl = "http://" + m.group(1); url = hackedOffUrl; } doc.setUrl(url); ParsedUrl parse = ParsedUrl.parseUrl(deliveryUrl); Canonicalizer.AGGRESSIVE.canonicalize(parse); doc.setDeliveryUrl(parse.toString()); try { doc.setHost(new URL(url).getHost()); doc.setSite(topPrivateDomain(url)); } catch (MalformedURLException e) { throw new TextExtractionException(e); } } public Document extract(ArchiveRecord record) throws TextExtractionException { Document doc = new Document(); ArchiveRecordHeader warcHeader = record.getHeader(); String url = WarcUtils.getCleanUrl(warcHeader); if (WarcUtils.isResponseRecord(warcHeader)) { HttpHeader httpHeader; try { httpHeader = HttpHeader.parse(record, url); } catch (IOException e) { throw new TextExtractionException("parsing http header: " + e.getMessage(), e); } if (httpHeader == null) { throw new TextExtractionException("response record missing http header"); } doc.setContentType(HttpHeader.cleanContentType(httpHeader.contentType)); doc.setStatusCode(httpHeader.status); if (httpHeader.location != null) { LinkInfo link = new LinkInfo(); link.setType("location"); link.setUrl(httpHeader.location); link.setHref(httpHeader.rawLocation); doc.addLink(link); } } else if (WarcUtils.isResourceRecord(warcHeader)) { doc.setContentType(HttpHeader.cleanContentType((String) warcHeader.getHeaderValue("Content-Type"))); doc.setStatusCode(200); } else { throw new TextExtractionException("unhandled WARC record type"); } String arcDate = WarcUtils.getArcDate(warcHeader); setUrls(doc, url); doc.setContentLength(warcHeader.getContentLength()); Instant instant = LocalDateTime.parse(arcDate, WarcUtils.arcDateFormat).atOffset(ZoneOffset.UTC).toInstant(); doc.setDate(Date.from(instant)); doc.setWarcOffset(warcHeader.getOffset()); InputStream contentStream = record; String digest = (String) warcHeader.getHeaderValue("WARC-Payload-Digest"); if (digest != null) { if (digest.startsWith("sha1:")) { digest = digest.substring(5); } doc.setContentSha1(digest); } else { // no digest was available so let's calculate one on the fly try { contentStream = new DigestInputStream(record, MessageDigest.getInstance("SHA1")); } catch (NoSuchAlgorithmException e) { log.warn("SHA1 not available", e); } } if (doc.getContentType() == null) { throw new TextExtractionException("no content type"); } URI uri; try { uri = new URI(doc.getUrl()); } catch (URISyntaxException e) { uri = null; } try { switch (doc.getContentType()) { case "text/html": if (useTika) { extractTika(contentStream, doc, uri); } else { extractHtml(contentStream, doc); } break; case "application/pdf": if (useTika) { extractTika(contentStream, doc, uri); } else if (usePdfBox) { extractPdfBox(contentStream, doc); } else { extractPdf(contentStream, record, doc); } break; case "application/vnd.ms-excel": case "text/csv": case "application/csv": case "application/vnd.ms-powerpoint": case "application/msword": case "application/vnd.ms-word.document.macroEnabled.12": case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": case "application/vnd.openxmlformats-officedocument.presentationml.presentation": case "application/vnd.oasis.opendocument.presentation": case "application/vnd.oasis.opendocument.text": case "application/vnd.oasis.opendocument.spreadsheet": if (useTika) { extractTika(contentStream, doc, uri); } else { doc.setTextError("not implemented for content-type"); } break; default: doc.setTextError("not implemented for content-type"); break; } } catch (TextExtractionException e) { doc.setTextError(e.getMessage()); } if (contentStream instanceof DigestInputStream) { fullyConsume(contentStream); byte[] digestBytes = ((DigestInputStream)contentStream).getMessageDigest().digest(); doc.setContentSha1(Base32.encode(digestBytes)); } return doc; } private void fullyConsume(InputStream stream) { byte[] buf = new byte[8192]; try { while (true) { if (stream.read(buf) == -1) break; } } catch (IOException e) { log.warn("error consuming rest of stream", e); } } public void extractTika(InputStream record, Document doc, URI baseUrl) throws TextExtractionException { Metadata metadata = new Metadata(); metadata.set(Metadata.CONTENT_TYPE, doc.getContentType()); try { ParseContext parseContext = new ParseContext(); LinkContentHandler linkHandler = new LinkContentHandler(true); BodyContentHandler bodyHandler = new BodyContentHandler(maxDocSize); HeadingContentHandler headingHandler = new HeadingContentHandler(); TeeContentHandler teeHandler = new TeeContentHandler(linkHandler, bodyHandler, headingHandler); parser.parse(record, teeHandler, metadata, parseContext); doc.setText(clean(bodyHandler.toString())); doc.setTitle(clean(getAny(metadata, TikaCoreProperties.TITLE.getName()))); doc.setDescription(clean(getAny(metadata, "description", "DC.description", "DC.Description", "dcterms.description"))); doc.setKeywords(clean(getAny(metadata, "keywords", "DC.keywords", "DC.Keywords", "dcterms.keywords"))); doc.setPublisher(clean(getAny(metadata, "publisher", "DC.publisher", "DC.Publisher", "dcterms.publisher"))); doc.setCreator(clean(getAny(metadata, "creator", "DC.creator", "DC.Creator", "dcterms.creator"))); doc.setContributor(clean(getAny(metadata, "contributor", "DC.contributor", "DC.Contributor", "dcterms.contributor"))); doc.setCoverage(clean(getAny(metadata, "coverage", "DC.coverage", "DC.Coverage", "dcterms.coverage"))); doc.setH1(headingHandler.getHeadings()); doc.setOgSiteName(clean(metadata.get("og:site_name"))); doc.setOgTitle(clean(metadata.get("og:title"))); List<LinkInfo> links = new ArrayList<>(); for (Link link: linkHandler.getLinks()) { if ("".equals(link.getUri()) || startsWithIgnoreCase(link.getUri(), "data:")) { continue; } LinkInfo info = new LinkInfo(); info.setType(link.getType()); info.setHref(link.getUri()); if (!"".equals(link.getText())) { info.setText(link.getText()); } if (!"".equals(link.getRel())) { info.setRel(link.getRel()); } if (!"".equals(link.getTitle())) { info.setTitle(link.getTitle()); } if (baseUrl != null) { String url = null; try { url = baseUrl.resolve(link.getUri()).toString(); info.setUrl(WarcUtils.cleanUrl(url)); } catch (IllegalArgumentException e) { // bad url } catch (StackOverflowError e) { log.warn("URL caused stackoverflow: " + url); } } doc.addLink(info); } } catch (IOException | TikaException | SAXException e) { throw new TextExtractionException("Tika failed", e); } } public static final Pattern MULTISPACE = Pattern.compile("\\s{2,}"); private String clean(String s) { if (s == null) return null; return MULTISPACE.matcher(s.trim()).replaceAll(" "); } private static boolean startsWithIgnoreCase(String str, String prefix) { return str.regionMatches(true, 0, prefix, 0, prefix.length()); } public static String getAny(Metadata metadata, String... keys) { for (String key : keys) { String value = metadata.get(key); if (value != null) { return value; } } return null; } private void extractHtml(InputStream record, Document doc) throws TextExtractionException { try { BoundedInputStream in = new BoundedInputStream(record, maxDocSize); TextDocument textDoc = new BoilerpipeSAXInput(new InputSource(in)).getTextDocument(); doc.setTitle(textDoc.getTitle()); doc.setText(textDoc.getText(true, true).replace("\uFFFF", "")); if (boilingEnabled) { DefaultExtractor.INSTANCE.process(textDoc); doc.setBoiled(textDoc.getContent().replace("\uFFFF", "")); } } catch (SAXException | BoilerpipeProcessingException | IllegalArgumentException | ArrayIndexOutOfBoundsException e) { throw new TextExtractionException(e); } } private static void extractPdf(InputStream stream, ArchiveRecord record, Document doc) throws TextExtractionException { doc.setTitle(record.getHeader().getUrl()); try { if (record.getHeader().getLength() > pdfDiskOffloadThreshold) { // PDFReader needs (uncompressed) random access to the file. When given a stream it loads the whole // lot into a memory buffer. So for large records let's decompress to a temporary file first. Path tmp = Files.createTempFile("bamboo-solr-tmp", ".pdf"); Files.copy(stream, tmp, StandardCopyOption.REPLACE_EXISTING); try { extractPdfContent(new PdfReader(tmp.toString()), doc); } finally { try { Files.deleteIfExists(tmp); } catch (IOException e) { // we can't do anything } } } else { extractPdfContent(new PdfReader(stream), doc); } } catch (NoClassDefFoundError | RuntimeException | IOException e) { throw new TextExtractionException(e); } } static void extractPdfContent(PdfReader pdfReader, Document doc) throws TextExtractionException, IOException { try { long deadline = System.currentTimeMillis() + timeLimitMillis; StringWriter sw = new StringWriter(); TruncatingWriter tw = new TruncatingWriter(sw, maxDocSize, deadline); PdfTextExtractor extractor = new PdfTextExtractor(pdfReader); try { for (int i = 1; i <= pdfReader.getNumberOfPages(); ++i) { String text = extractor.getTextFromPage(i); tw.append(text.replace("\uFFFF", "")); tw.append(' '); } doc.setText(sw.toString()); } catch (TruncatedException e) { // reached limits, stop early and save what we got doc.setText(sw.toString()); doc.setTextError("truncatedPdf " + e.getMessage()); } // extract the title from the metadata if it has one Object metadataTitle = pdfReader.getInfo().get("Title"); if (metadataTitle != null && metadataTitle instanceof String) { doc.setTitle((String) metadataTitle); } } catch (Error e) { if (e.getClass() == Error.class && (e.getMessage() == null || e.getMessage().startsWith("Unable to process ToUnicode map"))) { // pdf reader abuses java.lang.Error sometimes to indicate a parse error throw new TextExtractionException(e); } else { // let everything else (eg OutOfMemoryError) through throw e; } } } static void extractPdfBox(InputStream stream, Document doc) throws TextExtractionException { long deadline = System.currentTimeMillis() + timeLimitMillis; StringWriter sw = new StringWriter(); try (PDDocument pdf = PDDocument.load(stream, MemoryUsageSetting.setupTempFileOnly())) { String title = pdf.getDocumentInformation().getTitle(); if (title != null) { doc.setTitle(title); } doc.setKeywords(pdf.getDocumentInformation().getKeywords()); doc.setPublisher(pdf.getDocumentInformation().getAuthor()); doc.setCoverage(pdf.getDocumentInformation().getSubject()); PDFTextStripper stripper = new PDFTextStripper(); stripper.writeText(pdf, new TruncatingWriter(sw, maxDocSize, deadline)); doc.setText(sw.toString()); } catch (TruncatedException e) { // reached limits, write what we got and then stop early doc.setText(sw.toString()); doc.setTextError("truncatedPdf " + e.getMessage()); } catch (Exception e) { throw new TextExtractionException(e); } } public void setUsePdfBox(boolean usePdfBox) { this.usePdfBox = usePdfBox; } static class TruncatedException extends RuntimeException { public TruncatedException(String message) { super(message); } } public void setUseTika(boolean useTika) { this.useTika = useTika; } static class TruncatingWriter extends FilterWriter { private final long limit; private final long deadline; private long written; TruncatingWriter(Writer out, long limit, long deadline) { super(out); this.limit = limit; this.deadline = deadline; } @Override public void write(int i) throws IOException { checkLimits(); super.write(i); written++; } @Override public void write(String s, int off, int len) throws IOException { checkLimits(); int clamped = (int)Math.min(len, remaining()); super.write(s, off, clamped); written += clamped; } @Override public void write(char[] chars, int off, int len) throws IOException { checkLimits(); int clamped = (int)Math.min(len, remaining()); super.write(chars, off, clamped); written += clamped; } private void checkLimits() { if (remaining() <= 0) { throw new TruncatedException("space"); } else if (System.currentTimeMillis() >= deadline) { throw new TruncatedException("time"); } } private long remaining() { return limit - written; } } private final static Pattern WWW_PREFIX = Pattern.compile("^www[0-9]*\\."); private static String topPrivateDomain(String url) throws MalformedURLException { String host = new URL(url).getHost(); try { InternetDomainName domain = InternetDomainName.from(host); return domain.topPrivateDomain().toString(); } catch (IllegalStateException | IllegalArgumentException e) { // IP addresses, hosts which don't have a known TLD etc return WWW_PREFIX.matcher(host).replaceFirst(""); } } /** * Sets whether to use boilerpipe's article extractor to try to filter out the main article from a page. The article * text will be stored in Document.boiled. */ public void setBoilingEnabled(boolean boilingEnabled) { this.boilingEnabled = boilingEnabled; } public static void extract(ArchiveReader reader, OutputStream out) throws IOException { TextExtractor extractor = new TextExtractor(); extractor.setUsePdfBox(true); extractor.setUseTika(true); extractor.extractAll(reader, out); } void extractAll(ArchiveReader reader, OutputStream out) throws IOException { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX") .setPrettyPrinting().create(); try (JsonWriter writer = gson.newJsonWriter(new OutputStreamWriter(out))) { writer.beginArray(); for (ArchiveRecord record : reader) { String url = record.getHeader().getUrl(); if (url == null) continue; try { Document doc = extract(record); gson.toJson(doc, Document.class, writer); } catch (TextExtractionException e) { continue; // skip it } } writer.endArray(); writer.flush(); } } public static void main(String[] args) throws IOException { try (ArchiveReader reader = ArchiveReaderFactory.get(args[0])) { extract(reader, System.out); } } }
ui/src/bamboo/task/TextExtractor.java
package bamboo.task; import com.google.common.net.InternetDomainName; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.stream.JsonWriter; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.parser.PdfTextExtractor; import de.l3s.boilerpipe.BoilerpipeProcessingException; import de.l3s.boilerpipe.document.TextDocument; import de.l3s.boilerpipe.extractors.DefaultExtractor; import de.l3s.boilerpipe.sax.BoilerpipeSAXInput; import org.apache.commons.io.input.BoundedInputStream; import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.apache.tika.Tika; import org.apache.tika.config.TikaConfig; import org.apache.tika.exception.TikaException; import org.apache.tika.fork.ForkParser; import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.TikaCoreProperties; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.sax.BodyContentHandler; import org.apache.tika.sax.Link; import org.apache.tika.sax.LinkContentHandler; import org.apache.tika.sax.TeeContentHandler; import org.archive.io.ArchiveReader; import org.archive.io.ArchiveReaderFactory; import org.archive.io.ArchiveRecord; import org.archive.io.ArchiveRecordHeader; import org.archive.util.Base32; import org.netpreserve.urlcanon.Canonicalizer; import org.netpreserve.urlcanon.ParsedUrl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.*; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TextExtractor { private static final Logger log = LoggerFactory.getLogger(TextExtractor.class); static final int pdfDiskOffloadThreshold = 32 * 1024 * 1024; static final int maxDocSize = 0x100000; static final long timeLimitMillis = 5000; private boolean boilingEnabled = false; private boolean usePdfBox = false; private boolean useTika = false; public static final Pattern PANDORA_REGEX = Pattern.compile("http://pandora.nla.gov.au/pan/[0-9]+/[0-9-]+/([^/.]+\\.[^/]+/.*)"); private final Parser parser; public TextExtractor() { try { TikaConfig config = new TikaConfig(getClass().getResource("tika.xml")); ForkParser parser = new ForkParser(getClass().getClassLoader(), new AutoDetectParser(config)); parser.setJavaCommand(Arrays.asList("java", "-Xmx512m")); if (System.getenv("TIKA_POOL_SIZE") != null) { parser.setPoolSize(Integer.parseInt(System.getenv("TIKA_POOL_SIZE"))); } this.parser = parser; } catch (Exception e) { throw new RuntimeException("Error configuring tika via tika.xml", e); } } public static void setUrls(Document doc, String url) throws TextExtractionException { String deliveryUrl = url; Matcher m = PANDORA_REGEX.matcher(url); if (m.matches()) { // TODO: consult url.map String hackedOffUrl = "http://" + m.group(1); url = hackedOffUrl; } doc.setUrl(url); ParsedUrl parse = ParsedUrl.parseUrl(deliveryUrl); Canonicalizer.AGGRESSIVE.canonicalize(parse); doc.setDeliveryUrl(parse.toString()); try { doc.setHost(new URL(url).getHost()); doc.setSite(topPrivateDomain(url)); } catch (MalformedURLException e) { throw new TextExtractionException(e); } } public Document extract(ArchiveRecord record) throws TextExtractionException { Document doc = new Document(); ArchiveRecordHeader warcHeader = record.getHeader(); String url = WarcUtils.getCleanUrl(warcHeader); if (WarcUtils.isResponseRecord(warcHeader)) { HttpHeader httpHeader; try { httpHeader = HttpHeader.parse(record, url); } catch (IOException e) { throw new TextExtractionException("parsing http header: " + e.getMessage(), e); } if (httpHeader == null) { throw new TextExtractionException("response record missing http header"); } doc.setContentType(HttpHeader.cleanContentType(httpHeader.contentType)); doc.setStatusCode(httpHeader.status); if (httpHeader.location != null) { LinkInfo link = new LinkInfo(); link.setType("location"); link.setUrl(httpHeader.location); link.setHref(httpHeader.rawLocation); doc.addLink(link); } } else if (WarcUtils.isResourceRecord(warcHeader)) { doc.setContentType(HttpHeader.cleanContentType((String) warcHeader.getHeaderValue("Content-Type"))); doc.setStatusCode(200); } else { throw new TextExtractionException("unhandled WARC record type"); } String arcDate = WarcUtils.getArcDate(warcHeader); setUrls(doc, url); doc.setContentLength(warcHeader.getContentLength()); Instant instant = LocalDateTime.parse(arcDate, WarcUtils.arcDateFormat).atOffset(ZoneOffset.UTC).toInstant(); doc.setDate(Date.from(instant)); doc.setWarcOffset(warcHeader.getOffset()); InputStream contentStream = record; String digest = (String) warcHeader.getHeaderValue("WARC-Payload-Digest"); if (digest != null) { if (digest.startsWith("sha1:")) { digest = digest.substring(5); } doc.setContentSha1(digest); } else { // no digest was available so let's calculate one on the fly try { contentStream = new DigestInputStream(record, MessageDigest.getInstance("SHA1")); } catch (NoSuchAlgorithmException e) { log.warn("SHA1 not available", e); } } if (doc.getContentType() == null) { throw new TextExtractionException("no content type"); } URI uri; try { uri = new URI(doc.getUrl()); } catch (URISyntaxException e) { uri = null; } try { switch (doc.getContentType()) { case "text/html": if (useTika) { extractTika(contentStream, doc, uri); } else { extractHtml(contentStream, doc); } break; case "application/pdf": if (usePdfBox) { extractPdfBox(contentStream, doc); } else { extractPdf(contentStream, record, doc); } break; case "application/vnd.ms-excel": case "text/csv": case "application/csv": case "application/vnd.ms-powerpoint": case "application/msword": case "application/vnd.ms-word.document.macroEnabled.12": case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": case "application/vnd.openxmlformats-officedocument.presentationml.presentation": case "application/vnd.oasis.opendocument.presentation": case "application/vnd.oasis.opendocument.text": case "application/vnd.oasis.opendocument.spreadsheet": if (useTika) { extractTika(contentStream, doc, uri); } else { doc.setTextError("not implemented for content-type"); } break; default: doc.setTextError("not implemented for content-type"); break; } } catch (TextExtractionException e) { doc.setTextError(e.getMessage()); } if (contentStream instanceof DigestInputStream) { fullyConsume(contentStream); byte[] digestBytes = ((DigestInputStream)contentStream).getMessageDigest().digest(); doc.setContentSha1(Base32.encode(digestBytes)); } return doc; } private void fullyConsume(InputStream stream) { byte[] buf = new byte[8192]; try { while (true) { if (stream.read(buf) == -1) break; } } catch (IOException e) { log.warn("error consuming rest of stream", e); } } public void extractTika(InputStream record, Document doc, URI baseUrl) throws TextExtractionException { Metadata metadata = new Metadata(); metadata.set(Metadata.CONTENT_TYPE, doc.getContentType()); try { ParseContext parseContext = new ParseContext(); LinkContentHandler linkHandler = new LinkContentHandler(true); BodyContentHandler bodyHandler = new BodyContentHandler(maxDocSize); HeadingContentHandler headingHandler = new HeadingContentHandler(); TeeContentHandler teeHandler = new TeeContentHandler(linkHandler, bodyHandler, headingHandler); parser.parse(record, teeHandler, metadata, parseContext); doc.setText(clean(bodyHandler.toString())); doc.setTitle(clean(getAny(metadata, TikaCoreProperties.TITLE.getName()))); doc.setDescription(clean(getAny(metadata, "description", "DC.description", "DC.Description", "dcterms.description"))); doc.setKeywords(clean(getAny(metadata, "keywords", "DC.keywords", "DC.Keywords", "dcterms.keywords"))); doc.setPublisher(clean(getAny(metadata, "publisher", "DC.publisher", "DC.Publisher", "dcterms.publisher"))); doc.setCreator(clean(getAny(metadata, "creator", "DC.creator", "DC.Creator", "dcterms.creator"))); doc.setContributor(clean(getAny(metadata, "contributor", "DC.contributor", "DC.Contributor", "dcterms.contributor"))); doc.setCoverage(clean(getAny(metadata, "coverage", "DC.coverage", "DC.Coverage", "dcterms.coverage"))); doc.setH1(headingHandler.getHeadings()); doc.setOgSiteName(clean(metadata.get("og:site_name"))); doc.setOgTitle(clean(metadata.get("og:title"))); List<LinkInfo> links = new ArrayList<>(); for (Link link: linkHandler.getLinks()) { if ("".equals(link.getUri()) || startsWithIgnoreCase(link.getUri(), "data:")) { continue; } LinkInfo info = new LinkInfo(); info.setType(link.getType()); info.setHref(link.getUri()); if (!"".equals(link.getText())) { info.setText(link.getText()); } if (!"".equals(link.getRel())) { info.setRel(link.getRel()); } if (!"".equals(link.getTitle())) { info.setTitle(link.getTitle()); } if (baseUrl != null) { String url = null; try { url = baseUrl.resolve(link.getUri()).toString(); info.setUrl(WarcUtils.cleanUrl(url)); } catch (IllegalArgumentException e) { // bad url } catch (StackOverflowError e) { log.warn("URL caused stackoverflow: " + url); } } doc.addLink(info); } } catch (IOException | TikaException | SAXException e) { throw new TextExtractionException("Tika failed", e); } } public static final Pattern MULTISPACE = Pattern.compile("\\s{2,}"); private String clean(String s) { if (s == null) return null; return MULTISPACE.matcher(s.trim()).replaceAll(" "); } private static boolean startsWithIgnoreCase(String str, String prefix) { return str.regionMatches(true, 0, prefix, 0, prefix.length()); } public static String getAny(Metadata metadata, String... keys) { for (String key : keys) { String value = metadata.get(key); if (value != null) { return value; } } return null; } private void extractHtml(InputStream record, Document doc) throws TextExtractionException { try { BoundedInputStream in = new BoundedInputStream(record, maxDocSize); TextDocument textDoc = new BoilerpipeSAXInput(new InputSource(in)).getTextDocument(); doc.setTitle(textDoc.getTitle()); doc.setText(textDoc.getText(true, true).replace("\uFFFF", "")); if (boilingEnabled) { DefaultExtractor.INSTANCE.process(textDoc); doc.setBoiled(textDoc.getContent().replace("\uFFFF", "")); } } catch (SAXException | BoilerpipeProcessingException | IllegalArgumentException | ArrayIndexOutOfBoundsException e) { throw new TextExtractionException(e); } } private static void extractPdf(InputStream stream, ArchiveRecord record, Document doc) throws TextExtractionException { doc.setTitle(record.getHeader().getUrl()); try { if (record.getHeader().getLength() > pdfDiskOffloadThreshold) { // PDFReader needs (uncompressed) random access to the file. When given a stream it loads the whole // lot into a memory buffer. So for large records let's decompress to a temporary file first. Path tmp = Files.createTempFile("bamboo-solr-tmp", ".pdf"); Files.copy(stream, tmp, StandardCopyOption.REPLACE_EXISTING); try { extractPdfContent(new PdfReader(tmp.toString()), doc); } finally { try { Files.deleteIfExists(tmp); } catch (IOException e) { // we can't do anything } } } else { extractPdfContent(new PdfReader(stream), doc); } } catch (NoClassDefFoundError | RuntimeException | IOException e) { throw new TextExtractionException(e); } } static void extractPdfContent(PdfReader pdfReader, Document doc) throws TextExtractionException, IOException { try { long deadline = System.currentTimeMillis() + timeLimitMillis; StringWriter sw = new StringWriter(); TruncatingWriter tw = new TruncatingWriter(sw, maxDocSize, deadline); PdfTextExtractor extractor = new PdfTextExtractor(pdfReader); try { for (int i = 1; i <= pdfReader.getNumberOfPages(); ++i) { String text = extractor.getTextFromPage(i); tw.append(text.replace("\uFFFF", "")); tw.append(' '); } doc.setText(sw.toString()); } catch (TruncatedException e) { // reached limits, stop early and save what we got doc.setText(sw.toString()); doc.setTextError("truncatedPdf " + e.getMessage()); } // extract the title from the metadata if it has one Object metadataTitle = pdfReader.getInfo().get("Title"); if (metadataTitle != null && metadataTitle instanceof String) { doc.setTitle((String) metadataTitle); } } catch (Error e) { if (e.getClass() == Error.class && (e.getMessage() == null || e.getMessage().startsWith("Unable to process ToUnicode map"))) { // pdf reader abuses java.lang.Error sometimes to indicate a parse error throw new TextExtractionException(e); } else { // let everything else (eg OutOfMemoryError) through throw e; } } } static void extractPdfBox(InputStream stream, Document doc) throws TextExtractionException { long deadline = System.currentTimeMillis() + timeLimitMillis; StringWriter sw = new StringWriter(); try (PDDocument pdf = PDDocument.load(stream, MemoryUsageSetting.setupTempFileOnly())) { String title = pdf.getDocumentInformation().getTitle(); if (title != null) { doc.setTitle(title); } doc.setKeywords(pdf.getDocumentInformation().getKeywords()); doc.setPublisher(pdf.getDocumentInformation().getAuthor()); doc.setCoverage(pdf.getDocumentInformation().getSubject()); PDFTextStripper stripper = new PDFTextStripper(); stripper.writeText(pdf, new TruncatingWriter(sw, maxDocSize, deadline)); doc.setText(sw.toString()); } catch (TruncatedException e) { // reached limits, write what we got and then stop early doc.setText(sw.toString()); doc.setTextError("truncatedPdf " + e.getMessage()); } catch (Exception e) { throw new TextExtractionException(e); } } public void setUsePdfBox(boolean usePdfBox) { this.usePdfBox = usePdfBox; } static class TruncatedException extends RuntimeException { public TruncatedException(String message) { super(message); } } public void setUseTika(boolean useTika) { this.useTika = useTika; } static class TruncatingWriter extends FilterWriter { private final long limit; private final long deadline; private long written; TruncatingWriter(Writer out, long limit, long deadline) { super(out); this.limit = limit; this.deadline = deadline; } @Override public void write(int i) throws IOException { checkLimits(); super.write(i); written++; } @Override public void write(String s, int off, int len) throws IOException { checkLimits(); int clamped = (int)Math.min(len, remaining()); super.write(s, off, clamped); written += clamped; } @Override public void write(char[] chars, int off, int len) throws IOException { checkLimits(); int clamped = (int)Math.min(len, remaining()); super.write(chars, off, clamped); written += clamped; } private void checkLimits() { if (remaining() <= 0) { throw new TruncatedException("space"); } else if (System.currentTimeMillis() >= deadline) { throw new TruncatedException("time"); } } private long remaining() { return limit - written; } } private final static Pattern WWW_PREFIX = Pattern.compile("^www[0-9]*\\."); private static String topPrivateDomain(String url) throws MalformedURLException { String host = new URL(url).getHost(); try { InternetDomainName domain = InternetDomainName.from(host); return domain.topPrivateDomain().toString(); } catch (IllegalStateException | IllegalArgumentException e) { // IP addresses, hosts which don't have a known TLD etc return WWW_PREFIX.matcher(host).replaceFirst(""); } } /** * Sets whether to use boilerpipe's article extractor to try to filter out the main article from a page. The article * text will be stored in Document.boiled. */ public void setBoilingEnabled(boolean boilingEnabled) { this.boilingEnabled = boilingEnabled; } public static void extract(ArchiveReader reader, OutputStream out) throws IOException { TextExtractor extractor = new TextExtractor(); extractor.setUsePdfBox(true); extractor.setUseTika(true); extractor.extractAll(reader, out); } void extractAll(ArchiveReader reader, OutputStream out) throws IOException { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX") .setPrettyPrinting().create(); try (JsonWriter writer = gson.newJsonWriter(new OutputStreamWriter(out))) { writer.beginArray(); for (ArchiveRecord record : reader) { String url = record.getHeader().getUrl(); if (url == null) continue; try { Document doc = extract(record); gson.toJson(doc, Document.class, writer); } catch (TextExtractionException e) { continue; // skip it } } writer.endArray(); writer.flush(); } } public static void main(String[] args) throws IOException { try (ArchiveReader reader = ArchiveReaderFactory.get(args[0])) { extract(reader, System.out); } } }
Use tika for pdf
ui/src/bamboo/task/TextExtractor.java
Use tika for pdf
<ide><path>i/src/bamboo/task/TextExtractor.java <ide> } <ide> break; <ide> case "application/pdf": <del> if (usePdfBox) { <add> if (useTika) { <add> extractTika(contentStream, doc, uri); <add> } else if (usePdfBox) { <ide> extractPdfBox(contentStream, doc); <ide> } else { <ide> extractPdf(contentStream, record, doc);
JavaScript
apache-2.0
8ef6eef24c577d2deb4b800d27935d2c938a9ab1
0
AdaptiveScale/lxdui,AdaptiveScale/lxdui,AdaptiveScale/lxdui,AdaptiveScale/lxdui
App.images = App.images || { error: false, loading: false, data: [], remoteData: [], activeTab:'local', tableLocal: null, tableRemote: null, tableSettings: { searching:true, responsive: { details: false }, select: true, autoWidth: true, columnDefs: [ { orderable: false, className: 'select-checkbox', targets: 0 } ], select: { style: 'multi', selector: 'td:first-child' }, order: [[ 1, 'asc' ]] }, containerTemplate:null, newContainerForm:null, init: function(opts){ console.log('Images initialized'); this.data = constLocalImages || []; this.remoteData = constRemoteImages || []; this.containerTemplate = $('.multiContainerTemplate'); $('#btnLocalImages').on('click', $.proxy(this.switchView, this, 'localList')); $('#btnRemoteImages').on('click', $.proxy(this.switchView, this, 'remoteList')); $('#buttonUpdate').on('click', $.proxy(this.getData, this)); $('#buttonDelete').on('click', $.proxy(this.doDeleteLocalImages, this)); $('#buttonDownload').on('click', $.proxy(this.doDownload, this)); $('#buttonLaunchContainers').on('click', $.proxy(this.launchContainers, this)); $('#buttonBack').on('click', $.proxy(this.switchView, this, 'localList')); $('.image').on('click', $.proxy(this.setActive, this)); App.setActiveLink('image'); this.newContainerForm = $('#newContainerForm'); this.newContainerForm.on('submit', $.proxy(this.doCreateContainer, this)); this.initLocalTable(); this.initRemoteTable(); $('.imageSize').each(this.convertImageSize); $('#selectAllLocal').on('change', $.proxy(this.toggleSelectAll, this, 'Local')); $('#selectAllRemote').on('change', $.proxy(this.toggleSelectAll, this, 'Remote')); }, convertImageSize:function(index, item){ $(item).text(App.formatBytes($(item).text())); }, setLoading: function(state){ var tempLoaderState = state?'show':'hide'; var tempTableState = state?'hide':'show'; $('#loader')[tempLoaderState](); if(this.activeTab == 'local') return $('#tableImagesLocalWrapper')[tempTableState](); else return $('#tableImagesRemoteWrapper')[tempTableState](); }, initLocalTable: function(){ this.tableLocal =$('#tableImagesLocal').DataTable(App.mergeProps(this.tableSettings, {rowId: 'fingerprint'})); this.setLocalTableEvents(); }, setLocalTableEvents: function(){ this.tableLocal.on('select', $.proxy(this.onItemSelectChange, this)); this.tableLocal.on('deselect', $.proxy(this.onItemSelectChange, this)); }, initRemoteTable: function(){ this.tableRemote =$('#tableImagesRemote').DataTable(App.mergeProps(this.tableSettings, {rowId: 'image'})); this.setRemoteTableEvents(); }, setRemoteTableEvents: function(){ this.tableRemote.on('select', $.proxy(this.onItemSelectChange, this)); this.tableRemote.on('deselect', $.proxy(this.onItemSelectChange, this)); }, onItemSelectChange : function(e, dt, type, indexes ){ if(this.activeTab=='local'){ var state = this.tableLocal.rows({selected:true}).count()>0; var visibility= state?'visible':'hidden'; $('#buttonLaunchContainers').css('visibility',visibility); $('#buttonDelete').css('visibility',visibility); $('#selectAllLocal').prop('checked',state); return; } if(this.activeTab=='remote'){ var state = this.tableRemote.rows({selected:true}).count()>0 var visibility= state?'visible':'hidden'; $('#buttonDownload').css('visibility',visibility); $('#selectAllRemote').prop('checked',state); return; } }, doDeleteLocalImages: function(){ this.tableLocal.rows( { selected: true } ).data().map(function(row){ $.ajax({ url: App.baseAPI+'image/' + row['fingerprint'], type: 'DELETE', success: $.proxy(this.onDeleteSuccess, this, row['fingerprint']) }); }.bind(this)); }, onDeleteSuccess: function(fingerprint){ this.tableLocal.row("#"+fingerprint).remove().draw(); $('#buttonLaunchContainers').css('visibility','hidden'); $('#buttonDelete').css('visibility','hidden'); }, doDownload: function(){ this.tableRemote.rows({selected: true}).data().map(function(row){ $.ajax({ url:App.baseAPI+'image/remote', type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify({ image:row['image'] }), success: $.proxy(this.onDownloadSuccess, this, row['image']) }); this.tableRemote.row('#'+row['image']).remove().draw(false); }.bind(this)); }, onDownloadSuccess: function(imageName, response){ location.reload(); console.log('downloadSuccess:', 'TODO - add alert and refresh local data'); }, getData: function(){ //this.setLoading(true); if(this.activeTab=='local') location.reload(); //return $.get(App.baseAPI+'image', $.proxy(this.getDataSuccess, this)); if(this.activeTab=='remote') return $.get(App.baseAPI+'image/remote', $.proxy(this.getDataSuccess, this)); }, activateScreen: function(screen){ this.tableLocal.rows({selected:true}).deselect(); this.tableRemote.rows({selected:true}).deselect(); if(screen==='local'){ $('#tableImagesLocalWrapper').show(); $('#tableImagesRemoteWrapper').hide(); $('#buttonDownload').css('visibility','hidden'); this.activeTab = 'local'; return; } if(screen==='remote'){ $('#tableImagesLocalWrapper').hide(); $('#tableImagesRemoteWrapper').show(); $('#buttonDelete').css('visibility','hidden'); this.activeTab = 'remote'; return; } }, updateLocalTable: function(jsonData){ this.data = jsonData; this.tableLocal.clear(); this.tableLocal.destroy(); this.tableLocal = $('#tableImagesLocal').DataTable(App.mergeProps(this.tableSettings, { rowId:'fingerprint', data : this.data, columns : [ { title:'Select', data: null, defaultContent:''}, { title:'OS', data : 'properties.os'}, { title:'Description', data : 'properties.description' }, { title:'Aliases', data : 'aliases'}, { title:'Release', data : 'properties.release' }, { title:'Architecture', data : 'properties.architecture' }, { title:'Size', data : 'size', render:function(field){ return App.formatBytes(field); } } ] })); }, updateRemoteTable: function(jsonData){ this.remoteData = jsonData; this.tableRemote.clear(); this.tableRemote.destroy(); this.tableRemote=$('#tableImagesRemote').DataTable(App.mergeProps(this.tableSettings, { rowId:'image', data : this.remoteData, columns : [ { title:'Select', data: null, defaultContent:''}, { title: 'Distribution', data : 'distribution' }, { title: 'Architecture', data : 'architecture' }, { title: 'Image', data : 'image' }, { title: 'Name', data : 'name' } ] })); }, getDataSuccess: function(response){ this.setLoading(false); if(this.activeTab=='local'){ this.updateLocalTable(response.data); } if(this.activeTab == 'remote'){ this.updateRemoteTable(response.data); } }, getRemoteData: function(){ $.get(App.baseAPI+'image/remote', $.proxy(this.getDataSuccess, this)); }, generateContainerFormSection: function(image, pos){ var tempSection = this.containerTemplate.clone(); tempSection.prop('id',image.fingerprint); tempSection.find('input[name="name"]').prop('name', 'containers['+pos+'][name]'); tempSection.find('input[name="containers['+pos+'][name]"]').val(image.properties.os.toLowerCase()+'-'); tempSection.find('input[name="image"]').prop('name', 'containers['+pos+'][image]'); tempSection.find('input[name="containers['+pos+'][image]"]').val(image.fingerprint); tempSection.find('input[name="count"]').prop('name', 'containers['+pos+'][count]'); tempSection.find('input[name="containers['+pos+'][count]"]').on('change', $.proxy(this.onCountChange, this, tempSection.find('.nodeCount'))); tempSection.find('input[name="cpu[percentage]"]').prop('name', 'containers['+pos+'][cpu[percentage]]'); tempSection.find('input[name="cpu[hardLimitation]"]').prop('name', 'containers['+pos+'][cpu[hardLimitation]]'); tempSection.find('input[name="memory[sizeInMB]"]').prop('name', 'containers['+pos+'][memory[sizeInMB]]'); tempSection.find('input[name="memory[hardLimitation]"]').prop('name', 'containers['+pos+'][memory[hardLimitation]]'); tempSection.find('input[name="autostart"]').prop('name', 'containers['+pos+'][autostart]'); tempSection.find('input[name="stateful"]').prop('name', 'containers['+pos+'][stateful]'); tempSection.find('select[name="profiles"]').prop('name', 'containers['+pos+'][profiles]'); tempSection.find('select[name="containers['+pos+'][profiles]"]').addClass('selectpicker'); tempSection.find('select[name="containers['+pos+'][profiles]"]').prop('id', image.fingerprint+'_profiles'); tempSection.find('.imageName').text(image.properties.description); tempSection.show(); return tempSection; }, onCountChange: function(countNode, event){ $(countNode).text($(event.target).val() +' Node(s)'); }, getImageByFingerPrint: function(tempList, fingerprint){ return tempList.filter(function(image){ return image.fingerprint === fingerprint; })[0]; }, launchContainers: function(){ var count = 0; this.tableLocal.rows({selected: true}).data().map(function(row){ var tempForm = this.generateContainerFormSection( this.getImageByFingerPrint(this.data, row['fingerprint']) , count); $('#multiContainerSection').append(tempForm); count+=1; }.bind(this)); //initialize profile pickers $('.selectpicker').selectpicker(); this.switchView('form'); }, switchView: function(view){ $('#createMultipleContainersForm')[view=='form'?'show':'hide'](); $('#tableImagesLocalWrapper')[view=='localList'?'show':'hide'](); $('#tableImagesRemoteWrapper')[view=='remoteList'?'show':'hide'](); if(view!=='form'){ $('#multiContainerSection').empty(); } if(view=='remoteList'){ this.activateScreen('remote'); } if(view=='localList'){ return this.activateScreen('local'); } $('#buttonLaunchContainers').css('visibility','hidden'); $('#buttonDelete').css('visibility','hidden'); }, generateContainer: function(name, formData){ return { ...formData, name:name } }, generateImageContainers: function(formData){ var imageContainers = []; var tempData = this.cleanupFormData($.extend({}, true,formData)); for(var i=0;i<=Number(formData.count)-1;i++){ imageContainers.push(this.generateContainer(tempData.name+(i+1),tempData)); } return imageContainers; }, cleanupFormData(specs){ delete specs['count']; specs['cpu']['percentage']=Number(specs['cpu']['percentage']); specs['cpu']['hardLimitation']=Boolean(specs['cpu']['hardLimitation']) || false; specs['memory']['sizeInMB']=Number(specs['memory']['sizeInMB']); specs['memory']['hardLimitation']=Boolean(specs['memory']['hardLimitation']) || false; specs['stateful']=Boolean(specs['stateful']) || true; specs['autostart']=Boolean(specs['autostart']); if($('#'+specs.image+'_profiles').val()){ specs['profiles'] = $('#'+specs.image+'_profiles').val(); } return specs; }, generateRequest: function(inputJSON){ var tempRequest = []; var containerArray = $.map(inputJSON.containers, function(val, ind){ return [val]; }); for(var i=containerArray.length-1, container; container=containerArray[i];i--){ var tempData = this.generateImageContainers(container); tempRequest=tempRequest.concat(tempData); } return tempRequest; }, doCreateContainer: function(e){ e.preventDefault(); var tempForm = $.extend({}, true,this.newContainerForm.serializeJSON()); var tempJSON = this.generateRequest(tempForm); $.ajax({ url: App.baseAPI +'container/', type:'POST', dataType:'json', contentType: 'application/json', data: JSON.stringify(tempJSON), success: $.proxy(this.onCreateSuccess, this), error: $.proxy(this.onCreateFailed, this) }); }, onCreateSuccess: function(response){ this.switchView('localList'); window.location = App.baseWEB +'containers'; }, launchContainer:function(fingerprint){ this.tableLocal.row('#'+fingerprint).select(); this.launchContainers(); }, toggleSelectAll:function(name, event){ if(event.target.checked){ this['table'+name].rows().select(); }else{ this['table'+name].rows().deselect(); } } }
app/ui/static/js/images.js
App.images = App.images || { error: false, loading: false, data: [], remoteData: [], activeTab:'local', tableLocal: null, tableRemote: null, tableSettings: { searching:true, responsive: { details: false }, select: true, autoWidth: true, columnDefs: [ { orderable: false, className: 'select-checkbox', targets: 0 } ], select: { style: 'multi', selector: 'td:first-child' }, order: [[ 1, 'asc' ]] }, containerTemplate:null, newContainerForm:null, init: function(opts){ console.log('Images initialized'); this.data = constLocalImages || []; this.remoteData = constRemoteImages || []; this.containerTemplate = $('.multiContainerTemplate'); $('#btnLocalImages').on('click', $.proxy(this.switchView, this, 'localList')); $('#btnRemoteImages').on('click', $.proxy(this.switchView, this, 'remoteList')); $('#buttonUpdate').on('click', $.proxy(this.getData, this)); $('#buttonDelete').on('click', $.proxy(this.doDeleteLocalImages, this)); $('#buttonDownload').on('click', $.proxy(this.doDownload, this)); $('#buttonLaunchContainers').on('click', $.proxy(this.launchContainers, this)); $('#buttonBack').on('click', $.proxy(this.switchView, this, 'localList')); $('.image').on('click', $.proxy(this.setActive, this)); App.setActiveLink('image'); this.newContainerForm = $('#newContainerForm'); this.newContainerForm.on('submit', $.proxy(this.doCreateContainer, this)); this.initLocalTable(); this.initRemoteTable(); $('.imageSize').each(this.convertImageSize); $('#selectAllLocal').on('change', $.proxy(this.toggleSelectAll, this, 'Local')); $('#selectAllRemote').on('change', $.proxy(this.toggleSelectAll, this, 'Remote')); }, convertImageSize:function(index, item){ $(item).text(App.formatBytes($(item).text())); }, setLoading: function(state){ var tempLoaderState = state?'show':'hide'; var tempTableState = state?'hide':'show'; $('#loader')[tempLoaderState](); if(this.activeTab == 'local') return $('#tableImagesLocalWrapper')[tempTableState](); else return $('#tableImagesRemoteWrapper')[tempTableState](); }, initLocalTable: function(){ this.tableLocal =$('#tableImagesLocal').DataTable(App.mergeProps(this.tableSettings, {rowId: 'fingerprint'})); this.setLocalTableEvents(); }, setLocalTableEvents: function(){ this.tableLocal.on('select', $.proxy(this.onItemSelectChange, this)); this.tableLocal.on('deselect', $.proxy(this.onItemSelectChange, this)); }, initRemoteTable: function(){ this.tableRemote =$('#tableImagesRemote').DataTable(App.mergeProps(this.tableSettings, {rowId: 'image'})); this.setRemoteTableEvents(); }, setRemoteTableEvents: function(){ this.tableRemote.on('select', $.proxy(this.onItemSelectChange, this)); this.tableRemote.on('deselect', $.proxy(this.onItemSelectChange, this)); }, onItemSelectChange : function(e, dt, type, indexes ){ if(this.activeTab=='local'){ var state = this.tableLocal.rows({selected:true}).count()>0; var visibility= state?'visible':'hidden'; $('#buttonLaunchContainers').css('visibility',visibility); $('#buttonDelete').css('visibility',visibility); $('#selectAllLocal').prop('checked',state); return; } if(this.activeTab=='remote'){ var state = this.tableRemote.rows({selected:true}).count()>0 var visibility= state?'visible':'hidden'; $('#buttonDownload').css('visibility',visibility); $('#selectAllRemote').prop('checked',state); return; } }, doDeleteLocalImages: function(){ this.tableLocal.rows( { selected: true } ).data().map(function(row){ $.ajax({ url: App.baseAPI+'image/' + row['fingerprint'], type: 'DELETE', success: $.proxy(this.onDeleteSuccess, this, row['fingerprint']) }); }.bind(this)); }, onDeleteSuccess: function(fingerprint){ this.tableLocal.row("#"+fingerprint).remove().draw(); $('#buttonLaunchContainers').css('visibility','hidden'); $('#buttonDelete').css('visibility','hidden'); }, doDownload: function(){ this.tableRemote.rows({selected: true}).data().map(function(row){ $.ajax({ url:App.baseAPI+'image/remote', type: 'POST', dataType: 'json', contentType: 'application/json', data: JSON.stringify({ image:row['image'] }), success: $.proxy(this.onDownloadSuccess, this, row['image']) }); this.tableRemote.row('#'+row['image']).remove().draw(false); }.bind(this)); }, onDownloadSuccess: function(imageName, response){ location.reload(); console.log('downloadSuccess:', 'TODO - add alert and refresh local data'); }, getData: function(){ //this.setLoading(true); if(this.activeTab=='local') location.reload(); //return $.get(App.baseAPI+'image', $.proxy(this.getDataSuccess, this)); if(this.activeTab=='remote') return $.get(App.baseAPI+'image/remote', $.proxy(this.getDataSuccess, this)); }, activateScreen: function(screen){ this.tableLocal.rows({selected:true}).deselect(); this.tableRemote.rows({selected:true}).deselect(); if(screen==='local'){ $('#tableImagesLocalWrapper').show(); $('#tableImagesRemoteWrapper').hide(); $('#buttonDownload').css('visibility','hidden'); this.activeTab = 'local'; return; } if(screen==='remote'){ $('#tableImagesLocalWrapper').hide(); $('#tableImagesRemoteWrapper').show(); $('#buttonDelete').css('visibility','hidden'); this.activeTab = 'remote'; return; } }, updateLocalTable: function(jsonData){ this.data = jsonData; this.tableLocal.clear(); this.tableLocal.destroy(); this.tableLocal = $('#tableImagesLocal').DataTable(App.mergeProps(this.tableSettings, { rowId:'fingerprint', data : this.data, columns : [ { title:'Select', data: null, defaultContent:''}, { title:'OS', data : 'properties.os'}, { title:'Description', data : 'properties.description' }, { title:'Aliases', data : 'aliases'}, { title:'Release', data : 'properties.release' }, { title:'Architecture', data : 'properties.architecture' }, { title:'Size', data : 'size', render:function(field){ return App.formatBytes(field); } } ] })); }, updateRemoteTable: function(jsonData){ this.remoteData = jsonData; this.tableRemote.clear(); this.tableRemote.destroy(); this.tableRemote=$('#tableImagesRemote').DataTable(App.mergeProps(this.tableSettings, { rowId:'image', data : this.remoteData, columns : [ { title:'Select', data: null, defaultContent:''}, { title: 'Distribution', data : 'distribution' }, { title: 'Architecture', data : 'architecture' }, { title: 'Image', data : 'image' }, { title: 'Name', data : 'name' } ] })); }, getDataSuccess: function(response){ this.setLoading(false); if(this.activeTab=='local'){ this.updateLocalTable(response.data); } if(this.activeTab == 'remote'){ this.updateRemoteTable(response.data); } }, getRemoteData: function(){ $.get(App.baseAPI+'image/remote', $.proxy(this.getDataSuccess, this)); }, generateContainerFormSection: function(image, pos){ var tempSection = this.containerTemplate.clone(); tempSection.prop('id',image.fingerprint); tempSection.find('input[name="name"]').prop('name', 'containers['+pos+'][name]'); tempSection.find('input[name="containers['+pos+'][name]"]').val(image.properties.os.toLowerCase()+'-'); tempSection.find('input[name="image"]').prop('name', 'containers['+pos+'][image]'); tempSection.find('input[name="containers['+pos+'][image]"]').val(image.fingerprint); tempSection.find('input[name="count"]').prop('name', 'containers['+pos+'][count]'); tempSection.find('input[name="containers['+pos+'][count]"]').on('change', $.proxy(this.onCountChange, this, tempSection.find('.nodeCount'))); tempSection.find('input[name="cpu[percentage]"]').prop('name', 'containers['+pos+'][cpu[percentage]]'); tempSection.find('input[name="cpu[hardLimitation]"]').prop('name', 'containers['+pos+'][cpu[hardLimitation]]'); tempSection.find('input[name="memory[sizeInMB]"]').prop('name', 'containers['+pos+'][memory[sizeInMB]]'); tempSection.find('input[name="memory[hardLimitation]"]').prop('name', 'containers['+pos+'][memory[hardLimitation]]'); tempSection.find('input[name="autostart"]').prop('name', 'containers['+pos+'][autostart]'); tempSection.find('input[name="stateful"]').prop('name', 'containers['+pos+'][stateful]'); tempSection.find('select[name="profiles"]').prop('name', 'containers['+pos+'][profiles]'); tempSection.find('select[name="containers['+pos+'][profiles]"]').addClass('selectpicker'); tempSection.find('select[name="containers['+pos+'][profiles]"]').prop('id', image.fingerprint+'_profiles'); tempSection.find('.imageName').text(image.properties.description); tempSection.show(); return tempSection; }, onCountChange: function(countNode, event){ $(countNode).text($(event.target).val() +' Node(s)'); }, getImageByFingerPrint: function(tempList, fingerprint){ return tempList.filter(function(image){ return image.fingerprint === fingerprint; })[0]; }, launchContainers: function(){ var count = 0; this.tableLocal.rows({selected: true}).data().map(function(row){ var tempForm = this.generateContainerFormSection( this.getImageByFingerPrint(this.data, row['fingerprint']) , count); $('#multiContainerSection').append(tempForm); count+=1; }.bind(this)); //initialize profile pickers $('.selectpicker').selectpicker(); this.switchView('form'); }, switchView: function(view){ $('#createMultipleContainersForm')[view=='form'?'show':'hide'](); $('#tableImagesLocalWrapper')[view=='localList'?'show':'hide'](); $('#tableImagesRemoteWrapper')[view=='remoteList'?'show':'hide'](); if(view!=='form'){ $('#multiContainerSection').empty(); } if(view=='remoteList'){ this.activateScreen('remote'); } if(view=='localList'){ return this.activateScreen('local'); } $('#buttonLaunchContainers').css('visibility','hidden'); $('#buttonDelete').css('visibility','hidden'); }, generateContainer: function(name, formData){ return { ...formData, name:name } }, generateImageContainers: function(formData){ var imageContainers = []; var tempData = this.cleanupFormData($.extend({}, true,formData)); for(var i=0;i<=Number(formData.count)-1;i++){ imageContainers.push(this.generateContainer(tempData.name+(i+1),tempData)); } return imageContainers; }, cleanupFormData(specs){ delete specs['count']; specs['cpu']['percentage']=Number(specs['cpu']['percentage']); specs['cpu']['hardLimitation']=Boolean(specs['cpu']['hardLimitation']) || false; specs['memory']['sizeInMB']=Number(specs['memory']['sizeInMB']); specs['memory']['hardLimitation']=Boolean(specs['memory']['hardLimitation']) || false; specs['stateful']=Boolean(specs['stateful']) || true; specs['autostart']=Boolean(specs['autostart']) || true; if($('#'+specs.image+'_profiles').val()){ specs['profiles'] = $('#'+specs.image+'_profiles').val(); } return specs; }, generateRequest: function(inputJSON){ var tempRequest = []; var containerArray = $.map(inputJSON.containers, function(val, ind){ return [val]; }); for(var i=containerArray.length-1, container; container=containerArray[i];i--){ var tempData = this.generateImageContainers(container); tempRequest=tempRequest.concat(tempData); } return tempRequest; }, doCreateContainer: function(e){ e.preventDefault(); var tempForm = $.extend({}, true,this.newContainerForm.serializeJSON()); var tempJSON = this.generateRequest(tempForm); $.ajax({ url: App.baseAPI +'container/', type:'POST', dataType:'json', contentType: 'application/json', data: JSON.stringify(tempJSON), success: $.proxy(this.onCreateSuccess, this), error: $.proxy(this.onCreateFailed, this) }); }, onCreateSuccess: function(response){ this.switchView('localList'); window.location = App.baseWEB +'containers'; }, launchContainer:function(fingerprint){ this.tableLocal.row('#'+fingerprint).select(); this.launchContainers(); }, toggleSelectAll:function(name, event){ if(event.target.checked){ this['table'+name].rows().select(); }else{ this['table'+name].rows().deselect(); } } }
Fix autostart for multiple containers
app/ui/static/js/images.js
Fix autostart for multiple containers
<ide><path>pp/ui/static/js/images.js <ide> specs['memory']['sizeInMB']=Number(specs['memory']['sizeInMB']); <ide> specs['memory']['hardLimitation']=Boolean(specs['memory']['hardLimitation']) || false; <ide> specs['stateful']=Boolean(specs['stateful']) || true; <del> specs['autostart']=Boolean(specs['autostart']) || true; <add> specs['autostart']=Boolean(specs['autostart']); <ide> if($('#'+specs.image+'_profiles').val()){ <ide> specs['profiles'] = $('#'+specs.image+'_profiles').val(); <ide> }
Java
bsd-3-clause
92b2cb0da00ed6c8ac2e5aeb0bb5d71a57fb6164
0
amesrobotics/2013robot
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.ames.frc.robot; /* List of buttons/toggles needed * Manual pivot toggle: 2 * Speed boost button: Active joystick push * Force shoot button: 4 * Force Realign button: 7 * Stop auto-target toggle: 10 * Activate frisbee grab button: 8 * Launch climb procedure: Simultaneously & 5,6,7,8,9, and 10. * */ public class InputManager { }
src/edu/ames/frc/robot/InputManager.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.ames.frc.robot; /* List of buttons/toggles needed * Manual pivot toggle: 2 * Speed boost button: Active joystick push * Force shoot button: 4 * Force Realign button: 7 * Stop auto-target toggle: 10 * Activate frisbee grab button: 8 * Launch climb procedure: Simultaneously press 6 and 5 * */ public class InputManager { }
fixed wierd git issue
src/edu/ames/frc/robot/InputManager.java
fixed wierd git issue
<ide><path>rc/edu/ames/frc/robot/InputManager.java <ide> * Force Realign button: 7 <ide> * Stop auto-target toggle: 10 <ide> * Activate frisbee grab button: 8 <del> * Launch climb procedure: Simultaneously press 6 and 5 <add> * Launch climb procedure: Simultaneously & 5,6,7,8,9, and 10. <ide> * <ide> */ <ide> public class InputManager {
Java
apache-2.0
d95a5251eab6a0dfe3ff7f6c4a496c512a2cf23c
0
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
/* * JaamSim Discrete Event Simulation * Copyright (C) 2013 Ausenco Engineering Canada Inc. * Copyright (C) 2019-2020 JaamSim Software 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.jaamsim.ui; import java.awt.Point; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import com.jaamsim.basicsim.Entity; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.OutputHandle; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.Unit; public class OutputBox extends FrameBox { private static OutputBox myInstance; private Entity currentEntity; OutputTableModel tableModel; private final ArrayList<Object> entries = new ArrayList<>(); public OutputBox() { super( "Output Viewer" ); setDefaultCloseOperation(FrameBox.DISPOSE_ON_CLOSE); addWindowListener(FrameBox.getCloseListener("ShowOutputViewer")); tableModel = new OutputTableModel(); OutputTable table = new OutputTable(tableModel); JScrollPane scrollPane = new JScrollPane(table); getContentPane().add( scrollPane ); addComponentListener(FrameBox.getSizePosAdapter(this, "OutputViewerSize", "OutputViewerPos")); } /** * Returns the only instance of the property box */ public synchronized static OutputBox getInstance() { if (myInstance == null) myInstance = new OutputBox(); return myInstance; } @Override public void setEntity( Entity entity ) { currentEntity = entity; if (currentEntity == null) { setTitle("Output Viewer"); entries.clear(); return; } setTitle("Output Viewer - " + currentEntity.getName()); // Build up the row list, leaving extra rows for entity names Class<?> currClass = null; entries.clear(); ArrayList<OutputHandle> handles = OutputHandle.getOutputHandleList(currentEntity); for (OutputHandle h : handles) { Class<?> klass = h.getDeclaringClass(); if (currClass != klass) { // This is the first time we've seen this class, add a place holder row currClass = klass; entries.add(klass); } entries.add(h); } } @Override public void updateValues(double simTime) { if (tableModel == null) return; tableModel.simTime = simTime; tableModel.fireTableDataChanged(); } private synchronized static void killInstance() { myInstance = null; } @Override public void dispose() { killInstance(); super.dispose(); } private class OutputTable extends JTable { public OutputTable(TableModel model) { super(model); setDefaultRenderer(Object.class, colRenderer); getColumnModel().getColumn(0).setWidth(150); getColumnModel().getColumn(1).setWidth(100); this.getTableHeader().setFont(FrameBox.boldFont); this.getTableHeader().setReorderingAllowed(false); } @Override public String getToolTipText(MouseEvent event) { Point p = event.getPoint(); int row = rowAtPoint(p); int col = columnAtPoint(p); // Only the first column has tooltip if (col != 0) return null; if (currentEntity == null || row >= entries.size() || entries.get(row) instanceof Class) { return null; } OutputHandle output = (OutputHandle)entries.get(row); return GUIFrame.formatOutputToolTip(output.getName(), output.getDescription()); } @Override public Point getToolTipLocation(MouseEvent e) { int row = rowAtPoint(e.getPoint()); int y = getCellRect(row, 0, true).getLocation().y; return new Point(getColumnModel().getColumn(0).getWidth(), y); } @Override public void doLayout() { FrameBox.fitTableToLastColumn(this); } } private class OutputTableModel extends AbstractTableModel { double simTime = 0.0d; @Override public int getColumnCount() { return 2; } @Override public String getColumnName(int column) { switch (column) { case 0: return "Output"; case 1: return "Value"; } return "Unknown"; } @Override public int getRowCount() { return entries.size(); } @Override public Object getValueAt(int row, int col) { Object entry = entries.get(row); switch (col) { case 0: if (entry instanceof Class) return String.format("<HTML><B>%s</B></HTML>", ((Class<?>)entry).getSimpleName()); return String.format(" %s", ((OutputHandle)entry).getName()); case 1: if (entry instanceof Class) return ""; try { // Determine the preferred unit OutputHandle out = (OutputHandle)entry; Class<? extends Unit> ut = out.getUnitType(); double factor = Unit.getDisplayedUnitFactor(ut); // Select the appropriate format String fmt = "%s"; if (out.isNumericValue()) { if (out.isIntegerValue() && out.getUnitType() == DimensionlessUnit.class) { fmt = "%.0f"; } else { fmt = "%g"; } } // Evaluate the output StringBuilder sb = new StringBuilder(); sb.append(InputAgent.getValueAsString(out, simTime, fmt, factor)); // Append the appropriate unit if (ut != Unit.class && ut != DimensionlessUnit.class) { String unitString = Unit.getDisplayedUnit(ut); sb.append(Input.SEPARATOR).append(unitString); } return sb.toString(); } catch (Throwable e) { return "Cannot evaluate"; } default: assert false; return null; } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } } }
src/main/java/com/jaamsim/ui/OutputBox.java
/* * JaamSim Discrete Event Simulation * Copyright (C) 2013 Ausenco Engineering Canada Inc. * Copyright (C) 2019-2020 JaamSim Software 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.jaamsim.ui; import java.awt.Point; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import com.jaamsim.basicsim.Entity; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.OutputHandle; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.Unit; public class OutputBox extends FrameBox { private static OutputBox myInstance; private Entity currentEntity; OutputTableModel tableModel; private final ArrayList<Object> entries = new ArrayList<>(); public OutputBox() { super( "Output Viewer" ); setDefaultCloseOperation(FrameBox.DISPOSE_ON_CLOSE); addWindowListener(FrameBox.getCloseListener("ShowOutputViewer")); tableModel = new OutputTableModel(); OutputTable table = new OutputTable(tableModel); JScrollPane scrollPane = new JScrollPane(table); getContentPane().add( scrollPane ); addComponentListener(FrameBox.getSizePosAdapter(this, "OutputViewerSize", "OutputViewerPos")); } /** * Returns the only instance of the property box */ public synchronized static OutputBox getInstance() { if (myInstance == null) myInstance = new OutputBox(); return myInstance; } @Override public void setEntity( Entity entity ) { currentEntity = entity; if (currentEntity == null) { setTitle("Output Viewer"); entries.clear(); return; } setTitle("Output Viewer - " + currentEntity.getName()); // Build up the row list, leaving extra rows for entity names Class<?> currClass = null; entries.clear(); ArrayList<OutputHandle> handles = OutputHandle.getOutputHandleList(currentEntity); for (OutputHandle h : handles) { Class<?> klass = h.getDeclaringClass(); if (currClass != klass) { // This is the first time we've seen this class, add a place holder row currClass = klass; entries.add(klass); } entries.add(h); } } @Override public void updateValues(double simTime) { if (tableModel == null) return; tableModel.simTime = simTime; tableModel.fireTableDataChanged(); } private synchronized static void killInstance() { myInstance = null; } @Override public void dispose() { killInstance(); super.dispose(); } private class OutputTable extends JTable { public OutputTable(TableModel model) { super(model); setDefaultRenderer(Object.class, colRenderer); getColumnModel().getColumn(0).setWidth(150); getColumnModel().getColumn(1).setWidth(100); this.getTableHeader().setFont(FrameBox.boldFont); this.getTableHeader().setReorderingAllowed(false); } @Override public String getToolTipText(MouseEvent event) { Point p = event.getPoint(); int row = rowAtPoint(p); if (currentEntity == null || row >= entries.size() || entries.get(row) instanceof Class) { return null; } OutputHandle output = (OutputHandle)entries.get(row); return GUIFrame.formatOutputToolTip(output.getName(), output.getDescription()); } @Override public Point getToolTipLocation(MouseEvent e) { int row = rowAtPoint(e.getPoint()); int y = getCellRect(row, 0, true).getLocation().y; return new Point(getColumnModel().getColumn(0).getWidth(), y); } @Override public void doLayout() { FrameBox.fitTableToLastColumn(this); } } private class OutputTableModel extends AbstractTableModel { double simTime = 0.0d; @Override public int getColumnCount() { return 2; } @Override public String getColumnName(int column) { switch (column) { case 0: return "Output"; case 1: return "Value"; } return "Unknown"; } @Override public int getRowCount() { return entries.size(); } @Override public Object getValueAt(int row, int col) { Object entry = entries.get(row); switch (col) { case 0: if (entry instanceof Class) return String.format("<HTML><B>%s</B></HTML>", ((Class<?>)entry).getSimpleName()); return String.format(" %s", ((OutputHandle)entry).getName()); case 1: if (entry instanceof Class) return ""; try { // Determine the preferred unit OutputHandle out = (OutputHandle)entry; Class<? extends Unit> ut = out.getUnitType(); double factor = Unit.getDisplayedUnitFactor(ut); // Select the appropriate format String fmt = "%s"; if (out.isNumericValue()) { if (out.isIntegerValue() && out.getUnitType() == DimensionlessUnit.class) { fmt = "%.0f"; } else { fmt = "%g"; } } // Evaluate the output StringBuilder sb = new StringBuilder(); sb.append(InputAgent.getValueAsString(out, simTime, fmt, factor)); // Append the appropriate unit if (ut != Unit.class && ut != DimensionlessUnit.class) { String unitString = Unit.getDisplayedUnit(ut); sb.append(Input.SEPARATOR).append(unitString); } return sb.toString(); } catch (Throwable e) { return "Cannot evaluate"; } default: assert false; return null; } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } } }
JS: restrict OutputBox tooltips to the first column Signed-off-by: Harry King <[email protected]>
src/main/java/com/jaamsim/ui/OutputBox.java
JS: restrict OutputBox tooltips to the first column
<ide><path>rc/main/java/com/jaamsim/ui/OutputBox.java <ide> public String getToolTipText(MouseEvent event) { <ide> Point p = event.getPoint(); <ide> int row = rowAtPoint(p); <add> int col = columnAtPoint(p); <add> <add> // Only the first column has tooltip <add> if (col != 0) <add> return null; <add> <ide> if (currentEntity == null || <ide> row >= entries.size() || <ide> entries.get(row) instanceof Class) {
Java
bsd-3-clause
d422d8190e0a62752d4141837a38d17e79ccf01b
0
tinkerpop/blueprints,jwest-apigee/blueprints,joeyfreund/blueprints,iskytek/blueprints,nish5887/blueprints,maiklos-mirrors/tinkerpop_blueprints,datablend/blueprints,dmargo/blueprints-seas,qiangswa/blueprints,wmudge/blueprints,orientechnologies/blueprints,echinopsii/net.echinopsii.3rdparty.blueprints
package com.tinkerpop.blueprints.pgm; import com.tinkerpop.blueprints.pgm.impls.GraphTest; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.UUID; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class GraphTestSuite extends TestSuite { public GraphTestSuite() { } public GraphTestSuite(final GraphTest graphTest) { super(graphTest); } public void testEmptyOnConstruction() { Graph graph = graphTest.getGraphInstance(); if (graphTest.supportsVertexIteration) assertEquals(0, count(graph.getVertices())); if (graphTest.supportsEdgeIteration) assertEquals(0, count(graph.getEdges())); graph.shutdown(); } public void testStringRepresentation() { Graph graph = graphTest.getGraphInstance(); try { this.stopWatch(); assertNotNull(graph.toString()); printPerformance(graph.toString(), 1, "graph string representation generated", this.stopWatch()); } catch (Exception e) { assertFalse(true); } graph.shutdown(); } public void testClear() { Graph graph = graphTest.getGraphInstance(); this.stopWatch(); for (int i = 0; i < 25; i++) { Vertex a = graph.addVertex(null); Vertex b = graph.addVertex(null); graph.addEdge(null, a, b, convertId("knows")); } printPerformance(graph.toString(), 75, "elements added", this.stopWatch()); if (graphTest.supportsVertexIteration) assertEquals(50, count(graph.getVertices())); if (graphTest.supportsEdgeIteration) assertEquals(25, count(graph.getEdges())); this.stopWatch(); graph.clear(); printPerformance(graph.toString(), 75, "elements deleted", this.stopWatch()); if (graphTest.supportsVertexIteration) assertEquals(0, count(graph.getVertices())); if (graphTest.supportsEdgeIteration) assertEquals(0, count(graph.getEdges())); graph.shutdown(); } public void testAddingVerticesAndEdges() { Graph graph = graphTest.getGraphInstance(); Vertex a = graph.addVertex(null); Vertex b = graph.addVertex(null); Edge edge = graph.addEdge(null, a, b, convertId("knows")); if (graphTest.supportsEdgeIteration) { assertEquals(1, count(graph.getEdges())); } if (graphTest.supportsVertexIteration) { assertEquals(2, count(graph.getVertices())); } graph.removeVertex(a); if (graphTest.supportsEdgeIteration) { assertEquals(0, count(graph.getEdges())); } if (graphTest.supportsVertexIteration) { assertEquals(1, count(graph.getVertices())); } try { graph.removeEdge(edge); if (graphTest.supportsEdgeIteration) { assertEquals(0, count(graph.getEdges())); } if (graphTest.supportsVertexIteration) { assertEquals(1, count(graph.getVertices())); } } catch (Exception e) { assertTrue(true); } graph.shutdown(); } public void testSettingProperties() { Graph graph = graphTest.getGraphInstance(); Vertex a = graph.addVertex(null); Vertex b = graph.addVertex(null); graph.addEdge(null, a, b, "knows"); graph.addEdge(null, a, b, "knows"); for (Edge edge : b.getInEdges()) { edge.setProperty("key", "value"); } graph.shutdown(); } public void testRemovingEdges() { Graph graph = graphTest.getGraphInstance(); int vertexCount = 100; int edgeCount = 200; List<Vertex> vertices = new ArrayList<Vertex>(); List<Edge> edges = new ArrayList<Edge>(); Random random = new Random(); this.stopWatch(); for (int i = 0; i < vertexCount; i++) { vertices.add(graph.addVertex(null)); } printPerformance(graph.toString(), vertexCount, "vertices added", this.stopWatch()); this.stopWatch(); for (int i = 0; i < edgeCount; i++) { Vertex a = vertices.get(random.nextInt(vertices.size())); Vertex b = vertices.get(random.nextInt(vertices.size())); if (a != b) { edges.add(graph.addEdge(null, a, b, convertId("a" + UUID.randomUUID()))); } } printPerformance(graph.toString(), edgeCount, "edges added", this.stopWatch()); this.stopWatch(); int counter = 0; for (Edge e : edges) { counter = counter + 1; graph.removeEdge(e); if (graphTest.supportsEdgeIteration) { assertEquals(edges.size() - counter, count(graph.getEdges())); } if (graphTest.supportsVertexIteration) { assertEquals(vertices.size(), count(graph.getVertices())); } } printPerformance(graph.toString(), edgeCount, "edges deleted (with size check on each delete)", this.stopWatch()); graph.shutdown(); } public void testRemovingVertices() { Graph graph = graphTest.getGraphInstance(); int vertexCount = 500; List<Vertex> vertices = new ArrayList<Vertex>(); List<Edge> edges = new ArrayList<Edge>(); this.stopWatch(); for (int i = 0; i < vertexCount; i++) { vertices.add(graph.addVertex(null)); } printPerformance(graph.toString(), vertexCount, "vertices added", this.stopWatch()); this.stopWatch(); for (int i = 0; i < vertexCount; i = i + 2) { Vertex a = vertices.get(i); Vertex b = vertices.get(i + 1); edges.add(graph.addEdge(null, a, b, convertId("a" + UUID.randomUUID()))); } printPerformance(graph.toString(), vertexCount / 2, "edges added", this.stopWatch()); this.stopWatch(); int counter = 0; for (Vertex v : vertices) { counter = counter + 1; graph.removeVertex(v); if (counter + 1 % 2 == 0) { if (graphTest.supportsEdgeIteration) { assertEquals(edges.size() - counter, count(graph.getEdges())); } } if (graphTest.supportsVertexIteration) { assertEquals(vertices.size() - counter, count(graph.getVertices())); } } printPerformance(graph.toString(), vertexCount, "vertices deleted (with size check on each delete)", this.stopWatch()); graph.shutdown(); } public void testConnectivityPatterns() { Graph graph = graphTest.getGraphInstance(); List<String> ids = generateIds(4); Vertex a = graph.addVertex(convertId(ids.get(0))); Vertex b = graph.addVertex(convertId(ids.get(1))); Vertex c = graph.addVertex(convertId(ids.get(2))); Vertex d = graph.addVertex(convertId(ids.get(3))); if (graphTest.supportsVertexIteration) assertEquals(4, count(graph.getVertices())); Edge e = graph.addEdge(null, a, b, convertId("knows")); Edge f = graph.addEdge(null, b, c, convertId("knows")); Edge g = graph.addEdge(null, c, d, convertId("knows")); Edge h = graph.addEdge(null, d, a, convertId("knows")); if (graphTest.supportsEdgeIteration) assertEquals(4, count(graph.getEdges())); if (graphTest.supportsVertexIteration) { for (Vertex v : graph.getVertices()) { assertEquals(1, count(v.getOutEdges())); assertEquals(1, count(v.getInEdges())); } } if (graphTest.supportsEdgeIteration) { for (Edge x : graph.getEdges()) { assertEquals(convertId("knows"), x.getLabel()); } } if (!graphTest.ignoresSuppliedIds) { a = graph.getVertex(convertId(ids.get(0))); b = graph.getVertex(convertId(ids.get(1))); c = graph.getVertex(convertId(ids.get(2))); d = graph.getVertex(convertId(ids.get(3))); assertEquals(1, count(a.getInEdges())); assertEquals(1, count(a.getOutEdges())); assertEquals(1, count(b.getInEdges())); assertEquals(1, count(b.getOutEdges())); assertEquals(1, count(c.getInEdges())); assertEquals(1, count(c.getOutEdges())); assertEquals(1, count(d.getInEdges())); assertEquals(1, count(d.getOutEdges())); Edge i = graph.addEdge(null, a, b, convertId("hates")); assertEquals(1, count(a.getInEdges())); assertEquals(2, count(a.getOutEdges())); assertEquals(2, count(b.getInEdges())); assertEquals(1, count(b.getOutEdges())); assertEquals(1, count(c.getInEdges())); assertEquals(1, count(c.getOutEdges())); assertEquals(1, count(d.getInEdges())); assertEquals(1, count(d.getOutEdges())); assertEquals(1, count(a.getInEdges())); assertEquals(2, count(a.getOutEdges())); for (Edge x : a.getOutEdges()) { assertTrue(x.getLabel().equals(convertId("knows")) || x.getLabel().equals(convertId("hates"))); } assertEquals(convertId("hates"), i.getLabel()); assertEquals(i.getInVertex().getId().toString(), convertId(ids.get(1))); assertEquals(i.getOutVertex().getId().toString(), convertId(ids.get(0))); } Set<Object> vertexIds = new HashSet<Object>(); vertexIds.add(a.getId()); vertexIds.add(a.getId()); vertexIds.add(b.getId()); vertexIds.add(b.getId()); vertexIds.add(c.getId()); vertexIds.add(d.getId()); vertexIds.add(d.getId()); vertexIds.add(d.getId()); assertEquals(4, vertexIds.size()); graph.shutdown(); } public void testVertexEdgeLabels() { Graph graph = graphTest.getGraphInstance(); Vertex a = graph.addVertex(null); Vertex b = graph.addVertex(null); Vertex c = graph.addVertex(null); Edge aFriendB = graph.addEdge(null, a, b, convertId("friend")); Edge aFriendC = graph.addEdge(null, a, c, convertId("friend")); Edge aHateC = graph.addEdge(null, a, c, convertId("hate")); Edge cHateA = graph.addEdge(null, c, a, convertId("hate")); Edge cHateB = graph.addEdge(null, c, b, convertId("hate")); List<Edge> results = asList(a.getOutEdges()); assertEquals(results.size(), 3); assertTrue(results.contains(aFriendB)); assertTrue(results.contains(aFriendC)); assertTrue(results.contains(aHateC)); results = asList(a.getOutEdges(convertId("friend"))); assertEquals(results.size(), 2); assertTrue(results.contains(aFriendB)); assertTrue(results.contains(aFriendC)); results = asList(a.getOutEdges(convertId("hate"))); assertEquals(results.size(), 1); assertTrue(results.contains(aHateC)); results = asList(a.getInEdges(convertId("hate"))); assertEquals(results.size(), 1); assertTrue(results.contains(cHateA)); results = asList(a.getInEdges(convertId("friend"))); assertEquals(results.size(), 0); results = asList(b.getInEdges(convertId("hate"))); assertEquals(results.size(), 1); assertTrue(results.contains(cHateB)); results = asList(b.getInEdges(convertId("friend"))); assertEquals(results.size(), 1); assertTrue(results.contains(aFriendB)); graph.shutdown(); } public void testTreeConnectivity() { Graph graph = graphTest.getGraphInstance(); this.stopWatch(); int branchSize = 11; Vertex start = graph.addVertex(null); for (int i = 0; i < branchSize; i++) { Vertex a = graph.addVertex(null); graph.addEdge(null, start, a, convertId("test1")); for (int j = 0; j < branchSize; j++) { Vertex b = graph.addVertex(null); graph.addEdge(null, a, b, convertId("test2")); for (int k = 0; k < branchSize; k++) { Vertex c = graph.addVertex(null); graph.addEdge(null, b, c, convertId("test3")); } } } assertEquals(0, count(start.getInEdges())); assertEquals(branchSize, count(start.getOutEdges())); for (Edge e : start.getOutEdges()) { assertEquals(convertId("test1"), e.getLabel()); assertEquals(branchSize, count(e.getInVertex().getOutEdges())); assertEquals(1, count(e.getInVertex().getInEdges())); for (Edge f : e.getInVertex().getOutEdges()) { assertEquals(convertId("test2"), f.getLabel()); assertEquals(branchSize, count(f.getInVertex().getOutEdges())); assertEquals(1, count(f.getInVertex().getInEdges())); for (Edge g : f.getInVertex().getOutEdges()) { assertEquals(convertId("test3"), g.getLabel()); assertEquals(0, count(g.getInVertex().getOutEdges())); assertEquals(1, count(g.getInVertex().getInEdges())); } } } int totalVertices = 0; for (int i = 0; i < 4; i++) { totalVertices = totalVertices + (int) Math.pow(branchSize, i); } printPerformance(graph.toString(), totalVertices, "vertices added in a tree structure", this.stopWatch()); if (graphTest.supportsVertexIteration) { this.stopWatch(); Set<Vertex> vertices = new HashSet<Vertex>(); for (Vertex v : graph.getVertices()) { vertices.add(v); } assertEquals(totalVertices, vertices.size()); printPerformance(graph.toString(), totalVertices, "vertices iterated", this.stopWatch()); } if (graphTest.supportsEdgeIteration) { this.stopWatch(); Set<Edge> edges = new HashSet<Edge>(); for (Edge e : graph.getEdges()) { edges.add(e); } assertEquals(totalVertices - 1, edges.size()); printPerformance(graph.toString(), totalVertices - 1, "edges iterated", this.stopWatch()); } graph.shutdown(); } public void testGraphDataPersists() { if (graphTest.isPersistent) { Graph graph = graphTest.getGraphInstance(); Vertex v = graph.addVertex(null); Vertex u = graph.addVertex(null); if (!graphTest.isRDFModel) { v.setProperty("name", "marko"); u.setProperty("name", "pavel"); } Edge e = graph.addEdge(null, v, u, convertId("collaborator")); if (!graphTest.isRDFModel) e.setProperty("location", "internet"); if (graphTest.supportsVertexIteration) { assertEquals(count(graph.getVertices()), 2); } if (graphTest.supportsEdgeIteration) { assertEquals(count(graph.getEdges()), 1); } graph.shutdown(); this.stopWatch(); graph = graphTest.getGraphInstance(); printPerformance(graph.toString(), 1, "graph loaded", this.stopWatch()); if (graphTest.supportsVertexIteration) { assertEquals(count(graph.getVertices()), 2); if (!graphTest.isRDFModel) { for (Vertex vertex : graph.getVertices()) { assertTrue(vertex.getProperty("name").equals("marko") || vertex.getProperty("name").equals("pavel")); } } } if (graphTest.supportsEdgeIteration) { assertEquals(count(graph.getEdges()), 1); for (Edge edge : graph.getEdges()) { assertEquals(edge.getLabel(), convertId("collaborator")); if (!graphTest.isRDFModel) assertEquals(edge.getProperty("location"), "internet"); } } graph.shutdown(); } } }
blueprints-test/src/main/java/com/tinkerpop/blueprints/pgm/GraphTestSuite.java
package com.tinkerpop.blueprints.pgm; import com.tinkerpop.blueprints.BaseTest; import com.tinkerpop.blueprints.pgm.impls.GraphTest; import java.util.*; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class GraphTestSuite extends TestSuite { public GraphTestSuite() { } public GraphTestSuite(final GraphTest graphTest) { super(graphTest); } public void testEmptyOnConstruction() { Graph graph = graphTest.getGraphInstance(); if (graphTest.supportsVertexIteration) assertEquals(0, count(graph.getVertices())); if (graphTest.supportsEdgeIteration) assertEquals(0, count(graph.getEdges())); graph.shutdown(); } public void testStringRepresentation() { Graph graph = graphTest.getGraphInstance(); try { this.stopWatch(); assertNotNull(graph.toString()); printPerformance(graph.toString(), 1, "graph string representation generated", this.stopWatch()); } catch (Exception e) { assertFalse(true); } graph.shutdown(); } public void testClear() { Graph graph = graphTest.getGraphInstance(); this.stopWatch(); for (int i = 0; i < 25; i++) { Vertex a = graph.addVertex(null); Vertex b = graph.addVertex(null); graph.addEdge(null, a, b, convertId("knows")); } printPerformance(graph.toString(), 75, "elements added", this.stopWatch()); if (graphTest.supportsVertexIteration) assertEquals(50, count(graph.getVertices())); if (graphTest.supportsEdgeIteration) assertEquals(25, count(graph.getEdges())); this.stopWatch(); graph.clear(); printPerformance(graph.toString(), 75, "elements deleted", this.stopWatch()); if (graphTest.supportsVertexIteration) assertEquals(0, count(graph.getVertices())); if (graphTest.supportsEdgeIteration) assertEquals(0, count(graph.getEdges())); graph.shutdown(); } public void testAddingVerticesAndEdges() { Graph graph = graphTest.getGraphInstance(); Vertex a = graph.addVertex(null); Vertex b = graph.addVertex(null); Edge edge = graph.addEdge(null, a, b, convertId("knows")); if (graphTest.supportsEdgeIteration) { assertEquals(1, count(graph.getEdges())); } if (graphTest.supportsVertexIteration) { assertEquals(2, count(graph.getVertices())); } graph.removeVertex(a); if (graphTest.supportsEdgeIteration) { assertEquals(0, count(graph.getEdges())); } if (graphTest.supportsVertexIteration) { assertEquals(1, count(graph.getVertices())); } try { graph.removeEdge(edge); if (graphTest.supportsEdgeIteration) { assertEquals(0, count(graph.getEdges())); } if (graphTest.supportsVertexIteration) { assertEquals(1, count(graph.getVertices())); } } catch (Exception e) { assertTrue(true); } graph.shutdown(); } public void testRemovingEdges() { Graph graph = graphTest.getGraphInstance(); int vertexCount = 100; int edgeCount = 200; List<Vertex> vertices = new ArrayList<Vertex>(); List<Edge> edges = new ArrayList<Edge>(); Random random = new Random(); this.stopWatch(); for (int i = 0; i < vertexCount; i++) { vertices.add(graph.addVertex(null)); } printPerformance(graph.toString(), vertexCount, "vertices added", this.stopWatch()); this.stopWatch(); for (int i = 0; i < edgeCount; i++) { Vertex a = vertices.get(random.nextInt(vertices.size())); Vertex b = vertices.get(random.nextInt(vertices.size())); if (a != b) { edges.add(graph.addEdge(null, a, b, convertId("a" + UUID.randomUUID()))); } } printPerformance(graph.toString(), edgeCount, "edges added", this.stopWatch()); this.stopWatch(); int counter = 0; for (Edge e : edges) { counter = counter + 1; graph.removeEdge(e); if (graphTest.supportsEdgeIteration) { assertEquals(edges.size() - counter, count(graph.getEdges())); } if (graphTest.supportsVertexIteration) { assertEquals(vertices.size(), count(graph.getVertices())); } } printPerformance(graph.toString(), edgeCount, "edges deleted (with size check on each delete)", this.stopWatch()); graph.shutdown(); } public void testRemovingVertices() { Graph graph = graphTest.getGraphInstance(); int vertexCount = 500; List<Vertex> vertices = new ArrayList<Vertex>(); List<Edge> edges = new ArrayList<Edge>(); this.stopWatch(); for (int i = 0; i < vertexCount; i++) { vertices.add(graph.addVertex(null)); } printPerformance(graph.toString(), vertexCount, "vertices added", this.stopWatch()); this.stopWatch(); for (int i = 0; i < vertexCount; i = i + 2) { Vertex a = vertices.get(i); Vertex b = vertices.get(i + 1); edges.add(graph.addEdge(null, a, b, convertId("a" + UUID.randomUUID()))); } printPerformance(graph.toString(), vertexCount / 2, "edges added", this.stopWatch()); this.stopWatch(); int counter = 0; for (Vertex v : vertices) { counter = counter + 1; graph.removeVertex(v); if (counter + 1 % 2 == 0) { if (graphTest.supportsEdgeIteration) { assertEquals(edges.size() - counter, count(graph.getEdges())); } } if (graphTest.supportsVertexIteration) { assertEquals(vertices.size() - counter, count(graph.getVertices())); } } printPerformance(graph.toString(), vertexCount, "vertices deleted (with size check on each delete)", this.stopWatch()); graph.shutdown(); } public void testConnectivityPatterns() { Graph graph = graphTest.getGraphInstance(); List<String> ids = generateIds(4); Vertex a = graph.addVertex(convertId(ids.get(0))); Vertex b = graph.addVertex(convertId(ids.get(1))); Vertex c = graph.addVertex(convertId(ids.get(2))); Vertex d = graph.addVertex(convertId(ids.get(3))); if (graphTest.supportsVertexIteration) assertEquals(4, count(graph.getVertices())); Edge e = graph.addEdge(null, a, b, convertId("knows")); Edge f = graph.addEdge(null, b, c, convertId("knows")); Edge g = graph.addEdge(null, c, d, convertId("knows")); Edge h = graph.addEdge(null, d, a, convertId("knows")); if (graphTest.supportsEdgeIteration) assertEquals(4, count(graph.getEdges())); if (graphTest.supportsVertexIteration) { for (Vertex v : graph.getVertices()) { assertEquals(1, count(v.getOutEdges())); assertEquals(1, count(v.getInEdges())); } } if (graphTest.supportsEdgeIteration) { for (Edge x : graph.getEdges()) { assertEquals(convertId("knows"), x.getLabel()); } } if (!graphTest.ignoresSuppliedIds) { a = graph.getVertex(convertId(ids.get(0))); b = graph.getVertex(convertId(ids.get(1))); c = graph.getVertex(convertId(ids.get(2))); d = graph.getVertex(convertId(ids.get(3))); assertEquals(1, count(a.getInEdges())); assertEquals(1, count(a.getOutEdges())); assertEquals(1, count(b.getInEdges())); assertEquals(1, count(b.getOutEdges())); assertEquals(1, count(c.getInEdges())); assertEquals(1, count(c.getOutEdges())); assertEquals(1, count(d.getInEdges())); assertEquals(1, count(d.getOutEdges())); Edge i = graph.addEdge(null, a, b, convertId("hates")); assertEquals(1, count(a.getInEdges())); assertEquals(2, count(a.getOutEdges())); assertEquals(2, count(b.getInEdges())); assertEquals(1, count(b.getOutEdges())); assertEquals(1, count(c.getInEdges())); assertEquals(1, count(c.getOutEdges())); assertEquals(1, count(d.getInEdges())); assertEquals(1, count(d.getOutEdges())); assertEquals(1, count(a.getInEdges())); assertEquals(2, count(a.getOutEdges())); for (Edge x : a.getOutEdges()) { assertTrue(x.getLabel().equals(convertId("knows")) || x.getLabel().equals(convertId("hates"))); } assertEquals(convertId("hates"), i.getLabel()); assertEquals(i.getInVertex().getId().toString(), convertId(ids.get(1))); assertEquals(i.getOutVertex().getId().toString(), convertId(ids.get(0))); } Set<Object> vertexIds = new HashSet<Object>(); vertexIds.add(a.getId()); vertexIds.add(a.getId()); vertexIds.add(b.getId()); vertexIds.add(b.getId()); vertexIds.add(c.getId()); vertexIds.add(d.getId()); vertexIds.add(d.getId()); vertexIds.add(d.getId()); assertEquals(4, vertexIds.size()); graph.shutdown(); } public void testVertexEdgeLabels() { Graph graph = graphTest.getGraphInstance(); Vertex a = graph.addVertex(null); Vertex b = graph.addVertex(null); Vertex c = graph.addVertex(null); Edge aFriendB = graph.addEdge(null, a, b, convertId("friend")); Edge aFriendC = graph.addEdge(null, a, c, convertId("friend")); Edge aHateC = graph.addEdge(null, a, c, convertId("hate")); Edge cHateA = graph.addEdge(null, c, a, convertId("hate")); Edge cHateB = graph.addEdge(null, c, b, convertId("hate")); List<Edge> results = asList(a.getOutEdges()); assertEquals(results.size(), 3); assertTrue(results.contains(aFriendB)); assertTrue(results.contains(aFriendC)); assertTrue(results.contains(aHateC)); results = asList(a.getOutEdges(convertId("friend"))); assertEquals(results.size(), 2); assertTrue(results.contains(aFriendB)); assertTrue(results.contains(aFriendC)); results = asList(a.getOutEdges(convertId("hate"))); assertEquals(results.size(), 1); assertTrue(results.contains(aHateC)); results = asList(a.getInEdges(convertId("hate"))); assertEquals(results.size(), 1); assertTrue(results.contains(cHateA)); results = asList(a.getInEdges(convertId("friend"))); assertEquals(results.size(), 0); results = asList(b.getInEdges(convertId("hate"))); assertEquals(results.size(), 1); assertTrue(results.contains(cHateB)); results = asList(b.getInEdges(convertId("friend"))); assertEquals(results.size(), 1); assertTrue(results.contains(aFriendB)); graph.shutdown(); } public void testTreeConnectivity() { Graph graph = graphTest.getGraphInstance(); this.stopWatch(); int branchSize = 11; Vertex start = graph.addVertex(null); for (int i = 0; i < branchSize; i++) { Vertex a = graph.addVertex(null); graph.addEdge(null, start, a, convertId("test1")); for (int j = 0; j < branchSize; j++) { Vertex b = graph.addVertex(null); graph.addEdge(null, a, b, convertId("test2")); for (int k = 0; k < branchSize; k++) { Vertex c = graph.addVertex(null); graph.addEdge(null, b, c, convertId("test3")); } } } assertEquals(0, count(start.getInEdges())); assertEquals(branchSize, count(start.getOutEdges())); for (Edge e : start.getOutEdges()) { assertEquals(convertId("test1"), e.getLabel()); assertEquals(branchSize, count(e.getInVertex().getOutEdges())); assertEquals(1, count(e.getInVertex().getInEdges())); for (Edge f : e.getInVertex().getOutEdges()) { assertEquals(convertId("test2"), f.getLabel()); assertEquals(branchSize, count(f.getInVertex().getOutEdges())); assertEquals(1, count(f.getInVertex().getInEdges())); for (Edge g : f.getInVertex().getOutEdges()) { assertEquals(convertId("test3"), g.getLabel()); assertEquals(0, count(g.getInVertex().getOutEdges())); assertEquals(1, count(g.getInVertex().getInEdges())); } } } int totalVertices = 0; for (int i = 0; i < 4; i++) { totalVertices = totalVertices + (int) Math.pow(branchSize, i); } printPerformance(graph.toString(), totalVertices, "vertices added in a tree structure", this.stopWatch()); if (graphTest.supportsVertexIteration) { this.stopWatch(); Set<Vertex> vertices = new HashSet<Vertex>(); for (Vertex v : graph.getVertices()) { vertices.add(v); } assertEquals(totalVertices, vertices.size()); printPerformance(graph.toString(), totalVertices, "vertices iterated", this.stopWatch()); } if (graphTest.supportsEdgeIteration) { this.stopWatch(); Set<Edge> edges = new HashSet<Edge>(); for (Edge e : graph.getEdges()) { edges.add(e); } assertEquals(totalVertices - 1, edges.size()); printPerformance(graph.toString(), totalVertices - 1, "edges iterated", this.stopWatch()); } graph.shutdown(); } public void testGraphDataPersists() { if (graphTest.isPersistent) { Graph graph = graphTest.getGraphInstance(); Vertex v = graph.addVertex(null); Vertex u = graph.addVertex(null); if (!graphTest.isRDFModel) { v.setProperty("name", "marko"); u.setProperty("name", "pavel"); } Edge e = graph.addEdge(null, v, u, convertId("collaborator")); if (!graphTest.isRDFModel) e.setProperty("location", "internet"); if (graphTest.supportsVertexIteration) { assertEquals(count(graph.getVertices()), 2); } if (graphTest.supportsEdgeIteration) { assertEquals(count(graph.getEdges()), 1); } graph.shutdown(); this.stopWatch(); graph = graphTest.getGraphInstance(); printPerformance(graph.toString(), 1, "graph loaded", this.stopWatch()); if (graphTest.supportsVertexIteration) { assertEquals(count(graph.getVertices()), 2); if (!graphTest.isRDFModel) { for (Vertex vertex : graph.getVertices()) { assertTrue(vertex.getProperty("name").equals("marko") || vertex.getProperty("name").equals("pavel")); } } } if (graphTest.supportsEdgeIteration) { assertEquals(count(graph.getEdges()), 1); for (Edge edge : graph.getEdges()) { assertEquals(edge.getLabel(), convertId("collaborator")); if (!graphTest.isRDFModel) assertEquals(edge.getProperty("location"), "internet"); } } graph.shutdown(); } } }
ensured that properties can be set during edge iteration.
blueprints-test/src/main/java/com/tinkerpop/blueprints/pgm/GraphTestSuite.java
ensured that properties can be set during edge iteration.
<ide><path>lueprints-test/src/main/java/com/tinkerpop/blueprints/pgm/GraphTestSuite.java <ide> package com.tinkerpop.blueprints.pgm; <ide> <del>import com.tinkerpop.blueprints.BaseTest; <ide> import com.tinkerpop.blueprints.pgm.impls.GraphTest; <ide> <del>import java.util.*; <add>import java.util.ArrayList; <add>import java.util.HashSet; <add>import java.util.List; <add>import java.util.Random; <add>import java.util.Set; <add>import java.util.UUID; <ide> <ide> <ide> /** <ide> } <ide> } catch (Exception e) { <ide> assertTrue(true); <add> } <add> <add> graph.shutdown(); <add> } <add> <add> public void testSettingProperties() { <add> Graph graph = graphTest.getGraphInstance(); <add> Vertex a = graph.addVertex(null); <add> Vertex b = graph.addVertex(null); <add> graph.addEdge(null, a, b, "knows"); <add> graph.addEdge(null, a, b, "knows"); <add> for (Edge edge : b.getInEdges()) { <add> edge.setProperty("key", "value"); <ide> } <ide> graph.shutdown(); <ide> }
Java
apache-2.0
ee4a962f6998815a29459c79e0e0dddcb013d2fc
0
soul2zimate/undertow,baranowb/undertow,stuartwdouglas/undertow,ctomc/undertow,aldaris/undertow,golovnin/undertow,darranl/undertow,jamezp/undertow,soul2zimate/undertow,rhusar/undertow,soul2zimate/undertow,Karm/undertow,darranl/undertow,pferraro/undertow,Karm/undertow,rhusar/undertow,aldaris/undertow,golovnin/undertow,stuartwdouglas/undertow,Karm/undertow,jstourac/undertow,golovnin/undertow,aldaris/undertow,baranowb/undertow,ctomc/undertow,ctomc/undertow,undertow-io/undertow,darranl/undertow,jstourac/undertow,jstourac/undertow,stuartwdouglas/undertow,pferraro/undertow,jamezp/undertow,undertow-io/undertow,pferraro/undertow,undertow-io/undertow,jamezp/undertow,baranowb/undertow,rhusar/undertow
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.ClosedChannelException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLPeerUnverifiedException; import org.jboss.logging.Messages; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import io.undertow.predicate.PredicateBuilder; import io.undertow.protocols.http2.HpackException; import io.undertow.security.api.AuthenticationMechanism; import io.undertow.server.handlers.builder.HandlerBuilder; import io.undertow.util.HttpString; import io.undertow.util.ParameterLimitException; import io.undertow.util.BadRequestException; /** * @author Stuart Douglas */ @MessageBundle(projectCode = "UT") public interface UndertowMessages { UndertowMessages MESSAGES = Messages.getBundle(UndertowMessages.class); @Message(id = 1, value = "Maximum concurrent requests must be larger than zero.") IllegalArgumentException maximumConcurrentRequestsMustBeLargerThanZero(); @Message(id = 2, value = "The response has already been started") IllegalStateException responseAlreadyStarted(); // id = 3 @Message(id = 4, value = "getResponseChannel() has already been called") IllegalStateException responseChannelAlreadyProvided(); @Message(id = 5, value = "getRequestChannel() has already been called") IllegalStateException requestChannelAlreadyProvided(); // id = 6 // id = 7 @Message(id = 8, value = "Handler cannot be null") IllegalArgumentException handlerCannotBeNull(); @Message(id = 9, value = "Path must be specified") IllegalArgumentException pathMustBeSpecified(); @Message(id = 10, value = "Session is invalid %s") IllegalStateException sessionIsInvalid(String sessionId); @Message(id = 11, value = "Session manager must not be null") IllegalStateException sessionManagerMustNotBeNull(); @Message(id = 12, value = "Session manager was not attached to the request. Make sure that the SessionAttachmentHandler is installed in the handler chain") IllegalStateException sessionManagerNotFound(); @Message(id = 13, value = "Argument %s cannot be null") IllegalArgumentException argumentCannotBeNull(final String argument); @Message(id = 14, value = "close() called with data still to be flushed. Please call shutdownWrites() and then call flush() until it returns true before calling close()") IOException closeCalledWithDataStillToBeFlushed(); @Message(id = 16, value = "Could not add cookie as cookie handler was not present in the handler chain") IllegalStateException cookieHandlerNotPresent(); @Message(id = 17, value = "Form value is a file, use getFile() instead") IllegalStateException formValueIsAFile(); @Message(id = 18, value = "Form value is a String, use getValue() instead") IllegalStateException formValueIsAString(); @Message(id = 19, value = "Connection from %s terminated as request entity was larger than %s") IOException requestEntityWasTooLarge(SocketAddress address, long size); @Message(id = 20, value = "Connection terminated as request was larger than %s") IOException requestEntityWasTooLarge(long size); @Message(id = 21, value = "Session already invalidated") IllegalStateException sessionAlreadyInvalidated(); @Message(id = 22, value = "The specified hash algorithm '%s' can not be found.") IllegalArgumentException hashAlgorithmNotFound(String algorithmName); @Message(id = 23, value = "An invalid Base64 token has been received.") IllegalArgumentException invalidBase64Token(@Cause final IOException cause); @Message(id = 24, value = "An invalidly formatted nonce has been received.") IllegalArgumentException invalidNonceReceived(); @Message(id = 25, value = "Unexpected token '%s' within header.") IllegalArgumentException unexpectedTokenInHeader(final String name); @Message(id = 26, value = "Invalid header received.") IllegalArgumentException invalidHeader(); @Message(id = 27, value = "Could not find session cookie config in the request") IllegalStateException couldNotFindSessionCookieConfig(); @Message(id = 28, value = "Session %s already exists") IllegalStateException sessionAlreadyExists(final String id); @Message(id = 29, value = "Channel was closed mid chunk, if you have attempted to write chunked data you cannot shutdown the channel until after it has all been written.") IOException chunkedChannelClosedMidChunk(); @Message(id = 30, value = "User %s successfully authenticated.") String userAuthenticated(final String userName); @Message(id = 31, value = "User %s has logged out.") String userLoggedOut(final String userName); @Message(id = 33, value = "Authentication type %s cannot be combined with %s") IllegalStateException authTypeCannotBeCombined(String type, String existing); @Message(id = 34, value = "Stream is closed") IOException streamIsClosed(); @Message(id = 35, value = "Cannot get stream as startBlocking has not been invoked") IllegalStateException startBlockingHasNotBeenCalled(); @Message(id = 36, value = "Connection terminated parsing multipart data") IOException connectionTerminatedReadingMultiPartData(); @Message(id = 37, value = "Failed to parse path in HTTP request") RuntimeException failedToParsePath(); @Message(id = 38, value = "Authentication failed, requested user name '%s'") String authenticationFailed(final String userName); @Message(id = 39, value = "Too many query parameters, cannot have more than %s query parameters") BadRequestException tooManyQueryParameters(int noParams); @Message(id = 40, value = "Too many headers, cannot have more than %s header") String tooManyHeaders(int noParams); @Message(id = 41, value = "Channel is closed") ClosedChannelException channelIsClosed(); @Message(id = 42, value = "Could not decode trailers in HTTP request") IOException couldNotDecodeTrailers(); @Message(id = 43, value = "Data is already being sent. You must wait for the completion callback to be be invoked before calling send() again") IllegalStateException dataAlreadyQueued(); @Message(id = 44, value = "More than one predicate with name %s. Builder class %s and %s") IllegalStateException moreThanOnePredicateWithName(String name, Class<? extends PredicateBuilder> aClass, Class<? extends PredicateBuilder> existing); @Message(id = 45, value = "Error parsing predicated handler string %s:%n%s") IllegalArgumentException errorParsingPredicateString(String reason, String s); @Message(id = 46, value = "The number of cookies sent exceeded the maximum of %s") IllegalStateException tooManyCookies(int maxCookies); @Message(id = 47, value = "The number of parameters exceeded the maximum of %s") ParameterLimitException tooManyParameters(int maxValues); @Message(id = 48, value = "No request is currently active") IllegalStateException noRequestActive(); @Message(id = 50, value = "AuthenticationMechanism Outcome is null") IllegalStateException authMechanismOutcomeNull(); @Message(id = 51, value = "Not a valid IP pattern %s") IllegalArgumentException notAValidIpPattern(String peer); @Message(id = 52, value = "Session data requested when non session based authentication in use") IllegalStateException noSessionData(); @Message(id = 53, value = "Listener %s already registered") IllegalArgumentException listenerAlreadyRegistered(String name); @Message(id = 54, value = "The maximum size %s for an individual file in a multipart request was exceeded") IOException maxFileSizeExceeded(long maxIndividualFileSize); @Message(id = 55, value = "Could not set attribute %s to %s as it is read only") String couldNotSetAttribute(String attributeName, String newValue); @Message(id = 56, value = "Could not parse URI template %s, exception at char %s") RuntimeException couldNotParseUriTemplate(String path, int i); @Message(id = 57, value = "Mismatched braces in attribute string %s") RuntimeException mismatchedBraces(String valueString); @Message(id = 58, value = "More than one handler with name %s. Builder class %s and %s") IllegalStateException moreThanOneHandlerWithName(String name, Class<? extends HandlerBuilder> aClass, Class<? extends HandlerBuilder> existing); @Message(id = 59, value = "Invalid syntax %s") IllegalArgumentException invalidSyntax(String line); @Message(id = 60, value = "Error parsing handler string %s:%n%s") IllegalArgumentException errorParsingHandlerString(String reason, String s); @Message(id = 61, value = "Out of band responses only allowed for 100-continue requests") IllegalArgumentException outOfBandResponseOnlyAllowedFor100Continue(); @Message(id = 62, value = "AJP does not support HTTP upgrade") IllegalStateException ajpDoesNotSupportHTTPUpgrade(); @Message(id = 63, value = "File system watcher already started") IllegalStateException fileSystemWatcherAlreadyStarted(); @Message(id = 64, value = "File system watcher not started") IllegalStateException fileSystemWatcherNotStarted(); @Message(id = 65, value = "SSL must be specified to connect to a https URL") IOException sslWasNull(); @Message(id = 66, value = "Incorrect magic number %s for AJP packet header") IOException wrongMagicNumber(int number); @Message(id = 67, value = "No client cert was provided") SSLPeerUnverifiedException peerUnverified(); @Message(id = 68, value = "Servlet path match failed") IllegalArgumentException servletPathMatchFailed(); @Message(id = 69, value = "Could not parse set cookie header %s") IllegalArgumentException couldNotParseCookie(String headerValue); @Message(id = 70, value = "method can only be called by IO thread") IllegalStateException canOnlyBeCalledByIoThread(); @Message(id = 71, value = "Cannot add path template %s, matcher already contains an equivalent pattern %s") IllegalStateException matcherAlreadyContainsTemplate(String templateString, String templateString1); @Message(id = 72, value = "Failed to decode url %s to charset %s") IllegalArgumentException failedToDecodeURL(String s, String enc, @Cause Exception e); @Message(id = 73, value = "Resource change listeners are not supported") IllegalArgumentException resourceChangeListenerNotSupported(); @Message(id = 74, value = "Could not renegotiate SSL connection to require client certificate, as client had sent more data") IllegalStateException couldNotRenegotiate(); @Message(id = 75, value = "Object was freed") IllegalStateException objectWasFreed(); @Message(id = 76, value = "Handler not shutdown") IllegalStateException handlerNotShutdown(); @Message(id = 77, value = "The underlying transport does not support HTTP upgrade") IllegalStateException upgradeNotSupported(); @Message(id = 78, value = "Renegotiation not supported") IOException renegotiationNotSupported(); @Message(id = 79, value = "Not a valid user agent pattern %s") IllegalArgumentException notAValidUserAgentPattern(String userAgent); @Message(id = 80, value = "Not a valid regular expression pattern %s") IllegalArgumentException notAValidRegularExpressionPattern(String pattern); @Message(id = 81, value = "Bad request") BadRequestException badRequest(); @Message(id = 82, value = "Host %s already registered") RuntimeException hostAlreadyRegistered(Object host); @Message(id = 83, value = "Host %s has not been registered") RuntimeException hostHasNotBeenRegistered(Object host); @Message(id = 84, value = "Attempted to write additional data after the last chunk") IOException extraDataWrittenAfterChunkEnd(); @Message(id = 85, value = "Could not generate unique session id") RuntimeException couldNotGenerateUniqueSessionId(); @Message(id = 86, value = "SPDY needs to be provided with a heap buffer pool, for use in compressing and decompressing headers.") IllegalArgumentException mustProvideHeapBuffer(); @Message(id = 87, value = "Unexpected SPDY frame type %s") IOException unexpectedFrameType(int type); @Message(id = 88, value = "SPDY control frames cannot have body content") IOException controlFrameCannotHaveBodyContent(); // @Message(id = 89, value = "SPDY not supported") // IOException spdyNotSupported(); @Message(id = 90, value = "No ALPN implementation available (tried Jetty ALPN and JDK9)") IOException alpnNotAvailable(); @Message(id = 91, value = "Buffer has already been freed") IllegalStateException bufferAlreadyFreed(); @Message(id = 92, value = "A SPDY header was too large to fit in a response buffer, if you want to support larger headers please increase the buffer size") IllegalStateException headersTooLargeToFitInHeapBuffer(); // @Message(id = 93, value = "A SPDY stream was reset by the remote endpoint") // IOException spdyStreamWasReset(); @Message(id = 94, value = "Blocking await method called from IO thread. Blocking IO must be dispatched to a worker thread or deadlocks will result.") IOException awaitCalledFromIoThread(); @Message(id = 95, value = "Recursive call to flushSenders()") RuntimeException recursiveCallToFlushingSenders(); @Message(id = 96, value = "More data was written to the channel than specified in the content-length") IllegalStateException fixedLengthOverflow(); @Message(id = 97, value = "AJP request already in progress") IllegalStateException ajpRequestAlreadyInProgress(); @Message(id = 98, value = "HTTP ping data must be 8 bytes in length") String httpPingDataMustBeLength8(); @Message(id = 99, value = "Received a ping of size other than 8") String invalidPingSize(); @Message(id = 100, value = "stream id must be zero for frame type %s") String streamIdMustBeZeroForFrameType(int frameType); @Message(id = 101, value = "stream id must not be zero for frame type %s") String streamIdMustNotBeZeroForFrameType(int frameType); @Message(id = 102, value = "RST_STREAM received for idle stream") String rstStreamReceivedForIdleStream(); @Message(id = 103, value = "Http2 stream was reset") IOException http2StreamWasReset(); @Message(id = 104, value = "Incorrect HTTP2 preface") IOException incorrectHttp2Preface(); @Message(id = 105, value = "HTTP2 frame to large") IOException http2FrameTooLarge(); @Message(id = 106, value = "HTTP2 continuation frame received without a corresponding headers or push promise frame") IOException http2ContinuationFrameNotExpected(); @Message(id = 107, value = "Huffman encoded value in HPACK headers did not end with EOS padding") HpackException huffmanEncodedHpackValueDidNotEndWithEOS(); @Message(id = 108, value = "HPACK variable length integer encoded over too many octects, max is %s") HpackException integerEncodedOverTooManyOctets(int maxIntegerOctets); @Message(id = 109, value = "Zero is not a valid header table index") HpackException zeroNotValidHeaderTableIndex(); @Message(id = 110, value = "Cannot send 100-Continue, getResponseChannel() has already been called") IOException cannotSendContinueResponse(); @Message(id = 111, value = "Parser did not make progress") IOException parserDidNotMakeProgress(); @Message(id = 112, value = "Only client side can call createStream, if you wish to send a PUSH_PROMISE frame use createPushPromiseStream instead") IOException headersStreamCanOnlyBeCreatedByClient(); @Message(id = 113, value = "Only the server side can send a push promise stream") IOException pushPromiseCanOnlyBeCreatedByServer(); @Message(id = 114, value = "Invalid IP access control rule %s. Format is: [ip-match] allow|deny") IllegalArgumentException invalidAclRule(String rule); @Message(id = 115, value = "Server received PUSH_PROMISE frame from client") IOException serverReceivedPushPromise(); @Message(id = 116, value = "CONNECT not supported by this connector") IllegalStateException connectNotSupported(); @Message(id = 117, value = "Request was not a CONNECT request") IllegalStateException notAConnectRequest(); @Message(id = 118, value = "Cannot reset buffer, response has already been commited") IllegalStateException cannotResetBuffer(); @Message(id = 119, value = "HTTP2 via prior knowledge failed") IOException http2PriRequestFailed(); @Message(id = 120, value = "Out of band responses are not allowed for this connector") IllegalStateException outOfBandResponseNotSupported(); @Message(id = 121, value = "Session was rejected as the maximum number of sessions (%s) has been hit") IllegalStateException tooManySessions(int maxSessions); @Message(id = 122, value = "CONNECT attempt failed as target proxy returned %s") IOException proxyConnectionFailed(int responseCode); @Message(id = 123, value = "MCMP message %s rejected due to suspicious characters") RuntimeException mcmpMessageRejectedDueToSuspiciousCharacters(String data); @Message(id = 124, value = "renegotiation timed out") IllegalStateException rengotiationTimedOut(); @Message(id = 125, value = "Request body already read") IllegalStateException requestBodyAlreadyRead(); @Message(id = 126, value = "Attempted to do blocking IO from the IO thread. This is prohibited as it may result in deadlocks") IllegalStateException blockingIoFromIOThread(); @Message(id = 127, value = "Response has already been sent") IllegalStateException responseComplete(); @Message(id = 128, value = "Remote peer closed connection before all data could be read") IOException couldNotReadContentLengthData(); @Message(id = 129, value = "Failed to send after being safe to send") IllegalStateException failedToSendAfterBeingSafe(); @Message(id = 130, value = "HTTP reason phrase was too large for the buffer. Either provide a smaller message or a bigger buffer. Phrase: %s") IllegalStateException reasonPhraseToLargeForBuffer(String phrase); @Message(id = 131, value = "Buffer pool is closed") IllegalStateException poolIsClosed(); @Message(id = 132, value = "HPACK decode failed") HpackException hpackFailed(); @Message(id = 133, value = "Request did not contain an Upgrade header, upgrade is not permitted") IllegalStateException notAnUpgradeRequest(); @Message(id = 134, value = "Authentication mechanism %s requires property %s to be set") IllegalStateException authenticationPropertyNotSet(String name, String header); @Message(id = 135, value = "renegotiation failed") IllegalStateException rengotiationFailed(); @Message(id = 136, value = "User agent charset string must have an even number of items, in the form pattern,charset,pattern,charset,... Instead got: %s") IllegalArgumentException userAgentCharsetMustHaveEvenNumberOfItems(String supplied); @Message(id = 137, value = "Could not find the datasource called %s") IllegalArgumentException datasourceNotFound(String ds); @Message(id = 138, value = "Server not started") IllegalStateException serverNotStarted(); @Message(id = 139, value = "Exchange already complete") IllegalStateException exchangeAlreadyComplete(); @Message(id = 140, value = "Initial SSL/TLS data is not a handshake record") SSLHandshakeException notHandshakeRecord(); @Message(id = 141, value = "Initial SSL/TLS handshake record is invalid") SSLHandshakeException invalidHandshakeRecord(); @Message(id = 142, value = "Initial SSL/TLS handshake spans multiple records") SSLHandshakeException multiRecordSSLHandshake(); @Message(id = 143, value = "Expected \"client hello\" record") SSLHandshakeException expectedClientHello(); @Message(id = 144, value = "Expected server hello") SSLHandshakeException expectedServerHello(); @Message(id = 145, value = "Too many redirects") IOException tooManyRedirects(@Cause IOException exception); @Message(id = 146, value = "HttpServerExchange cannot have both async IO resumed and dispatch() called in the same cycle") IllegalStateException resumedAndDispatched(); @Message(id = 147, value = "No host header in a HTTP/1.1 request") IOException noHostInHttp11Request(); @Message(id = 148, value = "Invalid HPack encoding. First byte: %s") HpackException invalidHpackEncoding(byte b); @Message(id = 149, value = "HttpString is not allowed to contain newlines. value: %s") IllegalArgumentException newlineNotSupportedInHttpString(String value); @Message(id = 150, value = "Pseudo header %s received after receiving normal headers. Pseudo headers must be the first headers in a HTTP/2 header block.") String pseudoHeaderInWrongOrder(HttpString header); @Message(id = 151, value = "Expected to receive a continuation frame") String expectedContinuationFrame(); @Message(id = 152, value = "Incorrect frame size") String incorrectFrameSize(); @Message(id = 153, value = "Stream id not registered") IllegalStateException streamNotRegistered(); @Message(id = 154, value = "Mechanism %s returned a null result from sendChallenge()") NullPointerException sendChallengeReturnedNull(AuthenticationMechanism mechanism); @Message(id = 155, value = "Framed channel body was set when it was not ready for flush") IllegalStateException bodyIsSetAndNotReadyForFlush(); @Message(id = 156, value = "Invalid GZIP header") IOException invalidGzipHeader(); @Message(id = 157, value = "Invalid GZIP footer") IOException invalidGZIPFooter(); @Message(id = 158, value = "Response of length %s is too large to buffer") IllegalStateException responseTooLargeToBuffer(Long length); @Message(id = 159, value = "Max size must be larger than one") IllegalArgumentException maxSizeMustBeLargerThanOne(); @Message(id = 161, value = "HTTP/2 header block is too large") String headerBlockTooLarge(); @Message(id = 162, value = "Same-site attribute %s is invalid. It must be Strict or Lax") IllegalArgumentException invalidSameSiteMode(String mode); @Message(id = 163, value = "Invalid token %s") IllegalArgumentException invalidToken(byte c); @Message(id = 164, value = "Request contained invalid headers") IllegalArgumentException invalidHeaders(); @Message(id = 165, value = "Invalid character %s in request-target") String invalidCharacterInRequestTarget(char next); @Message(id = 166, value = "Pooled object is closed") IllegalStateException objectIsClosed(); @Message(id = 167, value = "More than one host header in request") IOException moreThanOneHostHeader(); @Message(id = 168, value = "An invalid character [ASCII code: %s] was present in the cookie value") IllegalArgumentException invalidCookieValue(String value); @Message(id = 169, value = "An invalid domain [%s] was specified for this cookie") IllegalArgumentException invalidCookieDomain(String value); @Message(id = 170, value = "An invalid path [%s] was specified for this cookie") IllegalArgumentException invalidCookiePath(String value); @Message(id = 173, value = "An invalid control character [%s] was present in the cookie value or attribute") IllegalArgumentException invalidControlCharacter(String value); @Message(id = 174, value = "An invalid escape character in cookie value") IllegalArgumentException invalidEscapeCharacter(); }
core/src/main/java/io/undertow/UndertowMessages.java
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.ClosedChannelException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLPeerUnverifiedException; import org.jboss.logging.Messages; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import io.undertow.predicate.PredicateBuilder; import io.undertow.protocols.http2.HpackException; import io.undertow.security.api.AuthenticationMechanism; import io.undertow.server.handlers.builder.HandlerBuilder; import io.undertow.util.HttpString; import io.undertow.util.ParameterLimitException; import io.undertow.util.BadRequestException; /** * @author Stuart Douglas */ @MessageBundle(projectCode = "UT") public interface UndertowMessages { UndertowMessages MESSAGES = Messages.getBundle(UndertowMessages.class); @Message(id = 1, value = "Maximum concurrent requests must be larger than zero.") IllegalArgumentException maximumConcurrentRequestsMustBeLargerThanZero(); @Message(id = 2, value = "The response has already been started") IllegalStateException responseAlreadyStarted(); // id = 3 @Message(id = 4, value = "getResponseChannel() has already been called") IllegalStateException responseChannelAlreadyProvided(); @Message(id = 5, value = "getRequestChannel() has already been called") IllegalStateException requestChannelAlreadyProvided(); // id = 6 // id = 7 @Message(id = 8, value = "Handler cannot be null") IllegalArgumentException handlerCannotBeNull(); @Message(id = 9, value = "Path must be specified") IllegalArgumentException pathMustBeSpecified(); @Message(id = 10, value = "Session is invalid %s") IllegalStateException sessionIsInvalid(String sessionId); @Message(id = 11, value = "Session manager must not be null") IllegalStateException sessionManagerMustNotBeNull(); @Message(id = 12, value = "Session manager was not attached to the request. Make sure that the SessionAttachmentHandler is installed in the handler chain") IllegalStateException sessionManagerNotFound(); @Message(id = 13, value = "Argument %s cannot be null") IllegalArgumentException argumentCannotBeNull(final String argument); @Message(id = 14, value = "close() called with data still to be flushed. Please call shutdownWrites() and then call flush() until it returns true before calling close()") IOException closeCalledWithDataStillToBeFlushed(); @Message(id = 16, value = "Could not add cookie as cookie handler was not present in the handler chain") IllegalStateException cookieHandlerNotPresent(); @Message(id = 17, value = "Form value is a file, use getFile() instead") IllegalStateException formValueIsAFile(); @Message(id = 18, value = "Form value is a String, use getValue() instead") IllegalStateException formValueIsAString(); @Message(id = 19, value = "Connection from %s terminated as request entity was larger than %s") IOException requestEntityWasTooLarge(SocketAddress address, long size); @Message(id = 20, value = "Connection terminated as request was larger than %s") IOException requestEntityWasTooLarge(long size); @Message(id = 21, value = "Session already invalidated") IllegalStateException sessionAlreadyInvalidated(); @Message(id = 22, value = "The specified hash algorithm '%s' can not be found.") IllegalArgumentException hashAlgorithmNotFound(String algorithmName); @Message(id = 23, value = "An invalid Base64 token has been received.") IllegalArgumentException invalidBase64Token(@Cause final IOException cause); @Message(id = 24, value = "An invalidly formatted nonce has been received.") IllegalArgumentException invalidNonceReceived(); @Message(id = 25, value = "Unexpected token '%s' within header.") IllegalArgumentException unexpectedTokenInHeader(final String name); @Message(id = 26, value = "Invalid header received.") IllegalArgumentException invalidHeader(); @Message(id = 27, value = "Could not find session cookie config in the request") IllegalStateException couldNotFindSessionCookieConfig(); @Message(id = 28, value = "Session %s already exists") IllegalStateException sessionAlreadyExists(final String id); @Message(id = 29, value = "Channel was closed mid chunk, if you have attempted to write chunked data you cannot shutdown the channel until after it has all been written.") IOException chunkedChannelClosedMidChunk(); @Message(id = 30, value = "User %s successfully authenticated.") String userAuthenticated(final String userName); @Message(id = 31, value = "User %s has logged out.") String userLoggedOut(final String userName); @Message(id = 33, value = "Authentication type %s cannot be combined with %s") IllegalStateException authTypeCannotBeCombined(String type, String existing); @Message(id = 34, value = "Stream is closed") IOException streamIsClosed(); @Message(id = 35, value = "Cannot get stream as startBlocking has not been invoked") IllegalStateException startBlockingHasNotBeenCalled(); @Message(id = 36, value = "Connection terminated parsing multipart data") IOException connectionTerminatedReadingMultiPartData(); @Message(id = 37, value = "Failed to parse path in HTTP request") RuntimeException failedToParsePath(); @Message(id = 38, value = "Authentication failed, requested user name '%s'") String authenticationFailed(final String userName); @Message(id = 39, value = "To many query parameters, cannot have more than %s query parameters") BadRequestException tooManyQueryParameters(int noParams); @Message(id = 40, value = "To many headers, cannot have more than %s header") String tooManyHeaders(int noParams); @Message(id = 41, value = "Channel is closed") ClosedChannelException channelIsClosed(); @Message(id = 42, value = "Could not decode trailers in HTTP request") IOException couldNotDecodeTrailers(); @Message(id = 43, value = "Data is already being sent. You must wait for the completion callback to be be invoked before calling send() again") IllegalStateException dataAlreadyQueued(); @Message(id = 44, value = "More than one predicate with name %s. Builder class %s and %s") IllegalStateException moreThanOnePredicateWithName(String name, Class<? extends PredicateBuilder> aClass, Class<? extends PredicateBuilder> existing); @Message(id = 45, value = "Error parsing predicated handler string %s:%n%s") IllegalArgumentException errorParsingPredicateString(String reason, String s); @Message(id = 46, value = "The number of cookies sent exceeded the maximum of %s") IllegalStateException tooManyCookies(int maxCookies); @Message(id = 47, value = "The number of parameters exceeded the maximum of %s") ParameterLimitException tooManyParameters(int maxValues); @Message(id = 48, value = "No request is currently active") IllegalStateException noRequestActive(); @Message(id = 50, value = "AuthenticationMechanism Outcome is null") IllegalStateException authMechanismOutcomeNull(); @Message(id = 51, value = "Not a valid IP pattern %s") IllegalArgumentException notAValidIpPattern(String peer); @Message(id = 52, value = "Session data requested when non session based authentication in use") IllegalStateException noSessionData(); @Message(id = 53, value = "Listener %s already registered") IllegalArgumentException listenerAlreadyRegistered(String name); @Message(id = 54, value = "The maximum size %s for an individual file in a multipart request was exceeded") IOException maxFileSizeExceeded(long maxIndividualFileSize); @Message(id = 55, value = "Could not set attribute %s to %s as it is read only") String couldNotSetAttribute(String attributeName, String newValue); @Message(id = 56, value = "Could not parse URI template %s, exception at char %s") RuntimeException couldNotParseUriTemplate(String path, int i); @Message(id = 57, value = "Mismatched braces in attribute string %s") RuntimeException mismatchedBraces(String valueString); @Message(id = 58, value = "More than one handler with name %s. Builder class %s and %s") IllegalStateException moreThanOneHandlerWithName(String name, Class<? extends HandlerBuilder> aClass, Class<? extends HandlerBuilder> existing); @Message(id = 59, value = "Invalid syntax %s") IllegalArgumentException invalidSyntax(String line); @Message(id = 60, value = "Error parsing handler string %s:%n%s") IllegalArgumentException errorParsingHandlerString(String reason, String s); @Message(id = 61, value = "Out of band responses only allowed for 100-continue requests") IllegalArgumentException outOfBandResponseOnlyAllowedFor100Continue(); @Message(id = 62, value = "AJP does not support HTTP upgrade") IllegalStateException ajpDoesNotSupportHTTPUpgrade(); @Message(id = 63, value = "File system watcher already started") IllegalStateException fileSystemWatcherAlreadyStarted(); @Message(id = 64, value = "File system watcher not started") IllegalStateException fileSystemWatcherNotStarted(); @Message(id = 65, value = "SSL must be specified to connect to a https URL") IOException sslWasNull(); @Message(id = 66, value = "Incorrect magic number %s for AJP packet header") IOException wrongMagicNumber(int number); @Message(id = 67, value = "No client cert was provided") SSLPeerUnverifiedException peerUnverified(); @Message(id = 68, value = "Servlet path match failed") IllegalArgumentException servletPathMatchFailed(); @Message(id = 69, value = "Could not parse set cookie header %s") IllegalArgumentException couldNotParseCookie(String headerValue); @Message(id = 70, value = "method can only be called by IO thread") IllegalStateException canOnlyBeCalledByIoThread(); @Message(id = 71, value = "Cannot add path template %s, matcher already contains an equivalent pattern %s") IllegalStateException matcherAlreadyContainsTemplate(String templateString, String templateString1); @Message(id = 72, value = "Failed to decode url %s to charset %s") IllegalArgumentException failedToDecodeURL(String s, String enc, @Cause Exception e); @Message(id = 73, value = "Resource change listeners are not supported") IllegalArgumentException resourceChangeListenerNotSupported(); @Message(id = 74, value = "Could not renegotiate SSL connection to require client certificate, as client had sent more data") IllegalStateException couldNotRenegotiate(); @Message(id = 75, value = "Object was freed") IllegalStateException objectWasFreed(); @Message(id = 76, value = "Handler not shutdown") IllegalStateException handlerNotShutdown(); @Message(id = 77, value = "The underlying transport does not support HTTP upgrade") IllegalStateException upgradeNotSupported(); @Message(id = 78, value = "Renegotiation not supported") IOException renegotiationNotSupported(); @Message(id = 79, value = "Not a valid user agent pattern %s") IllegalArgumentException notAValidUserAgentPattern(String userAgent); @Message(id = 80, value = "Not a valid regular expression pattern %s") IllegalArgumentException notAValidRegularExpressionPattern(String pattern); @Message(id = 81, value = "Bad request") BadRequestException badRequest(); @Message(id = 82, value = "Host %s already registered") RuntimeException hostAlreadyRegistered(Object host); @Message(id = 83, value = "Host %s has not been registered") RuntimeException hostHasNotBeenRegistered(Object host); @Message(id = 84, value = "Attempted to write additional data after the last chunk") IOException extraDataWrittenAfterChunkEnd(); @Message(id = 85, value = "Could not generate unique session id") RuntimeException couldNotGenerateUniqueSessionId(); @Message(id = 86, value = "SPDY needs to be provided with a heap buffer pool, for use in compressing and decompressing headers.") IllegalArgumentException mustProvideHeapBuffer(); @Message(id = 87, value = "Unexpected SPDY frame type %s") IOException unexpectedFrameType(int type); @Message(id = 88, value = "SPDY control frames cannot have body content") IOException controlFrameCannotHaveBodyContent(); // @Message(id = 89, value = "SPDY not supported") // IOException spdyNotSupported(); @Message(id = 90, value = "No ALPN implementation available (tried Jetty ALPN and JDK9)") IOException alpnNotAvailable(); @Message(id = 91, value = "Buffer has already been freed") IllegalStateException bufferAlreadyFreed(); @Message(id = 92, value = "A SPDY header was too large to fit in a response buffer, if you want to support larger headers please increase the buffer size") IllegalStateException headersTooLargeToFitInHeapBuffer(); // @Message(id = 93, value = "A SPDY stream was reset by the remote endpoint") // IOException spdyStreamWasReset(); @Message(id = 94, value = "Blocking await method called from IO thread. Blocking IO must be dispatched to a worker thread or deadlocks will result.") IOException awaitCalledFromIoThread(); @Message(id = 95, value = "Recursive call to flushSenders()") RuntimeException recursiveCallToFlushingSenders(); @Message(id = 96, value = "More data was written to the channel than specified in the content-length") IllegalStateException fixedLengthOverflow(); @Message(id = 97, value = "AJP request already in progress") IllegalStateException ajpRequestAlreadyInProgress(); @Message(id = 98, value = "HTTP ping data must be 8 bytes in length") String httpPingDataMustBeLength8(); @Message(id = 99, value = "Received a ping of size other than 8") String invalidPingSize(); @Message(id = 100, value = "stream id must be zero for frame type %s") String streamIdMustBeZeroForFrameType(int frameType); @Message(id = 101, value = "stream id must not be zero for frame type %s") String streamIdMustNotBeZeroForFrameType(int frameType); @Message(id = 102, value = "RST_STREAM received for idle stream") String rstStreamReceivedForIdleStream(); @Message(id = 103, value = "Http2 stream was reset") IOException http2StreamWasReset(); @Message(id = 104, value = "Incorrect HTTP2 preface") IOException incorrectHttp2Preface(); @Message(id = 105, value = "HTTP2 frame to large") IOException http2FrameTooLarge(); @Message(id = 106, value = "HTTP2 continuation frame received without a corresponding headers or push promise frame") IOException http2ContinuationFrameNotExpected(); @Message(id = 107, value = "Huffman encoded value in HPACK headers did not end with EOS padding") HpackException huffmanEncodedHpackValueDidNotEndWithEOS(); @Message(id = 108, value = "HPACK variable length integer encoded over too many octects, max is %s") HpackException integerEncodedOverTooManyOctets(int maxIntegerOctets); @Message(id = 109, value = "Zero is not a valid header table index") HpackException zeroNotValidHeaderTableIndex(); @Message(id = 110, value = "Cannot send 100-Continue, getResponseChannel() has already been called") IOException cannotSendContinueResponse(); @Message(id = 111, value = "Parser did not make progress") IOException parserDidNotMakeProgress(); @Message(id = 112, value = "Only client side can call createStream, if you wish to send a PUSH_PROMISE frame use createPushPromiseStream instead") IOException headersStreamCanOnlyBeCreatedByClient(); @Message(id = 113, value = "Only the server side can send a push promise stream") IOException pushPromiseCanOnlyBeCreatedByServer(); @Message(id = 114, value = "Invalid IP access control rule %s. Format is: [ip-match] allow|deny") IllegalArgumentException invalidAclRule(String rule); @Message(id = 115, value = "Server received PUSH_PROMISE frame from client") IOException serverReceivedPushPromise(); @Message(id = 116, value = "CONNECT not supported by this connector") IllegalStateException connectNotSupported(); @Message(id = 117, value = "Request was not a CONNECT request") IllegalStateException notAConnectRequest(); @Message(id = 118, value = "Cannot reset buffer, response has already been commited") IllegalStateException cannotResetBuffer(); @Message(id = 119, value = "HTTP2 via prior knowledge failed") IOException http2PriRequestFailed(); @Message(id = 120, value = "Out of band responses are not allowed for this connector") IllegalStateException outOfBandResponseNotSupported(); @Message(id = 121, value = "Session was rejected as the maximum number of sessions (%s) has been hit") IllegalStateException tooManySessions(int maxSessions); @Message(id = 122, value = "CONNECT attempt failed as target proxy returned %s") IOException proxyConnectionFailed(int responseCode); @Message(id = 123, value = "MCMP message %s rejected due to suspicious characters") RuntimeException mcmpMessageRejectedDueToSuspiciousCharacters(String data); @Message(id = 124, value = "renegotiation timed out") IllegalStateException rengotiationTimedOut(); @Message(id = 125, value = "Request body already read") IllegalStateException requestBodyAlreadyRead(); @Message(id = 126, value = "Attempted to do blocking IO from the IO thread. This is prohibited as it may result in deadlocks") IllegalStateException blockingIoFromIOThread(); @Message(id = 127, value = "Response has already been sent") IllegalStateException responseComplete(); @Message(id = 128, value = "Remote peer closed connection before all data could be read") IOException couldNotReadContentLengthData(); @Message(id = 129, value = "Failed to send after being safe to send") IllegalStateException failedToSendAfterBeingSafe(); @Message(id = 130, value = "HTTP reason phrase was too large for the buffer. Either provide a smaller message or a bigger buffer. Phrase: %s") IllegalStateException reasonPhraseToLargeForBuffer(String phrase); @Message(id = 131, value = "Buffer pool is closed") IllegalStateException poolIsClosed(); @Message(id = 132, value = "HPACK decode failed") HpackException hpackFailed(); @Message(id = 133, value = "Request did not contain an Upgrade header, upgrade is not permitted") IllegalStateException notAnUpgradeRequest(); @Message(id = 134, value = "Authentication mechanism %s requires property %s to be set") IllegalStateException authenticationPropertyNotSet(String name, String header); @Message(id = 135, value = "renegotiation failed") IllegalStateException rengotiationFailed(); @Message(id = 136, value = "User agent charset string must have an even number of items, in the form pattern,charset,pattern,charset,... Instead got: %s") IllegalArgumentException userAgentCharsetMustHaveEvenNumberOfItems(String supplied); @Message(id = 137, value = "Could not find the datasource called %s") IllegalArgumentException datasourceNotFound(String ds); @Message(id = 138, value = "Server not started") IllegalStateException serverNotStarted(); @Message(id = 139, value = "Exchange already complete") IllegalStateException exchangeAlreadyComplete(); @Message(id = 140, value = "Initial SSL/TLS data is not a handshake record") SSLHandshakeException notHandshakeRecord(); @Message(id = 141, value = "Initial SSL/TLS handshake record is invalid") SSLHandshakeException invalidHandshakeRecord(); @Message(id = 142, value = "Initial SSL/TLS handshake spans multiple records") SSLHandshakeException multiRecordSSLHandshake(); @Message(id = 143, value = "Expected \"client hello\" record") SSLHandshakeException expectedClientHello(); @Message(id = 144, value = "Expected server hello") SSLHandshakeException expectedServerHello(); @Message(id = 145, value = "Too many redirects") IOException tooManyRedirects(@Cause IOException exception); @Message(id = 146, value = "HttpServerExchange cannot have both async IO resumed and dispatch() called in the same cycle") IllegalStateException resumedAndDispatched(); @Message(id = 147, value = "No host header in a HTTP/1.1 request") IOException noHostInHttp11Request(); @Message(id = 148, value = "Invalid HPack encoding. First byte: %s") HpackException invalidHpackEncoding(byte b); @Message(id = 149, value = "HttpString is not allowed to contain newlines. value: %s") IllegalArgumentException newlineNotSupportedInHttpString(String value); @Message(id = 150, value = "Pseudo header %s received after receiving normal headers. Pseudo headers must be the first headers in a HTTP/2 header block.") String pseudoHeaderInWrongOrder(HttpString header); @Message(id = 151, value = "Expected to receive a continuation frame") String expectedContinuationFrame(); @Message(id = 152, value = "Incorrect frame size") String incorrectFrameSize(); @Message(id = 153, value = "Stream id not registered") IllegalStateException streamNotRegistered(); @Message(id = 154, value = "Mechanism %s returned a null result from sendChallenge()") NullPointerException sendChallengeReturnedNull(AuthenticationMechanism mechanism); @Message(id = 155, value = "Framed channel body was set when it was not ready for flush") IllegalStateException bodyIsSetAndNotReadyForFlush(); @Message(id = 156, value = "Invalid GZIP header") IOException invalidGzipHeader(); @Message(id = 157, value = "Invalid GZIP footer") IOException invalidGZIPFooter(); @Message(id = 158, value = "Response of length %s is too large to buffer") IllegalStateException responseTooLargeToBuffer(Long length); @Message(id = 159, value = "Max size must be larger than one") IllegalArgumentException maxSizeMustBeLargerThanOne(); @Message(id = 161, value = "HTTP/2 header block is too large") String headerBlockTooLarge(); @Message(id = 162, value = "Same-site attribute %s is invalid. It must be Strict or Lax") IllegalArgumentException invalidSameSiteMode(String mode); @Message(id = 163, value = "Invalid token %s") IllegalArgumentException invalidToken(byte c); @Message(id = 164, value = "Request contained invalid headers") IllegalArgumentException invalidHeaders(); @Message(id = 165, value = "Invalid character %s in request-target") String invalidCharacterInRequestTarget(char next); @Message(id = 166, value = "Pooled object is closed") IllegalStateException objectIsClosed(); @Message(id = 167, value = "More than one host header in request") IOException moreThanOneHostHeader(); @Message(id = 168, value = "An invalid character [ASCII code: %s] was present in the cookie value") IllegalArgumentException invalidCookieValue(String value); @Message(id = 169, value = "An invalid domain [%s] was specified for this cookie") IllegalArgumentException invalidCookieDomain(String value); @Message(id = 170, value = "An invalid path [%s] was specified for this cookie") IllegalArgumentException invalidCookiePath(String value); @Message(id = 173, value = "An invalid control character [%s] was present in the cookie value or attribute") IllegalArgumentException invalidControlCharacter(String value); @Message(id = 174, value = "An invalid escape character in cookie value") IllegalArgumentException invalidEscapeCharacter(); }
[UNDERTOW-1142] fix of two minor typos in log messages
core/src/main/java/io/undertow/UndertowMessages.java
[UNDERTOW-1142] fix of two minor typos in log messages
<ide><path>ore/src/main/java/io/undertow/UndertowMessages.java <ide> @Message(id = 38, value = "Authentication failed, requested user name '%s'") <ide> String authenticationFailed(final String userName); <ide> <del> @Message(id = 39, value = "To many query parameters, cannot have more than %s query parameters") <add> @Message(id = 39, value = "Too many query parameters, cannot have more than %s query parameters") <ide> BadRequestException tooManyQueryParameters(int noParams); <ide> <del> @Message(id = 40, value = "To many headers, cannot have more than %s header") <add> @Message(id = 40, value = "Too many headers, cannot have more than %s header") <ide> String tooManyHeaders(int noParams); <ide> <ide> @Message(id = 41, value = "Channel is closed")
Java
mit
50a3126442ece1c52d185c609bd9fa9782f5737a
0
bill176/tetris,bill176/tetris
package tetris.game; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Random; public class Canvas extends JPanel{ public static final int SIDE_OF_SQUARE = 25; public static final int WIDTH = 14; public static final int HEIGHT = 22; private static final int NUM_OF_SHAPES = 7; private static final int NUM_OF_ROTATIONS = 4; private static final int REFRESH_RATE = 1000; private static final int ONE_SHAPE = 0; private static final int L_SHAPE = 1; private static final int J_SHAPE = 2; private static final int Z_SHAPE = 3; private static final int S_SHAPE = 4; private static final int SQUARE = 5; private static final int T_SHAPE = 6; public static Shape [][] shapes = new Shape[NUM_OF_SHAPES][NUM_OF_ROTATIONS]; static{ shapes[ONE_SHAPE] = new Shape[]{new Shape(Color.GREEN, new Coordinates(1,0), new Coordinates(0,0), new Coordinates(2,0), new Coordinates(3,0)), new Shape(Color.GREEN, new Coordinates(1,0), new Coordinates(1,1), new Coordinates(1,2), new Coordinates(1,3)), new Shape(Color.GREEN, new Coordinates(1,0), new Coordinates(0,0), new Coordinates(2,0), new Coordinates(3,0)), new Shape(Color.GREEN, new Coordinates(1,0), new Coordinates(1,1), new Coordinates(1,2), new Coordinates(1,3))}; shapes[L_SHAPE] = new Shape[]{ new Shape(Color.CYAN,new Coordinates(0,1),new Coordinates(0,0),new Coordinates(0,2), new Coordinates(1,2)), new Shape(Color.CYAN,new Coordinates(-1,1),new Coordinates(0,1),new Coordinates(1,1), new Coordinates(1,0)), new Shape(Color.CYAN,new Coordinates(0,1),new Coordinates(0,0),new Coordinates(0,2), new Coordinates(-1,0)), new Shape(Color.CYAN,new Coordinates(0,1),new Coordinates(-1,1),new Coordinates(1,1), new Coordinates(-1,2))}; shapes[J_SHAPE] = new Shape[]{ new Shape(Color.ORANGE, new Coordinates(1,0), new Coordinates(1,1), new Coordinates(1,2), new Coordinates(0,2)), new Shape(Color.ORANGE, new Coordinates(0,1), new Coordinates(1,1), new Coordinates(2,1), new Coordinates(2,2)), new Shape(Color.ORANGE, new Coordinates(1,0), new Coordinates(1,1), new Coordinates(1,2), new Coordinates(2,0)), new Shape(Color.ORANGE, new Coordinates(0,1), new Coordinates(1,1), new Coordinates(2,1), new Coordinates(0,0))}; shapes[Z_SHAPE] = new Shape[]{ new Shape(Color.YELLOW, new Coordinates(0,1),new Coordinates(1,0),new Coordinates(1,1), new Coordinates(0,2)), new Shape(Color.YELLOW, new Coordinates(-1,0),new Coordinates(0,0),new Coordinates(1,1), new Coordinates(0,1)), new Shape(Color.YELLOW, new Coordinates(0,1),new Coordinates(1,0),new Coordinates(1,1), new Coordinates(0,2)), new Shape(Color.YELLOW, new Coordinates(-1,0),new Coordinates(0,0),new Coordinates(1,1), new Coordinates(0,1))}; shapes[S_SHAPE] = new Shape[]{ new Shape(Color.RED, new Coordinates(0,1),new Coordinates(0,0),new Coordinates(1,1), new Coordinates(1,2)), new Shape(Color.RED, new Coordinates(0,1),new Coordinates(0,0),new Coordinates(1,0), new Coordinates(-1,1)), new Shape(Color.RED, new Coordinates(0,1),new Coordinates(0,0),new Coordinates(1,1), new Coordinates(1,2)), new Shape(Color.RED, new Coordinates(0,1),new Coordinates(0,0),new Coordinates(1,0), new Coordinates(-1,1))}; shapes[SQUARE] = new Shape[]{ new Shape(Color.MAGENTA, new Coordinates(0,0),new Coordinates(0,1),new Coordinates(1,0), new Coordinates(1,1)), new Shape(Color.MAGENTA, new Coordinates(0,0),new Coordinates(0,1),new Coordinates(1,0), new Coordinates(1,1)), new Shape(Color.MAGENTA, new Coordinates(0,0),new Coordinates(0,1),new Coordinates(1,0), new Coordinates(1,1)), new Shape(Color.MAGENTA, new Coordinates(0,0),new Coordinates(0,1),new Coordinates(1,0), new Coordinates(1,1))}; shapes[T_SHAPE] = new Shape[]{ new Shape(Color.PINK, new Coordinates(1,1), new Coordinates(0,1), new Coordinates(2,1), new Coordinates(1,0)), new Shape(Color.PINK, new Coordinates(1,1), new Coordinates(0,1), new Coordinates(1,2), new Coordinates(1,0)), new Shape(Color.PINK, new Coordinates(1,1), new Coordinates(0,1), new Coordinates(2,1), new Coordinates(1,2)), new Shape(Color.PINK, new Coordinates(1,1), new Coordinates(1,2), new Coordinates(2,1), new Coordinates(1,0)),}; } public int[][] plane; private Random rand; private int currentShape; private int nextShape; private int currentRotation; private Coordinates currentCoordinate; private KeyListener theKeyListener; private Timer timer; private int score; private boolean gameActive; public Canvas(){ score = 0; gameActive = true; plane = new int[WIDTH][HEIGHT]; for(int i = 0; i < WIDTH; i++) for(int j = 0; j < HEIGHT; j++) if(i == 0 || i == WIDTH - 1 || j == HEIGHT - 1) plane[i][j] = -2; else plane[i][j] = -1; ActionListener theActionListener = new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ if(gameActive) moveDown(); } }; timer = new Timer(REFRESH_RATE, theActionListener); timer.start(); rand = new Random(); nextShape = rand.nextInt(7); generateShape(); theKeyListener = new KeyListener(){ public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e){} @Override public void keyPressed(KeyEvent e){ switch(e.getKeyCode()){ case KeyEvent.VK_UP: if(gameActive) rotate(); break; case KeyEvent.VK_DOWN: if(gameActive) moveDown(); break; case KeyEvent.VK_LEFT: if(gameActive) moveLeft(); break; case KeyEvent.VK_RIGHT: if(gameActive) moveRight(); break; case KeyEvent.VK_SPACE: if(gameActive) moveButtom(); break; case KeyEvent.VK_P: gameActive = false; break; case KeyEvent.VK_R: gameActive = true; } } }; } private void generateShape(){ currentShape = nextShape; nextShape = rand.nextInt(7); currentRotation = 0; currentCoordinate = new Coordinates(6,0); for(Coordinates c : shapes[currentShape][currentRotation].getCoordinates()) if(plane[currentCoordinate.getX() + c.getX()][currentCoordinate.getY() + c.getY()] != -1){ gameActive = false; JOptionPane.showMessageDialog(null, "Game Over!"); break; } repaint(); } private void resetShape(){ for(Coordinates c : shapes[currentShape][currentRotation].getCoordinates()) plane[currentCoordinate.getX() + c.getX()][currentCoordinate.getY() + c.getY()] = currentShape; generateShape(); } private boolean canMove(Coordinates coordinate, int shape, int rotation){ for(Coordinates c : shapes[shape][rotation].getCoordinates()) if(coordinate.getX() + c.getX() >= WIDTH || coordinate.getX() + c.getX() <= 0 || coordinate.getY() + c.getY() >= HEIGHT - 1 || coordinate.getY() + c.getY() < 0 || plane[coordinate.getX() + c.getX()][coordinate.getY() + c.getY()] != -1) return false; return true; } private boolean rotate(){ if(canMove(currentCoordinate, currentShape, (currentRotation + 1) % 4)){ currentRotation = (currentRotation + 1) % 4; repaint(); return true; } return false; } private boolean moveDown(){ if(canMove(new Coordinates(currentCoordinate.getX(), currentCoordinate.getY() + 1), currentShape, currentRotation)){ currentCoordinate = new Coordinates(currentCoordinate.getX(), currentCoordinate.getY() + 1); repaint(); return true; } resetShape(); clearRow(); return false; } private boolean moveLeft(){ if(canMove(new Coordinates(currentCoordinate.getX() - 1, currentCoordinate.getY()), currentShape, currentRotation)){ currentCoordinate = new Coordinates(currentCoordinate.getX() - 1, currentCoordinate.getY()); repaint(); return true; } return false; } private boolean moveRight(){ if(canMove(new Coordinates(currentCoordinate.getX() + 1, currentCoordinate.getY()), currentShape, currentRotation)){ currentCoordinate = new Coordinates(currentCoordinate.getX() + 1, currentCoordinate.getY()); repaint(); return true; } return false; } private void moveButtom(){ while(moveDown()); } private boolean isRowFilled(int y){ for(int x = 1; x < WIDTH - 1; x++) if(plane[x][y] == -1) return false; return true; } private void clearRow(){ int i = HEIGHT - 2; while(i > 0){ if(isRowFilled(i)){ for(int x = 1; x < WIDTH - 1; x++){ for(int y = i; y > 0; y--) plane[x][y] = plane[x][y - 1]; plane[x][0] = -1; } score += 10; }else i--; } repaint(); } public KeyListener getKeyListener(){ return theKeyListener; } @Override public void paintComponent(Graphics g){ super.paintComponent(g); for(Coordinates c : shapes[currentShape][currentRotation].getCoordinates()) plane[currentCoordinate.getX() + c.getX()][currentCoordinate.getY() + c.getY()] = currentShape; for(int i = 0; i < WIDTH; i++) for(int j = 0; j < HEIGHT; j++) paintSquare(g, new Coordinates(i, j), plane[i][j]); for(Coordinates c : shapes[currentShape][currentRotation].getCoordinates()) plane[currentCoordinate.getX() + c.getX()][currentCoordinate.getY() + c.getY()] = -1; g.setColor(Color.BLACK); g.drawString("Next shape", (WIDTH + 2) * SIDE_OF_SQUARE, SIDE_OF_SQUARE); for(Coordinates c : shapes[nextShape][0].getCoordinates()) paintSquare(g, new Coordinates(c.getX() + WIDTH + 2, c.getY() + 3), nextShape); g.setColor(Color.BLACK); g.drawString("Score: " + String.valueOf(score), (WIDTH + 2) * SIDE_OF_SQUARE, 8 * SIDE_OF_SQUARE); } private void paintSquare(Graphics g, Coordinates topLeftPoint, int color){ if(color == -1) return; g.setColor(Color.BLACK); g.drawRect(topLeftPoint.getX() * SIDE_OF_SQUARE, topLeftPoint.getY() * SIDE_OF_SQUARE, SIDE_OF_SQUARE, SIDE_OF_SQUARE); if(color >= 0 && color < NUM_OF_SHAPES) g.setColor(shapes[color][currentRotation].getColor()); else if(color == -2) g.setColor(Color.WHITE); g.fillRect(topLeftPoint.getX() * SIDE_OF_SQUARE, topLeftPoint.getY() * SIDE_OF_SQUARE, SIDE_OF_SQUARE, SIDE_OF_SQUARE); } }
Canvas.java
package tetris.game; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Random; public class Canvas extends JPanel{ public static final int SIDE_OF_SQUARE = 25; public static final int WIDTH = 14; public static final int HEIGHT = 22; private static final int NUM_OF_SHAPES = 7; private static final int NUM_OF_ROTATIONS = 4; private static final int REFRESH_RATE = 1000; private static final int ONE_SHAPE = 0; private static final int L_SHAPE = 1; private static final int J_SHAPE = 2; private static final int Z_SHAPE = 3; private static final int S_SHAPE = 4; private static final int SQUARE = 5; private static final int T_SHAPE = 6; public static Shape [][] shapes = new Shape[NUM_OF_SHAPES][NUM_OF_ROTATIONS]; static{ shapes[ONE_SHAPE] = new Shape[]{new Shape(Color.GREEN, new Coordinates(1,0), new Coordinates(0,0), new Coordinates(2,0), new Coordinates(3,0)), new Shape(Color.GREEN, new Coordinates(1,0), new Coordinates(1,1), new Coordinates(1,2), new Coordinates(1,3)), new Shape(Color.GREEN, new Coordinates(1,0), new Coordinates(0,0), new Coordinates(2,0), new Coordinates(3,0)), new Shape(Color.GREEN, new Coordinates(1,0), new Coordinates(1,1), new Coordinates(1,2), new Coordinates(1,3))}; shapes[L_SHAPE] = new Shape[]{ new Shape(Color.CYAN,new Coordinates(0,1),new Coordinates(0,0),new Coordinates(0,2), new Coordinates(1,2)), new Shape(Color.CYAN,new Coordinates(-1,1),new Coordinates(0,1),new Coordinates(1,1), new Coordinates(1,0)), new Shape(Color.CYAN,new Coordinates(0,1),new Coordinates(0,0),new Coordinates(0,2), new Coordinates(-1,0)), new Shape(Color.CYAN,new Coordinates(0,1),new Coordinates(-1,1),new Coordinates(1,1), new Coordinates(-1,2))}; shapes[J_SHAPE] = new Shape[]{ new Shape(Color.ORANGE, new Coordinates(1,0), new Coordinates(1,1), new Coordinates(1,2), new Coordinates(0,2)), new Shape(Color.ORANGE, new Coordinates(0,1), new Coordinates(1,1), new Coordinates(2,1), new Coordinates(2,2)), new Shape(Color.ORANGE, new Coordinates(1,0), new Coordinates(1,1), new Coordinates(1,2), new Coordinates(2,0)), new Shape(Color.ORANGE, new Coordinates(0,1), new Coordinates(1,1), new Coordinates(2,1), new Coordinates(0,0))}; shapes[Z_SHAPE] = new Shape[]{ new Shape(Color.YELLOW, new Coordinates(0,1),new Coordinates(1,0),new Coordinates(1,1), new Coordinates(0,2)), new Shape(Color.YELLOW, new Coordinates(-1,0),new Coordinates(0,0),new Coordinates(1,1), new Coordinates(0,1)), new Shape(Color.YELLOW, new Coordinates(0,1),new Coordinates(1,0),new Coordinates(1,1), new Coordinates(0,2)), new Shape(Color.YELLOW, new Coordinates(-1,0),new Coordinates(0,0),new Coordinates(1,1), new Coordinates(0,1))}; shapes[S_SHAPE] = new Shape[]{ new Shape(Color.RED, new Coordinates(0,1),new Coordinates(0,0),new Coordinates(1,1), new Coordinates(1,2)), new Shape(Color.RED, new Coordinates(0,1),new Coordinates(0,0),new Coordinates(1,0), new Coordinates(-1,1)), new Shape(Color.RED, new Coordinates(0,1),new Coordinates(0,0),new Coordinates(1,1), new Coordinates(1,2)), new Shape(Color.RED, new Coordinates(0,1),new Coordinates(0,0),new Coordinates(1,0), new Coordinates(-1,1))}; shapes[SQUARE] = new Shape[]{ new Shape(Color.MAGENTA, new Coordinates(0,0),new Coordinates(0,1),new Coordinates(1,0), new Coordinates(1,1)), new Shape(Color.MAGENTA, new Coordinates(0,0),new Coordinates(0,1),new Coordinates(1,0), new Coordinates(1,1)), new Shape(Color.MAGENTA, new Coordinates(0,0),new Coordinates(0,1),new Coordinates(1,0), new Coordinates(1,1)), new Shape(Color.MAGENTA, new Coordinates(0,0),new Coordinates(0,1),new Coordinates(1,0), new Coordinates(1,1))}; shapes[T_SHAPE] = new Shape[]{ new Shape(Color.PINK, new Coordinates(1,1), new Coordinates(0,1), new Coordinates(2,1), new Coordinates(1,0)), new Shape(Color.PINK, new Coordinates(1,1), new Coordinates(0,1), new Coordinates(1,2), new Coordinates(1,0)), new Shape(Color.PINK, new Coordinates(1,1), new Coordinates(0,1), new Coordinates(2,1), new Coordinates(1,2)), new Shape(Color.PINK, new Coordinates(1,1), new Coordinates(1,2), new Coordinates(2,1), new Coordinates(1,0)),}; } public int[][] plane; private Random rand; private int currentShape; private int nextShape; private int currentRotation; private Coordinates currentCoordinate; private KeyListener theKeyListener; private Timer timer; private int score; public Canvas(){ score = 0; plane = new int[WIDTH][HEIGHT]; for(int i = 0; i < WIDTH; i++){ for(int j = 0; j < HEIGHT; j++){ if(i == 0 || i == WIDTH - 1 || j == HEIGHT - 1) plane[i][j] = -2; else plane[i][j] = -1; } } ActionListener theActionListener = new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ moveDown(); } }; timer = new Timer(REFRESH_RATE, theActionListener); timer.start(); rand = new Random(); nextShape = rand.nextInt(7); generateShape(); theKeyListener = new KeyListener(){ public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e){} public void keyPressed(KeyEvent e){ switch(e.getKeyCode()){ case KeyEvent.VK_UP: rotate(); break; case KeyEvent.VK_DOWN: moveDown(); break; case KeyEvent.VK_LEFT: moveLeft(); break; case KeyEvent.VK_RIGHT: moveRight(); break; case KeyEvent.VK_SPACE: moveButtom(); break; } } }; } private void generateShape(){ currentShape = nextShape; nextShape = rand.nextInt(7); currentRotation = 0; currentCoordinate = new Coordinates(6,0); for(Coordinates c : shapes[currentShape][currentRotation].getCoordinates()){ if(plane[currentCoordinate.getX() + c.getX()][currentCoordinate.getY() + c.getY()] != -1){ timer.stop(); JOptionPane.showMessageDialog(null, "Game Over!"); break; } } repaint(); } private void resetShape(){ for(Coordinates c : shapes[currentShape][currentRotation].getCoordinates()) plane[currentCoordinate.getX() + c.getX()][currentCoordinate.getY() + c.getY()] = currentShape; generateShape(); } private boolean canMove(Coordinates coordinate, int shape, int rotation){ for(Coordinates c : shapes[shape][rotation].getCoordinates()) if(coordinate.getX() + c.getX() >= WIDTH || coordinate.getX() + c.getX() <= 0 || coordinate.getY() + c.getY() >= HEIGHT - 1 || coordinate.getY() + c.getY() < 0 || plane[coordinate.getX() + c.getX()][coordinate.getY() + c.getY()] != -1) return false; return true; } private boolean rotate(){ //check if can be rotated and then rotate if(canMove(currentCoordinate, currentShape, (currentRotation + 1) % 4)){ currentRotation = (currentRotation + 1) % 4; repaint(); return true; } return false; } private boolean moveDown(){ //determining if the blocks can be moved further down if(canMove(new Coordinates(currentCoordinate.getX(), currentCoordinate.getY() + 1), currentShape, currentRotation)){ currentCoordinate = new Coordinates(currentCoordinate.getX(), currentCoordinate.getY() + 1); repaint(); return true; } resetShape(); while(isRowFilled()) clearRow(); return false; } private boolean moveLeft(){ if(canMove(new Coordinates(currentCoordinate.getX() - 1, currentCoordinate.getY()), currentShape, currentRotation)){ currentCoordinate = new Coordinates(currentCoordinate.getX() - 1, currentCoordinate.getY()); repaint(); return true; } return false; } private boolean moveRight(){ if(canMove(new Coordinates(currentCoordinate.getX() + 1, currentCoordinate.getY()), currentShape, currentRotation)){ currentCoordinate = new Coordinates(currentCoordinate.getX() + 1, currentCoordinate.getY()); repaint(); return true; } return false; } private void moveButtom(){ while(moveDown()); } private boolean isRowFilled(){ for(int x = 1; x < WIDTH - 1; x++) if(plane[x][HEIGHT - 2] == -1) return false; return true; } private void clearRow(){ for(int x = 1; x < WIDTH - 1; x++){ for(int y = HEIGHT - 2; y > 0; y--) plane[x][y] = plane[x][y - 1]; plane[x][0] = -1; } score += 10; repaint(); } public KeyListener getKeyListener(){ return theKeyListener; } @Override public void paintComponent(Graphics g){ super.paintComponent(g); for(Coordinates c : shapes[currentShape][currentRotation].getCoordinates()) plane[currentCoordinate.getX() + c.getX()][currentCoordinate.getY() + c.getY()] = currentShape; for(int i = 0; i < WIDTH; i++) for(int j = 0; j < HEIGHT; j++) paintSquare(g, new Coordinates(i, j), plane[i][j]); for(Coordinates c : shapes[currentShape][currentRotation].getCoordinates()) plane[currentCoordinate.getX() + c.getX()][currentCoordinate.getY() + c.getY()] = -1; g.setColor(Color.BLACK); g.drawString("Next shape", (WIDTH + 2) * SIDE_OF_SQUARE, SIDE_OF_SQUARE); for(Coordinates c : shapes[nextShape][0].getCoordinates()) paintSquare(g, new Coordinates(c.getX() + WIDTH + 2, c.getY() + 3), nextShape); g.setColor(Color.BLACK); g.drawString("Score: " + String.valueOf(score), (WIDTH + 2) * SIDE_OF_SQUARE, 8 * SIDE_OF_SQUARE); } private void paintSquare(Graphics g, Coordinates topLeftPoint, int colorCode){ if(colorCode == -1) return; g.setColor(Color.BLACK); g.drawRect(topLeftPoint.getX() * SIDE_OF_SQUARE, topLeftPoint.getY() * SIDE_OF_SQUARE, SIDE_OF_SQUARE, SIDE_OF_SQUARE); if(colorCode >= 0 && colorCode < NUM_OF_SHAPES) g.setColor(shapes[colorCode][currentRotation].getColor()); else if(colorCode == -2) g.setColor(Color.WHITE); g.fillRect(topLeftPoint.getX() * SIDE_OF_SQUARE, topLeftPoint.getY() * SIDE_OF_SQUARE, SIDE_OF_SQUARE, SIDE_OF_SQUARE); } }
Fix clearRow method, add pause functionality
Canvas.java
Fix clearRow method, add pause functionality
<ide><path>anvas.java <ide> private KeyListener theKeyListener; <ide> private Timer timer; <ide> private int score; <add> private boolean gameActive; <ide> <ide> public Canvas(){ <ide> score = 0; <add> gameActive = true; <ide> plane = new int[WIDTH][HEIGHT]; <del> for(int i = 0; i < WIDTH; i++){ <del> for(int j = 0; j < HEIGHT; j++){ <add> for(int i = 0; i < WIDTH; i++) <add> for(int j = 0; j < HEIGHT; j++) <ide> if(i == 0 || i == WIDTH - 1 || j == HEIGHT - 1) <ide> plane[i][j] = -2; <ide> else <ide> plane[i][j] = -1; <del> } <del> } <ide> <ide> ActionListener theActionListener = new ActionListener(){ <ide> @Override <ide> public void actionPerformed(ActionEvent e){ <del> moveDown(); <add> if(gameActive) <add> moveDown(); <ide> } <ide> }; <ide> <ide> theKeyListener = new KeyListener(){ <ide> public void keyTyped(KeyEvent e){} <ide> public void keyReleased(KeyEvent e){} <add> @Override <ide> public void keyPressed(KeyEvent e){ <ide> switch(e.getKeyCode()){ <ide> case KeyEvent.VK_UP: <del> rotate(); <add> if(gameActive) <add> rotate(); <ide> break; <ide> case KeyEvent.VK_DOWN: <del> moveDown(); <add> if(gameActive) <add> moveDown(); <ide> break; <ide> case KeyEvent.VK_LEFT: <del> moveLeft(); <add> if(gameActive) <add> moveLeft(); <ide> break; <ide> case KeyEvent.VK_RIGHT: <del> moveRight(); <add> if(gameActive) <add> moveRight(); <ide> break; <ide> case KeyEvent.VK_SPACE: <del> moveButtom(); <del> break; <add> if(gameActive) <add> moveButtom(); <add> break; <add> case KeyEvent.VK_P: <add> gameActive = false; <add> break; <add> case KeyEvent.VK_R: <add> gameActive = true; <ide> } <ide> } <ide> }; <ide> <ide> currentCoordinate = new Coordinates(6,0); <ide> <del> for(Coordinates c : shapes[currentShape][currentRotation].getCoordinates()){ <add> for(Coordinates c : shapes[currentShape][currentRotation].getCoordinates()) <ide> if(plane[currentCoordinate.getX() + c.getX()][currentCoordinate.getY() + c.getY()] != -1){ <del> timer.stop(); <add> gameActive = false; <ide> JOptionPane.showMessageDialog(null, "Game Over!"); <ide> break; <ide> } <del> } <ide> repaint(); <ide> } <ide> <ide> } <ide> <ide> private boolean canMove(Coordinates coordinate, int shape, int rotation){ <del> <ide> for(Coordinates c : shapes[shape][rotation].getCoordinates()) <ide> if(coordinate.getX() + c.getX() >= WIDTH || coordinate.getX() + c.getX() <= 0 <ide> || coordinate.getY() + c.getY() >= HEIGHT - 1 || coordinate.getY() + c.getY() < 0 <ide> || plane[coordinate.getX() + c.getX()][coordinate.getY() + c.getY()] != -1) <ide> return false; <del> <ide> return true; <ide> } <ide> <ide> private boolean rotate(){ <del> <del> //check if can be rotated and then rotate <ide> if(canMove(currentCoordinate, currentShape, (currentRotation + 1) % 4)){ <ide> currentRotation = (currentRotation + 1) % 4; <ide> repaint(); <ide> return true; <ide> } <del> <ide> return false; <del> <ide> } <ide> <ide> private boolean moveDown(){ <del> <del> //determining if the blocks can be moved further down <ide> if(canMove(new Coordinates(currentCoordinate.getX(), currentCoordinate.getY() + 1), currentShape, currentRotation)){ <ide> currentCoordinate = new Coordinates(currentCoordinate.getX(), currentCoordinate.getY() + 1); <ide> repaint(); <ide> return true; <ide> } <del> <ide> resetShape(); <del> while(isRowFilled()) <del> clearRow(); <add> clearRow(); <ide> return false; <ide> } <ide> <ide> private boolean moveLeft(){ <del> <ide> if(canMove(new Coordinates(currentCoordinate.getX() - 1, currentCoordinate.getY()), currentShape, currentRotation)){ <ide> currentCoordinate = new Coordinates(currentCoordinate.getX() - 1, currentCoordinate.getY()); <ide> repaint(); <ide> } <ide> <ide> private boolean moveRight(){ <del> <ide> if(canMove(new Coordinates(currentCoordinate.getX() + 1, currentCoordinate.getY()), currentShape, currentRotation)){ <ide> currentCoordinate = new Coordinates(currentCoordinate.getX() + 1, currentCoordinate.getY()); <ide> repaint(); <ide> while(moveDown()); <ide> } <ide> <del> private boolean isRowFilled(){ <add> private boolean isRowFilled(int y){ <ide> for(int x = 1; x < WIDTH - 1; x++) <del> if(plane[x][HEIGHT - 2] == -1) <add> if(plane[x][y] == -1) <ide> return false; <ide> return true; <ide> } <ide> <ide> private void clearRow(){ <del> for(int x = 1; x < WIDTH - 1; x++){ <del> for(int y = HEIGHT - 2; y > 0; y--) <del> plane[x][y] = plane[x][y - 1]; <del> plane[x][0] = -1; <add> int i = HEIGHT - 2; <add> while(i > 0){ <add> if(isRowFilled(i)){ <add> for(int x = 1; x < WIDTH - 1; x++){ <add> for(int y = i; y > 0; y--) <add> plane[x][y] = plane[x][y - 1]; <add> plane[x][0] = -1; <add> } <add> score += 10; <add> }else <add> i--; <ide> } <del> score += 10; <ide> repaint(); <ide> } <ide> <ide> g.drawString("Score: " + String.valueOf(score), (WIDTH + 2) * SIDE_OF_SQUARE, 8 * SIDE_OF_SQUARE); <ide> } <ide> <del> private void paintSquare(Graphics g, Coordinates topLeftPoint, int colorCode){ <del> <del> if(colorCode == -1) <add> private void paintSquare(Graphics g, Coordinates topLeftPoint, int color){ <add> <add> if(color == -1) <ide> return; <ide> <ide> g.setColor(Color.BLACK); <ide> SIDE_OF_SQUARE, <ide> SIDE_OF_SQUARE); <ide> <del> if(colorCode >= 0 && colorCode < NUM_OF_SHAPES) <del> g.setColor(shapes[colorCode][currentRotation].getColor()); <del> else if(colorCode == -2) <add> if(color >= 0 && color < NUM_OF_SHAPES) <add> g.setColor(shapes[color][currentRotation].getColor()); <add> else if(color == -2) <ide> g.setColor(Color.WHITE); <ide> <ide> g.fillRect(topLeftPoint.getX() * SIDE_OF_SQUARE,
Java
mit
8f4fb2998f888421ac8e43a1c2a1b5edcce3a50b
0
xxyy/xyc
/* * Copyright (c) 2013 - 2015 xxyy (Philipp Nowak; [email protected]). All rights reserved. * * Any usage, including, but not limited to, compiling, running, redistributing, printing, * copying and reverse-engineering is strictly prohibited without explicit written permission * from the original author and may result in legal steps being taken. * * See the included LICENSE file (core/src/main/resources) or email [email protected] for details. */ package li.l1t.common.tree; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Spliterators; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * Simple implementation of a tree node. * * @param <N> the node type of the tree this node is part of * @param <V> the value type of the tree this node is part of * @author <a href="http://xxyy.github.io/">xxyy</a> * @since 2016-06-22 */ @SuppressWarnings("WeakerAccess") public class SimpleTreeNode<N extends TreeNode<N, V>, V> implements TreeNode<N, V> { private final N parent; private final Class<N> nodeClass; //for checking of nodes private final List<N> children = new ArrayList<>(4); //and even that is an exaggeration private V value; private int[] position; public SimpleTreeNode(N parent, Class<N> nodeClass) { this.nodeClass = nodeClass; checkNodeType(getClass()); this.parent = parent; if (parent != null) { position = Arrays.copyOf(parent.getPosition(), parent.getPosition().length + 1); position[position.length - 1] = parent.getChildren().size(); //must be id of next child, that's us } else { position = new int[0]; //We're the root node } } @Override public N getParent() { return parent; } @Override public List<N> getChildren() { return children; } @Override public void addChild(N newChild) { checkNodeType(newChild.getClass()); children.add(newChild); } @Override public void removeChild(N oldChild) { //no type check necessary: child type gets checked on add, anything else won't have any effect children.remove(oldChild); forEachNode(TreeNode::updatePosition); //update children positions } @Override public boolean isRoot() { return parent == null; } @Override public boolean hasChildren() { return !children.isEmpty(); } @Override public boolean isBranching() { return children.size() > 1; } @Override public V getValue() { return value; } @Override public void setValue(V newValue) { this.value = newValue; } @Override public int getChildId(N child) { Preconditions.checkArgument(children.contains(child), "%s must be a direct child!", child); return getChildren().indexOf(child); } @Override public int[] getPosition() { return position; } @Override @SuppressWarnings("unchecked") public void updatePosition() { position = Arrays.copyOf(parent.getPosition(), parent.getPosition().length + 1); position[position.length - 1] = parent.getChildId((N) this); // <-- unchecked (check in constructor) } @Override public N getChild(int childId) { return children.get(childId); } @SuppressWarnings("unchecked") @Override public N getChild(int[] position) { N node = (N) this; //<-- unchecked (not necessary because we check in constructor) for (int childId : position) { //go all the way down node = node.getChild(childId); //select the child at that position } // v zero-length arrays return ourselves return node; } @Override public boolean hasChild(int childId) { return childId < getChildren().size(); } /** * <p><b>Attention:</b> Read {@link TreeNodeSpliterator the node spliterator's JavaDoc} for * important notes about its behaviour.</p> * {@inheritDoc} */ @Override public Iterator<V> iterator() { return Spliterators.iterator(spliterator()); } /** * <p><b>Attention:</b> Read {@link TreeNodeSpliterator the node spliterator's JavaDoc} for * important notes about its behaviour.</p> * {@inheritDoc} */ @Override public void forEach(Consumer<? super V> action) { spliterator().forEachRemaining(action); } /** * <p><b>Attention:</b> Read {@link TreeNodeSpliterator the node spliterator's JavaDoc} for * important notes about its behaviour.</p> * {@inheritDoc} */ @Override public TreeValueSpliterator<N, V> spliterator() { return new TreeValueSpliterator<>(nodeSpliterator()); } @Override public Stream<V> stream() { return StreamSupport.stream(spliterator(), false); } @Override @SuppressWarnings("unchecked") public TreeNodeSpliterator<N, V> nodeSpliterator() { return new TreeNodeSpliterator<>((N) this); } @Override public Stream<N> nodeStream() { return StreamSupport.stream(nodeSpliterator(), false); } @Override public void forEachNode(Consumer<? super N> action) { nodeSpliterator().forEachRemaining(action); } private void checkNodeType(Class<?> aClass) { Preconditions.checkArgument(nodeClass.isAssignableFrom(aClass), "node must be subclass of <N> (%s), is: %s", nodeClass, aClass); } }
core/src/main/java/li/l1t/common/tree/SimpleTreeNode.java
/* * Copyright (c) 2013 - 2015 xxyy (Philipp Nowak; [email protected]). All rights reserved. * * Any usage, including, but not limited to, compiling, running, redistributing, printing, * copying and reverse-engineering is strictly prohibited without explicit written permission * from the original author and may result in legal steps being taken. * * See the included LICENSE file (core/src/main/resources) or email [email protected] for details. */ package li.l1t.common.tree; import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Spliterators; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * Simple implementation of a tree node. * * @param <N> the node type of the tree this node is part of * @param <V> the value type of the tree this node is part of * @author <a href="http://xxyy.github.io/">xxyy</a> * @since 2016-06-22 */ @SuppressWarnings("WeakerAccess") public class SimpleTreeNode<N extends TreeNode<N, V>, V> implements TreeNode<N, V> { private final N parent; private final Class<N> nodeClass; //for checking of nodes private final List<N> children = new ArrayList<>(4); //and even that is an exaggeration private V value; private int[] position; public SimpleTreeNode(N parent, Class<N> nodeClass) { this.nodeClass = nodeClass; checkNodeType(getClass()); this.parent = parent; if (parent != null) { position = Arrays.copyOf(parent.getPosition(), parent.getPosition().length + 1); position[position.length - 1] = parent.getChildren().size(); //must be id of next child, that's us } else { position = new int[0]; //We're the root node } } @Override public N getParent() { return parent; } @Override public List<N> getChildren() { return children; } @Override public void addChild(N newChild) { Preconditions.checkArgument(nodeClass.isAssignableFrom(newChild.getClass()), ""); children.add(newChild); } @Override public void removeChild(N oldChild) { //no type check necessary: child type gets checked on add, anything else won't have any effect children.remove(oldChild); forEachNode(TreeNode::updatePosition); //update children positions } @Override public boolean isRoot() { return parent == null; } @Override public boolean hasChildren() { return !children.isEmpty(); } @Override public boolean isBranching() { return children.size() > 1; } @Override public V getValue() { return value; } @Override public void setValue(V newValue) { this.value = newValue; } @Override public int getChildId(N child) { Preconditions.checkArgument(children.contains(child), "%s must be a direct child!", child); return getChildren().indexOf(child); } @Override public int[] getPosition() { return position; } @Override @SuppressWarnings("unchecked") public void updatePosition() { position = Arrays.copyOf(parent.getPosition(), parent.getPosition().length + 1); position[position.length - 1] = parent.getChildId((N) this); // <-- unchecked (check in constructor) } @Override public N getChild(int childId) { return children.get(childId); } @SuppressWarnings("unchecked") @Override public N getChild(int[] position) { N node = (N) this; //<-- unchecked (not necessary because we check in constructor) for (int childId : position) { //go all the way down node = node.getChild(childId); //select the child at that position } // v zero-length arrays return ourselves return node; } @Override public boolean hasChild(int childId) { return childId < getChildren().size(); } /** * <p><b>Attention:</b> Read {@link TreeNodeSpliterator the node spliterator's JavaDoc} for * important notes about its behaviour.</p> * {@inheritDoc} */ @Override public Iterator<V> iterator() { return Spliterators.iterator(spliterator()); } /** * <p><b>Attention:</b> Read {@link TreeNodeSpliterator the node spliterator's JavaDoc} for * important notes about its behaviour.</p> * {@inheritDoc} */ @Override public void forEach(Consumer<? super V> action) { spliterator().forEachRemaining(action); } /** * <p><b>Attention:</b> Read {@link TreeNodeSpliterator the node spliterator's JavaDoc} for * important notes about its behaviour.</p> * {@inheritDoc} */ @Override public TreeValueSpliterator<N, V> spliterator() { return new TreeValueSpliterator<>(nodeSpliterator()); } @Override public Stream<V> stream() { return StreamSupport.stream(spliterator(), false); } @Override @SuppressWarnings("unchecked") public TreeNodeSpliterator<N, V> nodeSpliterator() { return new TreeNodeSpliterator<>((N) this); } @Override public Stream<N> nodeStream() { return StreamSupport.stream(nodeSpliterator(), false); } @Override public void forEachNode(Consumer<? super N> action) { nodeSpliterator().forEachRemaining(action); } private void checkNodeType(Class<?> aClass) { Preconditions.checkArgument(aClass.isAssignableFrom(nodeClass), "node must be subclass of <N> (%s), is: %s", nodeClass, aClass); } }
Actually fix unable to add subclasses of <N> to tree nodes
core/src/main/java/li/l1t/common/tree/SimpleTreeNode.java
Actually fix unable to add subclasses of <N> to tree nodes
<ide><path>ore/src/main/java/li/l1t/common/tree/SimpleTreeNode.java <ide> <ide> @Override <ide> public void addChild(N newChild) { <del> Preconditions.checkArgument(nodeClass.isAssignableFrom(newChild.getClass()), ""); <add> checkNodeType(newChild.getClass()); <ide> children.add(newChild); <ide> } <ide> <ide> } <ide> <ide> private void checkNodeType(Class<?> aClass) { <del> Preconditions.checkArgument(aClass.isAssignableFrom(nodeClass), <add> Preconditions.checkArgument(nodeClass.isAssignableFrom(aClass), <ide> "node must be subclass of <N> (%s), is: %s", nodeClass, aClass); <ide> } <ide> }
JavaScript
mit
217fb242e5918305cd960d6fd30ee2e1487e3bb9
0
jcquery/represent
'use strict' const fsp = require('../src/node_modules/fs-promise') const axios = require('../src/node_modules/axios') const dotenv = require('../src/node_modules/dotenv').config() const path = require('path') const AWS = require('../src/node_modules/aws-sdk') const Promise = require('../src/node_modules/bluebird') AWS.config.update({ region: 'us-east-1', accessKeyId: process.env.AWS_FULL_ID, secretAccessKey: process.env.AWS_FULL_SECRET }) AWS.config.setPromisesDependency(Promise) const table = new AWS.DynamoDB({apiVersion: '2012-08-10', params: {TableName: 'represent'}}) function getReps () { console.log('getting reps') axios.get('https://congress.api.sunlightfoundation.com/legislators?fields=aliases,bioguide_id&per_page=all') .then((res) => { console.log('got \'em') return createEntries(buildMap(res.data.results)) }) .catch((error) => { return { error } }) } function buildMap (list) { console.log('building a hashmap') return list.reduce((obj, rep) => { for (let alias of rep.aliases) { if (alias === null || alias.includes('Rep. ') || alias.includes('Sen. ') || alias.includes('Com. ')) { continue } if (!obj[alias]) { obj[alias] = [rep.bioguide_id] } else { obj[alias].push(rep.bioguide_id) } } return obj }, {}) } function createEntries (obj) { console.log('creating database entries') var promiseArr = [] Object.keys(obj).forEach((name) => { var params = { Item: { rep_name: { S: name }, rep_id: { S: obj[name].join(',') } } } promiseArr.push(table.putItem(params).promise()) }) console.log('created promises') Promise.map(promiseArr, (put) => put, { concurrency: 3 }) .then(() => { fsp.writeFile(path.join(__dirname, '/congressMap.json'), JSON.stringify(obj)) }) .then(() => { console.log('success') }) .catch((err) => { throw err }) } getReps()
generation/dynamoGenerate.js
'use strict' const fsp = require('fs-promise') const axios = require('axios') const dotenv = require('dotenv').config() const path = require('path') const AWS = require('aws-sdk') const Promise = require('bluebird') AWS.config.update({ region: 'us-east-1', accessKeyId: process.env.AWS_FULL_ID, secretAccessKey: process.env.AWS_FULL_SECRET }) AWS.config.setPromisesDependency(Promise) const table = new AWS.DynamoDB({apiVersion: '2012-08-10', params: {TableName: 'represent'}}) function getReps () { console.log('getting reps') axios.get('https://congress.api.sunlightfoundation.com/legislators?fields=aliases,bioguide_id&per_page=all') .then((res) => { console.log('got \'em') return createEntries(buildMap(res.data.results)) }) .catch((error) => { return { error } }) } function buildMap (list) { console.log('building a hashmap') return list.reduce((obj, rep) => { for (let alias of rep.aliases) { if (alias === null || alias.includes('Rep. ') || alias.includes('Sen. ') || alias.includes('Com. ')) { continue } if (!obj[alias]) { obj[alias] = [rep.bioguide_id] } else { obj[alias].push(rep.bioguide_id) } } return obj }, {}) } function createEntries (obj) { console.log('creating database entries') var promiseArr = [] Object.keys(obj).forEach((name) => { var params = { Item: { rep_name: { S: name }, rep_id: { S: obj[name].join(',') } } } promiseArr.push(table.putItem(params).promise()) }) console.log('created promises') Promise.map(promiseArr, (put) => put, { concurrency: 3 }) .then(() => { fsp.writeFile(path.join(__dirname, '/congressMap.json'), JSON.stringify(obj)) }) .then(() => { console.log('success') }) .catch((err) => { throw err }) } getReps()
update dependency tree
generation/dynamoGenerate.js
update dependency tree
<ide><path>eneration/dynamoGenerate.js <ide> 'use strict' <ide> <del>const fsp = require('fs-promise') <del>const axios = require('axios') <del>const dotenv = require('dotenv').config() <add>const fsp = require('../src/node_modules/fs-promise') <add>const axios = require('../src/node_modules/axios') <add>const dotenv = require('../src/node_modules/dotenv').config() <ide> const path = require('path') <del>const AWS = require('aws-sdk') <del>const Promise = require('bluebird') <add>const AWS = require('../src/node_modules/aws-sdk') <add>const Promise = require('../src/node_modules/bluebird') <ide> <ide> AWS.config.update({ <ide> region: 'us-east-1',
Java
apache-2.0
4d18e383dd681bde968a15e97d6e5238dd15a7a5
0
MICommunity/psi-jami,MICommunity/psi-jami,MICommunity/psi-jami
package psidev.psi.mi.jami.datasource; import psidev.psi.mi.jami.exception.DataSourceWriterException; import psidev.psi.mi.jami.model.Interaction; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * The InteractionWriter can write interactions in a datasource (files, database) * * @author Marine Dumousseau ([email protected]) * @version $Id$ * @since <pre>07/06/13</pre> */ public interface InteractionWriter<T extends Interaction> { /** * Initialise the context of the InteractionWriter given a map of options * @param options */ public void initialiseContext(Map<String, Object> options); /** * Writes an interaction * @param interaction */ public void write(T interaction) throws DataSourceWriterException; /** * Writes a collection of Interaction objects * @param interactions */ public void write(Collection<T> interactions) throws DataSourceWriterException; /** * Writes Interaction objects using iterator * @param interactions */ public void write(Iterator<T> interactions) throws DataSourceWriterException; /** * Flushes the writer (commit or write on disk) */ public void flush() throws DataSourceWriterException; /** * Closes the InteractionWriter. It will flushes before closing. */ public void close() throws DataSourceWriterException; }
jami-core/src/main/java/psidev/psi/mi/jami/datasource/InteractionWriter.java
package psidev.psi.mi.jami.datasource; import psidev.psi.mi.jami.exception.DataSourceWriterException; import psidev.psi.mi.jami.model.Interaction; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * The InteractionWriter can write interactions in a datasource (files, database) * * @author Marine Dumousseau ([email protected]) * @version $Id$ * @since <pre>07/06/13</pre> */ public interface InteractionWriter<T extends Interaction> { /** * Initialise the context of the InteractionWriter given a map of options * @param options */ public void initialiseContext(Map<String, Object> options) throws DataSourceWriterException; /** * Writes an interaction * @param interaction */ public void write(T interaction) throws DataSourceWriterException; /** * Writes a collection of Interaction objects * @param interactions */ public void write(Collection<T> interactions) throws DataSourceWriterException; /** * Writes Interaction objects using iterator * @param interactions */ public void write(Iterator<T> interactions) throws DataSourceWriterException; /** * Flushes the writer (commit or write on disk) */ public void flush() throws DataSourceWriterException; /** * Closes the InteractionWriter. It will flushes before closing. */ public void close() throws DataSourceWriterException; }
Updated InteractionWriter interface
jami-core/src/main/java/psidev/psi/mi/jami/datasource/InteractionWriter.java
Updated InteractionWriter interface
<ide><path>ami-core/src/main/java/psidev/psi/mi/jami/datasource/InteractionWriter.java <ide> * Initialise the context of the InteractionWriter given a map of options <ide> * @param options <ide> */ <del> public void initialiseContext(Map<String, Object> options) throws DataSourceWriterException; <add> public void initialiseContext(Map<String, Object> options); <ide> <ide> /** <ide> * Writes an interaction
JavaScript
mit
269c5bfd2f812a45c92550f5ae76fb02526182a9
0
susisu/Optics
/* * Optics / command.js * copyright (c) 2016 Susisu */ /** * @module command */ "use strict"; function endModule() { module.exports = Object.freeze({ Argument, OptionalArgument, RequiredArgument, CommandBase, Command }); } /** * The `Argument` class is the base class of command arguments. * @static */ class Argument { /** * Create a new `Argument` instance. */ constructor() { } /** * Returns if the argument is required. * @throws {Error} Not implemented. */ isRequired() { throw new Error("not implemented"); } /** * Returns a string which is used as a placeholder in command description. * @throws {Error} Not implemented. */ toPlaceholder() { throw new Error("not implemented"); } /** * Returns the default value, which is used when the argument is not specified. * @throws {Error} Not implemented. */ getDefaultValue() { throw new Error("not implemented"); } } class OptionalArgument extends Argument { constructor(placeholder, defaultVal, reader) { super(); this.placeholder = placeholder; this.defaultVal = defaultVal; this.reader = reader; } } class RequiredArgument extends Argument { constructor(placeholder, reader) { super(); this.placeholder = placeholder; this.reader = reader; } } /** * The `CommandBase` class is the base class of commands. * @static */ class CommandBase { /** * Creates an instance of `CommandBase`. */ constructor() { } /** * Parse `argv` and run action associated with the command. * @param {module:output.Output} out Output target. * @param {string[]} argv Command-line arguments. * @throws {Error} Not implemented. */ run(out, argv) { throw new Error("not implemented"); } } /** * An instance of the `Command` class represents an ordinary command. * @extends module:command.CommandBase * @static */ class Command extends CommandBase { /** * Creates an instance of `Command`. * @param {string} desc * @param {module:command.Argument[]} args * @param {module:option.Option[]} opts * @param {Function} action */ constructor(desc, args, opts, action) { super(); this.desc = desc; this.args = args; this.opts = opts; this.action = action; } } endModule();
lib/command.js
/* * Optics / command.js * copyright (c) 2016 Susisu */ /** * @module command */ "use strict"; function endModule() { module.exports = Object.freeze({ Argument, OptionalArgument, RequiredArgument, CommandBase, Command }); } /** * The `Argument` class is the base class of command arguments. * @static */ class Argument { /** * Create a new `Argument` instance. */ constructor() { } /** * Returns if the argument is required. * @throws {Error} Not implemented. */ isRequired() { throw new Error("not implemented"); } /** * Returns a string which is used as a placeholder in command description. * @throws {Error} Not implemented. */ toPlaceholder() { throw new Error("not implemented"); } /** * Returns the default value, which is used when the argument is not specified. * @throws {Error} Not implemented. */ getDefaultValue() { throw new Error("not implemented"); } } class OptionalArgument extends Argument { constructor(placeholder, defaultVal, reader) { super(); this.placeholder = placeholder; this.defaultVal = defaultVal; this.reader = reader; } } class RequiredArgument extends Argument { constructor(placeholder, reader) { super(); this.placeholder = placeholder; this.reader = reader; } } /** * The `CommandBase` class is the base class of commands. * @static */ class CommandBase { /** * Create an instance of `CommandBase`. */ constructor() { } /** * Parse `argv` and run action associated with the command. * @param {module:output.Output} out Output target. * @param {string[]} argv Command-line arguments. * @throws {Error} Not implemented. */ run(out, argv) { throw new Error("not implemented"); } } /** * The `Command` class represents an ordinary command. * @extends module:command.CommandBase * @static */ class Command extends CommandBase { /** * Create an instance of `Command`. * @param {string} desc * @param {module:command.Argument[]} args * @param {module:option.Option[]} opts * @param {Function} action */ constructor(desc, args, opts, action) { super(); this.desc = desc; this.args = args; this.opts = opts; this.action = action; } } endModule();
Fix some doc comments
lib/command.js
Fix some doc comments
<ide><path>ib/command.js <ide> */ <ide> class CommandBase { <ide> /** <del> * Create an instance of `CommandBase`. <add> * Creates an instance of `CommandBase`. <ide> */ <ide> constructor() { <ide> } <ide> } <ide> <ide> /** <del> * The `Command` class represents an ordinary command. <add> * An instance of the `Command` class represents an ordinary command. <ide> * @extends module:command.CommandBase <ide> * @static <ide> */ <ide> class Command extends CommandBase { <ide> /** <del> * Create an instance of `Command`. <add> * Creates an instance of `Command`. <ide> * @param {string} desc <ide> * @param {module:command.Argument[]} args <ide> * @param {module:option.Option[]} opts
Java
apache-2.0
9737a4f7bfa8da7cd6caf72d9f91c58f98b9660c
0
synthetichealth/synthea,synthetichealth/synthea,synthetichealth/synthea
package org.mitre.synthea.export; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.nio.file.Files; import java.util.stream.Collectors; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mitre.synthea.TestHelper; import org.mitre.synthea.engine.Generator; import org.mitre.synthea.helpers.Config; import org.mitre.synthea.helpers.SimpleCSV; public class CSVExporterTest { /** * Temporary folder for any exported files, guaranteed to be deleted at the end of the test. */ @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Test public void testCSVExport() throws Exception { TestHelper.exportOff(); Config.set("exporter.csv.export", "true"); File tempOutputFolder = tempFolder.newFolder(); Config.set("exporter.baseDirectory", tempOutputFolder.toString()); int numberOfPeople = 10; Generator generator = new Generator(numberOfPeople); for (int i = 0; i < numberOfPeople; i++) { generator.generatePerson(i); } // if we get here we at least had no exceptions File expectedExportFolder = tempOutputFolder.toPath().resolve("csv").toFile(); assertTrue(expectedExportFolder.exists() && expectedExportFolder.isDirectory()); int count = 0; for (File csvFile : expectedExportFolder.listFiles()) { if (!csvFile.getName().endsWith(".csv")) { continue; } String csvData = Files.readAllLines(csvFile.toPath()).stream() .collect(Collectors.joining("\n")); // the CSV exporter doesn't use the SimpleCSV class to write the data, // so we can use it here for a level of validation SimpleCSV.parse(csvData); count++; } assertEquals("Expected 10 CSV files in the output directory, found " + count, 10, count); } }
src/test/java/org/mitre/synthea/export/CSVExporterTest.java
package org.mitre.synthea.export; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.nio.file.Files; import java.util.stream.Collectors; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mitre.synthea.TestHelper; import org.mitre.synthea.engine.Generator; import org.mitre.synthea.helpers.Config; import org.mitre.synthea.helpers.SimpleCSV; public class CSVExporterTest { /** * Temporary folder for any exported files, guaranteed to be deleted at the end of the test. */ @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Test public void testCSVExport() throws Exception { TestHelper.exportOff(); Config.set("exporter.csv.export", "true"); File tempOutputFolder = tempFolder.newFolder(); Config.set("exporter.baseDirectory", tempOutputFolder.toString()); int numberOfPeople = 10; Generator generator = new Generator(numberOfPeople); for (int i = 0; i < numberOfPeople; i++) { generator.generatePerson(i); } // if we get here we at least had no exceptions File expectedExportFolder = tempOutputFolder.toPath().resolve("csv").toFile(); assertTrue(expectedExportFolder.exists() && expectedExportFolder.isDirectory()); int count = 0; for (File csvFile : expectedExportFolder.listFiles()) { if (!csvFile.getName().endsWith(".csv")) { continue; } String csvData = Files.readAllLines(csvFile.toPath()).stream() .collect(Collectors.joining("\n")); // the CSV exporter doesn't use the SimpleCSV class to write the data, // so we can use it here for a level of validation SimpleCSV.parse(csvData); count++; } assertEquals("Expected 9 CSV files in the output directory, found " + count, 9, count); } }
9 files => 10 files expected
src/test/java/org/mitre/synthea/export/CSVExporterTest.java
9 files => 10 files expected
<ide><path>rc/test/java/org/mitre/synthea/export/CSVExporterTest.java <ide> */ <ide> @Rule <ide> public TemporaryFolder tempFolder = new TemporaryFolder(); <del> <add> <ide> @Test <ide> public void testCSVExport() throws Exception { <ide> TestHelper.exportOff(); <ide> Config.set("exporter.csv.export", "true"); <ide> File tempOutputFolder = tempFolder.newFolder(); <ide> Config.set("exporter.baseDirectory", tempOutputFolder.toString()); <del> <add> <ide> int numberOfPeople = 10; <ide> Generator generator = new Generator(numberOfPeople); <ide> for (int i = 0; i < numberOfPeople; i++) { <ide> generator.generatePerson(i); <ide> } <del> <add> <ide> // if we get here we at least had no exceptions <del> <add> <ide> File expectedExportFolder = tempOutputFolder.toPath().resolve("csv").toFile(); <del> <add> <ide> assertTrue(expectedExportFolder.exists() && expectedExportFolder.isDirectory()); <del> <add> <ide> int count = 0; <ide> for (File csvFile : expectedExportFolder.listFiles()) { <ide> if (!csvFile.getName().endsWith(".csv")) { <ide> continue; <ide> } <del> <add> <ide> String csvData = Files.readAllLines(csvFile.toPath()).stream() <ide> .collect(Collectors.joining("\n")); <del> <add> <ide> // the CSV exporter doesn't use the SimpleCSV class to write the data, <ide> // so we can use it here for a level of validation <ide> SimpleCSV.parse(csvData); <del> <add> <ide> count++; <ide> } <del> <del> assertEquals("Expected 9 CSV files in the output directory, found " + count, 9, count); <add> <add> assertEquals("Expected 10 CSV files in the output directory, found " + count, 10, count); <ide> } <ide> }
JavaScript
bsd-2-clause
a96d560e0bdee7e5000dffe9f01e84ab745c4e8d
0
eegeo/eegeo.js,eegeo/eegeo.js
var Popup = L.Popup.extend({ options: { elevation: 0 }, getElevation: function() { return this.options.elevation; }, setElevation: function(elevation) { this.options.elevation = elevation; return this; }, _updateContent: function () { if (!this._content) { return; } var node = this._contentNode; var content = (typeof this._content === "function") ? this._content(this._source || this) : this._content; var contentNeedsUpdate = true; if (content.outerHTML && content.outerHTML === node.innerHTML) { // This test will fail to detect changes which don't affect HTML, but otherwise the DOM for the popup is // rebuilt every update cycle. This makes embedding external HTML impossible. contentNeedsUpdate = false; } if (typeof content === "string") { node.innerHTML = content; } else if (!node.hasChildNodes() || contentNeedsUpdate) { while (node.hasChildNodes()) { node.removeChild(node.firstChild); } node.appendChild(content); } this.fire("contentupdate"); }, _updatePosition: function() { if (!this._map) { return; } var pos = this._map.getScreenPositionOfLayer(this).round(), offset = L.point(this.options.offset), anchor = this._getAnchor(); if (this._zoomAnimated) { L.DomUtil.setPosition(this._container, pos.add(anchor)); } else { offset = offset.add(pos).add(anchor); } var bottom = this._containerBottom = -offset.y, left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x; // bottom position the popup in case the height of the popup changes (images loading etc) this._container.style.bottom = bottom + "px"; this._container.style.left = left + "px"; } }); var popup = function(options, source) { return new Popup(options, source); }; module.exports = { Popup: Popup, popup: popup };
src/public/popup.js
var Popup = L.Popup.extend({ options: { elevation: 0 }, getElevation: function() { return this.options.elevation; }, setElevation: function(elevation) { this.options.elevation = elevation; return this; }, _updateContent: function () { if (!this._content) { return; } var node = this._contentNode; var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content; var contentNeedsUpdate = true; if (content.outerHTML && content.outerHTML === node.innerHTML) { // This test will fail to detect changes which don't affect HTML, but otherwise the DOM for the popup is // rebuilt every update cycle. This makes embedding external HTML impossible. contentNeedsUpdate = false; } if (typeof content === 'string') { node.innerHTML = content; } else if (!node.hasChildNodes() || contentNeedsUpdate) { while (node.hasChildNodes()) { node.removeChild(node.firstChild); } node.appendChild(content); } this.fire('contentupdate'); }, _updatePosition: function() { if (!this._map) { return; } var pos = this._map.getScreenPositionOfLayer(this).round(), offset = L.point(this.options.offset), anchor = this._getAnchor(); if (this._zoomAnimated) { L.DomUtil.setPosition(this._container, pos.add(anchor)); } else { offset = offset.add(pos).add(anchor); } var bottom = this._containerBottom = -offset.y, left = this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x; // bottom position the popup in case the height of the popup changes (images loading etc) this._container.style.bottom = bottom + "px"; this._container.style.left = left + "px"; } }); var popup = function(options, source) { return new Popup(options, source); }; module.exports = { Popup: Popup, popup: popup };
Fix lint errors. Buddy: Ben
src/public/popup.js
Fix lint errors. Buddy: Ben
<ide><path>rc/public/popup.js <ide> if (!this._content) { return; } <ide> <ide> var node = this._contentNode; <del> var content = (typeof this._content === 'function') ? this._content(this._source || this) : this._content; <add> var content = (typeof this._content === "function") ? this._content(this._source || this) : this._content; <ide> <ide> var contentNeedsUpdate = true; <ide> if (content.outerHTML && content.outerHTML === node.innerHTML) { <ide> contentNeedsUpdate = false; <ide> } <ide> <del> if (typeof content === 'string') { <add> if (typeof content === "string") { <ide> node.innerHTML = content; <ide> } else if (!node.hasChildNodes() || contentNeedsUpdate) { <ide> while (node.hasChildNodes()) { <ide> } <ide> node.appendChild(content); <ide> } <del> this.fire('contentupdate'); <add> this.fire("contentupdate"); <ide> }, <ide> <ide> _updatePosition: function() {
Java
apache-2.0
eb1dfc5d6328b48c5fb6d12b3ae24fbeeb8676b7
0
lucastheisen/apache-directory-server,lucastheisen/apache-directory-server,darranl/directory-server,apache/directory-server,drankye/directory-server,darranl/directory-server,apache/directory-server,drankye/directory-server
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.directory.server.core.partition.impl.btree.jdbm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.directory.server.xdbm.Tuple; import org.apache.directory.server.core.cursor.Cursor; import org.apache.directory.server.core.cursor.InvalidCursorPositionException; import org.apache.directory.server.schema.SerializableComparator; import org.apache.directory.server.schema.registries.ComparatorRegistry; import org.apache.directory.shared.ldap.schema.syntax.ComparatorDescription; import org.junit.Before; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import java.io.File; import java.util.Comparator; import java.util.Iterator; import jdbm.RecordManager; import jdbm.helper.IntegerSerializer; import jdbm.recman.BaseRecordManager; import javax.naming.NamingException; /** * Tests the DupsContainerCursor. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class DupsContainerCursorTest { private static final Logger LOG = LoggerFactory.getLogger( NoDupsCursorTest.class.getSimpleName() ); private static final String TEST_OUTPUT_PATH = "test.output.path"; transient JdbmTable<Integer,Integer> table; transient File dbFile; transient RecordManager recman; private static final int SIZE = 15; @Before public void createTable() throws Exception { File tmpDir = null; if ( System.getProperty( TEST_OUTPUT_PATH, null ) != null ) { tmpDir = new File( System.getProperty( TEST_OUTPUT_PATH ) ); tmpDir.deleteOnExit(); } dbFile = File.createTempFile( getClass().getSimpleName(), "db", tmpDir ); dbFile.deleteOnExit(); recman = new BaseRecordManager( dbFile.getAbsolutePath() ); // gosh this is a terrible use of a global static variable SerializableComparator.setRegistry( new MockComparatorRegistry() ); table = new JdbmTable<Integer,Integer>( "test", SIZE, recman, new SerializableComparator<Integer>( "" ), new SerializableComparator<Integer>( "" ), null, new IntegerSerializer() ); LOG.debug( "Created new table and populated it with data" ); } @After public void destroyTable() throws Exception { table.close(); table = null; recman.close(); recman = null; String fileToDelete = dbFile.getAbsolutePath(); new File( fileToDelete ).delete(); new File( fileToDelete + ".db" ).delete(); new File( fileToDelete + ".lg" ).delete(); dbFile = null; } @Test( expected=IllegalStateException.class ) public void testUsingNoDuplicates() throws Exception { recman = new BaseRecordManager( dbFile.getAbsolutePath() ); // gosh this is a terrible use of a global static variable SerializableComparator.setRegistry( new MockComparatorRegistry() ); table = new JdbmTable<Integer,Integer>( "test", recman, new SerializableComparator<Integer>( "" ), null, null ); Cursor<Tuple<Integer,DupsContainer<Integer>>> cursor = new DupsContainerCursor<Integer,Integer>( table ); assertNotNull( cursor ); } @Test( expected=InvalidCursorPositionException.class ) public void testEmptyTable() throws Exception { Cursor<Tuple<Integer,DupsContainer<Integer>>> cursor = new DupsContainerCursor<Integer,Integer>( table ); assertNotNull( cursor ); assertFalse( cursor.available() ); assertFalse( cursor.isClosed() ); assertTrue( cursor.isElementReused() ); cursor = new DupsContainerCursor<Integer,Integer>( table ); assertFalse( cursor.previous() ); cursor = new DupsContainerCursor<Integer,Integer>( table ); assertFalse( cursor.next() ); cursor.after( new Tuple<Integer,DupsContainer<Integer>>( 7, null ) ); cursor.get(); } @Test public void testOnTableWithSingleEntry() throws Exception { table.put( 1, 1 ); Cursor<Tuple<Integer,DupsContainer<Integer>>> cursor = new DupsContainerCursor<Integer,Integer>( table ); assertTrue( cursor.first() ); Tuple<Integer,DupsContainer<Integer>> tuple = cursor.get(); assertTrue( tuple.getKey().equals( 1 ) ); assertEquals( 1, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); cursor.beforeFirst(); assertFalse( cursor.previous() ); assertTrue( cursor.next() ); } @Test public void testOnTableWithMultipleEntries() throws Exception { for( int i=1; i < 10; i++ ) { table.put( i, i ); } Cursor<Tuple<Integer,DupsContainer<Integer>>> cursor = new DupsContainerCursor<Integer,Integer>( table ); cursor.after( new Tuple<Integer,DupsContainer<Integer>>( 2, null ) ); assertTrue( cursor.next() ); Tuple<Integer,DupsContainer<Integer>> tuple = cursor.get(); assertTrue( tuple.getKey().equals( 3 ) ); assertEquals( 3, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); cursor.before( new Tuple<Integer,DupsContainer<Integer>>( 7, null ) ); cursor.next(); tuple = cursor.get(); assertTrue( tuple.getKey().equals( 7 ) ); assertEquals( 7, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); cursor.last(); cursor.next(); assertFalse( cursor.available() ); /* tuple = cursor.get(); assertTrue( tuple.getKey().equals( 9 ) ); assertEquals( 9, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); */ cursor.beforeFirst(); cursor.next(); tuple = cursor.get(); assertTrue( tuple.getKey().equals( 1 ) ); assertEquals( 1, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); cursor.afterLast(); assertFalse( cursor.next() ); cursor.beforeFirst(); assertFalse( cursor.previous() ); // just to clear the jdbmTuple value so that line 127 inside after(tuple) method // can be executed as part of the below after(tuple) call cursor.before(new Tuple<Integer,DupsContainer<Integer>>( 1, null ) ); cursor.after( new Tuple<Integer,DupsContainer<Integer>>( 0, null ) ); // this positions on tuple with key 1 cursor.next(); // this moves onto tuple with key 2 tuple = cursor.get(); assertTrue( tuple.getKey().equals( 2 ) ); assertEquals( 2, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); } @Test public void testMiscellaneous() throws Exception { } private class MockComparatorRegistry implements ComparatorRegistry { private Comparator<Integer> comparator = new Comparator<Integer>() { public int compare( Integer i1, Integer i2 ) { return i1.compareTo( i2 ); } }; public String getSchemaName( String oid ) throws NamingException { return null; } public void register( ComparatorDescription description, Comparator comparator ) throws NamingException { } public Comparator lookup( String oid ) throws NamingException { return comparator; } public boolean hasComparator( String oid ) { return true; } public Iterator<String> oidIterator() { return null; } public Iterator<ComparatorDescription> comparatorDescriptionIterator() { return null; } public void unregister( String oid ) throws NamingException { } public void unregisterSchemaElements( String schemaName ) { } public void renameSchema( String originalSchemaName, String newSchemaName ) { } } }
jdbm-store/src/test/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsContainerCursorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.directory.server.core.partition.impl.btree.jdbm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.directory.server.xdbm.Tuple; import org.apache.directory.server.core.cursor.Cursor; import org.apache.directory.server.core.cursor.InvalidCursorPositionException; import org.apache.directory.server.schema.SerializableComparator; import org.apache.directory.server.schema.registries.ComparatorRegistry; import org.apache.directory.shared.ldap.schema.syntax.ComparatorDescription; import org.junit.Before; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import java.io.File; import java.util.Comparator; import java.util.Iterator; import jdbm.RecordManager; import jdbm.helper.IntegerSerializer; import jdbm.recman.BaseRecordManager; import javax.naming.NamingException; /** * Tests the DupsContainerCursor. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class DupsContainerCursorTest { private static final Logger LOG = LoggerFactory.getLogger( NoDupsCursorTest.class.getSimpleName() ); private static final String TEST_OUTPUT_PATH = "test.output.path"; transient JdbmTable<Integer,Integer> table; transient File dbFile; transient RecordManager recman; private static final int SIZE = 15; @Before public void createTable() throws Exception { File tmpDir = null; if ( System.getProperty( TEST_OUTPUT_PATH, null ) != null ) { tmpDir = new File( System.getProperty( TEST_OUTPUT_PATH ) ); } dbFile = File.createTempFile( getClass().getSimpleName(), "db", tmpDir ); recman = new BaseRecordManager( dbFile.getAbsolutePath() ); // gosh this is a terrible use of a global static variable SerializableComparator.setRegistry( new MockComparatorRegistry() ); table = new JdbmTable<Integer,Integer>( "test", SIZE, recman, new SerializableComparator<Integer>( "" ), new SerializableComparator<Integer>( "" ), null, new IntegerSerializer() ); LOG.debug( "Created new table and populated it with data" ); } @After public void destryTable() throws Exception { table.close(); table = null; recman.close(); recman = null; dbFile.deleteOnExit(); dbFile = null; } @Test( expected=IllegalStateException.class ) public void testUsingNoDuplicates() throws Exception { File tmpDir = null; if ( System.getProperty( TEST_OUTPUT_PATH, null ) != null ) { tmpDir = new File( System.getProperty( TEST_OUTPUT_PATH ) ); } dbFile = File.createTempFile( getClass().getSimpleName(), "db", tmpDir ); recman = new BaseRecordManager( dbFile.getAbsolutePath() ); // gosh this is a terrible use of a global static variable SerializableComparator.setRegistry( new MockComparatorRegistry() ); table = new JdbmTable<Integer,Integer>( "test", recman, new SerializableComparator<Integer>( "" ), null, null ); Cursor<Tuple<Integer,DupsContainer<Integer>>> cursor = new DupsContainerCursor<Integer,Integer>( table ); assertNotNull( cursor ); } @Test( expected=InvalidCursorPositionException.class ) public void testEmptyTable() throws Exception { Cursor<Tuple<Integer,DupsContainer<Integer>>> cursor = new DupsContainerCursor<Integer,Integer>( table ); assertNotNull( cursor ); assertFalse( cursor.available() ); assertFalse( cursor.isClosed() ); assertTrue( cursor.isElementReused() ); cursor = new DupsContainerCursor<Integer,Integer>( table ); assertFalse( cursor.previous() ); cursor = new DupsContainerCursor<Integer,Integer>( table ); assertFalse( cursor.next() ); cursor.after( new Tuple<Integer,DupsContainer<Integer>>( 7, null ) ); cursor.get(); } @Test public void testOnTableWithSingleEntry() throws Exception { table.put( 1, 1 ); Cursor<Tuple<Integer,DupsContainer<Integer>>> cursor = new DupsContainerCursor<Integer,Integer>( table ); assertTrue( cursor.first() ); Tuple<Integer,DupsContainer<Integer>> tuple = cursor.get(); assertTrue( tuple.getKey().equals( 1 ) ); assertEquals( 1, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); cursor.beforeFirst(); assertFalse( cursor.previous() ); assertTrue( cursor.next() ); } @Test public void testOnTableWithMultipleEntries() throws Exception { for( int i=1; i < 10; i++ ) { table.put( i, i ); } Cursor<Tuple<Integer,DupsContainer<Integer>>> cursor = new DupsContainerCursor<Integer,Integer>( table ); cursor.after( new Tuple<Integer,DupsContainer<Integer>>( 2, null ) ); assertTrue( cursor.next() ); Tuple<Integer,DupsContainer<Integer>> tuple = cursor.get(); assertTrue( tuple.getKey().equals( 3 ) ); assertEquals( 3, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); cursor.before( new Tuple<Integer,DupsContainer<Integer>>( 7, null ) ); cursor.next(); tuple = cursor.get(); assertTrue( tuple.getKey().equals( 7 ) ); assertEquals( 7, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); cursor.last(); cursor.next(); assertFalse( cursor.available() ); /* tuple = cursor.get(); assertTrue( tuple.getKey().equals( 9 ) ); assertEquals( 9, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); */ cursor.beforeFirst(); cursor.next(); tuple = cursor.get(); assertTrue( tuple.getKey().equals( 1 ) ); assertEquals( 1, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); cursor.afterLast(); assertFalse( cursor.next() ); cursor.beforeFirst(); assertFalse( cursor.previous() ); // just to clear the jdbmTuple value so that line 127 inside after(tuple) method // can be executed as part of the below after(tuple) call cursor.before(new Tuple<Integer,DupsContainer<Integer>>( 1, null ) ); cursor.after( new Tuple<Integer,DupsContainer<Integer>>( 0, null ) ); // this positions on tuple with key 1 cursor.next(); // this moves onto tuple with key 2 tuple = cursor.get(); assertTrue( tuple.getKey().equals( 2 ) ); assertEquals( 2, ( int ) tuple.getValue().getAvlTree().getFirst().getKey() ); } @Test public void testMiscellaneous() throws Exception { } private class MockComparatorRegistry implements ComparatorRegistry { private Comparator<Integer> comparator = new Comparator<Integer>() { public int compare( Integer i1, Integer i2 ) { return i1.compareTo( i2 ); } }; public String getSchemaName( String oid ) throws NamingException { return null; } public void register( ComparatorDescription description, Comparator comparator ) throws NamingException { } public Comparator lookup( String oid ) throws NamingException { return comparator; } public boolean hasComparator( String oid ) { return true; } public Iterator<String> oidIterator() { return null; } public Iterator<ComparatorDescription> comparatorDescriptionIterator() { return null; } public void unregister( String oid ) throws NamingException { } public void unregisterSchemaElements( String schemaName ) { } public void renameSchema( String originalSchemaName, String newSchemaName ) { } } }
Modify the code to remove temporary files created during the test git-svn-id: dd90f696ee312d86d1f195500465131112b150f5@679621 13f79535-47bb-0310-9956-ffa450edef68
jdbm-store/src/test/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsContainerCursorTest.java
Modify the code to remove temporary files created during the test
<ide><path>dbm-store/src/test/java/org/apache/directory/server/core/partition/impl/btree/jdbm/DupsContainerCursorTest.java <ide> public void createTable() throws Exception <ide> { <ide> File tmpDir = null; <add> <ide> if ( System.getProperty( TEST_OUTPUT_PATH, null ) != null ) <ide> { <ide> tmpDir = new File( System.getProperty( TEST_OUTPUT_PATH ) ); <add> tmpDir.deleteOnExit(); <ide> } <ide> <ide> dbFile = File.createTempFile( getClass().getSimpleName(), "db", tmpDir ); <add> dbFile.deleteOnExit(); <ide> recman = new BaseRecordManager( dbFile.getAbsolutePath() ); <ide> <ide> // gosh this is a terrible use of a global static variable <ide> <ide> <ide> @After <del> public void destryTable() throws Exception <add> public void destroyTable() throws Exception <ide> { <ide> table.close(); <ide> table = null; <ide> recman.close(); <ide> recman = null; <del> dbFile.deleteOnExit(); <add> String fileToDelete = dbFile.getAbsolutePath(); <add> new File( fileToDelete ).delete(); <add> new File( fileToDelete + ".db" ).delete(); <add> new File( fileToDelete + ".lg" ).delete(); <ide> dbFile = null; <ide> } <ide> <ide> @Test( expected=IllegalStateException.class ) <ide> public void testUsingNoDuplicates() throws Exception <ide> { <del> File tmpDir = null; <del> if ( System.getProperty( TEST_OUTPUT_PATH, null ) != null ) <del> { <del> tmpDir = new File( System.getProperty( TEST_OUTPUT_PATH ) ); <del> } <del> <del> dbFile = File.createTempFile( getClass().getSimpleName(), "db", tmpDir ); <ide> recman = new BaseRecordManager( dbFile.getAbsolutePath() ); <ide> <ide> // gosh this is a terrible use of a global static variable
Java
mit
error: pathspec 'src/Fenestra.java' did not match any file(s) known to git
e2a2f5851c7aad7773cfc65e2e26c1d52b5cee3b
1
Luke-lujunxian/Amazing-animals
import java.awt.*; import javax.swing.*; public class Fenestra { private static JFrame bufo; private static Button b1; private static Button b2; public static void Fenestra(String[] args) { bufo=new JFrame("Bufonem Emittunt Aeternum"); bufo.setSize(400,400); bufo.setLayout(new FlowLayout()); b1 = new Button("Initium"); b2 = new Button("Finis"); bufo.add(b1); bufo.add(b2); bufo.setBackground(Color.green); bufo.setVisible(true); bufo.setDefaultCloseOperation(bufo.EXIT_ON_CLOSE); } }
src/Fenestra.java
Mise à jour de l'interface graphique Mise à jour des bases de l'interface graphique.
src/Fenestra.java
Mise à jour de l'interface graphique
<ide><path>rc/Fenestra.java <add>import java.awt.*; <add>import javax.swing.*; <add>public class Fenestra { <add> private static JFrame bufo; <add> private static Button b1; <add> private static Button b2; <add> <add> public static void Fenestra(String[] args) { <add> bufo=new JFrame("Bufonem Emittunt Aeternum"); <add> bufo.setSize(400,400); <add> bufo.setLayout(new FlowLayout()); <add> b1 = new Button("Initium"); <add> b2 = new Button("Finis"); <add> bufo.add(b1); <add> bufo.add(b2); <add> bufo.setBackground(Color.green); <add> bufo.setVisible(true); <add> bufo.setDefaultCloseOperation(bufo.EXIT_ON_CLOSE); <add> <add> } <add> <add> <add> <add>}
JavaScript
mit
8dc1f8e00e4b1cac11346fc080c465d0b2852a7f
0
kuitos/angular.js,jaredcacurak/angular.js,aoancea/angular.js,yathos/angular.js,petebacondarwin/angular.js,mgol/angular.js,kuitos/angular.js,marcin-wosinek/angular.js,angular/angular.js,nsina/angular.js,rjamet/angular.js,BobChao87/angular.js,laurent-le-graverend/angular.js,a-lucas/angular.js,ivomju/angular.js,laurent-le-graverend/angular.js,Teremok/angular.js,jbedard/angular.js,LenaDonohoe/angular.js,BobChao87/angular.js,ivomju/angular.js,reneploetz/angular.js,Hartmarken/angular.js,Narretz/angular.js,sjbarker/angular.js,nsina/angular.js,lgalfaso/angular.js,nsina/angular.js,ollie314/angular.js,Awingu/angular.js,Hartmarken/angular.js,arunkannan/angular.js,pondermatic/angular.js,Teremok/angular.js,chrisbautista/angular.js,lgalfaso/angular.js,Awingu/angular.js,Aremyst/angular.js,chrisbautista/angular.js,angular/angular.js,aoancea/angular.js,mosoft521/angular.js,rlugojr/angular.js,yathos/angular.js,jaredcacurak/angular.js,sunoterra/angular.js,eistrati/angular.js,Teremok/angular.js,eistrati/angular.js,sercaneraslan/angular.js,jbedard/angular.js,rbevers/angular.js,arunkannan/angular.js,pondermatic/angular.js,kuitos/angular.js,LenaDonohoe/angular.js,mosoft521/angular.js,Awingu/angular.js,laurent-le-graverend/angular.js,rbevers/angular.js,d0g/angular.js,mgol/angular.js,wesleycho/angular.js,yathos/angular.js,abdihaikal/angular.js,sercaneraslan/angular.js,jaredcacurak/angular.js,BobChao87/angular.js,mgol/angular.js,hnccho/angular.js,Aremyst/angular.js,petebacondarwin/angular.js,Hartmarken/angular.js,Aremyst/angular.js,pbr1111/angular.js,sunoterra/angular.js,sjbarker/angular.js,mprobst/angular.js,pbr1111/angular.js,Awingu/angular.js,kylewuolle/angular.js,a-lucas/angular.js,rlugojr/angular.js,jbedard/angular.js,notebowl/angular.js,angularbrasil/angular.js,arunkannan/angular.js,BobChao87/angular.js,chrisbautista/angular.js,reneploetz/angular.js,eistrati/angular.js,mgol/angular.js,zuzusik/angular.js,rlugojr/angular.js,jaredcacurak/angular.js,shengoo/angular.js,ivomju/angular.js,petebacondarwin/angular.js,gkalpak/angular.js,hnccho/angular.js,Teremok/angular.js,sunoterra/angular.js,amitse/angular.js,sercaneraslan/angular.js,wesleycho/angular.js,gkalpak/angular.js,yathos/angular.js,dmuellner/angular.js,shengoo/angular.js,mprobst/angular.js,kylewuolle/angular.js,reneploetz/angular.js,zuzusik/angular.js,zuzusik/angular.js,pbr1111/angular.js,d0g/angular.js,arunkannan/angular.js,d0g/angular.js,abdihaikal/angular.js,eistrati/angular.js,Narretz/angular.js,ze-pequeno/angular.js,gkalpak/angular.js,rjamet/angular.js,rjamet/angular.js,ze-pequeno/angular.js,mprobst/angular.js,ollie314/angular.js,aoancea/angular.js,shengoo/angular.js,marcin-wosinek/angular.js,LenaDonohoe/angular.js,mprobst/angular.js,jbedard/angular.js,kylewuolle/angular.js,marcin-wosinek/angular.js,dmuellner/angular.js,rlugojr/angular.js,angular/angular.js,Aremyst/angular.js,hnccho/angular.js,dmuellner/angular.js,angularbrasil/angular.js,dmuellner/angular.js,LenaDonohoe/angular.js,aoancea/angular.js,rbevers/angular.js,wesleycho/angular.js,pondermatic/angular.js,Narretz/angular.js,hnccho/angular.js,notebowl/angular.js,pondermatic/angular.js,angular/angular.js,nsina/angular.js,ze-pequeno/angular.js,petebacondarwin/angular.js,ze-pequeno/angular.js,wesleycho/angular.js,abdihaikal/angular.js,mosoft521/angular.js,chrisbautista/angular.js,ollie314/angular.js,amitse/angular.js,angularbrasil/angular.js,pbr1111/angular.js,zuzusik/angular.js,sjbarker/angular.js,angularbrasil/angular.js,sunoterra/angular.js,kylewuolle/angular.js,amitse/angular.js,notebowl/angular.js,sercaneraslan/angular.js,reneploetz/angular.js,marcin-wosinek/angular.js,abdihaikal/angular.js,amitse/angular.js,Hartmarken/angular.js,lgalfaso/angular.js,sjbarker/angular.js,shengoo/angular.js,ollie314/angular.js,rbevers/angular.js,lgalfaso/angular.js,Narretz/angular.js,a-lucas/angular.js,kuitos/angular.js,a-lucas/angular.js,gkalpak/angular.js,notebowl/angular.js,rjamet/angular.js,laurent-le-graverend/angular.js,ivomju/angular.js,d0g/angular.js,mosoft521/angular.js
'use strict'; /** * @ngdoc function * @module ng * @name angular.injector * @kind function * * @description * Creates an injector object that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which * disallows argument name annotation inference. * @returns {injector} Injector object. See {@link auto.$injector $injector}. * * @example * Typical usage * ```js * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document) { * $compile($document)($rootScope); * $rootScope.$digest(); * }); * ``` * * Sometimes you want to get access to the injector of a currently running Angular app * from outside Angular. Perhaps, you want to inject and compile some markup after the * application has been bootstrapped. You can do this using the extra `injector()` added * to JQuery/jqLite elements. See {@link angular.element}. * * *This is fairly rare but could be the case if a third party library is injecting the * markup.* * * In the following example a new block of HTML containing a `ng-controller` * directive is added to the end of the document body by JQuery. We then compile and link * it into the current AngularJS scope. * * ```js * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>'); * $(document.body).append($div); * * angular.element(document).injector().invoke(function($compile) { * var scope = angular.element($div).scope(); * $compile($div)(scope); * }); * ``` */ /** * @ngdoc module * @name auto * @installation * @description * * Implicit module which gets automatically added to each {@link auto.$injector $injector}. */ var ARROW_ARG = /^([^\(]+?)=>/; var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var $injectorMinErr = minErr('$injector'); function extractArgs(fn) { // Support: Chrome 50-51 only // Creating a new string by adding `' '` at the end, to hack around some bug in Chrome v50/51 // (See https://github.com/angular/angular.js/issues/14487.) // TODO (gkalpak): Remove workaround when Chrome v52 is released var fnText = Function.prototype.toString.call(fn).replace(STRIP_COMMENTS, '') + ' ', args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS); return args; } function anonFn(fn) { // For anonymous functions, showing at the very least the function signature can help in // debugging. var args = extractArgs(fn); if (args) { return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; } return 'fn'; } function annotate(fn, strictDi, name) { var $inject, argDecl, last; if (typeof fn === 'function') { if (!($inject = fn.$inject)) { $inject = []; if (fn.length) { if (strictDi) { if (!isString(name) || !name) { name = fn.name || anonFn(fn); } throw $injectorMinErr('strictdi', '{0} is not using explicit annotation and cannot be invoked in strict mode', name); } argDecl = extractArgs(fn); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) { arg.replace(FN_ARG, function(all, underscore, name) { $inject.push(name); }); }); } fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn'); $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc service * @name $injector * * @description * * `$injector` is used to retrieve object instances as defined by * {@link auto.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * ```js * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector) { * return $injector; * })).toBe($injector); * ``` * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. * * ```js * // inferred (only works if code not minified/obfuscated) * $injector.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $injector.invoke(explicit); * * // inline * $injector.invoke(['serviceA', function(serviceA){}]); * ``` * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition * can then be parsed and the function arguments can be extracted. This method of discovering * annotations is disallowed when the injector is in strict mode. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the * argument names. * * ## `$inject` Annotation * By adding an `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name $injector#get * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @param {string=} caller An optional string to provide the origin of the function call for error messages. * @return {*} The instance. */ /** * @ngdoc method * @name $injector#invoke * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are * injected according to the {@link guide/di $inject Annotation} rules. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name $injector#has * * @description * Allows the user to query if the particular service exists. * * @param {string} name Name of the service to query. * @returns {boolean} `true` if injector has given service. */ /** * @ngdoc method * @name $injector#instantiate * @description * Create a new instance of JS type. The method takes a constructor function, invokes the new * operator, and supplies all of the arguments to the constructor function as specified by the * constructor annotation. * * @param {Function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name $injector#annotate * * @description * Returns an array of service names which the function is requesting for injection. This API is * used by the injector to determine which services need to be injected into the function when the * function is invoked. There are three ways in which the function can be annotated with the needed * dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done * by converting the function into a string using `toString()` method and extracting the argument * names. * ```js * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * You can disallow this method by using strict injection mode. * * This method does not work with code minification / obfuscation. For this reason the following * annotation strategies are supported. * * # The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings * represent names of services to be injected into the function. * ```js * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController['$inject'] = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property * is very inconvenient. In these situations using the array notation to specify the dependencies in * a way that survives minification is a better choice: * * ```js * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tmpFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * ``` * * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to * be retrieved as described above. * * @param {boolean=} [strictDi=false] Disallow argument name annotation inference. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc service * @name $provide * * @description * * The {@link auto.$provide $provide} service has a number of methods for registering components * with the {@link auto.$injector $injector}. Many of these functions are also exposed on * {@link angular.Module}. * * An Angular **service** is a singleton object created by a **service factory**. These **service * factories** are functions which, in turn, are created by a **service provider**. * The **service providers** are constructor functions. When instantiated they must contain a * property called `$get`, which holds the **service factory** function. * * When you request a service, the {@link auto.$injector $injector} is responsible for finding the * correct **service provider**, instantiating it and then calling its `$get` **service factory** * function to get the instance of the **service**. * * Often services have no configuration options and there is no need to add methods to the service * provider. The provider will be no more than a constructor function with a `$get` property. For * these cases the {@link auto.$provide $provide} service has additional helper methods to register * services without specifying a provider. * * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the * {@link auto.$injector $injector} * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by * providers and services. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by * services, not providers. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, * that will be wrapped in a **service provider** object, whose `$get` property will contain the * given factory function. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` * that will be wrapped in a **service provider** object, whose `$get` property will instantiate * a new object using the given constructor function. * * See the individual methods for more information and examples. */ /** * @ngdoc method * @name $provide#provider * @description * * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions * are constructor functions, whose instances are responsible for "providing" a factory for a * service. * * Service provider names start with the name of the service they provide followed by `Provider`. * For example, the {@link ng.$log $log} service has a provider called * {@link ng.$logProvider $logProvider}. * * Service provider objects can have additional methods which allow configuration of the provider * and its service. Importantly, you can configure what kind of service is created by the `$get` * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a * method {@link ng.$logProvider#debugEnabled debugEnabled} * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the * console or not. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance * @example * * The following example shows how to create a simple event tracking service and register it using * {@link auto.$provide#provider $provide.provider()}. * * ```js * // Define the eventTracker provider * function EventTrackerProvider() { * var trackingUrl = '/track'; * * // A provider method for configuring where the tracked events should been saved * this.setTrackingUrl = function(url) { * trackingUrl = url; * }; * * // The service factory function * this.$get = ['$http', function($http) { * var trackedEvents = {}; * return { * // Call this to track an event * event: function(event) { * var count = trackedEvents[event] || 0; * count += 1; * trackedEvents[event] = count; * return count; * }, * // Call this to save the tracked events to the trackingUrl * save: function() { * $http.post(trackingUrl, trackedEvents); * } * }; * }]; * } * * describe('eventTracker', function() { * var postSpy; * * beforeEach(module(function($provide) { * // Register the eventTracker provider * $provide.provider('eventTracker', EventTrackerProvider); * })); * * beforeEach(module(function(eventTrackerProvider) { * // Configure eventTracker provider * eventTrackerProvider.setTrackingUrl('/custom-track'); * })); * * it('tracks events', inject(function(eventTracker) { * expect(eventTracker.event('login')).toEqual(1); * expect(eventTracker.event('login')).toEqual(2); * })); * * it('saves to the tracking url', inject(function(eventTracker, $http) { * postSpy = spyOn($http, 'post'); * eventTracker.event('login'); * eventTracker.save(); * expect(postSpy).toHaveBeenCalled(); * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); * })); * }); * ``` */ /** * @ngdoc method * @name $provide#factory * @description * * Register a **service factory**, which will be called to return the service instance. * This is short for registering a service where its provider consists of only a `$get` property, * which is the given service factory function. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to * configure your service in a provider. * * @param {string} name The name of the instance. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service * ```js * $provide.factory('ping', ['$http', function($http) { * return function ping() { * return $http.send('/ping'); * }; * }]); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping(); * }]); * ``` */ /** * @ngdoc method * @name $provide#service * @description * * Register a **service constructor**, which will be invoked with `new` to create the service * instance. * This is short for registering a service where its provider's `$get` property is a factory * function that returns an instance instantiated by the injector from the service constructor * function. * * Internally it looks a bit like this: * * ``` * { * $get: function() { * return $injector.instantiate(constructor); * } * } * ``` * * * You should use {@link auto.$provide#service $provide.service(class)} if you define your service * as a type/class. * * @param {string} name The name of the instance. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function) * that will be instantiated. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service using * {@link auto.$provide#service $provide.service(class)}. * ```js * var Ping = function($http) { * this.$http = $http; * }; * * Ping.$inject = ['$http']; * * Ping.prototype.send = function() { * return this.$http.get('/ping'); * }; * $provide.service('ping', Ping); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping.send(); * }]); * ``` */ /** * @ngdoc method * @name $provide#value * @description * * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a * number, an array, an object or a function. This is short for registering a service where its * provider's `$get` property is a factory function that takes no arguments and returns the **value * service**. That also means it is not possible to inject other services into a value service. * * Value services are similar to constant services, except that they cannot be injected into a * module configuration function (see {@link angular.Module#config}) but they can be overridden by * an Angular {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance * * @example * Here are some examples of creating value services. * ```js * $provide.value('ADMIN_USER', 'admin'); * * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); * * $provide.value('halfOf', function(value) { * return value / 2; * }); * ``` */ /** * @ngdoc method * @name $provide#constant * @description * * Register a **constant service** with the {@link auto.$injector $injector}, such as a string, * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not * possible to inject other services into a constant. * * But unlike {@link auto.$provide#value value}, a constant can be * injected into a module configuration function (see {@link angular.Module#config}) and it cannot * be overridden by an Angular {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance * * @example * Here a some examples of creating constants: * ```js * $provide.constant('SHARD_HEIGHT', 306); * * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); * * $provide.constant('double', function(value) { * return value * 2; * }); * ``` */ /** * @ngdoc method * @name $provide#decorator * @description * * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator * intercepts the creation of a service, allowing it to override or modify the behavior of the * service. The object returned by the decorator may be the original service, or a new service * object which replaces or wraps and delegates to the original service. * * @param {string} name The name of the service to decorate. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be * instantiated and should return the decorated service instance. The function is called using * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. * Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. * * @example * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting * calls to {@link ng.$log#error $log.warn()}. * ```js * $provide.decorator('$log', ['$delegate', function($delegate) { * $delegate.warn = $delegate.error; * return $delegate; * }]); * ``` */ function createInjector(modulesToLoad, strictDi) { strictDi = (strictDi === true); var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap([], true), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = (providerCache.$injector = createInternalInjector(providerCache, function(serviceName, caller) { if (angular.isString(caller)) { path.push(caller); } throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); })), instanceCache = {}, protoInstanceInjector = createInternalInjector(instanceCache, function(serviceName, caller) { var provider = providerInjector.get(serviceName + providerSuffix, caller); return instanceInjector.invoke( provider.$get, provider, undefined, serviceName); }), instanceInjector = protoInstanceInjector; providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) }; var runBlocks = loadModules(modulesToLoad); instanceInjector = protoInstanceInjector.get('$injector'); instanceInjector.strictDi = strictDi; forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } }; } function provider(name, provider_) { assertNotHasOwnProperty(name, 'service'); if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); } return providerCache[name + providerSuffix] = provider_; } function enforceReturnValue(name, factory) { return function enforcedReturnValue() { var result = instanceInjector.invoke(factory, this); if (isUndefined(result)) { throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name); } return result; }; } function factory(name, factoryFn, enforce) { return provider(name, { $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, val) { return factory(name, valueFn(val), false); } function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad) { assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array'); var runBlocks = [], moduleFn; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); function runInvokeQueue(queue) { var i, ii; for (i = 0, ii = queue.length; i < ii; i++) { var invokeArgs = queue[i], provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } try { if (isString(module)) { moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); runInvokeQueue(moduleFn._invokeQueue); runInvokeQueue(moduleFn._configBlocks); } else if (isFunction(module)) { runBlocks.push(providerInjector.invoke(module)); } else if (isArray(module)) { runBlocks.push(providerInjector.invoke(module)); } else { assertArgFn(module, 'module'); } } catch (e) { if (isArray(module)) { module = module[module.length - 1]; } if (e.message && e.stack && e.stack.indexOf(e.message) === -1) { // Safari & FF's stack traces don't contain error.message content // unlike those of Chrome and IE // So if stack doesn't contain message, we create a new string that contains both. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. /* jshint -W022 */ e = e.message + '\n' + e.stack; } throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", module, e.stack || e.message || e); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName, caller) { if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw $injectorMinErr('cdep', 'Circular dependency found: {0}', serviceName + ' <- ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName, caller); } catch (err) { if (cache[serviceName] === INSTANTIATING) { delete cache[serviceName]; } throw err; } finally { path.shift(); } } } function injectionArgs(fn, locals, serviceName) { var args = [], $inject = createInjector.$$annotate(fn, strictDi, serviceName); for (var i = 0, length = $inject.length; i < length; i++) { var key = $inject[i]; if (typeof key !== 'string') { throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); } args.push(locals && locals.hasOwnProperty(key) ? locals[key] : getService(key, serviceName)); } return args; } function isClass(func) { // IE 9-11 do not support classes and IE9 leaks with the code below. if (msie <= 11 || typeof func !== 'function') { return false; } var result = func.$$ngIsClass; if (!isBoolean(result)) { // Workaround for MS Edge. // Check https://connect.microsoft.com/IE/Feedback/Details/2211653 result = func.$$ngIsClass = /^(?:class\s|constructor\()/.test(Function.prototype.toString.call(func)); } return result; } function invoke(fn, self, locals, serviceName) { if (typeof locals === 'string') { serviceName = locals; locals = null; } var args = injectionArgs(fn, locals, serviceName); if (isArray(fn)) { fn = fn[fn.length - 1]; } if (!isClass(fn)) { // http://jsperf.com/angularjs-invoke-apply-vs-switch // #5388 return fn.apply(self, args); } else { args.unshift(null); return new (Function.prototype.bind.apply(fn, args))(); } } function instantiate(Type, locals, serviceName) { // Check if Type is annotated and use just the given function at n-1 as parameter // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); var ctor = (isArray(Type) ? Type[Type.length - 1] : Type); var args = injectionArgs(Type, locals, serviceName); // Empty object at position 0 is ignored for invocation with `new`, but required. args.unshift(null); return new (Function.prototype.bind.apply(ctor, args))(); } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: createInjector.$$annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } }; } } createInjector.$$annotate = annotate;
src/auto/injector.js
'use strict'; /** * @ngdoc function * @module ng * @name angular.injector * @kind function * * @description * Creates an injector object that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which * disallows argument name annotation inference. * @returns {injector} Injector object. See {@link auto.$injector $injector}. * * @example * Typical usage * ```js * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document) { * $compile($document)($rootScope); * $rootScope.$digest(); * }); * ``` * * Sometimes you want to get access to the injector of a currently running Angular app * from outside Angular. Perhaps, you want to inject and compile some markup after the * application has been bootstrapped. You can do this using the extra `injector()` added * to JQuery/jqLite elements. See {@link angular.element}. * * *This is fairly rare but could be the case if a third party library is injecting the * markup.* * * In the following example a new block of HTML containing a `ng-controller` * directive is added to the end of the document body by JQuery. We then compile and link * it into the current AngularJS scope. * * ```js * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>'); * $(document.body).append($div); * * angular.element(document).injector().invoke(function($compile) { * var scope = angular.element($div).scope(); * $compile($div)(scope); * }); * ``` */ /** * @ngdoc module * @name auto * @installation * @description * * Implicit module which gets automatically added to each {@link auto.$injector $injector}. */ var ARROW_ARG = /^([^\(]+?)=>/; var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var $injectorMinErr = minErr('$injector'); function extractArgs(fn) { var fnText = Function.prototype.toString.call(fn).replace(STRIP_COMMENTS, ''), args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS); return args; } function anonFn(fn) { // For anonymous functions, showing at the very least the function signature can help in // debugging. var args = extractArgs(fn); if (args) { return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; } return 'fn'; } function annotate(fn, strictDi, name) { var $inject, argDecl, last; if (typeof fn === 'function') { if (!($inject = fn.$inject)) { $inject = []; if (fn.length) { if (strictDi) { if (!isString(name) || !name) { name = fn.name || anonFn(fn); } throw $injectorMinErr('strictdi', '{0} is not using explicit annotation and cannot be invoked in strict mode', name); } argDecl = extractArgs(fn); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) { arg.replace(FN_ARG, function(all, underscore, name) { $inject.push(name); }); }); } fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn'); $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc service * @name $injector * * @description * * `$injector` is used to retrieve object instances as defined by * {@link auto.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * ```js * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector) { * return $injector; * })).toBe($injector); * ``` * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. * * ```js * // inferred (only works if code not minified/obfuscated) * $injector.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $injector.invoke(explicit); * * // inline * $injector.invoke(['serviceA', function(serviceA){}]); * ``` * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition * can then be parsed and the function arguments can be extracted. This method of discovering * annotations is disallowed when the injector is in strict mode. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the * argument names. * * ## `$inject` Annotation * By adding an `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name $injector#get * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @param {string=} caller An optional string to provide the origin of the function call for error messages. * @return {*} The instance. */ /** * @ngdoc method * @name $injector#invoke * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are * injected according to the {@link guide/di $inject Annotation} rules. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name $injector#has * * @description * Allows the user to query if the particular service exists. * * @param {string} name Name of the service to query. * @returns {boolean} `true` if injector has given service. */ /** * @ngdoc method * @name $injector#instantiate * @description * Create a new instance of JS type. The method takes a constructor function, invokes the new * operator, and supplies all of the arguments to the constructor function as specified by the * constructor annotation. * * @param {Function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name $injector#annotate * * @description * Returns an array of service names which the function is requesting for injection. This API is * used by the injector to determine which services need to be injected into the function when the * function is invoked. There are three ways in which the function can be annotated with the needed * dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done * by converting the function into a string using `toString()` method and extracting the argument * names. * ```js * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * You can disallow this method by using strict injection mode. * * This method does not work with code minification / obfuscation. For this reason the following * annotation strategies are supported. * * # The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings * represent names of services to be injected into the function. * ```js * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController['$inject'] = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property * is very inconvenient. In these situations using the array notation to specify the dependencies in * a way that survives minification is a better choice: * * ```js * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tmpFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * ``` * * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to * be retrieved as described above. * * @param {boolean=} [strictDi=false] Disallow argument name annotation inference. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc service * @name $provide * * @description * * The {@link auto.$provide $provide} service has a number of methods for registering components * with the {@link auto.$injector $injector}. Many of these functions are also exposed on * {@link angular.Module}. * * An Angular **service** is a singleton object created by a **service factory**. These **service * factories** are functions which, in turn, are created by a **service provider**. * The **service providers** are constructor functions. When instantiated they must contain a * property called `$get`, which holds the **service factory** function. * * When you request a service, the {@link auto.$injector $injector} is responsible for finding the * correct **service provider**, instantiating it and then calling its `$get` **service factory** * function to get the instance of the **service**. * * Often services have no configuration options and there is no need to add methods to the service * provider. The provider will be no more than a constructor function with a `$get` property. For * these cases the {@link auto.$provide $provide} service has additional helper methods to register * services without specifying a provider. * * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the * {@link auto.$injector $injector} * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by * providers and services. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by * services, not providers. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, * that will be wrapped in a **service provider** object, whose `$get` property will contain the * given factory function. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` * that will be wrapped in a **service provider** object, whose `$get` property will instantiate * a new object using the given constructor function. * * See the individual methods for more information and examples. */ /** * @ngdoc method * @name $provide#provider * @description * * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions * are constructor functions, whose instances are responsible for "providing" a factory for a * service. * * Service provider names start with the name of the service they provide followed by `Provider`. * For example, the {@link ng.$log $log} service has a provider called * {@link ng.$logProvider $logProvider}. * * Service provider objects can have additional methods which allow configuration of the provider * and its service. Importantly, you can configure what kind of service is created by the `$get` * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a * method {@link ng.$logProvider#debugEnabled debugEnabled} * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the * console or not. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance * @example * * The following example shows how to create a simple event tracking service and register it using * {@link auto.$provide#provider $provide.provider()}. * * ```js * // Define the eventTracker provider * function EventTrackerProvider() { * var trackingUrl = '/track'; * * // A provider method for configuring where the tracked events should been saved * this.setTrackingUrl = function(url) { * trackingUrl = url; * }; * * // The service factory function * this.$get = ['$http', function($http) { * var trackedEvents = {}; * return { * // Call this to track an event * event: function(event) { * var count = trackedEvents[event] || 0; * count += 1; * trackedEvents[event] = count; * return count; * }, * // Call this to save the tracked events to the trackingUrl * save: function() { * $http.post(trackingUrl, trackedEvents); * } * }; * }]; * } * * describe('eventTracker', function() { * var postSpy; * * beforeEach(module(function($provide) { * // Register the eventTracker provider * $provide.provider('eventTracker', EventTrackerProvider); * })); * * beforeEach(module(function(eventTrackerProvider) { * // Configure eventTracker provider * eventTrackerProvider.setTrackingUrl('/custom-track'); * })); * * it('tracks events', inject(function(eventTracker) { * expect(eventTracker.event('login')).toEqual(1); * expect(eventTracker.event('login')).toEqual(2); * })); * * it('saves to the tracking url', inject(function(eventTracker, $http) { * postSpy = spyOn($http, 'post'); * eventTracker.event('login'); * eventTracker.save(); * expect(postSpy).toHaveBeenCalled(); * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); * })); * }); * ``` */ /** * @ngdoc method * @name $provide#factory * @description * * Register a **service factory**, which will be called to return the service instance. * This is short for registering a service where its provider consists of only a `$get` property, * which is the given service factory function. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to * configure your service in a provider. * * @param {string} name The name of the instance. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service * ```js * $provide.factory('ping', ['$http', function($http) { * return function ping() { * return $http.send('/ping'); * }; * }]); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping(); * }]); * ``` */ /** * @ngdoc method * @name $provide#service * @description * * Register a **service constructor**, which will be invoked with `new` to create the service * instance. * This is short for registering a service where its provider's `$get` property is a factory * function that returns an instance instantiated by the injector from the service constructor * function. * * Internally it looks a bit like this: * * ``` * { * $get: function() { * return $injector.instantiate(constructor); * } * } * ``` * * * You should use {@link auto.$provide#service $provide.service(class)} if you define your service * as a type/class. * * @param {string} name The name of the instance. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function) * that will be instantiated. * @returns {Object} registered provider instance * * @example * Here is an example of registering a service using * {@link auto.$provide#service $provide.service(class)}. * ```js * var Ping = function($http) { * this.$http = $http; * }; * * Ping.$inject = ['$http']; * * Ping.prototype.send = function() { * return this.$http.get('/ping'); * }; * $provide.service('ping', Ping); * ``` * You would then inject and use this service like this: * ```js * someModule.controller('Ctrl', ['ping', function(ping) { * ping.send(); * }]); * ``` */ /** * @ngdoc method * @name $provide#value * @description * * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a * number, an array, an object or a function. This is short for registering a service where its * provider's `$get` property is a factory function that takes no arguments and returns the **value * service**. That also means it is not possible to inject other services into a value service. * * Value services are similar to constant services, except that they cannot be injected into a * module configuration function (see {@link angular.Module#config}) but they can be overridden by * an Angular {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance * * @example * Here are some examples of creating value services. * ```js * $provide.value('ADMIN_USER', 'admin'); * * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); * * $provide.value('halfOf', function(value) { * return value / 2; * }); * ``` */ /** * @ngdoc method * @name $provide#constant * @description * * Register a **constant service** with the {@link auto.$injector $injector}, such as a string, * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not * possible to inject other services into a constant. * * But unlike {@link auto.$provide#value value}, a constant can be * injected into a module configuration function (see {@link angular.Module#config}) and it cannot * be overridden by an Angular {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance * * @example * Here a some examples of creating constants: * ```js * $provide.constant('SHARD_HEIGHT', 306); * * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); * * $provide.constant('double', function(value) { * return value * 2; * }); * ``` */ /** * @ngdoc method * @name $provide#decorator * @description * * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator * intercepts the creation of a service, allowing it to override or modify the behavior of the * service. The object returned by the decorator may be the original service, or a new service * object which replaces or wraps and delegates to the original service. * * @param {string} name The name of the service to decorate. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be * instantiated and should return the decorated service instance. The function is called using * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. * Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. * * @example * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting * calls to {@link ng.$log#error $log.warn()}. * ```js * $provide.decorator('$log', ['$delegate', function($delegate) { * $delegate.warn = $delegate.error; * return $delegate; * }]); * ``` */ function createInjector(modulesToLoad, strictDi) { strictDi = (strictDi === true); var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap([], true), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = (providerCache.$injector = createInternalInjector(providerCache, function(serviceName, caller) { if (angular.isString(caller)) { path.push(caller); } throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); })), instanceCache = {}, protoInstanceInjector = createInternalInjector(instanceCache, function(serviceName, caller) { var provider = providerInjector.get(serviceName + providerSuffix, caller); return instanceInjector.invoke( provider.$get, provider, undefined, serviceName); }), instanceInjector = protoInstanceInjector; providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) }; var runBlocks = loadModules(modulesToLoad); instanceInjector = protoInstanceInjector.get('$injector'); instanceInjector.strictDi = strictDi; forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } }; } function provider(name, provider_) { assertNotHasOwnProperty(name, 'service'); if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); } return providerCache[name + providerSuffix] = provider_; } function enforceReturnValue(name, factory) { return function enforcedReturnValue() { var result = instanceInjector.invoke(factory, this); if (isUndefined(result)) { throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name); } return result; }; } function factory(name, factoryFn, enforce) { return provider(name, { $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, val) { return factory(name, valueFn(val), false); } function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad) { assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array'); var runBlocks = [], moduleFn; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); function runInvokeQueue(queue) { var i, ii; for (i = 0, ii = queue.length; i < ii; i++) { var invokeArgs = queue[i], provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } try { if (isString(module)) { moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); runInvokeQueue(moduleFn._invokeQueue); runInvokeQueue(moduleFn._configBlocks); } else if (isFunction(module)) { runBlocks.push(providerInjector.invoke(module)); } else if (isArray(module)) { runBlocks.push(providerInjector.invoke(module)); } else { assertArgFn(module, 'module'); } } catch (e) { if (isArray(module)) { module = module[module.length - 1]; } if (e.message && e.stack && e.stack.indexOf(e.message) === -1) { // Safari & FF's stack traces don't contain error.message content // unlike those of Chrome and IE // So if stack doesn't contain message, we create a new string that contains both. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. /* jshint -W022 */ e = e.message + '\n' + e.stack; } throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", module, e.stack || e.message || e); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName, caller) { if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw $injectorMinErr('cdep', 'Circular dependency found: {0}', serviceName + ' <- ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName, caller); } catch (err) { if (cache[serviceName] === INSTANTIATING) { delete cache[serviceName]; } throw err; } finally { path.shift(); } } } function injectionArgs(fn, locals, serviceName) { var args = [], $inject = createInjector.$$annotate(fn, strictDi, serviceName); for (var i = 0, length = $inject.length; i < length; i++) { var key = $inject[i]; if (typeof key !== 'string') { throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); } args.push(locals && locals.hasOwnProperty(key) ? locals[key] : getService(key, serviceName)); } return args; } function isClass(func) { // IE 9-11 do not support classes and IE9 leaks with the code below. if (msie <= 11 || typeof func !== 'function') { return false; } var result = func.$$ngIsClass; if (!isBoolean(result)) { // Workaround for MS Edge. // Check https://connect.microsoft.com/IE/Feedback/Details/2211653 result = func.$$ngIsClass = /^(?:class\s|constructor\()/.test(Function.prototype.toString.call(func)); } return result; } function invoke(fn, self, locals, serviceName) { if (typeof locals === 'string') { serviceName = locals; locals = null; } var args = injectionArgs(fn, locals, serviceName); if (isArray(fn)) { fn = fn[fn.length - 1]; } if (!isClass(fn)) { // http://jsperf.com/angularjs-invoke-apply-vs-switch // #5388 return fn.apply(self, args); } else { args.unshift(null); return new (Function.prototype.bind.apply(fn, args))(); } } function instantiate(Type, locals, serviceName) { // Check if Type is annotated and use just the given function at n-1 as parameter // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); var ctor = (isArray(Type) ? Type[Type.length - 1] : Type); var args = injectionArgs(Type, locals, serviceName); // Empty object at position 0 is ignored for invocation with `new`, but required. args.unshift(null); return new (Function.prototype.bind.apply(ctor, args))(); } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: createInjector.$$annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } }; } } createInjector.$$annotate = annotate;
fix($injector): add workaround for fat-arrow stringification in Chrome v50/51 Closes #14487 Closes #14495
src/auto/injector.js
fix($injector): add workaround for fat-arrow stringification in Chrome v50/51
<ide><path>rc/auto/injector.js <ide> var $injectorMinErr = minErr('$injector'); <ide> <ide> function extractArgs(fn) { <del> var fnText = Function.prototype.toString.call(fn).replace(STRIP_COMMENTS, ''), <add> // Support: Chrome 50-51 only <add> // Creating a new string by adding `' '` at the end, to hack around some bug in Chrome v50/51 <add> // (See https://github.com/angular/angular.js/issues/14487.) <add> // TODO (gkalpak): Remove workaround when Chrome v52 is released <add> var fnText = Function.prototype.toString.call(fn).replace(STRIP_COMMENTS, '') + ' ', <ide> args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS); <ide> return args; <ide> }
Java
apache-2.0
c9ea3331afa2daefdd7ce3ed6eb4ec2afc0e763e
0
dumars/mybatis-pagination
package com.github.dumars.mybatis.pagination.dialect.type; import org.apache.commons.lang3.StringUtils; import com.github.dumars.mybatis.pagination.dialect.Dialect; public class Oracle implements Dialect { @Override public String generateLimitSQL(String sql, int offset, int limit) { sql = sql.trim(); String forUpdate = null; int index = StringUtils.indexOf(sql, " for update"); if(index > 0) { forUpdate = StringUtils.substring(sql, index); sql = StringUtils.substring(sql, 0, index); } StringBuilder sb = new StringBuilder(sql.length() + 100); if (offset > 0) { sb.append("select * from ( select row_.*, rownum rownum_ from ( "); } else { sb.append("select * from ( "); } sb.append(sql); if (offset > 0) { sb.append(" ) row_ ) where rownum_ <= ").append(offset + limit) .append(" and rownum_ > ").append(offset); } else { sb.append(" ) where rownum <= ").append(limit); } if (StringUtils.isNotEmpty(forUpdate)) { sb.append(forUpdate); } return sb.toString(); } @Override public String generateCountSQL(String sql) { return "select count(1) from (" + sql + ")"; } }
src/main/java/com/github/dumars/mybatis/pagination/dialect/type/Oracle.java
package com.github.dumars.mybatis.pagination.dialect.type; import org.apache.commons.lang3.StringUtils; import com.github.dumars.mybatis.pagination.dialect.Dialect; public class Oracle implements Dialect { @Override public String generateLimitSQL(String sql, int offset, int limit) { sql = sql.trim().toLowerCase(); String forUpdate = null; int index = StringUtils.indexOf(sql, " for update"); if(index > 0) { forUpdate = StringUtils.substring(sql, index); sql = StringUtils.substring(sql, 0, index); } StringBuilder sb = new StringBuilder(sql.length() + 100); if (offset > 0) { sb.append("select * from ( select row_.*, rownum rownum_ from ( "); } else { sb.append("select * from ( "); } sb.append(sql); if (offset > 0) { sb.append(" ) row_ ) where rownum_ <= ").append(limit) .append(" and rownum_ > ").append(offset); } else { sb.append(" ) where rownum <= ").append(limit); } if (StringUtils.isNotEmpty(forUpdate)) { sb.append(forUpdate); } return sb.toString(); } @Override public String generateCountSQL(String sql) { return "select count(1) from (" + sql + ")"; } }
fixed bug
src/main/java/com/github/dumars/mybatis/pagination/dialect/type/Oracle.java
fixed bug
<ide><path>rc/main/java/com/github/dumars/mybatis/pagination/dialect/type/Oracle.java <ide> <ide> @Override <ide> public String generateLimitSQL(String sql, int offset, int limit) { <del> sql = sql.trim().toLowerCase(); <add> sql = sql.trim(); <ide> String forUpdate = null; <ide> int index = StringUtils.indexOf(sql, " for update"); <ide> if(index > 0) { <ide> sb.append(sql); <ide> <ide> if (offset > 0) { <del> sb.append(" ) row_ ) where rownum_ <= ").append(limit) <add> sb.append(" ) row_ ) where rownum_ <= ").append(offset + limit) <ide> .append(" and rownum_ > ").append(offset); <ide> } else { <ide> sb.append(" ) where rownum <= ").append(limit);
Java
agpl-3.0
9401a328638b488e471dcbeb208a6ae3c1890d8b
0
mukadder/kc,geothomasp/kcmit,mukadder/kc,jwillia/kc-old1,ColostateResearchServices/kc,kuali/kc,UniversityOfHawaiiORS/kc,geothomasp/kcmit,iu-uits-es/kc,ColostateResearchServices/kc,geothomasp/kcmit,jwillia/kc-old1,geothomasp/kcmit,UniversityOfHawaiiORS/kc,iu-uits-es/kc,kuali/kc,mukadder/kc,UniversityOfHawaiiORS/kc,geothomasp/kcmit,jwillia/kc-old1,ColostateResearchServices/kc,jwillia/kc-old1,kuali/kc,iu-uits-es/kc
/* * Copyright 2005-2010 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.irb; import java.io.Serializable; import java.sql.Date; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.kuali.kra.SequenceOwner; import org.kuali.kra.UnitAclLoadable; import org.kuali.kra.bo.AttachmentFile; import org.kuali.kra.bo.CustomAttributeDocument; import org.kuali.kra.bo.KraPersistableBusinessObjectBase; import org.kuali.kra.coi.Disclosurable; import org.kuali.kra.committee.bo.Committee; import org.kuali.kra.committee.bo.CommitteeMembership; import org.kuali.kra.common.committee.bo.CommitteeMembershipType; import org.kuali.kra.committee.bo.CommitteeSchedule; import org.kuali.kra.common.permissions.Permissionable; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.infrastructure.RoleConstants; import org.kuali.kra.irb.actions.ProtocolAction; import org.kuali.kra.irb.actions.ProtocolStatus; import org.kuali.kra.irb.actions.amendrenew.ProtocolAmendRenewModule; import org.kuali.kra.irb.actions.amendrenew.ProtocolAmendRenewal; import org.kuali.kra.irb.actions.amendrenew.ProtocolModule; import org.kuali.kra.irb.actions.risklevel.ProtocolRiskLevel; import org.kuali.kra.irb.actions.submit.ProtocolReviewType; import org.kuali.kra.irb.actions.submit.ProtocolSubmission; import org.kuali.kra.irb.actions.submit.ProtocolSubmissionQualifierType; import org.kuali.kra.irb.actions.submit.ProtocolSubmissionStatus; import org.kuali.kra.irb.actions.submit.ProtocolSubmissionType; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentBase; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentFilter; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentPersonnel; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentProtocol; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentService; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentStatus; import org.kuali.kra.irb.noteattachment.ProtocolNotepad; import org.kuali.kra.irb.onlinereview.ProtocolOnlineReview; import org.kuali.kra.irb.personnel.ProtocolPerson; import org.kuali.kra.irb.personnel.ProtocolPersonnelService; import org.kuali.kra.irb.personnel.ProtocolUnit; import org.kuali.kra.irb.protocol.ProtocolType; import org.kuali.kra.irb.protocol.funding.ProtocolFundingSource; import org.kuali.kra.irb.protocol.location.ProtocolLocation; import org.kuali.kra.irb.protocol.location.ProtocolLocationService; import org.kuali.kra.irb.protocol.participant.ProtocolParticipant; import org.kuali.kra.irb.protocol.reference.ProtocolReference; import org.kuali.kra.irb.protocol.research.ProtocolResearchArea; import org.kuali.kra.irb.questionnaire.ProtocolModuleQuestionnaireBean; import org.kuali.kra.irb.specialreview.ProtocolSpecialReview; import org.kuali.kra.irb.specialreview.ProtocolSpecialReviewExemption; import org.kuali.kra.irb.summary.AdditionalInfoSummary; import org.kuali.kra.irb.summary.AttachmentSummary; import org.kuali.kra.irb.summary.FundingSourceSummary; import org.kuali.kra.irb.summary.OrganizationSummary; import org.kuali.kra.irb.summary.ParticipantSummary; import org.kuali.kra.irb.summary.PersonnelSummary; import org.kuali.kra.irb.summary.ProtocolSummary; import org.kuali.kra.irb.summary.ResearchAreaSummary; import org.kuali.kra.irb.summary.SpecialReviewSummary; import org.kuali.kra.krms.KcKrmsContextBo; import org.kuali.kra.krms.KrmsRulesContext; import org.kuali.kra.meeting.CommitteeScheduleAttendance; import org.kuali.kra.questionnaire.answer.Answer; import org.kuali.kra.questionnaire.answer.AnswerHeader; import org.kuali.kra.questionnaire.answer.ModuleQuestionnaireBean; import org.kuali.kra.questionnaire.answer.QuestionnaireAnswerService; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.service.SequenceAccessorService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.ObjectUtils; /** * * This class is Protocol Business Object. */ public class Protocol extends KraPersistableBusinessObjectBase implements SequenceOwner<Protocol>, Permissionable, UnitAclLoadable, Disclosurable, KcKrmsContextBo { private static final long serialVersionUID = 4396393806439396971L; private static final CharSequence AMENDMENT_LETTER = "A"; private static final CharSequence RENEWAL_LETTER = "R"; private static final String DEFAULT_PROTOCOL_TYPE_CODE = "1"; private static final String NEXT_ACTION_ID_KEY = "actionId"; // TODO *********code has been moved to base class, should ultimately be removed********** private Long protocolId; private String protocolNumber; // TODO **********************end************************ private Integer sequenceNumber; // TODO *********code has been moved to base class, should ultimately be removed********** private boolean active = true; private String protocolTypeCode; private String protocolStatusCode; private String title; private String description; private Date initialSubmissionDate; private Date approvalDate; private Date expirationDate; private Date lastApprovalDate; private String fdaApplicationNumber; private String referenceNumber1; private String referenceNumber2; private String specialReviewIndicator = "Y"; // TODO **********************end************************ private String vulnerableSubjectIndicator; // TODO *********code has been moved to base class, should ultimately be removed********** private String keyStudyPersonIndicator; private String fundingSourceIndicator; private String correspondentIndicator; private String referenceIndicator; // TODO **********************end************************ private String relatedProjectsIndicator; private ProtocolDocument protocolDocument; private ProtocolStatus protocolStatus; private ProtocolType protocolType; private List<ProtocolRiskLevel> protocolRiskLevels; private List<ProtocolParticipant> protocolParticipants; private List<ProtocolResearchArea> protocolResearchAreas; private List<ProtocolReference> protocolReferences; private List<ProtocolLocation> protocolLocations; //Is transient, used for lookup select option in UI by KNS private String newDescription; private boolean nonEmployeeFlag; private List<ProtocolFundingSource> protocolFundingSources; // TODO *********code has been moved to base class, should ultimately be removed********** private String leadUnitNumber; // TODO **********************end************************ private String principalInvestigatorId; // lookup field private String keyPerson; private String investigator; private String fundingSource; private String performingOrganizationId; private String researchAreaCode; // TODO *********code has been moved to base class, should ultimately be removed********** private String leadUnitName; private List<ProtocolPerson> protocolPersons; // TODO **********************end************************ private List<ProtocolSpecialReview> specialReviews; //these are the m:m attachment protocols that that a protocol has private List<ProtocolAttachmentProtocol> attachmentProtocols; private List<ProtocolNotepad> notepads; private List<ProtocolAction> protocolActions; private List<ProtocolSubmission> protocolSubmissions; private ProtocolSubmission protocolSubmission; private transient List<ProtocolAction> sortedActions; /* * There should only be zero or one entry in the protocolAmendRenewals * list. It is because of OJB that a list is used instead of a single item. */ private List<ProtocolAmendRenewal> protocolAmendRenewals; private transient boolean correctionMode = false; private transient DateTimeService dateTimeService; private transient SequenceAccessorService sequenceAccessorService; //Used to filter protocol attachments private transient ProtocolAttachmentFilter protocolAttachmentFilter; // passed in req param submissionid. used to check if irb ack is needed // this link is from protocosubmission or notify irb message private transient Long notifyIrbSubmissionId; // transient for protocol header combined label private transient String initiatorLastUpdated; private transient String protocolSubmissionStatus; // Custom Protocol lookup fields private transient boolean lookupPendingProtocol; private transient boolean lookupPendingPIActionProtocol; private transient boolean lookupActionAmendRenewProtocol; private transient boolean lookupActionNotifyIRBProtocol; private transient boolean lookupActionRequestProtocol; private transient boolean lookupProtocolPersonId; private transient boolean mergeAmendment; public String getInitiatorLastUpdated() { return initiatorLastUpdated; } public String getProtocolSubmissionStatus() { return protocolSubmissionStatus; } /** * * Constructs an Protocol BO. */ public Protocol() { super(); sequenceNumber = new Integer(0); //billable = false; protocolRiskLevels = new ArrayList<ProtocolRiskLevel>(); protocolParticipants = new ArrayList<ProtocolParticipant>(); protocolResearchAreas = new ArrayList<ProtocolResearchArea>(); protocolReferences = new ArrayList<ProtocolReference>(); newDescription = getDefaultNewDescription(); protocolStatus = new ProtocolStatus(); protocolStatusCode = protocolStatus.getProtocolStatusCode(); protocolLocations = new ArrayList<ProtocolLocation>(); protocolPersons = new ArrayList<ProtocolPerson>(); // set the default protocol type protocolTypeCode = DEFAULT_PROTOCOL_TYPE_CODE; // initializeProtocolLocation(); protocolFundingSources = new ArrayList<ProtocolFundingSource>(); specialReviews = new ArrayList<ProtocolSpecialReview>(); setProtocolActions(new ArrayList<ProtocolAction>()); setProtocolSubmissions(new ArrayList<ProtocolSubmission>()); protocolAmendRenewals = new ArrayList<ProtocolAmendRenewal>(); // set statuscode default setProtocolStatusCode(Constants.DEFAULT_PROTOCOL_STATUS_CODE); this.refreshReferenceObject(Constants.PROPERTY_PROTOCOL_STATUS); initializeProtocolAttachmentFilter(); // TODO : not sure why this method is here. It looks like a temp method. commented out to see if it is ok. // I had to remove the comment in front of the following statement. // By adding the comment, a null pointer exception occurs when navigating to the Protocol Actions tab. //populateTempViewDate(); } // TODO *********code has been moved to base class, should ultimately be removed********** public Long getProtocolId() { return protocolId; } public void setProtocolId(Long protocolId) { this.protocolId = protocolId; } public String getProtocolNumber() { return protocolNumber; } public void setProtocolNumber(String protocolNumber) { this.protocolNumber = protocolNumber; } public Integer getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(Integer sequenceNumber) { this.sequenceNumber = sequenceNumber; } public void setActive(boolean active) { this.active = active; } public boolean isActive() { return active; } public String getProtocolTypeCode() { return protocolTypeCode; } public void setProtocolTypeCode(String protocolTypeCode) { this.protocolTypeCode = protocolTypeCode; } public String getProtocolStatusCode() { return protocolStatusCode; } public void setProtocolStatusCode(String protocolStatusCode) { this.protocolStatusCode = protocolStatusCode; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } // TODO **********************end************************ /** * Gets the submission date. If the submission date is the last * submission for the protocol. If the protocol has not been submitted, * null is returned. * @return the submission date or null if not yet submitted */ public Date getSubmissionDate() { // TODO : the last one in the list may not be the last one submitted // getProtocolSubmission will get the last one. SO, this method may not needed. // Also, this method only referenced in test once. Date submissionDate = null; if (protocolSubmissions.size() > 0) { // ProtocolSubmission submission = protocolSubmissions.get(protocolSubmissions.size() - 1); // submissionDate = submission.getSubmissionDate(); submissionDate = getProtocolSubmission().getSubmissionDate(); } return submissionDate; } // TODO *********code has been moved to base class, should ultimately be removed********** public Date getInitialSubmissionDate() { return initialSubmissionDate; } public void setInitialSubmissionDate(Date initialSubmissionDate) { this.initialSubmissionDate = initialSubmissionDate; } public Date getApprovalDate() { return approvalDate; } public void setApprovalDate(Date approvalDate) { this.approvalDate = approvalDate; } public Date getExpirationDate() { return expirationDate; } public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; } public Date getLastApprovalDate() { return lastApprovalDate; } public void setLastApprovalDate(Date lastApprovalDate) { this.lastApprovalDate = lastApprovalDate; } public String getFdaApplicationNumber() { return fdaApplicationNumber; } public void setFdaApplicationNumber(String fdaApplicationNumber) { this.fdaApplicationNumber = fdaApplicationNumber; } public String getReferenceNumber1() { return referenceNumber1; } public void setReferenceNumber1(String referenceNumber1) { this.referenceNumber1 = referenceNumber1; } public String getReferenceNumber2() { return referenceNumber2; } public void setReferenceNumber2(String referenceNumber2) { this.referenceNumber2 = referenceNumber2; } public String getSpecialReviewIndicator() { return specialReviewIndicator; } public void setSpecialReviewIndicator(String specialReviewIndicator) { this.specialReviewIndicator = specialReviewIndicator; } // TODO **********************end************************ public String getVulnerableSubjectIndicator() { return vulnerableSubjectIndicator; } public void setVulnerableSubjectIndicator(String vulnerableSubjectIndicator) { this.vulnerableSubjectIndicator = vulnerableSubjectIndicator; } // TODO *********code has been moved to base class, should ultimately be removed********** public String getKeyStudyPersonIndicator() { return keyStudyPersonIndicator; } public void setKeyStudyPersonIndicator(String keyStudyPersonIndicator) { this.keyStudyPersonIndicator = keyStudyPersonIndicator; } public String getFundingSourceIndicator() { return fundingSourceIndicator; } public void setFundingSourceIndicator(String fundingSourceIndicator) { this.fundingSourceIndicator = fundingSourceIndicator; } public String getCorrespondentIndicator() { return correspondentIndicator; } public void setCorrespondentIndicator(String correspondentIndicator) { this.correspondentIndicator = correspondentIndicator; } public String getReferenceIndicator() { return referenceIndicator; } public void setReferenceIndicator(String referenceIndicator) { this.referenceIndicator = referenceIndicator; } // TODO **********************end************************ public String getRelatedProjectsIndicator() { return relatedProjectsIndicator; } public void setRelatedProjectsIndicator(String relatedProjectsIndicator) { this.relatedProjectsIndicator = relatedProjectsIndicator; } /** * Collects and returns all online reviews for all submissions for this protocol. * @return all online reviews for this protocol */ public List<ProtocolOnlineReview> getProtocolOnlineReviews() { List<ProtocolOnlineReview> reviews = new ArrayList<ProtocolOnlineReview>(); for (ProtocolSubmission submission : getProtocolSubmissions()) { reviews.addAll(submission.getProtocolOnlineReviews()); } return reviews; } public ProtocolStatus getProtocolStatus() { return protocolStatus; } public void setProtocolStatus(ProtocolStatus protocolStatus) { this.protocolStatus = protocolStatus; } public ProtocolType getProtocolType() { return protocolType; } public void setProtocolType(ProtocolType protocolType) { this.protocolType = protocolType; } public List<ProtocolRiskLevel> getProtocolRiskLevels() { return protocolRiskLevels; } public void setProtocolRiskLevels(List<ProtocolRiskLevel> protocolRiskLevels) { this.protocolRiskLevels = protocolRiskLevels; for (ProtocolRiskLevel riskLevel : protocolRiskLevels) { riskLevel.init(this); } } public List<ProtocolParticipant> getProtocolParticipants() { return protocolParticipants; } public void setProtocolParticipants(List<ProtocolParticipant> protocolParticipants) { this.protocolParticipants = protocolParticipants; for (ProtocolParticipant participant : protocolParticipants) { participant.init(this); } } /** * Gets index i from the protocol participant list. * * @param index * @return protocol participant at index i */ public ProtocolParticipant getProtocolParticipant(int index) { return getProtocolParticipants().get(index); } public String getNewDescription() { return newDescription; } public void setNewDescription(String newDescription) { this.newDescription = newDescription; } public String getDefaultNewDescription() { return "(select)"; } public void setProtocolResearchAreas(List<ProtocolResearchArea> protocolResearchAreas) { this.protocolResearchAreas = protocolResearchAreas; for (ProtocolResearchArea researchArea : protocolResearchAreas) { researchArea.init(this); } } public List<ProtocolResearchArea> getProtocolResearchAreas() { return protocolResearchAreas; } public void addProtocolResearchAreas(ProtocolResearchArea protocolResearchArea) { getProtocolResearchAreas().add(protocolResearchArea); } public ProtocolResearchArea getProtocolResearchAreas(int index) { while (getProtocolResearchAreas().size() <= index) { getProtocolResearchAreas().add(new ProtocolResearchArea()); } return getProtocolResearchAreas().get(index); } public void setProtocolReferences(List<ProtocolReference> protocolReferences) { this.protocolReferences = protocolReferences; for (ProtocolReference reference : protocolReferences) { reference.init(this); } } public List<ProtocolReference> getProtocolReferences() { return protocolReferences; } public ProtocolDocument getProtocolDocument() { return protocolDocument; } public void setProtocolDocument(ProtocolDocument protocolDocument) { this.protocolDocument = protocolDocument; } public void setProtocolLocations(List<ProtocolLocation> protocolLocations) { this.protocolLocations = protocolLocations; for (ProtocolLocation location : protocolLocations) { location.init(this); } } public List<ProtocolLocation> getProtocolLocations() { return protocolLocations; } @SuppressWarnings("unchecked") @Override public List buildListOfDeletionAwareLists() { List managedLists = super.buildListOfDeletionAwareLists(); managedLists.add(this.protocolResearchAreas); managedLists.add(this.protocolReferences); managedLists.add(getProtocolFundingSources()); managedLists.add(getProtocolLocations()); managedLists.add(getProtocolRiskLevels()); managedLists.add(getProtocolParticipants()); managedLists.add(getProtocolAttachmentPersonnel()); managedLists.add(getProtocolUnits()); managedLists.add(getAttachmentProtocols()); managedLists.add(getProtocolPersons()); managedLists.add(getProtocolActions()); managedLists.add(getProtocolSubmissions()); if (getProtocolAmendRenewal() != null) { managedLists.add(getProtocolAmendRenewal().getModules()); } else { // needed to ensure that the OjbCollectionHelper receives constant list size. managedLists.add(new ArrayList<ProtocolAmendRenewModule>()); } managedLists.add(getProtocolAmendRenewals()); List<ProtocolSpecialReviewExemption> specialReviewExemptions = new ArrayList<ProtocolSpecialReviewExemption>(); for (ProtocolSpecialReview specialReview : getSpecialReviews()) { specialReviewExemptions.addAll(specialReview.getSpecialReviewExemptions()); } managedLists.add(specialReviewExemptions); managedLists.add(getSpecialReviews()); managedLists.add(getNotepads()); return managedLists; } /** * This method is to return all attachments for each person. * Purpose of this method is to use the list in buildListOfDeletionAwareLists. * Looks like OJB is not searching beyond the first level. It doesn't delete * from collection under ProtocolPerson. * @return List<ProtocolAttachmentPersonnel> */ private List<ProtocolAttachmentPersonnel> getProtocolAttachmentPersonnel() { List<ProtocolAttachmentPersonnel> protocolAttachmentPersonnel = new ArrayList<ProtocolAttachmentPersonnel>(); for (ProtocolPerson protocolPerson : getProtocolPersons()) { protocolAttachmentPersonnel.addAll(protocolPerson.getAttachmentPersonnels()); } return protocolAttachmentPersonnel; } /** * This method is to return all protocol units for each person. * Purpose of this method is to use the list in buildListOfDeletionAwareLists. * Looks like OJB is not searching beyond the first level. It doesn't delete * from collection under ProtocolPerson. * @return List<ProtocolUnit> */ private List<ProtocolUnit> getProtocolUnits() { List<ProtocolUnit> protocolUnits = new ArrayList<ProtocolUnit>(); for (ProtocolPerson protocolPerson : getProtocolPersons()) { protocolUnits.addAll(protocolPerson.getProtocolUnits()); } return protocolUnits; } /** * This method is to find Principal Investigator from ProtocolPerson list * @return ProtocolPerson */ public ProtocolPerson getPrincipalInvestigator() { return getProtocolPersonnelService().getPrincipalInvestigator(getProtocolPersons()); } public String getPrincipalInvestigatorName() { ProtocolPerson pi = getPrincipalInvestigator(); return pi != null ? pi.getFullName() : null; } public ProtocolUnit getLeadUnit() { ProtocolUnit leadUnit = null; if (getPrincipalInvestigator() != null) { for ( ProtocolUnit unit : getPrincipalInvestigator().getProtocolUnits() ) { if (unit.getLeadUnitFlag()) { leadUnit = unit; } } } return leadUnit; } public String getLeadUnitNumber() { if (StringUtils.isBlank(leadUnitNumber)) { if (getLeadUnit() != null) { setLeadUnitNumber(getLeadUnit().getUnitNumber()); } } return leadUnitNumber; } // TODO *********code has been moved to base class, should ultimately be removed********** public void setLeadUnitNumber(String leadUnitNumber) { this.leadUnitNumber = leadUnitNumber; } public String getPrincipalInvestigatorId() { if (StringUtils.isBlank(principalInvestigatorId)) { if (getPrincipalInvestigator() != null) { ProtocolPerson principalInvestigator = getPrincipalInvestigator(); if (StringUtils.isNotBlank(principalInvestigator.getPersonId())) { setPrincipalInvestigatorId(principalInvestigator.getPersonId()); } else { //ProtocolUnit leadUnit = new ProtocolUnit(); //leadUnit.setUnitNumber(leadUnitNumber); //leadUnit.setPersonId(getPrincipalInvestigator().getPersonId()); //leadUnit.setLeadUnitFlag(true); // TODO : rice upgrade temp fix //leadUnit.setProtocolNumber("0"); //leadUnit.setSequenceNumber(0); //getPrincipalInvestigator().getProtocolUnits().add(leadUnit); if (principalInvestigator.getRolodexId() != null) { setPrincipalInvestigatorId(principalInvestigator.getRolodexId().toString()); } } } } return principalInvestigatorId; } public void setPrincipalInvestigatorId(String principalInvestigatorId) { this.principalInvestigatorId = principalInvestigatorId; } // TODO **********************end************************ public boolean isNonEmployeeFlag() { return this.nonEmployeeFlag; } public void setNonEmployeeFlag(boolean nonEmployeeFlag) { this.nonEmployeeFlag = nonEmployeeFlag; } /** * This method is to get protocol location service * @return ProtocolLocationService */ protected ProtocolLocationService getProtocolLocationService() { ProtocolLocationService protocolLocationService = (ProtocolLocationService)KraServiceLocator.getService("protocolLocationService"); return protocolLocationService; } /* * Initialize protocol location. * Add default organization. */ private void initializeProtocolLocation() { getProtocolLocationService().addDefaultProtocolLocation(this); } // TODO *********code has been moved to base class, should ultimately be removed********** public List<ProtocolPerson> getProtocolPersons() { return protocolPersons; } public void setProtocolPersons(List<ProtocolPerson> protocolPersons) { this.protocolPersons = protocolPersons; for (ProtocolPerson person : protocolPersons) { person.init(this); } } // TODO **********************end************************ /** * Gets index i from the protocol person list. * * @param index * @return protocol person at index i */ public ProtocolPerson getProtocolPerson(int index) { return getProtocolPersons().get(index); } // TODO This method has been moved to base class as a protected hook method, and so should be replaced by the hook implementation /** * This method is to get protocol personnel service * @return protocolPersonnelService */ private ProtocolPersonnelService getProtocolPersonnelService() { ProtocolPersonnelService protocolPersonnelService = (ProtocolPersonnelService)KraServiceLocator.getService("protocolPersonnelService"); return protocolPersonnelService; } public List<ProtocolFundingSource> getProtocolFundingSources() { return protocolFundingSources; } public void setProtocolFundingSources(List<ProtocolFundingSource> protocolFundingSources) { this.protocolFundingSources = protocolFundingSources; for (ProtocolFundingSource fundingSource : protocolFundingSources) { fundingSource.init(this); } } public String getResearchAreaCode() { return researchAreaCode; } public void setResearchAreaCode(String researchAreaCode) { this.researchAreaCode = researchAreaCode; } public String getFundingSource() { return fundingSource; } public void setFundingSource(String fundingSource) { this.fundingSource = fundingSource; } public String getPerformingOrganizationId() { return performingOrganizationId; } public void setPerformingOrganizationId(String performingOrganizationId) { this.performingOrganizationId = performingOrganizationId; } // TODO *********code has been moved to base class, should ultimately be removed********** public String getLeadUnitName() { if (StringUtils.isBlank(leadUnitName)) { if (getLeadUnit() != null) { setLeadUnitName(getLeadUnit().getUnitName()); } } return leadUnitName; } public void setLeadUnitName(String leadUnitName) { this.leadUnitName = leadUnitName; } // TODO **********************end************************ public void setSpecialReviews(List<ProtocolSpecialReview> specialReviews) { this.specialReviews = specialReviews; } /** * @see org.kuali.kra.document.SpecialReviewHandler#addSpecialReview(org.kuali.kra.bo.AbstractSpecialReview) */ public void addSpecialReview(ProtocolSpecialReview specialReview) { specialReview.setSequenceOwner(this); getSpecialReviews().add(specialReview); } /** * @see org.kuali.kra.document.SpecialReviewHandler#getSpecialReview(int) */ public ProtocolSpecialReview getSpecialReview(int index) { return getSpecialReviews().get(index); } /** * @see org.kuali.kra.document.SpecialReviewHandler#getSpecialReviews() */ public List<ProtocolSpecialReview> getSpecialReviews() { return specialReviews; } /** * Gets the attachment protocols. Cannot return {@code null}. * @return the attachment protocols */ public List<ProtocolAttachmentProtocol> getAttachmentProtocols() { if (this.attachmentProtocols == null) { this.attachmentProtocols = new ArrayList<ProtocolAttachmentProtocol>(); } return this.attachmentProtocols; } /** * Gets an attachment protocol. * @param index the index * @return an attachment protocol */ public ProtocolAttachmentProtocol getAttachmentProtocol(int index) { return this.attachmentProtocols.get(index); } /** * Gets the notepads. Cannot return {@code null}. * @return the notepads */ public List<ProtocolNotepad> getNotepads() { if (this.notepads == null) { this.notepads = new ArrayList<ProtocolNotepad>(); } Collections.sort(notepads, Collections.reverseOrder()); return this.notepads; } /** * Gets an attachment protocol. * @param index the index * @return an attachment protocol */ public ProtocolNotepad getNotepad(int index) { return this.notepads.get(index); } /** * adds an attachment protocol. * @param attachmentProtocol the attachment protocol * @throws IllegalArgumentException if attachmentProtocol is null */ private void addAttachmentProtocol(ProtocolAttachmentProtocol attachmentProtocol) { ProtocolAttachmentBase.addAttachmentToCollection(attachmentProtocol, this.getAttachmentProtocols()); } /** * removes an attachment protocol. * @param attachmentProtocol the attachment protocol * @throws IllegalArgumentException if attachmentProtocol is null */ private void removeAttachmentProtocol(ProtocolAttachmentProtocol attachmentProtocol) { ProtocolAttachmentBase.removeAttachmentFromCollection(attachmentProtocol, this.getAttachmentProtocols()); } /** * @deprecated * Gets the attachment personnels. Cannot return {@code null}. * @return the attachment personnels */ @Deprecated public List<ProtocolAttachmentPersonnel> getAttachmentPersonnels() { return getProtocolAttachmentPersonnel(); } private void updateUserFields(KraPersistableBusinessObjectBase bo) { bo.setUpdateUser(GlobalVariables.getUserSession().getPrincipalName()); bo.setUpdateTimestamp(getDateTimeService().getCurrentTimestamp()); } /** * Adds a attachment to a Protocol where the type of attachment is used to determine * where to add the attachment. * @param attachment the attachment * @throws IllegalArgumentException if attachment is null or if an unsupported attachment is found */ public <T extends ProtocolAttachmentBase> void addAttachmentsByType(T attachment) { if (attachment == null) { throw new IllegalArgumentException("the attachment is null"); } updateUserFields(attachment); attachment.setProtocolId(getProtocolId()); if (attachment instanceof ProtocolAttachmentProtocol) { this.addAttachmentProtocol((ProtocolAttachmentProtocol) attachment); } else { throw new IllegalArgumentException("unsupported type: " + attachment.getClass().getName()); } } /** * removes an attachment to a Protocol where the type of attachment is used to determine * where to add the attachment. * @param attachment the attachment * @throws IllegalArgumentException if attachment is null or if an unsupported attachment is found */ public <T extends ProtocolAttachmentBase> void removeAttachmentsByType(T attachment) { if (attachment == null) { throw new IllegalArgumentException("the attachment is null"); } if (attachment instanceof ProtocolAttachmentProtocol) { this.removeAttachmentProtocol((ProtocolAttachmentProtocol) attachment); } else { throw new IllegalArgumentException("unsupported type: " + attachment.getClass().getName()); } } public String getKeyPerson() { return keyPerson; } public void setKeyPerson(String keyPerson) { this.keyPerson = keyPerson; } public String getInvestigator() { if (StringUtils.isBlank(principalInvestigatorId)) { if (getPrincipalInvestigator() != null) { investigator = getPrincipalInvestigator().getPersonName(); } } return investigator; } public void setInvestigator(String investigator) { this.investigator = investigator; } /* TODO : why this temp method is in Protocol method */ private void populateTempViewDate() { this.protocolSubmission = new ProtocolSubmission(); Committee committee = new Committee(); committee.setId(1L); committee.setCommitteeId("Comm-1"); committee.setCommitteeName("Test By Kiltesh"); this.protocolSubmission.setCommittee(committee); this.protocolSubmission.setSubmissionNumber(1); this.protocolSubmission.setSubmissionDate(new Date(System.currentTimeMillis())); this.protocolSubmission.setSubmissionStatusCode("100"); ProtocolSubmissionType submissionType = new ProtocolSubmissionType(); submissionType.setDescription("Initial Protocol Application for Approval "); this.protocolSubmission.setProtocolSubmissionType(submissionType); ProtocolReviewType review = new ProtocolReviewType(); review.setDescription("Full"); this.protocolSubmission.setProtocolReviewType(review); ProtocolSubmissionQualifierType qual = new ProtocolSubmissionQualifierType(); qual.setDescription("Lorem Ipsum Dolor "); this.protocolSubmission.setProtocolSubmissionQualifierType(qual); ProtocolSubmissionStatus substatus = new ProtocolSubmissionStatus(); substatus.setDescription("Approved"); this.protocolSubmission.setSubmissionStatus(substatus); CommitteeMembershipType committeeMembershipType1 = new CommitteeMembershipType(); committeeMembershipType1.setDescription("Primary"); CommitteeMembershipType committeeMembershipType2 = new CommitteeMembershipType(); committeeMembershipType2.setDescription("Secondary"); CommitteeMembership committeeMembership1 = new CommitteeMembership(); committeeMembership1.setPersonName("Bryan Hutchinson"); committeeMembership1.setMembershipType(committeeMembershipType1); CommitteeMembership committeeMembership2 = new CommitteeMembership(); committeeMembership2.setPersonName("Kiltesh Patel"); committeeMembership2.setMembershipType(committeeMembershipType2); List<CommitteeMembership> list = new ArrayList<CommitteeMembership>(); list.add(committeeMembership1); list.add(committeeMembership2); committee.setCommitteeMemberships(list); this.protocolSubmission.setYesVoteCount(2); this.protocolSubmission.setNoVoteCount(3); this.protocolSubmission.setAbstainerCount(1); this.protocolSubmission.setVotingComments("Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Suspendisse purus. Nullam et justo. In volutpat odio sit amet pede. Pellentesque ipsum dui, convallis in, mollis a, lacinia vel, diam. " + "Phasellus molestie neque at sapien condimentum massa nunc" + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Suspendisse purus. Nullam et justo. In volutpat odio sit amet pede. Pellentesque ipsum dui, convallis in, mollis a, lacinia vel, diam. " + "Phasellus molestie neque at sapien condimentum massa nunc"); CommitteeSchedule committeeSchedule= new CommitteeSchedule(); CommitteeScheduleAttendance committeeScheduleAttendance = new CommitteeScheduleAttendance(); List<CommitteeScheduleAttendance> cslist = new ArrayList<CommitteeScheduleAttendance>(); cslist.add(committeeScheduleAttendance); committeeSchedule.setCommitteeScheduleAttendances(cslist); this.protocolSubmission.setCommitteeSchedule(committeeSchedule); } public ProtocolSubmission getProtocolSubmission() { // TODO : this is a fix to remove 'populateTempViewDate' // if (protocolSubmission == null) { if (!protocolSubmissions.isEmpty()) { // sorted by ojb if (protocolSubmission == null || protocolSubmission.getSubmissionNumber() == null || protocolSubmissions.get(protocolSubmissions.size() - 1).getSubmissionNumber() > protocolSubmission .getSubmissionNumber()) { protocolSubmission = protocolSubmissions.get(protocolSubmissions.size() - 1); } // for (ProtocolSubmission submission : protocolSubmissions) { // if (protocolSubmission == null || protocolSubmission.getSubmissionNumber() == null // || submission.getSubmissionNumber() > protocolSubmission.getSubmissionNumber()) { // protocolSubmission = submission; // } // } } else { protocolSubmission = new ProtocolSubmission(); // TODO : the update protocol rule may not like null protocolSubmission.setProtocolSubmissionType(new ProtocolSubmissionType()); protocolSubmission.setSubmissionStatus(new ProtocolSubmissionStatus()); } // } refreshReferenceObject(protocolSubmission); return protocolSubmission; } private void refreshReferenceObject(ProtocolSubmission submission) { // if submission just added, then these probably are empty if (StringUtils.isNotBlank(submission.getProtocolReviewTypeCode()) && submission.getProtocolReviewType() == null) { submission.refreshReferenceObject("protocolReviewType"); } if (StringUtils.isNotBlank(submission.getSubmissionStatusCode()) && submission.getSubmissionStatus() == null) { submission.refreshReferenceObject("submissionStatus"); } if (StringUtils.isNotBlank(submission.getSubmissionTypeCode()) && submission.getProtocolSubmissionType() == null) { submission.refreshReferenceObject("protocolSubmissionType"); } if (StringUtils.isNotBlank(submission.getSubmissionTypeQualifierCode()) && submission.getProtocolSubmissionQualifierType() == null) { submission.refreshReferenceObject("protocolSubmissionQualifierType"); } } public void setProtocolSubmission(ProtocolSubmission protocolSubmission) { this.protocolSubmission = protocolSubmission; } public void setProtocolActions(List<ProtocolAction> protocolActions) { this.protocolActions = protocolActions; } public List<ProtocolAction> getProtocolActions() { return protocolActions; } public ProtocolAction getLastProtocolAction() { if (protocolActions.size() == 0) { return null; } Collections.sort(protocolActions, new Comparator<ProtocolAction>() { public int compare(ProtocolAction action1, ProtocolAction action2) { return action2.getActualActionDate().compareTo(action1.getActualActionDate()); } }); return protocolActions.get(0); } public void setProtocolSubmissions(List<ProtocolSubmission> protocolSubmissions) { this.protocolSubmissions = protocolSubmissions; } public List<ProtocolSubmission> getProtocolSubmissions() { return protocolSubmissions; } /** * Get the next value in a sequence. * @param key the unique key of the sequence * @return the next value */ public Integer getNextValue(String key) { return protocolDocument.getDocumentNextValue(key); } public void setAttachmentProtocols(List<ProtocolAttachmentProtocol> attachmentProtocols) { this.attachmentProtocols = attachmentProtocols; for (ProtocolAttachmentProtocol attachment : attachmentProtocols) { attachment.resetPersistenceState(); attachment.setSequenceNumber(0); } } public void setNotepads(List<ProtocolNotepad> notepads) { this.notepads = notepads; } public void setProtocolAmendRenewal(ProtocolAmendRenewal amendRenewal) { protocolAmendRenewals.add(amendRenewal); } public ProtocolAmendRenewal getProtocolAmendRenewal() { if (protocolAmendRenewals.size() == 0) return null; return protocolAmendRenewals.get(0); } public List<ProtocolAmendRenewal> getProtocolAmendRenewals() { return protocolAmendRenewals; } public void setProtocolAmendRenewals(List<ProtocolAmendRenewal> protocolAmendRenewals) { this.protocolAmendRenewals = protocolAmendRenewals; } // TODO *********code has been moved to base class, should ultimately be removed********** /** {@inheritDoc} */ public Integer getOwnerSequenceNumber() { return null; } /** * @see org.kuali.kra.SequenceOwner#getVersionNameField() */ public String getVersionNameField() { return "protocolNumber"; } /** {@inheritDoc} */ public void incrementSequenceNumber() { this.sequenceNumber++; } /** {@inheritDoc} */ public Protocol getSequenceOwner() { return this; } /** {@inheritDoc} */ public void setSequenceOwner(Protocol newOwner) { //no-op } /** {@inheritDoc} */ public void resetPersistenceState() { this.protocolId = null; } // TODO **********************end************************ /** * * This method merges the data of the amended protocol into this protocol. * @param amendment */ public void merge(Protocol amendment) { merge(amendment, true); } public void merge(Protocol amendment, boolean mergeActions) { List<ProtocolAmendRenewModule> modules = amendment.getProtocolAmendRenewal().getModules(); for (ProtocolAmendRenewModule module : modules) { merge(amendment, module.getProtocolModuleTypeCode()); } if (amendment.isRenewalWithoutAmendment() && isRenewalWithNewAttachment(amendment)) { merge(amendment, ProtocolModule.ADD_MODIFY_ATTACHMENTS); } //mergeProtocolSubmission(amendment); if (mergeActions) { mergeProtocolSubmission(amendment); mergeProtocolAction(amendment); } } private boolean isRenewalWithNewAttachment(Protocol renewal) { boolean hasNewAttachment = false; for (ProtocolAttachmentProtocol attachment : renewal.getAttachmentProtocols()) { if (attachment.isDraft()) { hasNewAttachment = true; break; } } return hasNewAttachment; } /** * * This method merges the data of a specific module of the amended protocol into this protocol. * @param amendment * @param protocolModuleTypeCode */ public void merge(Protocol amendment, String protocolModuleTypeCode) { if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.GENERAL_INFO)) { mergeGeneralInfo(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.AREAS_OF_RESEARCH)) { mergeResearchAreas(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.FUNDING_SOURCE)) { mergeFundingSources(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.PROTOCOL_ORGANIZATIONS)) { mergeOrganizations(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.PROTOCOL_PERSONNEL)) { mergePersonnel(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.ADD_MODIFY_ATTACHMENTS)) { if (amendment.isAmendment() || amendment.isRenewal() || (!amendment.getAttachmentProtocols().isEmpty() && this.getAttachmentProtocols().isEmpty())) { mergeAttachments(amendment); } else { restoreAttachments(this); } } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.PROTOCOL_REFERENCES)) { mergeReferences(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.SPECIAL_REVIEW)) { mergeSpecialReview(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.SUBJECTS)) { mergeSubjects(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.OTHERS)) { mergeOthers(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.PROTOCOL_PERMISSIONS)) { mergeProtocolPermissions(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.QUESTIONNAIRE)) { mergeProtocolQuestionnaire(amendment); } } private void mergeProtocolQuestionnaire(Protocol amendment) { // TODO : what if user did not edit questionnaire at all, then questionnaire will be wiped out ? removeOldQuestionnaire(); amendQuestionnaire(amendment); } /* * remove existing questionnaire from current */ private void removeOldQuestionnaire() { List <AnswerHeader> answerHeaders = getAnswerHeaderForProtocol(this); if (!answerHeaders.isEmpty() && answerHeaders.get(0).getAnswerHeaderId() != null){ getBusinessObjectService().delete(answerHeaders); } } /* * add questionnaire answer from amendment to protocol */ private void amendQuestionnaire(Protocol amendment) { List <AnswerHeader> answerHeaders = getAnswerHeaderForProtocol(amendment); if (!answerHeaders.isEmpty()){ for (AnswerHeader answerHeader : answerHeaders) { for (Answer answer : answerHeader.getAnswers()) { answer.setAnswerHeaderIdFk(null); answer.setId(null); } answerHeader.setAnswerHeaderId(null); answerHeader.setModuleItemKey(this.getProtocolNumber()); answerHeader.setModuleSubItemKey(this.getSequenceNumber().toString()); } getBusinessObjectService().save(answerHeaders); } } /* * get submit for review questionnaire answerheaders */ private List <AnswerHeader> getAnswerHeaderForProtocol(Protocol protocol) { ModuleQuestionnaireBean moduleQuestionnaireBean = new ProtocolModuleQuestionnaireBean(protocol); moduleQuestionnaireBean.setModuleSubItemCode("0"); List <AnswerHeader> answerHeaders = new ArrayList<AnswerHeader>(); answerHeaders = getQuestionnaireAnswerService().getQuestionnaireAnswer(moduleQuestionnaireBean); return answerHeaders; } protected QuestionnaireAnswerService getQuestionnaireAnswerService() { return KraServiceLocator.getService(QuestionnaireAnswerService.class); } protected BusinessObjectService getBusinessObjectService() { return KraServiceLocator.getService(BusinessObjectService.class); } @SuppressWarnings("unchecked") private void mergeProtocolSubmission(Protocol amendment) { List<ProtocolSubmission> submissions = (List<ProtocolSubmission>) deepCopy(amendment.getProtocolSubmissions()); for (ProtocolSubmission submission : submissions) { submission.setProtocolNumber(this.getProtocolNumber()); submission.setSubmissionId(null); submission.setSequenceNumber(sequenceNumber); submission.setProtocolId(this.getProtocolId()); // submission.setSubmissionNumber(this.getProtocolSubmissions().size() + 1); this.getProtocolSubmissions().add(submission); //how about meting data // online review data } } /* * merge amendment/renewal protocol action to original protocol when A/R is approved */ @SuppressWarnings("unchecked") private void mergeProtocolAction(Protocol amendment) { List<ProtocolAction> protocolActions = (List<ProtocolAction>) deepCopy(amendment.getProtocolActions()); Collections.sort(protocolActions, new Comparator<ProtocolAction>() { public int compare(ProtocolAction action1, ProtocolAction action2) { return action1.getActionId().compareTo(action2.getActionId()); } }); // the first 1 'protocol created is already added to original protocol // the last one is 'approve' protocolActions.remove(0); protocolActions.remove(protocolActions.size() - 1); for (ProtocolAction protocolAction : protocolActions) { protocolAction.setProtocolNumber(this.getProtocolNumber()); protocolAction.setProtocolActionId(null); protocolAction.setSequenceNumber(sequenceNumber); protocolAction.setProtocolId(this.getProtocolId()); String index = amendment.getProtocolNumber().substring(11); protocolAction.setActionId(getNextValue(NEXT_ACTION_ID_KEY)); String type = "Amendment"; if (amendment.isRenewal()) { type = "Renewal"; } if (StringUtils.isNotBlank(protocolAction.getComments())) { protocolAction.setComments(type + "-" + index + ": " + protocolAction.getComments()); } else { protocolAction.setComments(type + "-" + index + ": "); } this.getProtocolActions().add(protocolAction); } } public void mergeGeneralInfo(Protocol amendment) { this.protocolTypeCode = amendment.getProtocolTypeCode(); this.title = amendment.getTitle(); this.initialSubmissionDate = amendment.getInitialSubmissionDate(); this.approvalDate = amendment.getApprovalDate(); this.expirationDate = amendment.getExpirationDate(); this.lastApprovalDate = amendment.getLastApprovalDate(); this.description = amendment.getDescription(); this.fdaApplicationNumber = amendment.getFdaApplicationNumber(); //this.billable = amendment.isBillable(); this.referenceNumber1 = amendment.getReferenceNumber1(); this.referenceNumber2 = amendment.getReferenceNumber2(); } @SuppressWarnings("unchecked") private void mergeResearchAreas(Protocol amendment) { setProtocolResearchAreas((List<ProtocolResearchArea>) deepCopy(amendment.getProtocolResearchAreas())); } @SuppressWarnings("unchecked") private void mergeFundingSources(Protocol amendment) { setProtocolFundingSources((List<ProtocolFundingSource>) deepCopy(amendment.getProtocolFundingSources())); } @SuppressWarnings("unchecked") private void mergeReferences(Protocol amendment) { setProtocolReferences((List<ProtocolReference>) deepCopy(amendment.getProtocolReferences())); this.fdaApplicationNumber = amendment.getFdaApplicationNumber(); this.referenceNumber1 = amendment.getReferenceNumber1(); this.referenceNumber2 = amendment.getReferenceNumber2(); this.description = amendment.getDescription(); } @SuppressWarnings("unchecked") private void mergeOrganizations(Protocol amendment) { setProtocolLocations((List<ProtocolLocation>) deepCopy(amendment.getProtocolLocations())); } @SuppressWarnings("unchecked") private void mergeSubjects(Protocol amendment) { setProtocolParticipants((List<ProtocolParticipant>) deepCopy(amendment.getProtocolParticipants())); } @SuppressWarnings("unchecked") private void mergeAttachments(Protocol amendment) { // TODO : may need to set protocolnumber // personnel attachment may have protocol person id issue // how about sequence number ? // need to change documentstatus to 2 if it is 1 // what the new protocol's protocol_status should be ? List<ProtocolAttachmentProtocol> attachmentProtocols = new ArrayList<ProtocolAttachmentProtocol>(); for (ProtocolAttachmentProtocol attachment : (List<ProtocolAttachmentProtocol>) deepCopy(amendment.getAttachmentProtocols())) { attachment.setProtocolNumber(this.getProtocolNumber()); attachment.setSequenceNumber(this.getSequenceNumber()); attachment.setProtocolId(this.getProtocolId()); attachment.setId(null); if (attachment.getFile() != null ) { attachment.getFile().setId(null); } if (attachment.isDraft()) { attachment.setDocumentStatusCode(ProtocolAttachmentStatus.FINALIZED); attachmentProtocols.add(attachment); attachment.setProtocol(this); } if (attachment.isDeleted() && KraServiceLocator.getService(ProtocolAttachmentService.class).isNewAttachmentVersion((ProtocolAttachmentProtocol) attachment)) { attachmentProtocols.add(attachment); attachment.setProtocol(this); } } getAttachmentProtocols().addAll(attachmentProtocols); removeDeletedAttachment(); mergeNotepads(amendment); } /* * the deleted attachment will not be merged */ private void removeDeletedAttachment() { List<Integer> documentIds = new ArrayList<Integer>(); List<ProtocolAttachmentProtocol> attachments = new ArrayList<ProtocolAttachmentProtocol>(); for (ProtocolAttachmentProtocol attachment : this.getAttachmentProtocols()) { attachment.setProtocol(this); if (attachment.isDeleted()) { documentIds.add(attachment.getDocumentId()); } } if (!documentIds.isEmpty()) { for (ProtocolAttachmentProtocol attachment : this.getAttachmentProtocols()) { attachment.setProtocol(this); if (!documentIds.contains(attachment.getDocumentId())) { attachments.add(attachment); } } this.setAttachmentProtocols(new ArrayList<ProtocolAttachmentProtocol>()); this.getAttachmentProtocols().addAll(attachments); } } /* * This is to restore attachments from protocol to amendment when 'attachment' section is unselected. * The attachment in amendment may have been modified. * delete 'attachment' need to be careful. * - if the 'file' is also used in other 'finalized' attachment, then should remove this file reference from attachment * otherwise, the delete will also delete any attachment that reference to this file */ private void restoreAttachments(Protocol protocol) { List<ProtocolAttachmentProtocol> attachmentProtocols = new ArrayList<ProtocolAttachmentProtocol>(); List<ProtocolAttachmentProtocol> deleteAttachments = new ArrayList<ProtocolAttachmentProtocol>(); List<AttachmentFile> deleteFiles = new ArrayList<AttachmentFile>(); for (ProtocolAttachmentProtocol attachment : this.getAttachmentProtocols()) { if (attachment.isFinal()) { attachmentProtocols.add(attachment); // } else if (attachment.isDraft()) { } else { // in amendment, DRAFT & DELETED must be new attachment because DELETED // will not be copied from original protocol deleteAttachments.add(attachment); if (!fileIsReferencedByOther(attachment.getFileId())) { deleteFiles.add(attachment.getFile()); } attachment.setFileId(null); } } if (!deleteAttachments.isEmpty()) { getBusinessObjectService().save(deleteAttachments); if (!deleteFiles.isEmpty()) { getBusinessObjectService().delete(deleteFiles); } getBusinessObjectService().delete(deleteAttachments); } this.getAttachmentProtocols().clear(); this.getAttachmentProtocols().addAll(attachmentProtocols); mergeNotepads(protocol); } private boolean fileIsReferencedByOther(Long fileId) { Map<String, String> fieldValues = new HashMap<String, String>(); fieldValues.put("fileId", fileId.toString()); return getBusinessObjectService().countMatching(ProtocolAttachmentProtocol.class, fieldValues) > 1; } private void mergeNotepads(Protocol amendment) { List <ProtocolNotepad> notepads = new ArrayList<ProtocolNotepad>(); if (amendment.getNotepads() != null) { for (ProtocolNotepad notepad : (List<ProtocolNotepad>) deepCopy(amendment.getNotepads())) { notepad.setProtocolNumber(this.getProtocolNumber()); notepad.setSequenceNumber(this.getSequenceNumber()); notepad.setProtocolId(this.getProtocolId()); notepad.setId(null); notepad.setProtocol(this); notepads.add(notepad); } } this.setNotepads(notepads); } private ProtocolPerson findMatchingPerson(ProtocolPerson person) { ProtocolPerson matchingPerson = null; for (ProtocolPerson newPerson : this.getProtocolPersons()) { if (newPerson.getProtocolPersonRoleId().equals(person.getProtocolPersonRoleId())) { if ((StringUtils.isNotBlank(newPerson.getPersonId()) && StringUtils.isNotBlank(person.getPersonId()) && newPerson.getPersonId().equals(person.getPersonId())) || (newPerson.getRolodexId() != null && person.getRolodexId() != null && newPerson.getRolodexId().equals(person.getRolodexId()))) { matchingPerson = newPerson; break; } } } return matchingPerson; } @SuppressWarnings("unchecked") private void mergeSpecialReview(Protocol amendment) { setSpecialReviews((List<ProtocolSpecialReview>) deepCopy(amendment.getSpecialReviews())); cleanupSpecialReviews(amendment); } @SuppressWarnings("unchecked") private void mergePersonnel(Protocol amendment) { setProtocolPersons((List<ProtocolPerson>) deepCopy(amendment.getProtocolPersons())); for (ProtocolPerson person : protocolPersons) { Integer nextPersonId = getSequenceAccessorService().getNextAvailableSequenceNumber("SEQ_PROTOCOL_ID").intValue(); person.setProtocolPersonId(nextPersonId); for (ProtocolAttachmentPersonnel protocolAttachmentPersonnel : person.getAttachmentPersonnels()) { protocolAttachmentPersonnel.setId(null); protocolAttachmentPersonnel.setPersonId(person.getProtocolPersonId()); protocolAttachmentPersonnel.setProtocolId(getProtocolId()); protocolAttachmentPersonnel.setProtocolNumber(getProtocolNumber()); } } } private void mergeOthers(Protocol amendment) { if (protocolDocument.getCustomAttributeDocuments() == null || protocolDocument.getCustomAttributeDocuments().isEmpty()) { protocolDocument.initialize(); } if (amendment.getProtocolDocument().getCustomAttributeDocuments() == null || amendment.getProtocolDocument().getCustomAttributeDocuments().isEmpty()) { amendment.getProtocolDocument().initialize(); } for (Entry<String, CustomAttributeDocument> entry : protocolDocument.getCustomAttributeDocuments().entrySet()) { CustomAttributeDocument cad = amendment.getProtocolDocument().getCustomAttributeDocuments().get(entry.getKey()); entry.getValue().getCustomAttribute().setValue(cad.getCustomAttribute().getValue()); } } private void mergeProtocolPermissions(Protocol amendment) { // ToDo: merge permissions } private Object deepCopy(Object obj) { return ObjectUtils.deepCopy((Serializable) obj); } public ProtocolSummary getProtocolSummary() { ProtocolSummary protocolSummary = createProtocolSummary(); addPersonnelSummaries(protocolSummary); addResearchAreaSummaries(protocolSummary); addAttachmentSummaries(protocolSummary); addFundingSourceSummaries(protocolSummary); addParticipantSummaries(protocolSummary); addOrganizationSummaries(protocolSummary); addSpecialReviewSummaries(protocolSummary); addAdditionalInfoSummary(protocolSummary); return protocolSummary; } private void addAdditionalInfoSummary(ProtocolSummary protocolSummary) { AdditionalInfoSummary additionalInfoSummary = new AdditionalInfoSummary(); additionalInfoSummary.setFdaApplicationNumber(this.getFdaApplicationNumber()); //additionalInfoSummary.setBillable(isBillable()); additionalInfoSummary.setReferenceId1(this.getReferenceNumber1()); additionalInfoSummary.setReferenceId2(this.getReferenceNumber2()); additionalInfoSummary.setDescription(getDescription()); protocolSummary.setAdditionalInfo(additionalInfoSummary); } private void addSpecialReviewSummaries(ProtocolSummary protocolSummary) { for (ProtocolSpecialReview specialReview : getSpecialReviews()) { SpecialReviewSummary specialReviewSummary = new SpecialReviewSummary(); if (specialReview.getSpecialReviewType() == null) { specialReview.refreshReferenceObject("specialReviewType"); } specialReviewSummary.setType(specialReview.getSpecialReviewType().getDescription()); if (specialReview.getApprovalType() == null) { specialReview.refreshReferenceObject("approvalType"); } specialReviewSummary.setApprovalStatus(specialReview.getApprovalType().getDescription()); specialReviewSummary.setProtocolNumber(specialReview.getProtocolNumber()); specialReviewSummary.setApplicationDate(specialReview.getApplicationDate()); specialReviewSummary.setApprovalDate(specialReview.getApprovalDate()); specialReviewSummary.setExpirationDate(specialReview.getExpirationDate()); if (specialReview.getSpecialReviewExemptions() == null) { specialReview.refreshReferenceObject("specialReviewExemptions"); } specialReviewSummary.setExemptionNumbers(specialReview.getSpecialReviewExemptions()); specialReviewSummary.setComment(specialReview.getComments()); protocolSummary.add(specialReviewSummary); } } private void addOrganizationSummaries(ProtocolSummary protocolSummary) { for (ProtocolLocation organization : this.getProtocolLocations()) { OrganizationSummary organizationSummary = new OrganizationSummary(); organizationSummary.setId(organization.getOrganizationId()); organizationSummary.setOrganizationId(organization.getOrganizationId()); organizationSummary.setName(organization.getOrganization().getOrganizationName()); organizationSummary.setType(organization.getProtocolOrganizationType().getDescription()); organizationSummary.setContactId(organization.getRolodexId()); organizationSummary.setContact(organization.getRolodex()); organizationSummary.setFwaNumber(organization.getOrganization().getHumanSubAssurance()); protocolSummary.add(organizationSummary); } } private void addParticipantSummaries(ProtocolSummary protocolSummary) { for (ProtocolParticipant participant : this.getProtocolParticipants()) { ParticipantSummary participantSummary = new ParticipantSummary(); participantSummary.setDescription(participant.getParticipantType().getDescription()); participantSummary.setCount(participant.getParticipantCount()); protocolSummary.add(participantSummary); } } private void addFundingSourceSummaries(ProtocolSummary protocolSummary) { for (ProtocolFundingSource source : getProtocolFundingSources()) { FundingSourceSummary fundingSourceSummary = new FundingSourceSummary(); fundingSourceSummary.setFundingSourceType(source.getFundingSourceType().getDescription()); fundingSourceSummary.setFundingSource(source.getFundingSourceNumber()); fundingSourceSummary.setFundingSourceNumber(source.getFundingSourceNumber()); fundingSourceSummary.setFundingSourceName(source.getFundingSourceName()); fundingSourceSummary.setFundingSourceTitle(source.getFundingSourceTitle()); protocolSummary.add(fundingSourceSummary); } } private void addAttachmentSummaries(ProtocolSummary protocolSummary) { for (ProtocolAttachmentProtocol attachment : getActiveAttachmentProtocols()) { if (!attachment.isDeleted()) { AttachmentSummary attachmentSummary = new AttachmentSummary(); attachmentSummary.setAttachmentId(attachment.getId()); attachmentSummary.setFileType(attachment.getFile().getType()); attachmentSummary.setFileName(attachment.getFile().getName()); attachmentSummary.setAttachmentType("Protocol: " + attachment.getType().getDescription()); attachmentSummary.setDescription(attachment.getDescription()); attachmentSummary.setDataLength(attachment.getFile().getData() == null ? 0 : attachment.getFile().getData().length); attachmentSummary.setUpdateTimestamp(attachment.getUpdateTimestamp()); attachmentSummary.setUpdateUser(attachment.getUpdateUser()); protocolSummary.add(attachmentSummary); } } for (ProtocolPerson person : getProtocolPersons()) { for (ProtocolAttachmentPersonnel attachment : person.getAttachmentPersonnels()) { AttachmentSummary attachmentSummary = new AttachmentSummary(); attachmentSummary.setAttachmentId(attachment.getId()); attachmentSummary.setFileType(attachment.getFile().getType()); attachmentSummary.setFileName(attachment.getFile().getName()); attachmentSummary.setAttachmentType(person.getPersonName() + ": " + attachment.getType().getDescription()); attachmentSummary.setDescription(attachment.getDescription()); attachmentSummary.setDataLength(attachment.getFile().getData() == null ? 0 : attachment.getFile().getData().length); attachmentSummary.setUpdateTimestamp(attachment.getUpdateTimestamp()); attachmentSummary.setUpdateUser(attachment.getUpdateUser()); protocolSummary.add(attachmentSummary); } } } private void addResearchAreaSummaries(ProtocolSummary protocolSummary) { for (ProtocolResearchArea researchArea : getProtocolResearchAreas()) { ResearchAreaSummary researchAreaSummary = new ResearchAreaSummary(); researchAreaSummary.setResearchAreaCode(researchArea.getResearchAreaCode()); researchAreaSummary.setDescription(researchArea.getResearchAreas().getDescription()); protocolSummary.add(researchAreaSummary); } } private void addPersonnelSummaries(ProtocolSummary protocolSummary) { for (ProtocolPerson person : getProtocolPersons()) { PersonnelSummary personnelSummary = new PersonnelSummary(); personnelSummary.setPersonId(person.getPersonId()); personnelSummary.setName(person.getPersonName()); personnelSummary.setRoleName(person.getProtocolPersonRole().getDescription()); if (person.getAffiliationTypeCode() == null) { personnelSummary.setAffiliation(""); } else { if (person.getAffiliationType() == null) { person.refreshReferenceObject("affiliationType"); } personnelSummary.setAffiliation(person.getAffiliationType().getDescription()); } for (ProtocolUnit unit : person.getProtocolUnits()) { personnelSummary.addUnit(unit.getUnitNumber(), unit.getUnitName()); } protocolSummary.add(personnelSummary); } } private ProtocolSummary createProtocolSummary() { ProtocolSummary summary = new ProtocolSummary(); summary.setLastProtocolAction(getLastProtocolAction()); summary.setProtocolNumber(getProtocolNumber().toString()); summary.setPiName(getPrincipalInvestigator().getPersonName()); summary.setPiProtocolPersonId(getPrincipalInvestigator().getProtocolPersonId()); summary.setInitialSubmissionDate(getInitialSubmissionDate()); summary.setApprovalDate(getApprovalDate()); summary.setLastApprovalDate(getLastApprovalDate()); summary.setExpirationDate(getExpirationDate()); if (getProtocolType() == null) { refreshReferenceObject("protocolType"); } summary.setType(getProtocolType().getDescription()); if (getProtocolStatus() == null) { refreshReferenceObject("protocolStatus"); } summary.setStatus(getProtocolStatus().getDescription()); summary.setTitle(getTitle()); return summary; } // TODO *********code has been moved to base class, should ultimately be removed********** /** * * @see org.kuali.kra.common.permissions.Permissionable#getDocumentKey() */ public String getDocumentKey() { return Permissionable.PROTOCOL_KEY; } /** * * @see org.kuali.kra.common.permissions.Permissionable#getDocumentNumberForPermission() */ public String getDocumentNumberForPermission() { return protocolNumber; } /** * * @see org.kuali.kra.common.permissions.Permissionable#getRoleNames() */ public List<String> getRoleNames() { List<String> roleNames = new ArrayList<String>(); roleNames.add(RoleConstants.PROTOCOL_AGGREGATOR); roleNames.add(RoleConstants.PROTOCOL_VIEWER); return roleNames; } // TODO **********************end************************ public void resetForeignKeys() { for (ProtocolAction action : protocolActions) { action.resetForeignKeys(); } } // TODO *********code has been moved to base class, should ultimately be removed********** public String getNamespace() { return Constants.MODULE_NAMESPACE_PROTOCOL; } /** * * @see org.kuali.kra.UnitAclLoadable#getUnitNumberOfDocument() */ public String getDocumentUnitNumber() { return getLeadUnitNumber(); } /** * * @see org.kuali.kra.UnitAclLoadable#getDocumentRoleTypeCode() */ public String getDocumentRoleTypeCode() { return RoleConstants.PROTOCOL_ROLE_TYPE; } public void populateAdditionalQualifiedRoleAttributes(Map<String, String> qualifiedRoleAttributes) { return; } // TODO **********************end************************ public boolean isNew() { return !isAmendment() && !isRenewal(); } public boolean isAmendment() { return protocolNumber.contains(AMENDMENT_LETTER); } public boolean isRenewal() { return protocolNumber.contains(RENEWAL_LETTER); } public boolean isRenewalWithoutAmendment() { return isRenewal() && CollectionUtils.isEmpty(this.getProtocolAmendRenewal().getModules()); } /** * * If the protocol document is an amendment or renewal the parent protocol number is being returned. * (i.e. the protocol number of the protocol that is being amended or renewed). * * Null will be returned if the protocol is not an amendment or renewal. * * @return protocolNumber of the Protocol that is being amended/renewed */ public String getAmendedProtocolNumber() { if (isAmendment()) { return StringUtils.substringBefore(getProtocolNumber(), AMENDMENT_LETTER.toString()); } else if (isRenewal()) { return StringUtils.substringBefore(getProtocolNumber(), RENEWAL_LETTER.toString()); } else { return null; } } /** * Decides whether or not the Protocol is in a state where changes will require versioning. For example: has the protocol * had a change in status and not been versioned yet? * @return true if versioning required false if not. */ public boolean isVersioningRequired() { // TODO : why need this. it's always true return true; } /** * This method will return the list of all active attachments for this protocol; an attachment A is active for a * protocol if either A has a doc status code of 'draft' or * if for all other attachments for that protocol having the same doc id as A's doc id, none have a version number * greater than A's version number. * is defined as the o * @return */ public List<ProtocolAttachmentProtocol> getActiveAttachmentProtocols() { List<ProtocolAttachmentProtocol> activeAttachments = new ArrayList<ProtocolAttachmentProtocol>(); for (ProtocolAttachmentProtocol attachment1 : getAttachmentProtocols()) { if (attachment1.isDraft()) { activeAttachments.add(attachment1); } else if (attachment1.isFinal() || attachment1.isDeleted()) { //else if (attachment1.isFinal())) { boolean isActive = true; for (ProtocolAttachmentProtocol attachment2 : getAttachmentProtocols()) { if (attachment1.getDocumentId().equals(attachment2.getDocumentId()) && attachment1.getAttachmentVersion() < attachment2.getAttachmentVersion()) { isActive = false; break; } } if (isActive) { activeAttachments.add(attachment1); } else { attachment1.setActive(isActive); } } else { attachment1.setActive(false); } } return activeAttachments; } /** * This method will return the list of undeleted attachments that are still active for this protocol. * Essentially it filters out all the deleted elements from the list of active attachments. * See getActiveAttachmentProtocols() for a specification of what is an 'active attachment'. * * * @return */ // TODO the method code below could be restructured to combine the two for loops into one loop. public List<ProtocolAttachmentProtocol> getActiveAttachmentProtocolsNoDelete() { List<Integer> documentIds = new ArrayList<Integer>(); List<ProtocolAttachmentProtocol> activeAttachments = new ArrayList<ProtocolAttachmentProtocol>(); for (ProtocolAttachmentProtocol attachment : getActiveAttachmentProtocols()) { if (attachment.isDeleted()) { documentIds.add(attachment.getDocumentId()); } } for (ProtocolAttachmentProtocol attachment : getActiveAttachmentProtocols()) { if (documentIds.isEmpty() || !documentIds.contains(attachment.getDocumentId())) { activeAttachments.add(attachment); } else { attachment.setActive(false); } } return activeAttachments; } public boolean isCorrectionMode() { return correctionMode; } public void setCorrectionMode(boolean correctionMode) { this.correctionMode = correctionMode; } protected DateTimeService getDateTimeService() { if(dateTimeService == null) { dateTimeService = (DateTimeService) KraServiceLocator.getService(DateTimeService.class); } return dateTimeService; } protected SequenceAccessorService getSequenceAccessorService() { if(sequenceAccessorService == null) { sequenceAccessorService = (SequenceAccessorService) KraServiceLocator.getService(SequenceAccessorService.class); } return sequenceAccessorService; } public Long getNotifyIrbSubmissionId() { return notifyIrbSubmissionId; } public void setNotifyIrbSubmissionId(Long notifyIrbSubmissionId) { this.notifyIrbSubmissionId = notifyIrbSubmissionId; } public boolean isLookupPendingProtocol() { return lookupPendingProtocol; } public void setLookupPendingProtocol(boolean lookupPendingProtocol) { this.lookupPendingProtocol = lookupPendingProtocol; } public boolean isLookupPendingPIActionProtocol() { return lookupPendingPIActionProtocol; } public void setLookupPendingPIActionProtocol(boolean lookupPendingPIActionProtocol) { this.lookupPendingPIActionProtocol = lookupPendingPIActionProtocol; } public boolean isLookupActionAmendRenewProtocol() { return lookupActionAmendRenewProtocol; } public void setLookupActionAmendRenewProtocol(boolean lookupActionAmendRenewProtocol) { this.lookupActionAmendRenewProtocol = lookupActionAmendRenewProtocol; } public boolean isLookupActionNotifyIRBProtocol() { return lookupActionNotifyIRBProtocol; } public void setLookupActionNotifyIRBProtocol(boolean lookupActionNotifyIRBProtocol) { this.lookupActionNotifyIRBProtocol = lookupActionNotifyIRBProtocol; } public boolean isLookupActionRequestProtocol() { return lookupActionRequestProtocol; } public void setLookupActionRequestProtocol(boolean lookupActionRequestProtocol) { this.lookupActionRequestProtocol = lookupActionRequestProtocol; } public boolean isLookupProtocolPersonId() { return lookupProtocolPersonId; } public void setLookupProtocolPersonId(boolean lookupProtocolPersonId) { this.lookupProtocolPersonId = lookupProtocolPersonId; } /** * * This method is to check if the actiontypecode is a followup action. * @param actionTypeCode * @return */ public boolean isFollowupAction(String actionTypeCode) { return (getLastProtocolAction() == null || StringUtils.isBlank(getLastProtocolAction().getFollowupActionCode())) ? false : actionTypeCode.equals(getLastProtocolAction().getFollowupActionCode()); } public boolean isMergeAmendment() { return mergeAmendment; } public void setMergeAmendment(boolean mergeAmendment) { this.mergeAmendment = mergeAmendment; } public ProtocolAttachmentFilter getProtocolAttachmentFilter() { return protocolAttachmentFilter; } public void setProtocolAttachmentFilter(ProtocolAttachmentFilter protocolAttachmentFilter) { this.protocolAttachmentFilter = protocolAttachmentFilter; } /** * * This method returns a list of attachments which respect the sort filter * @return a filtered list of protocol attachments */ public List<ProtocolAttachmentProtocol> getFilteredAttachmentProtocols() { List<ProtocolAttachmentProtocol> filteredAttachments = new ArrayList<ProtocolAttachmentProtocol>(); ProtocolAttachmentFilter attachmentFilter = getProtocolAttachmentFilter(); if (attachmentFilter != null && StringUtils.isNotBlank(attachmentFilter.getFilterBy())) { for (ProtocolAttachmentProtocol attachment1 : getAttachmentProtocols()) { if ((attachment1.getTypeCode()).equals(attachmentFilter.getFilterBy())) { filteredAttachments.add(attachment1); } } } else { filteredAttachments = getAttachmentProtocols(); } if (attachmentFilter != null && StringUtils.isNotBlank(attachmentFilter.getSortBy())) { Collections.sort(filteredAttachments, attachmentFilter.getProtocolAttachmentComparator()); } return filteredAttachments; } public void initializeProtocolAttachmentFilter() { protocolAttachmentFilter = new ProtocolAttachmentFilter(); //Lets see if there is a default set for the attachment sort try { String defaultSortBy = getParameterService().getParameterValueAsString(ProtocolDocument.class, Constants.PARAMETER_PROTOCOL_ATTACHMENT_DEFAULT_SORT); if (StringUtils.isNotBlank(defaultSortBy)) { protocolAttachmentFilter.setSortBy(defaultSortBy); } } catch (Exception e) { //No default found, do nothing. } } public ParameterService getParameterService() { return (ParameterService)KraServiceLocator.getService(ParameterService.class); } public void cleanupSpecialReviews(Protocol srcProtocol) { List<ProtocolSpecialReview> srcSpecialReviews = srcProtocol.getSpecialReviews(); List<ProtocolSpecialReview> dstSpecialReviews = getSpecialReviews(); for (int i=0; i < srcSpecialReviews.size(); i++) { ProtocolSpecialReview srcSpecialReview = srcSpecialReviews.get(i); ProtocolSpecialReview dstSpecialReview = dstSpecialReviews.get(i); // copy exemption codes, since they are transient and ignored by deepCopy() if (srcSpecialReview.getExemptionTypeCodes() != null) { List<String> exemptionCodeCopy = new ArrayList<String>(); for (String s: srcSpecialReview.getExemptionTypeCodes()) { exemptionCodeCopy.add(new String(s)); } dstSpecialReview.setExemptionTypeCodes(exemptionCodeCopy); } // force new table entry dstSpecialReview.resetPersistenceState(); } } /** * This method encapsulates the logic to decide if a committee member appears in the list of protocol personnel. * It will first try to match by personIds and if personIds are not available then it will try matching by rolodexIds. * @param member * @return */ public boolean isMemberInProtocolPersonnel(CommitteeMembership member) { boolean retValue = false; for(ProtocolPerson protocolPerson: this.protocolPersons) { if( StringUtils.isNotBlank(member.getPersonId()) && StringUtils.isNotBlank(protocolPerson.getPersonId()) ) { if(member.getPersonId().equals(protocolPerson.getPersonId())){ retValue = true; break; } } else if( StringUtils.isBlank(member.getPersonId()) && StringUtils.isBlank(protocolPerson.getPersonId()) ) { // in this case check rolodex id if( (null != member.getRolodexId()) && (null != protocolPerson.getRolodexId()) ) { if(member.getRolodexId().equals(protocolPerson.getRolodexId())) { retValue = true; break; } } } } return retValue; } /** * This method will filter out this protocol's personnel from the given list of committee memberships * @param members * @return the filtered list of members */ public List<CommitteeMembership> filterOutProtocolPersonnel(List<CommitteeMembership> members) { List<CommitteeMembership> filteredMemebers = new ArrayList<CommitteeMembership>(); for (CommitteeMembership member : members) { if(!isMemberInProtocolPersonnel(member)) { filteredMemebers.add(member); } } return filteredMemebers; } /** * * This method is to return the first submission date as application date. see kccoi-36 comment * @return */ public Date getApplicationDate() { if (CollectionUtils.isNotEmpty(this.protocolSubmissions)) { return this.protocolSubmissions.get(0).getSubmissionDate(); } else { return null; } } @Override public String getProjectName() { // TODO Auto-generated method stub return getTitle(); } @Override public String getProjectId() { // TODO Auto-generated method stub return getProtocolNumber(); } // This is for viewhistory/corespondence to search prev submission public List<ProtocolAction> getSortedActions() { if (sortedActions == null) { sortedActions = new ArrayList<ProtocolAction>(); for (ProtocolAction action : getProtocolActions()) { sortedActions.add((ProtocolAction) ObjectUtils.deepCopy(action)); } Collections.sort(sortedActions, new Comparator<ProtocolAction>() { public int compare(ProtocolAction action1, ProtocolAction action2) { return action1.getActionId().compareTo(action2.getActionId()); } }); } return sortedActions; } public KrmsRulesContext getKrmsRulesContext() { return (KrmsRulesContext) getProtocolDocument(); } }
src/main/java/org/kuali/kra/irb/Protocol.java
/* * Copyright 2005-2010 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kra.irb; import java.io.Serializable; import java.sql.Date; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.kuali.kra.SequenceOwner; import org.kuali.kra.UnitAclLoadable; import org.kuali.kra.bo.AttachmentFile; import org.kuali.kra.bo.CustomAttributeDocument; import org.kuali.kra.bo.KraPersistableBusinessObjectBase; import org.kuali.kra.coi.Disclosurable; import org.kuali.kra.committee.bo.Committee; import org.kuali.kra.committee.bo.CommitteeMembership; import org.kuali.kra.common.committee.bo.CommitteeMembershipType; import org.kuali.kra.committee.bo.CommitteeSchedule; import org.kuali.kra.common.permissions.Permissionable; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.infrastructure.KraServiceLocator; import org.kuali.kra.infrastructure.RoleConstants; import org.kuali.kra.irb.actions.ProtocolAction; import org.kuali.kra.irb.actions.ProtocolStatus; import org.kuali.kra.irb.actions.amendrenew.ProtocolAmendRenewModule; import org.kuali.kra.irb.actions.amendrenew.ProtocolAmendRenewal; import org.kuali.kra.irb.actions.amendrenew.ProtocolModule; import org.kuali.kra.irb.actions.risklevel.ProtocolRiskLevel; import org.kuali.kra.irb.actions.submit.ProtocolReviewType; import org.kuali.kra.irb.actions.submit.ProtocolSubmission; import org.kuali.kra.irb.actions.submit.ProtocolSubmissionQualifierType; import org.kuali.kra.irb.actions.submit.ProtocolSubmissionStatus; import org.kuali.kra.irb.actions.submit.ProtocolSubmissionType; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentBase; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentFilter; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentPersonnel; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentProtocol; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentService; import org.kuali.kra.irb.noteattachment.ProtocolAttachmentStatus; import org.kuali.kra.irb.noteattachment.ProtocolNotepad; import org.kuali.kra.irb.onlinereview.ProtocolOnlineReview; import org.kuali.kra.irb.personnel.ProtocolPerson; import org.kuali.kra.irb.personnel.ProtocolPersonnelService; import org.kuali.kra.irb.personnel.ProtocolUnit; import org.kuali.kra.irb.protocol.ProtocolType; import org.kuali.kra.irb.protocol.funding.ProtocolFundingSource; import org.kuali.kra.irb.protocol.location.ProtocolLocation; import org.kuali.kra.irb.protocol.location.ProtocolLocationService; import org.kuali.kra.irb.protocol.participant.ProtocolParticipant; import org.kuali.kra.irb.protocol.reference.ProtocolReference; import org.kuali.kra.irb.protocol.research.ProtocolResearchArea; import org.kuali.kra.irb.questionnaire.ProtocolModuleQuestionnaireBean; import org.kuali.kra.irb.specialreview.ProtocolSpecialReview; import org.kuali.kra.irb.specialreview.ProtocolSpecialReviewExemption; import org.kuali.kra.irb.summary.AdditionalInfoSummary; import org.kuali.kra.irb.summary.AttachmentSummary; import org.kuali.kra.irb.summary.FundingSourceSummary; import org.kuali.kra.irb.summary.OrganizationSummary; import org.kuali.kra.irb.summary.ParticipantSummary; import org.kuali.kra.irb.summary.PersonnelSummary; import org.kuali.kra.irb.summary.ProtocolSummary; import org.kuali.kra.irb.summary.ResearchAreaSummary; import org.kuali.kra.irb.summary.SpecialReviewSummary; import org.kuali.kra.krms.KcKrmsContextBo; import org.kuali.kra.krms.KrmsRulesContext; import org.kuali.kra.meeting.CommitteeScheduleAttendance; import org.kuali.kra.questionnaire.answer.Answer; import org.kuali.kra.questionnaire.answer.AnswerHeader; import org.kuali.kra.questionnaire.answer.ModuleQuestionnaireBean; import org.kuali.kra.questionnaire.answer.QuestionnaireAnswerService; import org.kuali.rice.core.api.datetime.DateTimeService; import org.kuali.rice.coreservice.framework.parameter.ParameterService; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.service.SequenceAccessorService; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.ObjectUtils; /** * * This class is Protocol Business Object. */ public class Protocol extends KraPersistableBusinessObjectBase implements SequenceOwner<Protocol>, Permissionable, UnitAclLoadable, Disclosurable, KcKrmsContextBo { private static final long serialVersionUID = 4396393806439396971L; private static final CharSequence AMENDMENT_LETTER = "A"; private static final CharSequence RENEWAL_LETTER = "R"; private static final String DEFAULT_PROTOCOL_TYPE_CODE = "1"; private static final String NEXT_ACTION_ID_KEY = "actionId"; // TODO *********code has been moved to base class, should ultimately be removed********** private Long protocolId; private String protocolNumber; // TODO **********************end************************ private Integer sequenceNumber; // TODO *********code has been moved to base class, should ultimately be removed********** private boolean active = true; private String protocolTypeCode; private String protocolStatusCode; private String title; private String description; private Date initialSubmissionDate; private Date approvalDate; private Date expirationDate; private Date lastApprovalDate; private String fdaApplicationNumber; private String referenceNumber1; private String referenceNumber2; private String specialReviewIndicator = "Y"; // TODO **********************end************************ private String vulnerableSubjectIndicator; // TODO *********code has been moved to base class, should ultimately be removed********** private String keyStudyPersonIndicator; private String fundingSourceIndicator; private String correspondentIndicator; private String referenceIndicator; // TODO **********************end************************ private String relatedProjectsIndicator; private ProtocolDocument protocolDocument; private ProtocolStatus protocolStatus; private ProtocolType protocolType; private List<ProtocolRiskLevel> protocolRiskLevels; private List<ProtocolParticipant> protocolParticipants; private List<ProtocolResearchArea> protocolResearchAreas; private List<ProtocolReference> protocolReferences; private List<ProtocolLocation> protocolLocations; //Is transient, used for lookup select option in UI by KNS private String newDescription; private boolean nonEmployeeFlag; private List<ProtocolFundingSource> protocolFundingSources; // TODO *********code has been moved to base class, should ultimately be removed********** private String leadUnitNumber; // TODO **********************end************************ private String principalInvestigatorId; // lookup field private String keyPerson; private String investigator; private String fundingSource; private String performingOrganizationId; private String researchAreaCode; // TODO *********code has been moved to base class, should ultimately be removed********** private String leadUnitName; private List<ProtocolPerson> protocolPersons; // TODO **********************end************************ private List<ProtocolSpecialReview> specialReviews; //these are the m:m attachment protocols that that a protocol has private List<ProtocolAttachmentProtocol> attachmentProtocols; private List<ProtocolNotepad> notepads; private List<ProtocolAction> protocolActions; private List<ProtocolSubmission> protocolSubmissions; private ProtocolSubmission protocolSubmission; private transient List<ProtocolAction> sortedActions; /* * There should only be zero or one entry in the protocolAmendRenewals * list. It is because of OJB that a list is used instead of a single item. */ private List<ProtocolAmendRenewal> protocolAmendRenewals; private transient boolean correctionMode = false; private transient DateTimeService dateTimeService; private transient SequenceAccessorService sequenceAccessorService; //Used to filter protocol attachments private transient ProtocolAttachmentFilter protocolAttachmentFilter; // passed in req param submissionid. used to check if irb ack is needed // this link is from protocosubmission or notify irb message private transient Long notifyIrbSubmissionId; // transient for protocol header combined label private transient String initiatorLastUpdated; private transient String protocolSubmissionStatus; // Custom Protocol lookup fields private transient boolean lookupPendingProtocol; private transient boolean lookupPendingPIActionProtocol; private transient boolean lookupActionAmendRenewProtocol; private transient boolean lookupActionNotifyIRBProtocol; private transient boolean lookupActionRequestProtocol; private transient boolean lookupProtocolPersonId; private transient boolean mergeAmendment; public String getInitiatorLastUpdated() { return initiatorLastUpdated; } public String getProtocolSubmissionStatus() { return protocolSubmissionStatus; } /** * * Constructs an Protocol BO. */ public Protocol() { super(); sequenceNumber = new Integer(0); //billable = false; protocolRiskLevels = new ArrayList<ProtocolRiskLevel>(); protocolParticipants = new ArrayList<ProtocolParticipant>(); protocolResearchAreas = new ArrayList<ProtocolResearchArea>(); protocolReferences = new ArrayList<ProtocolReference>(); newDescription = getDefaultNewDescription(); protocolStatus = new ProtocolStatus(); protocolStatusCode = protocolStatus.getProtocolStatusCode(); protocolLocations = new ArrayList<ProtocolLocation>(); protocolPersons = new ArrayList<ProtocolPerson>(); // set the default protocol type protocolTypeCode = DEFAULT_PROTOCOL_TYPE_CODE; // initializeProtocolLocation(); protocolFundingSources = new ArrayList<ProtocolFundingSource>(); specialReviews = new ArrayList<ProtocolSpecialReview>(); setProtocolActions(new ArrayList<ProtocolAction>()); setProtocolSubmissions(new ArrayList<ProtocolSubmission>()); protocolAmendRenewals = new ArrayList<ProtocolAmendRenewal>(); // set statuscode default setProtocolStatusCode(Constants.DEFAULT_PROTOCOL_STATUS_CODE); this.refreshReferenceObject(Constants.PROPERTY_PROTOCOL_STATUS); initializeProtocolAttachmentFilter(); // TODO : not sure why this method is here. It looks like a temp method. commented out to see if it is ok. // I had to remove the comment in front of the following statement. // By adding the comment, a null pointer exception occurs when navigating to the Protocol Actions tab. //populateTempViewDate(); } // TODO *********code has been moved to base class, should ultimately be removed********** public Long getProtocolId() { return protocolId; } public void setProtocolId(Long protocolId) { this.protocolId = protocolId; } public String getProtocolNumber() { return protocolNumber; } public void setProtocolNumber(String protocolNumber) { this.protocolNumber = protocolNumber; } public Integer getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(Integer sequenceNumber) { this.sequenceNumber = sequenceNumber; } public void setActive(boolean active) { this.active = active; } public boolean isActive() { return active; } public String getProtocolTypeCode() { return protocolTypeCode; } public void setProtocolTypeCode(String protocolTypeCode) { this.protocolTypeCode = protocolTypeCode; } public String getProtocolStatusCode() { return protocolStatusCode; } public void setProtocolStatusCode(String protocolStatusCode) { this.protocolStatusCode = protocolStatusCode; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } // TODO **********************end************************ /** * Gets the submission date. If the submission date is the last * submission for the protocol. If the protocol has not been submitted, * null is returned. * @return the submission date or null if not yet submitted */ public Date getSubmissionDate() { // TODO : the last one in the list may not be the last one submitted // getProtocolSubmission will get the last one. SO, this method may not needed. // Also, this method only referenced in test once. Date submissionDate = null; if (protocolSubmissions.size() > 0) { // ProtocolSubmission submission = protocolSubmissions.get(protocolSubmissions.size() - 1); // submissionDate = submission.getSubmissionDate(); submissionDate = getProtocolSubmission().getSubmissionDate(); } return submissionDate; } // TODO *********code has been moved to base class, should ultimately be removed********** public Date getInitialSubmissionDate() { return initialSubmissionDate; } public void setInitialSubmissionDate(Date initialSubmissionDate) { this.initialSubmissionDate = initialSubmissionDate; } public Date getApprovalDate() { return approvalDate; } public void setApprovalDate(Date approvalDate) { this.approvalDate = approvalDate; } public Date getExpirationDate() { return expirationDate; } public void setExpirationDate(Date expirationDate) { this.expirationDate = expirationDate; } public Date getLastApprovalDate() { return lastApprovalDate; } public void setLastApprovalDate(Date lastApprovalDate) { this.lastApprovalDate = lastApprovalDate; } public String getFdaApplicationNumber() { return fdaApplicationNumber; } public void setFdaApplicationNumber(String fdaApplicationNumber) { this.fdaApplicationNumber = fdaApplicationNumber; } public String getReferenceNumber1() { return referenceNumber1; } public void setReferenceNumber1(String referenceNumber1) { this.referenceNumber1 = referenceNumber1; } public String getReferenceNumber2() { return referenceNumber2; } public void setReferenceNumber2(String referenceNumber2) { this.referenceNumber2 = referenceNumber2; } public String getSpecialReviewIndicator() { return specialReviewIndicator; } public void setSpecialReviewIndicator(String specialReviewIndicator) { this.specialReviewIndicator = specialReviewIndicator; } // TODO **********************end************************ public String getVulnerableSubjectIndicator() { return vulnerableSubjectIndicator; } public void setVulnerableSubjectIndicator(String vulnerableSubjectIndicator) { this.vulnerableSubjectIndicator = vulnerableSubjectIndicator; } // TODO *********code has been moved to base class, should ultimately be removed********** public String getKeyStudyPersonIndicator() { return keyStudyPersonIndicator; } public void setKeyStudyPersonIndicator(String keyStudyPersonIndicator) { this.keyStudyPersonIndicator = keyStudyPersonIndicator; } public String getFundingSourceIndicator() { return fundingSourceIndicator; } public void setFundingSourceIndicator(String fundingSourceIndicator) { this.fundingSourceIndicator = fundingSourceIndicator; } public String getCorrespondentIndicator() { return correspondentIndicator; } public void setCorrespondentIndicator(String correspondentIndicator) { this.correspondentIndicator = correspondentIndicator; } public String getReferenceIndicator() { return referenceIndicator; } public void setReferenceIndicator(String referenceIndicator) { this.referenceIndicator = referenceIndicator; } // TODO **********************end************************ public String getRelatedProjectsIndicator() { return relatedProjectsIndicator; } public void setRelatedProjectsIndicator(String relatedProjectsIndicator) { this.relatedProjectsIndicator = relatedProjectsIndicator; } /** * Collects and returns all online reviews for all submissions for this protocol. * @return all online reviews for this protocol */ public List<ProtocolOnlineReview> getProtocolOnlineReviews() { List<ProtocolOnlineReview> reviews = new ArrayList<ProtocolOnlineReview>(); for (ProtocolSubmission submission : getProtocolSubmissions()) { reviews.addAll(submission.getProtocolOnlineReviews()); } return reviews; } public ProtocolStatus getProtocolStatus() { return protocolStatus; } public void setProtocolStatus(ProtocolStatus protocolStatus) { this.protocolStatus = protocolStatus; } public ProtocolType getProtocolType() { return protocolType; } public void setProtocolType(ProtocolType protocolType) { this.protocolType = protocolType; } public List<ProtocolRiskLevel> getProtocolRiskLevels() { return protocolRiskLevels; } public void setProtocolRiskLevels(List<ProtocolRiskLevel> protocolRiskLevels) { this.protocolRiskLevels = protocolRiskLevels; for (ProtocolRiskLevel riskLevel : protocolRiskLevels) { riskLevel.init(this); } } public List<ProtocolParticipant> getProtocolParticipants() { return protocolParticipants; } public void setProtocolParticipants(List<ProtocolParticipant> protocolParticipants) { this.protocolParticipants = protocolParticipants; for (ProtocolParticipant participant : protocolParticipants) { participant.init(this); } } /** * Gets index i from the protocol participant list. * * @param index * @return protocol participant at index i */ public ProtocolParticipant getProtocolParticipant(int index) { return getProtocolParticipants().get(index); } public String getNewDescription() { return newDescription; } public void setNewDescription(String newDescription) { this.newDescription = newDescription; } public String getDefaultNewDescription() { return "(select)"; } public void setProtocolResearchAreas(List<ProtocolResearchArea> protocolResearchAreas) { this.protocolResearchAreas = protocolResearchAreas; for (ProtocolResearchArea researchArea : protocolResearchAreas) { researchArea.init(this); } } public List<ProtocolResearchArea> getProtocolResearchAreas() { return protocolResearchAreas; } public void addProtocolResearchAreas(ProtocolResearchArea protocolResearchArea) { getProtocolResearchAreas().add(protocolResearchArea); } public ProtocolResearchArea getProtocolResearchAreas(int index) { while (getProtocolResearchAreas().size() <= index) { getProtocolResearchAreas().add(new ProtocolResearchArea()); } return getProtocolResearchAreas().get(index); } public void setProtocolReferences(List<ProtocolReference> protocolReferences) { this.protocolReferences = protocolReferences; for (ProtocolReference reference : protocolReferences) { reference.init(this); } } public List<ProtocolReference> getProtocolReferences() { return protocolReferences; } public ProtocolDocument getProtocolDocument() { return protocolDocument; } public void setProtocolDocument(ProtocolDocument protocolDocument) { this.protocolDocument = protocolDocument; } public void setProtocolLocations(List<ProtocolLocation> protocolLocations) { this.protocolLocations = protocolLocations; for (ProtocolLocation location : protocolLocations) { location.init(this); } } public List<ProtocolLocation> getProtocolLocations() { return protocolLocations; } @SuppressWarnings("unchecked") @Override public List buildListOfDeletionAwareLists() { List managedLists = super.buildListOfDeletionAwareLists(); managedLists.add(this.protocolResearchAreas); managedLists.add(this.protocolReferences); managedLists.add(getProtocolFundingSources()); managedLists.add(getProtocolLocations()); managedLists.add(getProtocolRiskLevels()); managedLists.add(getProtocolParticipants()); managedLists.add(getProtocolAttachmentPersonnel()); managedLists.add(getProtocolUnits()); managedLists.add(getAttachmentProtocols()); managedLists.add(getProtocolPersons()); managedLists.add(getProtocolActions()); managedLists.add(getProtocolSubmissions()); if (getProtocolAmendRenewal() != null) { managedLists.add(getProtocolAmendRenewal().getModules()); } else { // needed to ensure that the OjbCollectionHelper receives constant list size. managedLists.add(new ArrayList<ProtocolAmendRenewModule>()); } managedLists.add(getProtocolAmendRenewals()); List<ProtocolSpecialReviewExemption> specialReviewExemptions = new ArrayList<ProtocolSpecialReviewExemption>(); for (ProtocolSpecialReview specialReview : getSpecialReviews()) { specialReviewExemptions.addAll(specialReview.getSpecialReviewExemptions()); } managedLists.add(specialReviewExemptions); managedLists.add(getSpecialReviews()); managedLists.add(getNotepads()); return managedLists; } /** * This method is to return all attachments for each person. * Purpose of this method is to use the list in buildListOfDeletionAwareLists. * Looks like OJB is not searching beyond the first level. It doesn't delete * from collection under ProtocolPerson. * @return List<ProtocolAttachmentPersonnel> */ private List<ProtocolAttachmentPersonnel> getProtocolAttachmentPersonnel() { List<ProtocolAttachmentPersonnel> protocolAttachmentPersonnel = new ArrayList<ProtocolAttachmentPersonnel>(); for (ProtocolPerson protocolPerson : getProtocolPersons()) { protocolAttachmentPersonnel.addAll(protocolPerson.getAttachmentPersonnels()); } return protocolAttachmentPersonnel; } /** * This method is to return all protocol units for each person. * Purpose of this method is to use the list in buildListOfDeletionAwareLists. * Looks like OJB is not searching beyond the first level. It doesn't delete * from collection under ProtocolPerson. * @return List<ProtocolUnit> */ private List<ProtocolUnit> getProtocolUnits() { List<ProtocolUnit> protocolUnits = new ArrayList<ProtocolUnit>(); for (ProtocolPerson protocolPerson : getProtocolPersons()) { protocolUnits.addAll(protocolPerson.getProtocolUnits()); } return protocolUnits; } /** * This method is to find Principal Investigator from ProtocolPerson list * @return ProtocolPerson */ public ProtocolPerson getPrincipalInvestigator() { return getProtocolPersonnelService().getPrincipalInvestigator(getProtocolPersons()); } public String getPrincipalInvestigatorName() { ProtocolPerson pi = getPrincipalInvestigator(); return pi != null ? pi.getFullName() : null; } public ProtocolUnit getLeadUnit() { ProtocolUnit leadUnit = null; if (getPrincipalInvestigator() != null) { for ( ProtocolUnit unit : getPrincipalInvestigator().getProtocolUnits() ) { if (unit.getLeadUnitFlag()) { leadUnit = unit; } } } return leadUnit; } public String getLeadUnitNumber() { if (StringUtils.isBlank(leadUnitNumber)) { if (getLeadUnit() != null) { setLeadUnitNumber(getLeadUnit().getUnitNumber()); } } return leadUnitNumber; } // TODO *********code has been moved to base class, should ultimately be removed********** public void setLeadUnitNumber(String leadUnitNumber) { this.leadUnitNumber = leadUnitNumber; } public String getPrincipalInvestigatorId() { if (StringUtils.isBlank(principalInvestigatorId)) { if (getPrincipalInvestigator() != null) { ProtocolPerson principalInvestigator = getPrincipalInvestigator(); if (StringUtils.isNotBlank(principalInvestigator.getPersonId())) { setPrincipalInvestigatorId(principalInvestigator.getPersonId()); } else { //ProtocolUnit leadUnit = new ProtocolUnit(); //leadUnit.setUnitNumber(leadUnitNumber); //leadUnit.setPersonId(getPrincipalInvestigator().getPersonId()); //leadUnit.setLeadUnitFlag(true); // TODO : rice upgrade temp fix //leadUnit.setProtocolNumber("0"); //leadUnit.setSequenceNumber(0); //getPrincipalInvestigator().getProtocolUnits().add(leadUnit); if (principalInvestigator.getRolodexId() != null) { setPrincipalInvestigatorId(principalInvestigator.getRolodexId().toString()); } } } } return principalInvestigatorId; } public void setPrincipalInvestigatorId(String principalInvestigatorId) { this.principalInvestigatorId = principalInvestigatorId; } // TODO **********************end************************ public boolean isNonEmployeeFlag() { return this.nonEmployeeFlag; } public void setNonEmployeeFlag(boolean nonEmployeeFlag) { this.nonEmployeeFlag = nonEmployeeFlag; } /** * This method is to get protocol location service * @return ProtocolLocationService */ protected ProtocolLocationService getProtocolLocationService() { ProtocolLocationService protocolLocationService = (ProtocolLocationService)KraServiceLocator.getService("protocolLocationService"); return protocolLocationService; } /* * Initialize protocol location. * Add default organization. */ private void initializeProtocolLocation() { getProtocolLocationService().addDefaultProtocolLocation(this); } // TODO *********code has been moved to base class, should ultimately be removed********** public List<ProtocolPerson> getProtocolPersons() { return protocolPersons; } public void setProtocolPersons(List<ProtocolPerson> protocolPersons) { this.protocolPersons = protocolPersons; for (ProtocolPerson person : protocolPersons) { person.init(this); } } // TODO **********************end************************ /** * Gets index i from the protocol person list. * * @param index * @return protocol person at index i */ public ProtocolPerson getProtocolPerson(int index) { return getProtocolPersons().get(index); } // TODO This method has been moved to base class as a protected hook method, and so should be replaced by the hook implementation /** * This method is to get protocol personnel service * @return protocolPersonnelService */ private ProtocolPersonnelService getProtocolPersonnelService() { ProtocolPersonnelService protocolPersonnelService = (ProtocolPersonnelService)KraServiceLocator.getService("protocolPersonnelService"); return protocolPersonnelService; } public List<ProtocolFundingSource> getProtocolFundingSources() { return protocolFundingSources; } public void setProtocolFundingSources(List<ProtocolFundingSource> protocolFundingSources) { this.protocolFundingSources = protocolFundingSources; for (ProtocolFundingSource fundingSource : protocolFundingSources) { fundingSource.init(this); } } public String getResearchAreaCode() { return researchAreaCode; } public void setResearchAreaCode(String researchAreaCode) { this.researchAreaCode = researchAreaCode; } public String getFundingSource() { return fundingSource; } public void setFundingSource(String fundingSource) { this.fundingSource = fundingSource; } public String getPerformingOrganizationId() { return performingOrganizationId; } public void setPerformingOrganizationId(String performingOrganizationId) { this.performingOrganizationId = performingOrganizationId; } // TODO *********code has been moved to base class, should ultimately be removed********** public String getLeadUnitName() { if (StringUtils.isBlank(leadUnitName)) { if (getLeadUnit() != null) { setLeadUnitName(getLeadUnit().getUnitName()); } } return leadUnitName; } public void setLeadUnitName(String leadUnitName) { this.leadUnitName = leadUnitName; } // TODO **********************end************************ public void setSpecialReviews(List<ProtocolSpecialReview> specialReviews) { this.specialReviews = specialReviews; } /** * @see org.kuali.kra.document.SpecialReviewHandler#addSpecialReview(org.kuali.kra.bo.AbstractSpecialReview) */ public void addSpecialReview(ProtocolSpecialReview specialReview) { specialReview.setSequenceOwner(this); getSpecialReviews().add(specialReview); } /** * @see org.kuali.kra.document.SpecialReviewHandler#getSpecialReview(int) */ public ProtocolSpecialReview getSpecialReview(int index) { return getSpecialReviews().get(index); } /** * @see org.kuali.kra.document.SpecialReviewHandler#getSpecialReviews() */ public List<ProtocolSpecialReview> getSpecialReviews() { return specialReviews; } /** * Gets the attachment protocols. Cannot return {@code null}. * @return the attachment protocols */ public List<ProtocolAttachmentProtocol> getAttachmentProtocols() { if (this.attachmentProtocols == null) { this.attachmentProtocols = new ArrayList<ProtocolAttachmentProtocol>(); } return this.attachmentProtocols; } /** * Gets an attachment protocol. * @param index the index * @return an attachment protocol */ public ProtocolAttachmentProtocol getAttachmentProtocol(int index) { return this.attachmentProtocols.get(index); } /** * Gets the notepads. Cannot return {@code null}. * @return the notepads */ public List<ProtocolNotepad> getNotepads() { if (this.notepads == null) { this.notepads = new ArrayList<ProtocolNotepad>(); } Collections.sort(notepads, Collections.reverseOrder()); return this.notepads; } /** * Gets an attachment protocol. * @param index the index * @return an attachment protocol */ public ProtocolNotepad getNotepad(int index) { return this.notepads.get(index); } /** * adds an attachment protocol. * @param attachmentProtocol the attachment protocol * @throws IllegalArgumentException if attachmentProtocol is null */ private void addAttachmentProtocol(ProtocolAttachmentProtocol attachmentProtocol) { ProtocolAttachmentBase.addAttachmentToCollection(attachmentProtocol, this.getAttachmentProtocols()); } /** * removes an attachment protocol. * @param attachmentProtocol the attachment protocol * @throws IllegalArgumentException if attachmentProtocol is null */ private void removeAttachmentProtocol(ProtocolAttachmentProtocol attachmentProtocol) { ProtocolAttachmentBase.removeAttachmentFromCollection(attachmentProtocol, this.getAttachmentProtocols()); } /** * @deprecated * Gets the attachment personnels. Cannot return {@code null}. * @return the attachment personnels */ @Deprecated public List<ProtocolAttachmentPersonnel> getAttachmentPersonnels() { return getProtocolAttachmentPersonnel(); } private void updateUserFields(KraPersistableBusinessObjectBase bo) { bo.setUpdateUser(GlobalVariables.getUserSession().getPrincipalName()); bo.setUpdateTimestamp(getDateTimeService().getCurrentTimestamp()); } /** * Adds a attachment to a Protocol where the type of attachment is used to determine * where to add the attachment. * @param attachment the attachment * @throws IllegalArgumentException if attachment is null or if an unsupported attachment is found */ public <T extends ProtocolAttachmentBase> void addAttachmentsByType(T attachment) { if (attachment == null) { throw new IllegalArgumentException("the attachment is null"); } updateUserFields(attachment); attachment.setProtocolId(getProtocolId()); if (attachment instanceof ProtocolAttachmentProtocol) { this.addAttachmentProtocol((ProtocolAttachmentProtocol) attachment); } else { throw new IllegalArgumentException("unsupported type: " + attachment.getClass().getName()); } } /** * removes an attachment to a Protocol where the type of attachment is used to determine * where to add the attachment. * @param attachment the attachment * @throws IllegalArgumentException if attachment is null or if an unsupported attachment is found */ public <T extends ProtocolAttachmentBase> void removeAttachmentsByType(T attachment) { if (attachment == null) { throw new IllegalArgumentException("the attachment is null"); } if (attachment instanceof ProtocolAttachmentProtocol) { this.removeAttachmentProtocol((ProtocolAttachmentProtocol) attachment); } else { throw new IllegalArgumentException("unsupported type: " + attachment.getClass().getName()); } } public String getKeyPerson() { return keyPerson; } public void setKeyPerson(String keyPerson) { this.keyPerson = keyPerson; } public String getInvestigator() { if (StringUtils.isBlank(principalInvestigatorId)) { if (getPrincipalInvestigator() != null) { investigator = getPrincipalInvestigator().getPersonName(); } } return investigator; } public void setInvestigator(String investigator) { this.investigator = investigator; } /* TODO : why this temp method is in Protocol method */ private void populateTempViewDate() { this.protocolSubmission = new ProtocolSubmission(); Committee committee = new Committee(); committee.setId(1L); committee.setCommitteeId("Comm-1"); committee.setCommitteeName("Test By Kiltesh"); this.protocolSubmission.setCommittee(committee); this.protocolSubmission.setSubmissionNumber(1); this.protocolSubmission.setSubmissionDate(new Date(System.currentTimeMillis())); this.protocolSubmission.setSubmissionStatusCode("100"); ProtocolSubmissionType submissionType = new ProtocolSubmissionType(); submissionType.setDescription("Initial Protocol Application for Approval "); this.protocolSubmission.setProtocolSubmissionType(submissionType); ProtocolReviewType review = new ProtocolReviewType(); review.setDescription("Full"); this.protocolSubmission.setProtocolReviewType(review); ProtocolSubmissionQualifierType qual = new ProtocolSubmissionQualifierType(); qual.setDescription("Lorem Ipsum Dolor "); this.protocolSubmission.setProtocolSubmissionQualifierType(qual); ProtocolSubmissionStatus substatus = new ProtocolSubmissionStatus(); substatus.setDescription("Approved"); this.protocolSubmission.setSubmissionStatus(substatus); CommitteeMembershipType committeeMembershipType1 = new CommitteeMembershipType(); committeeMembershipType1.setDescription("Primary"); CommitteeMembershipType committeeMembershipType2 = new CommitteeMembershipType(); committeeMembershipType2.setDescription("Secondary"); CommitteeMembership committeeMembership1 = new CommitteeMembership(); committeeMembership1.setPersonName("Bryan Hutchinson"); committeeMembership1.setMembershipType(committeeMembershipType1); CommitteeMembership committeeMembership2 = new CommitteeMembership(); committeeMembership2.setPersonName("Kiltesh Patel"); committeeMembership2.setMembershipType(committeeMembershipType2); List<CommitteeMembership> list = new ArrayList<CommitteeMembership>(); list.add(committeeMembership1); list.add(committeeMembership2); committee.setCommitteeMemberships(list); this.protocolSubmission.setYesVoteCount(2); this.protocolSubmission.setNoVoteCount(3); this.protocolSubmission.setAbstainerCount(1); this.protocolSubmission.setVotingComments("Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Suspendisse purus. Nullam et justo. In volutpat odio sit amet pede. Pellentesque ipsum dui, convallis in, mollis a, lacinia vel, diam. " + "Phasellus molestie neque at sapien condimentum massa nunc" + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Suspendisse purus. Nullam et justo. In volutpat odio sit amet pede. Pellentesque ipsum dui, convallis in, mollis a, lacinia vel, diam. " + "Phasellus molestie neque at sapien condimentum massa nunc"); CommitteeSchedule committeeSchedule= new CommitteeSchedule(); CommitteeScheduleAttendance committeeScheduleAttendance = new CommitteeScheduleAttendance(); List<CommitteeScheduleAttendance> cslist = new ArrayList<CommitteeScheduleAttendance>(); cslist.add(committeeScheduleAttendance); committeeSchedule.setCommitteeScheduleAttendances(cslist); this.protocolSubmission.setCommitteeSchedule(committeeSchedule); } public ProtocolSubmission getProtocolSubmission() { // TODO : this is a fix to remove 'populateTempViewDate' // if (protocolSubmission == null) { if (!protocolSubmissions.isEmpty()) { // sorted by ojb if (protocolSubmission == null || protocolSubmission.getSubmissionNumber() == null || protocolSubmissions.get(protocolSubmissions.size() - 1).getSubmissionNumber() > protocolSubmission .getSubmissionNumber()) { protocolSubmission = protocolSubmissions.get(protocolSubmissions.size() - 1); } // for (ProtocolSubmission submission : protocolSubmissions) { // if (protocolSubmission == null || protocolSubmission.getSubmissionNumber() == null // || submission.getSubmissionNumber() > protocolSubmission.getSubmissionNumber()) { // protocolSubmission = submission; // } // } } else { protocolSubmission = new ProtocolSubmission(); // TODO : the update protocol rule may not like null protocolSubmission.setProtocolSubmissionType(new ProtocolSubmissionType()); protocolSubmission.setSubmissionStatus(new ProtocolSubmissionStatus()); } // } refreshReferenceObject(protocolSubmission); return protocolSubmission; } private void refreshReferenceObject(ProtocolSubmission submission) { // if submission just added, then these probably are empty if (StringUtils.isNotBlank(submission.getProtocolReviewTypeCode()) && submission.getProtocolReviewType() == null) { submission.refreshReferenceObject("protocolReviewType"); } if (StringUtils.isNotBlank(submission.getSubmissionStatusCode()) && submission.getSubmissionStatus() == null) { submission.refreshReferenceObject("submissionStatus"); } if (StringUtils.isNotBlank(submission.getSubmissionTypeCode()) && submission.getProtocolSubmissionType() == null) { submission.refreshReferenceObject("protocolSubmissionType"); } if (StringUtils.isNotBlank(submission.getSubmissionTypeQualifierCode()) && submission.getProtocolSubmissionQualifierType() == null) { submission.refreshReferenceObject("protocolSubmissionQualifierType"); } } public void setProtocolSubmission(ProtocolSubmission protocolSubmission) { this.protocolSubmission = protocolSubmission; } public void setProtocolActions(List<ProtocolAction> protocolActions) { this.protocolActions = protocolActions; } public List<ProtocolAction> getProtocolActions() { return protocolActions; } public ProtocolAction getLastProtocolAction() { if (protocolActions.size() == 0) { return null; } Collections.sort(protocolActions, new Comparator<ProtocolAction>() { public int compare(ProtocolAction action1, ProtocolAction action2) { return action2.getActualActionDate().compareTo(action1.getActualActionDate()); } }); return protocolActions.get(0); } public void setProtocolSubmissions(List<ProtocolSubmission> protocolSubmissions) { this.protocolSubmissions = protocolSubmissions; } public List<ProtocolSubmission> getProtocolSubmissions() { return protocolSubmissions; } /** * Get the next value in a sequence. * @param key the unique key of the sequence * @return the next value */ public Integer getNextValue(String key) { return protocolDocument.getDocumentNextValue(key); } public void setAttachmentProtocols(List<ProtocolAttachmentProtocol> attachmentProtocols) { this.attachmentProtocols = attachmentProtocols; for (ProtocolAttachmentProtocol attachment : attachmentProtocols) { attachment.resetPersistenceState(); attachment.setSequenceNumber(0); } } public void setNotepads(List<ProtocolNotepad> notepads) { this.notepads = notepads; } public void setProtocolAmendRenewal(ProtocolAmendRenewal amendRenewal) { protocolAmendRenewals.add(amendRenewal); } public ProtocolAmendRenewal getProtocolAmendRenewal() { if (protocolAmendRenewals.size() == 0) return null; return protocolAmendRenewals.get(0); } public List<ProtocolAmendRenewal> getProtocolAmendRenewals() { return protocolAmendRenewals; } public void setProtocolAmendRenewals(List<ProtocolAmendRenewal> protocolAmendRenewals) { this.protocolAmendRenewals = protocolAmendRenewals; } // TODO *********code has been moved to base class, should ultimately be removed********** /** {@inheritDoc} */ public Integer getOwnerSequenceNumber() { return null; } /** * @see org.kuali.kra.SequenceOwner#getVersionNameField() */ public String getVersionNameField() { return "protocolNumber"; } /** {@inheritDoc} */ public void incrementSequenceNumber() { this.sequenceNumber++; } /** {@inheritDoc} */ public Protocol getSequenceOwner() { return this; } /** {@inheritDoc} */ public void setSequenceOwner(Protocol newOwner) { //no-op } /** {@inheritDoc} */ public void resetPersistenceState() { this.protocolId = null; } // TODO **********************end************************ /** * * This method merges the data of the amended protocol into this protocol. * @param amendment */ public void merge(Protocol amendment) { merge(amendment, true); } public void merge(Protocol amendment, boolean mergeActions) { List<ProtocolAmendRenewModule> modules = amendment.getProtocolAmendRenewal().getModules(); for (ProtocolAmendRenewModule module : modules) { merge(amendment, module.getProtocolModuleTypeCode()); } if (amendment.isRenewalWithoutAmendment() && isRenewalWithNewAttachment(amendment)) { merge(amendment, ProtocolModule.ADD_MODIFY_ATTACHMENTS); } mergeProtocolSubmission(amendment); if (mergeActions) { mergeProtocolAction(amendment); } } private boolean isRenewalWithNewAttachment(Protocol renewal) { boolean hasNewAttachment = false; for (ProtocolAttachmentProtocol attachment : renewal.getAttachmentProtocols()) { if (attachment.isDraft()) { hasNewAttachment = true; break; } } return hasNewAttachment; } /** * * This method merges the data of a specific module of the amended protocol into this protocol. * @param amendment * @param protocolModuleTypeCode */ public void merge(Protocol amendment, String protocolModuleTypeCode) { if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.GENERAL_INFO)) { mergeGeneralInfo(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.AREAS_OF_RESEARCH)) { mergeResearchAreas(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.FUNDING_SOURCE)) { mergeFundingSources(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.PROTOCOL_ORGANIZATIONS)) { mergeOrganizations(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.PROTOCOL_PERSONNEL)) { mergePersonnel(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.ADD_MODIFY_ATTACHMENTS)) { if (amendment.isAmendment() || amendment.isRenewal() || (!amendment.getAttachmentProtocols().isEmpty() && this.getAttachmentProtocols().isEmpty())) { mergeAttachments(amendment); } else { restoreAttachments(this); } } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.PROTOCOL_REFERENCES)) { mergeReferences(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.SPECIAL_REVIEW)) { mergeSpecialReview(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.SUBJECTS)) { mergeSubjects(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.OTHERS)) { mergeOthers(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.PROTOCOL_PERMISSIONS)) { mergeProtocolPermissions(amendment); } else if (StringUtils.equals(protocolModuleTypeCode, ProtocolModule.QUESTIONNAIRE)) { mergeProtocolQuestionnaire(amendment); } } private void mergeProtocolQuestionnaire(Protocol amendment) { // TODO : what if user did not edit questionnaire at all, then questionnaire will be wiped out ? removeOldQuestionnaire(); amendQuestionnaire(amendment); } /* * remove existing questionnaire from current */ private void removeOldQuestionnaire() { List <AnswerHeader> answerHeaders = getAnswerHeaderForProtocol(this); if (!answerHeaders.isEmpty() && answerHeaders.get(0).getAnswerHeaderId() != null){ getBusinessObjectService().delete(answerHeaders); } } /* * add questionnaire answer from amendment to protocol */ private void amendQuestionnaire(Protocol amendment) { List <AnswerHeader> answerHeaders = getAnswerHeaderForProtocol(amendment); if (!answerHeaders.isEmpty()){ for (AnswerHeader answerHeader : answerHeaders) { for (Answer answer : answerHeader.getAnswers()) { answer.setAnswerHeaderIdFk(null); answer.setId(null); } answerHeader.setAnswerHeaderId(null); answerHeader.setModuleItemKey(this.getProtocolNumber()); answerHeader.setModuleSubItemKey(this.getSequenceNumber().toString()); } getBusinessObjectService().save(answerHeaders); } } /* * get submit for review questionnaire answerheaders */ private List <AnswerHeader> getAnswerHeaderForProtocol(Protocol protocol) { ModuleQuestionnaireBean moduleQuestionnaireBean = new ProtocolModuleQuestionnaireBean(protocol); moduleQuestionnaireBean.setModuleSubItemCode("0"); List <AnswerHeader> answerHeaders = new ArrayList<AnswerHeader>(); answerHeaders = getQuestionnaireAnswerService().getQuestionnaireAnswer(moduleQuestionnaireBean); return answerHeaders; } protected QuestionnaireAnswerService getQuestionnaireAnswerService() { return KraServiceLocator.getService(QuestionnaireAnswerService.class); } protected BusinessObjectService getBusinessObjectService() { return KraServiceLocator.getService(BusinessObjectService.class); } @SuppressWarnings("unchecked") private void mergeProtocolSubmission(Protocol amendment) { List<ProtocolSubmission> submissions = (List<ProtocolSubmission>) deepCopy(amendment.getProtocolSubmissions()); for (ProtocolSubmission submission : submissions) { submission.setProtocolNumber(this.getProtocolNumber()); submission.setSubmissionId(null); submission.setSequenceNumber(sequenceNumber); submission.setProtocolId(this.getProtocolId()); // submission.setSubmissionNumber(this.getProtocolSubmissions().size() + 1); this.getProtocolSubmissions().add(submission); //how about meting data // online review data } } /* * merge amendment/renewal protocol action to original protocol when A/R is approved */ @SuppressWarnings("unchecked") private void mergeProtocolAction(Protocol amendment) { List<ProtocolAction> protocolActions = (List<ProtocolAction>) deepCopy(amendment.getProtocolActions()); Collections.sort(protocolActions, new Comparator<ProtocolAction>() { public int compare(ProtocolAction action1, ProtocolAction action2) { return action1.getActionId().compareTo(action2.getActionId()); } }); // the first 1 'protocol created is already added to original protocol // the last one is 'approve' protocolActions.remove(0); protocolActions.remove(protocolActions.size() - 1); for (ProtocolAction protocolAction : protocolActions) { protocolAction.setProtocolNumber(this.getProtocolNumber()); protocolAction.setProtocolActionId(null); protocolAction.setSequenceNumber(sequenceNumber); protocolAction.setProtocolId(this.getProtocolId()); String index = amendment.getProtocolNumber().substring(11); protocolAction.setActionId(getNextValue(NEXT_ACTION_ID_KEY)); String type = "Amendment"; if (amendment.isRenewal()) { type = "Renewal"; } if (StringUtils.isNotBlank(protocolAction.getComments())) { protocolAction.setComments(type + "-" + index + ": " + protocolAction.getComments()); } else { protocolAction.setComments(type + "-" + index + ": "); } this.getProtocolActions().add(protocolAction); } } public void mergeGeneralInfo(Protocol amendment) { this.protocolTypeCode = amendment.getProtocolTypeCode(); this.title = amendment.getTitle(); this.initialSubmissionDate = amendment.getInitialSubmissionDate(); this.approvalDate = amendment.getApprovalDate(); this.expirationDate = amendment.getExpirationDate(); this.lastApprovalDate = amendment.getLastApprovalDate(); this.description = amendment.getDescription(); this.fdaApplicationNumber = amendment.getFdaApplicationNumber(); //this.billable = amendment.isBillable(); this.referenceNumber1 = amendment.getReferenceNumber1(); this.referenceNumber2 = amendment.getReferenceNumber2(); } @SuppressWarnings("unchecked") private void mergeResearchAreas(Protocol amendment) { setProtocolResearchAreas((List<ProtocolResearchArea>) deepCopy(amendment.getProtocolResearchAreas())); } @SuppressWarnings("unchecked") private void mergeFundingSources(Protocol amendment) { setProtocolFundingSources((List<ProtocolFundingSource>) deepCopy(amendment.getProtocolFundingSources())); } @SuppressWarnings("unchecked") private void mergeReferences(Protocol amendment) { setProtocolReferences((List<ProtocolReference>) deepCopy(amendment.getProtocolReferences())); this.fdaApplicationNumber = amendment.getFdaApplicationNumber(); this.referenceNumber1 = amendment.getReferenceNumber1(); this.referenceNumber2 = amendment.getReferenceNumber2(); this.description = amendment.getDescription(); } @SuppressWarnings("unchecked") private void mergeOrganizations(Protocol amendment) { setProtocolLocations((List<ProtocolLocation>) deepCopy(amendment.getProtocolLocations())); } @SuppressWarnings("unchecked") private void mergeSubjects(Protocol amendment) { setProtocolParticipants((List<ProtocolParticipant>) deepCopy(amendment.getProtocolParticipants())); } @SuppressWarnings("unchecked") private void mergeAttachments(Protocol amendment) { // TODO : may need to set protocolnumber // personnel attachment may have protocol person id issue // how about sequence number ? // need to change documentstatus to 2 if it is 1 // what the new protocol's protocol_status should be ? List<ProtocolAttachmentProtocol> attachmentProtocols = new ArrayList<ProtocolAttachmentProtocol>(); for (ProtocolAttachmentProtocol attachment : (List<ProtocolAttachmentProtocol>) deepCopy(amendment.getAttachmentProtocols())) { attachment.setProtocolNumber(this.getProtocolNumber()); attachment.setSequenceNumber(this.getSequenceNumber()); attachment.setProtocolId(this.getProtocolId()); attachment.setId(null); if (attachment.getFile() != null ) { attachment.getFile().setId(null); } if (attachment.isDraft()) { attachment.setDocumentStatusCode(ProtocolAttachmentStatus.FINALIZED); attachmentProtocols.add(attachment); attachment.setProtocol(this); } if (attachment.isDeleted() && KraServiceLocator.getService(ProtocolAttachmentService.class).isNewAttachmentVersion((ProtocolAttachmentProtocol) attachment)) { attachmentProtocols.add(attachment); attachment.setProtocol(this); } } getAttachmentProtocols().addAll(attachmentProtocols); removeDeletedAttachment(); mergeNotepads(amendment); } /* * the deleted attachment will not be merged */ private void removeDeletedAttachment() { List<Integer> documentIds = new ArrayList<Integer>(); List<ProtocolAttachmentProtocol> attachments = new ArrayList<ProtocolAttachmentProtocol>(); for (ProtocolAttachmentProtocol attachment : this.getAttachmentProtocols()) { attachment.setProtocol(this); if (attachment.isDeleted()) { documentIds.add(attachment.getDocumentId()); } } if (!documentIds.isEmpty()) { for (ProtocolAttachmentProtocol attachment : this.getAttachmentProtocols()) { attachment.setProtocol(this); if (!documentIds.contains(attachment.getDocumentId())) { attachments.add(attachment); } } this.setAttachmentProtocols(new ArrayList<ProtocolAttachmentProtocol>()); this.getAttachmentProtocols().addAll(attachments); } } /* * This is to restore attachments from protocol to amendment when 'attachment' section is unselected. * The attachment in amendment may have been modified. * delete 'attachment' need to be careful. * - if the 'file' is also used in other 'finalized' attachment, then should remove this file reference from attachment * otherwise, the delete will also delete any attachment that reference to this file */ private void restoreAttachments(Protocol protocol) { List<ProtocolAttachmentProtocol> attachmentProtocols = new ArrayList<ProtocolAttachmentProtocol>(); List<ProtocolAttachmentProtocol> deleteAttachments = new ArrayList<ProtocolAttachmentProtocol>(); List<AttachmentFile> deleteFiles = new ArrayList<AttachmentFile>(); for (ProtocolAttachmentProtocol attachment : this.getAttachmentProtocols()) { if (attachment.isFinal()) { attachmentProtocols.add(attachment); // } else if (attachment.isDraft()) { } else { // in amendment, DRAFT & DELETED must be new attachment because DELETED // will not be copied from original protocol deleteAttachments.add(attachment); if (!fileIsReferencedByOther(attachment.getFileId())) { deleteFiles.add(attachment.getFile()); } attachment.setFileId(null); } } if (!deleteAttachments.isEmpty()) { getBusinessObjectService().save(deleteAttachments); if (!deleteFiles.isEmpty()) { getBusinessObjectService().delete(deleteFiles); } getBusinessObjectService().delete(deleteAttachments); } this.getAttachmentProtocols().clear(); this.getAttachmentProtocols().addAll(attachmentProtocols); mergeNotepads(protocol); } private boolean fileIsReferencedByOther(Long fileId) { Map<String, String> fieldValues = new HashMap<String, String>(); fieldValues.put("fileId", fileId.toString()); return getBusinessObjectService().countMatching(ProtocolAttachmentProtocol.class, fieldValues) > 1; } private void mergeNotepads(Protocol amendment) { List <ProtocolNotepad> notepads = new ArrayList<ProtocolNotepad>(); if (amendment.getNotepads() != null) { for (ProtocolNotepad notepad : (List<ProtocolNotepad>) deepCopy(amendment.getNotepads())) { notepad.setProtocolNumber(this.getProtocolNumber()); notepad.setSequenceNumber(this.getSequenceNumber()); notepad.setProtocolId(this.getProtocolId()); notepad.setId(null); notepad.setProtocol(this); notepads.add(notepad); } } this.setNotepads(notepads); } private ProtocolPerson findMatchingPerson(ProtocolPerson person) { ProtocolPerson matchingPerson = null; for (ProtocolPerson newPerson : this.getProtocolPersons()) { if (newPerson.getProtocolPersonRoleId().equals(person.getProtocolPersonRoleId())) { if ((StringUtils.isNotBlank(newPerson.getPersonId()) && StringUtils.isNotBlank(person.getPersonId()) && newPerson.getPersonId().equals(person.getPersonId())) || (newPerson.getRolodexId() != null && person.getRolodexId() != null && newPerson.getRolodexId().equals(person.getRolodexId()))) { matchingPerson = newPerson; break; } } } return matchingPerson; } @SuppressWarnings("unchecked") private void mergeSpecialReview(Protocol amendment) { setSpecialReviews((List<ProtocolSpecialReview>) deepCopy(amendment.getSpecialReviews())); cleanupSpecialReviews(amendment); } @SuppressWarnings("unchecked") private void mergePersonnel(Protocol amendment) { setProtocolPersons((List<ProtocolPerson>) deepCopy(amendment.getProtocolPersons())); for (ProtocolPerson person : protocolPersons) { Integer nextPersonId = getSequenceAccessorService().getNextAvailableSequenceNumber("SEQ_PROTOCOL_ID").intValue(); person.setProtocolPersonId(nextPersonId); for (ProtocolAttachmentPersonnel protocolAttachmentPersonnel : person.getAttachmentPersonnels()) { protocolAttachmentPersonnel.setId(null); protocolAttachmentPersonnel.setPersonId(person.getProtocolPersonId()); protocolAttachmentPersonnel.setProtocolId(getProtocolId()); protocolAttachmentPersonnel.setProtocolNumber(getProtocolNumber()); } } } private void mergeOthers(Protocol amendment) { if (protocolDocument.getCustomAttributeDocuments() == null || protocolDocument.getCustomAttributeDocuments().isEmpty()) { protocolDocument.initialize(); } if (amendment.getProtocolDocument().getCustomAttributeDocuments() == null || amendment.getProtocolDocument().getCustomAttributeDocuments().isEmpty()) { amendment.getProtocolDocument().initialize(); } for (Entry<String, CustomAttributeDocument> entry : protocolDocument.getCustomAttributeDocuments().entrySet()) { CustomAttributeDocument cad = amendment.getProtocolDocument().getCustomAttributeDocuments().get(entry.getKey()); entry.getValue().getCustomAttribute().setValue(cad.getCustomAttribute().getValue()); } } private void mergeProtocolPermissions(Protocol amendment) { // ToDo: merge permissions } private Object deepCopy(Object obj) { return ObjectUtils.deepCopy((Serializable) obj); } public ProtocolSummary getProtocolSummary() { ProtocolSummary protocolSummary = createProtocolSummary(); addPersonnelSummaries(protocolSummary); addResearchAreaSummaries(protocolSummary); addAttachmentSummaries(protocolSummary); addFundingSourceSummaries(protocolSummary); addParticipantSummaries(protocolSummary); addOrganizationSummaries(protocolSummary); addSpecialReviewSummaries(protocolSummary); addAdditionalInfoSummary(protocolSummary); return protocolSummary; } private void addAdditionalInfoSummary(ProtocolSummary protocolSummary) { AdditionalInfoSummary additionalInfoSummary = new AdditionalInfoSummary(); additionalInfoSummary.setFdaApplicationNumber(this.getFdaApplicationNumber()); //additionalInfoSummary.setBillable(isBillable()); additionalInfoSummary.setReferenceId1(this.getReferenceNumber1()); additionalInfoSummary.setReferenceId2(this.getReferenceNumber2()); additionalInfoSummary.setDescription(getDescription()); protocolSummary.setAdditionalInfo(additionalInfoSummary); } private void addSpecialReviewSummaries(ProtocolSummary protocolSummary) { for (ProtocolSpecialReview specialReview : getSpecialReviews()) { SpecialReviewSummary specialReviewSummary = new SpecialReviewSummary(); if (specialReview.getSpecialReviewType() == null) { specialReview.refreshReferenceObject("specialReviewType"); } specialReviewSummary.setType(specialReview.getSpecialReviewType().getDescription()); if (specialReview.getApprovalType() == null) { specialReview.refreshReferenceObject("approvalType"); } specialReviewSummary.setApprovalStatus(specialReview.getApprovalType().getDescription()); specialReviewSummary.setProtocolNumber(specialReview.getProtocolNumber()); specialReviewSummary.setApplicationDate(specialReview.getApplicationDate()); specialReviewSummary.setApprovalDate(specialReview.getApprovalDate()); specialReviewSummary.setExpirationDate(specialReview.getExpirationDate()); if (specialReview.getSpecialReviewExemptions() == null) { specialReview.refreshReferenceObject("specialReviewExemptions"); } specialReviewSummary.setExemptionNumbers(specialReview.getSpecialReviewExemptions()); specialReviewSummary.setComment(specialReview.getComments()); protocolSummary.add(specialReviewSummary); } } private void addOrganizationSummaries(ProtocolSummary protocolSummary) { for (ProtocolLocation organization : this.getProtocolLocations()) { OrganizationSummary organizationSummary = new OrganizationSummary(); organizationSummary.setId(organization.getOrganizationId()); organizationSummary.setOrganizationId(organization.getOrganizationId()); organizationSummary.setName(organization.getOrganization().getOrganizationName()); organizationSummary.setType(organization.getProtocolOrganizationType().getDescription()); organizationSummary.setContactId(organization.getRolodexId()); organizationSummary.setContact(organization.getRolodex()); organizationSummary.setFwaNumber(organization.getOrganization().getHumanSubAssurance()); protocolSummary.add(organizationSummary); } } private void addParticipantSummaries(ProtocolSummary protocolSummary) { for (ProtocolParticipant participant : this.getProtocolParticipants()) { ParticipantSummary participantSummary = new ParticipantSummary(); participantSummary.setDescription(participant.getParticipantType().getDescription()); participantSummary.setCount(participant.getParticipantCount()); protocolSummary.add(participantSummary); } } private void addFundingSourceSummaries(ProtocolSummary protocolSummary) { for (ProtocolFundingSource source : getProtocolFundingSources()) { FundingSourceSummary fundingSourceSummary = new FundingSourceSummary(); fundingSourceSummary.setFundingSourceType(source.getFundingSourceType().getDescription()); fundingSourceSummary.setFundingSource(source.getFundingSourceNumber()); fundingSourceSummary.setFundingSourceNumber(source.getFundingSourceNumber()); fundingSourceSummary.setFundingSourceName(source.getFundingSourceName()); fundingSourceSummary.setFundingSourceTitle(source.getFundingSourceTitle()); protocolSummary.add(fundingSourceSummary); } } private void addAttachmentSummaries(ProtocolSummary protocolSummary) { for (ProtocolAttachmentProtocol attachment : getActiveAttachmentProtocols()) { if (!attachment.isDeleted()) { AttachmentSummary attachmentSummary = new AttachmentSummary(); attachmentSummary.setAttachmentId(attachment.getId()); attachmentSummary.setFileType(attachment.getFile().getType()); attachmentSummary.setFileName(attachment.getFile().getName()); attachmentSummary.setAttachmentType("Protocol: " + attachment.getType().getDescription()); attachmentSummary.setDescription(attachment.getDescription()); attachmentSummary.setDataLength(attachment.getFile().getData() == null ? 0 : attachment.getFile().getData().length); attachmentSummary.setUpdateTimestamp(attachment.getUpdateTimestamp()); attachmentSummary.setUpdateUser(attachment.getUpdateUser()); protocolSummary.add(attachmentSummary); } } for (ProtocolPerson person : getProtocolPersons()) { for (ProtocolAttachmentPersonnel attachment : person.getAttachmentPersonnels()) { AttachmentSummary attachmentSummary = new AttachmentSummary(); attachmentSummary.setAttachmentId(attachment.getId()); attachmentSummary.setFileType(attachment.getFile().getType()); attachmentSummary.setFileName(attachment.getFile().getName()); attachmentSummary.setAttachmentType(person.getPersonName() + ": " + attachment.getType().getDescription()); attachmentSummary.setDescription(attachment.getDescription()); attachmentSummary.setDataLength(attachment.getFile().getData() == null ? 0 : attachment.getFile().getData().length); attachmentSummary.setUpdateTimestamp(attachment.getUpdateTimestamp()); attachmentSummary.setUpdateUser(attachment.getUpdateUser()); protocolSummary.add(attachmentSummary); } } } private void addResearchAreaSummaries(ProtocolSummary protocolSummary) { for (ProtocolResearchArea researchArea : getProtocolResearchAreas()) { ResearchAreaSummary researchAreaSummary = new ResearchAreaSummary(); researchAreaSummary.setResearchAreaCode(researchArea.getResearchAreaCode()); researchAreaSummary.setDescription(researchArea.getResearchAreas().getDescription()); protocolSummary.add(researchAreaSummary); } } private void addPersonnelSummaries(ProtocolSummary protocolSummary) { for (ProtocolPerson person : getProtocolPersons()) { PersonnelSummary personnelSummary = new PersonnelSummary(); personnelSummary.setPersonId(person.getPersonId()); personnelSummary.setName(person.getPersonName()); personnelSummary.setRoleName(person.getProtocolPersonRole().getDescription()); if (person.getAffiliationTypeCode() == null) { personnelSummary.setAffiliation(""); } else { if (person.getAffiliationType() == null) { person.refreshReferenceObject("affiliationType"); } personnelSummary.setAffiliation(person.getAffiliationType().getDescription()); } for (ProtocolUnit unit : person.getProtocolUnits()) { personnelSummary.addUnit(unit.getUnitNumber(), unit.getUnitName()); } protocolSummary.add(personnelSummary); } } private ProtocolSummary createProtocolSummary() { ProtocolSummary summary = new ProtocolSummary(); summary.setLastProtocolAction(getLastProtocolAction()); summary.setProtocolNumber(getProtocolNumber().toString()); summary.setPiName(getPrincipalInvestigator().getPersonName()); summary.setPiProtocolPersonId(getPrincipalInvestigator().getProtocolPersonId()); summary.setInitialSubmissionDate(getInitialSubmissionDate()); summary.setApprovalDate(getApprovalDate()); summary.setLastApprovalDate(getLastApprovalDate()); summary.setExpirationDate(getExpirationDate()); if (getProtocolType() == null) { refreshReferenceObject("protocolType"); } summary.setType(getProtocolType().getDescription()); if (getProtocolStatus() == null) { refreshReferenceObject("protocolStatus"); } summary.setStatus(getProtocolStatus().getDescription()); summary.setTitle(getTitle()); return summary; } // TODO *********code has been moved to base class, should ultimately be removed********** /** * * @see org.kuali.kra.common.permissions.Permissionable#getDocumentKey() */ public String getDocumentKey() { return Permissionable.PROTOCOL_KEY; } /** * * @see org.kuali.kra.common.permissions.Permissionable#getDocumentNumberForPermission() */ public String getDocumentNumberForPermission() { return protocolNumber; } /** * * @see org.kuali.kra.common.permissions.Permissionable#getRoleNames() */ public List<String> getRoleNames() { List<String> roleNames = new ArrayList<String>(); roleNames.add(RoleConstants.PROTOCOL_AGGREGATOR); roleNames.add(RoleConstants.PROTOCOL_VIEWER); return roleNames; } // TODO **********************end************************ public void resetForeignKeys() { for (ProtocolAction action : protocolActions) { action.resetForeignKeys(); } } // TODO *********code has been moved to base class, should ultimately be removed********** public String getNamespace() { return Constants.MODULE_NAMESPACE_PROTOCOL; } /** * * @see org.kuali.kra.UnitAclLoadable#getUnitNumberOfDocument() */ public String getDocumentUnitNumber() { return getLeadUnitNumber(); } /** * * @see org.kuali.kra.UnitAclLoadable#getDocumentRoleTypeCode() */ public String getDocumentRoleTypeCode() { return RoleConstants.PROTOCOL_ROLE_TYPE; } public void populateAdditionalQualifiedRoleAttributes(Map<String, String> qualifiedRoleAttributes) { return; } // TODO **********************end************************ public boolean isNew() { return !isAmendment() && !isRenewal(); } public boolean isAmendment() { return protocolNumber.contains(AMENDMENT_LETTER); } public boolean isRenewal() { return protocolNumber.contains(RENEWAL_LETTER); } public boolean isRenewalWithoutAmendment() { return isRenewal() && CollectionUtils.isEmpty(this.getProtocolAmendRenewal().getModules()); } /** * * If the protocol document is an amendment or renewal the parent protocol number is being returned. * (i.e. the protocol number of the protocol that is being amended or renewed). * * Null will be returned if the protocol is not an amendment or renewal. * * @return protocolNumber of the Protocol that is being amended/renewed */ public String getAmendedProtocolNumber() { if (isAmendment()) { return StringUtils.substringBefore(getProtocolNumber(), AMENDMENT_LETTER.toString()); } else if (isRenewal()) { return StringUtils.substringBefore(getProtocolNumber(), RENEWAL_LETTER.toString()); } else { return null; } } /** * Decides whether or not the Protocol is in a state where changes will require versioning. For example: has the protocol * had a change in status and not been versioned yet? * @return true if versioning required false if not. */ public boolean isVersioningRequired() { // TODO : why need this. it's always true return true; } /** * This method will return the list of all active attachments for this protocol; an attachment A is active for a * protocol if either A has a doc status code of 'draft' or * if for all other attachments for that protocol having the same doc id as A's doc id, none have a version number * greater than A's version number. * is defined as the o * @return */ public List<ProtocolAttachmentProtocol> getActiveAttachmentProtocols() { List<ProtocolAttachmentProtocol> activeAttachments = new ArrayList<ProtocolAttachmentProtocol>(); for (ProtocolAttachmentProtocol attachment1 : getAttachmentProtocols()) { if (attachment1.isDraft()) { activeAttachments.add(attachment1); } else if (attachment1.isFinal() || attachment1.isDeleted()) { //else if (attachment1.isFinal())) { boolean isActive = true; for (ProtocolAttachmentProtocol attachment2 : getAttachmentProtocols()) { if (attachment1.getDocumentId().equals(attachment2.getDocumentId()) && attachment1.getAttachmentVersion() < attachment2.getAttachmentVersion()) { isActive = false; break; } } if (isActive) { activeAttachments.add(attachment1); } else { attachment1.setActive(isActive); } } else { attachment1.setActive(false); } } return activeAttachments; } /** * This method will return the list of undeleted attachments that are still active for this protocol. * Essentially it filters out all the deleted elements from the list of active attachments. * See getActiveAttachmentProtocols() for a specification of what is an 'active attachment'. * * * @return */ // TODO the method code below could be restructured to combine the two for loops into one loop. public List<ProtocolAttachmentProtocol> getActiveAttachmentProtocolsNoDelete() { List<Integer> documentIds = new ArrayList<Integer>(); List<ProtocolAttachmentProtocol> activeAttachments = new ArrayList<ProtocolAttachmentProtocol>(); for (ProtocolAttachmentProtocol attachment : getActiveAttachmentProtocols()) { if (attachment.isDeleted()) { documentIds.add(attachment.getDocumentId()); } } for (ProtocolAttachmentProtocol attachment : getActiveAttachmentProtocols()) { if (documentIds.isEmpty() || !documentIds.contains(attachment.getDocumentId())) { activeAttachments.add(attachment); } else { attachment.setActive(false); } } return activeAttachments; } public boolean isCorrectionMode() { return correctionMode; } public void setCorrectionMode(boolean correctionMode) { this.correctionMode = correctionMode; } protected DateTimeService getDateTimeService() { if(dateTimeService == null) { dateTimeService = (DateTimeService) KraServiceLocator.getService(DateTimeService.class); } return dateTimeService; } protected SequenceAccessorService getSequenceAccessorService() { if(sequenceAccessorService == null) { sequenceAccessorService = (SequenceAccessorService) KraServiceLocator.getService(SequenceAccessorService.class); } return sequenceAccessorService; } public Long getNotifyIrbSubmissionId() { return notifyIrbSubmissionId; } public void setNotifyIrbSubmissionId(Long notifyIrbSubmissionId) { this.notifyIrbSubmissionId = notifyIrbSubmissionId; } public boolean isLookupPendingProtocol() { return lookupPendingProtocol; } public void setLookupPendingProtocol(boolean lookupPendingProtocol) { this.lookupPendingProtocol = lookupPendingProtocol; } public boolean isLookupPendingPIActionProtocol() { return lookupPendingPIActionProtocol; } public void setLookupPendingPIActionProtocol(boolean lookupPendingPIActionProtocol) { this.lookupPendingPIActionProtocol = lookupPendingPIActionProtocol; } public boolean isLookupActionAmendRenewProtocol() { return lookupActionAmendRenewProtocol; } public void setLookupActionAmendRenewProtocol(boolean lookupActionAmendRenewProtocol) { this.lookupActionAmendRenewProtocol = lookupActionAmendRenewProtocol; } public boolean isLookupActionNotifyIRBProtocol() { return lookupActionNotifyIRBProtocol; } public void setLookupActionNotifyIRBProtocol(boolean lookupActionNotifyIRBProtocol) { this.lookupActionNotifyIRBProtocol = lookupActionNotifyIRBProtocol; } public boolean isLookupActionRequestProtocol() { return lookupActionRequestProtocol; } public void setLookupActionRequestProtocol(boolean lookupActionRequestProtocol) { this.lookupActionRequestProtocol = lookupActionRequestProtocol; } public boolean isLookupProtocolPersonId() { return lookupProtocolPersonId; } public void setLookupProtocolPersonId(boolean lookupProtocolPersonId) { this.lookupProtocolPersonId = lookupProtocolPersonId; } /** * * This method is to check if the actiontypecode is a followup action. * @param actionTypeCode * @return */ public boolean isFollowupAction(String actionTypeCode) { return (getLastProtocolAction() == null || StringUtils.isBlank(getLastProtocolAction().getFollowupActionCode())) ? false : actionTypeCode.equals(getLastProtocolAction().getFollowupActionCode()); } public boolean isMergeAmendment() { return mergeAmendment; } public void setMergeAmendment(boolean mergeAmendment) { this.mergeAmendment = mergeAmendment; } public ProtocolAttachmentFilter getProtocolAttachmentFilter() { return protocolAttachmentFilter; } public void setProtocolAttachmentFilter(ProtocolAttachmentFilter protocolAttachmentFilter) { this.protocolAttachmentFilter = protocolAttachmentFilter; } /** * * This method returns a list of attachments which respect the sort filter * @return a filtered list of protocol attachments */ public List<ProtocolAttachmentProtocol> getFilteredAttachmentProtocols() { List<ProtocolAttachmentProtocol> filteredAttachments = new ArrayList<ProtocolAttachmentProtocol>(); ProtocolAttachmentFilter attachmentFilter = getProtocolAttachmentFilter(); if (attachmentFilter != null && StringUtils.isNotBlank(attachmentFilter.getFilterBy())) { for (ProtocolAttachmentProtocol attachment1 : getAttachmentProtocols()) { if ((attachment1.getTypeCode()).equals(attachmentFilter.getFilterBy())) { filteredAttachments.add(attachment1); } } } else { filteredAttachments = getAttachmentProtocols(); } if (attachmentFilter != null && StringUtils.isNotBlank(attachmentFilter.getSortBy())) { Collections.sort(filteredAttachments, attachmentFilter.getProtocolAttachmentComparator()); } return filteredAttachments; } public void initializeProtocolAttachmentFilter() { protocolAttachmentFilter = new ProtocolAttachmentFilter(); //Lets see if there is a default set for the attachment sort try { String defaultSortBy = getParameterService().getParameterValueAsString(ProtocolDocument.class, Constants.PARAMETER_PROTOCOL_ATTACHMENT_DEFAULT_SORT); if (StringUtils.isNotBlank(defaultSortBy)) { protocolAttachmentFilter.setSortBy(defaultSortBy); } } catch (Exception e) { //No default found, do nothing. } } public ParameterService getParameterService() { return (ParameterService)KraServiceLocator.getService(ParameterService.class); } public void cleanupSpecialReviews(Protocol srcProtocol) { List<ProtocolSpecialReview> srcSpecialReviews = srcProtocol.getSpecialReviews(); List<ProtocolSpecialReview> dstSpecialReviews = getSpecialReviews(); for (int i=0; i < srcSpecialReviews.size(); i++) { ProtocolSpecialReview srcSpecialReview = srcSpecialReviews.get(i); ProtocolSpecialReview dstSpecialReview = dstSpecialReviews.get(i); // copy exemption codes, since they are transient and ignored by deepCopy() if (srcSpecialReview.getExemptionTypeCodes() != null) { List<String> exemptionCodeCopy = new ArrayList<String>(); for (String s: srcSpecialReview.getExemptionTypeCodes()) { exemptionCodeCopy.add(new String(s)); } dstSpecialReview.setExemptionTypeCodes(exemptionCodeCopy); } // force new table entry dstSpecialReview.resetPersistenceState(); } } /** * This method encapsulates the logic to decide if a committee member appears in the list of protocol personnel. * It will first try to match by personIds and if personIds are not available then it will try matching by rolodexIds. * @param member * @return */ public boolean isMemberInProtocolPersonnel(CommitteeMembership member) { boolean retValue = false; for(ProtocolPerson protocolPerson: this.protocolPersons) { if( StringUtils.isNotBlank(member.getPersonId()) && StringUtils.isNotBlank(protocolPerson.getPersonId()) ) { if(member.getPersonId().equals(protocolPerson.getPersonId())){ retValue = true; break; } } else if( StringUtils.isBlank(member.getPersonId()) && StringUtils.isBlank(protocolPerson.getPersonId()) ) { // in this case check rolodex id if( (null != member.getRolodexId()) && (null != protocolPerson.getRolodexId()) ) { if(member.getRolodexId().equals(protocolPerson.getRolodexId())) { retValue = true; break; } } } } return retValue; } /** * This method will filter out this protocol's personnel from the given list of committee memberships * @param members * @return the filtered list of members */ public List<CommitteeMembership> filterOutProtocolPersonnel(List<CommitteeMembership> members) { List<CommitteeMembership> filteredMemebers = new ArrayList<CommitteeMembership>(); for (CommitteeMembership member : members) { if(!isMemberInProtocolPersonnel(member)) { filteredMemebers.add(member); } } return filteredMemebers; } /** * * This method is to return the first submission date as application date. see kccoi-36 comment * @return */ public Date getApplicationDate() { if (CollectionUtils.isNotEmpty(this.protocolSubmissions)) { return this.protocolSubmissions.get(0).getSubmissionDate(); } else { return null; } } @Override public String getProjectName() { // TODO Auto-generated method stub return getTitle(); } @Override public String getProjectId() { // TODO Auto-generated method stub return getProtocolNumber(); } // This is for viewhistory/corespondence to search prev submission public List<ProtocolAction> getSortedActions() { if (sortedActions == null) { sortedActions = new ArrayList<ProtocolAction>(); for (ProtocolAction action : getProtocolActions()) { sortedActions.add((ProtocolAction) ObjectUtils.deepCopy(action)); } Collections.sort(sortedActions, new Comparator<ProtocolAction>() { public int compare(ProtocolAction action1, ProtocolAction action2) { return action1.getActionId().compareTo(action2.getActionId()); } }); } return sortedActions; } public KrmsRulesContext getKrmsRulesContext() { return (KrmsRulesContext) getProtocolDocument(); } }
KRACOEUS-5985 Fix issue with merge submission
src/main/java/org/kuali/kra/irb/Protocol.java
KRACOEUS-5985 Fix issue with merge submission
<ide><path>rc/main/java/org/kuali/kra/irb/Protocol.java <ide> if (amendment.isRenewalWithoutAmendment() && isRenewalWithNewAttachment(amendment)) { <ide> merge(amendment, ProtocolModule.ADD_MODIFY_ATTACHMENTS); <ide> } <del> mergeProtocolSubmission(amendment); <add> //mergeProtocolSubmission(amendment); <ide> if (mergeActions) { <add> mergeProtocolSubmission(amendment); <ide> mergeProtocolAction(amendment); <ide> } <ide> }
JavaScript
agpl-3.0
eb22446d0c52938d9ad169a7194a0d6d039ab46e
0
tracking-exposed/web-extension,tracking-exposed/web-extension
import * as profile from "./profile"; import * as sync from "./sync"; import { refreshUserInfo } from "./userInfo"; const mapping = { ...profile, ...sync }; // ## Dispatch requests // // The `content_script` needs to communicate to the `background` page to send // and receive information, e.g.: // // - Get information about the current user. // - Send the scraped post. // - ... // // Here we connect the "backend functions" (where *backend* here is intended as // the **background page**) to a dispatcher. // ### Log errors // // To understand better what happens when calling a "backend function", here we // wrap its call and log errors for better debugging. async function wrapAndLog(func, params) { try { return await func(...params); } catch (e) { console.error(`Error dispatching "${func.name}"`, e); throw e; } } // ### Global listener // It's **not** a good practice to plug an async fuction as a listener. // The Mozilla documentation [says][1]: // // > Do not call addListener using the async function [...] as the listener // will consume every message it receives, effectively blocking all other // listeners from receiving and processing messages. // // You may notice that there is no `sendMessage` in the `addListener` callback. // Returning a Promise is now preferred as sendResponse will be removed from // the [W3C spec][2]. The popular [webextension-polyfill library][3] has // already removed the sendResponse function from its implementation. browser.runtime.onMessage.addListener(({ method, params }, sender) => { const func = mapping[method]; params = params === undefined ? [] : params; if (!func) { const message = `Method "${method}" not supported.`; console.error(message); return Promise.reject(new Error(message)); } console.log(`Dispatch "${method}" from ${sender.url}`); return wrapAndLog(func, params); }); // ## Alarms // // Alarms are a neat way to schedule code to run at a specific time. // Here we set a listener to refresh some user info every hour. // browser.alarms.onAlarm.addListener(refreshUserInfo); // browser.alarms.create("refreshUserInfo", { // periodInMinutes: 60 // }); // ## Extra stuff // // We also want to refresh the user info when the extension boots. // refreshUserInfo(); // [1]: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage // [2]: https://github.com/mozilla/webextension-polyfill/issues/16#issuecomment-296693219 // [3]: https://github.com/mozilla/webextension-polyfill // [4]: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/alarms
src/domains/facebook.com/background/index.js
import * as profile from "./profile"; import * as sync from "./sync"; import { refreshUserInfo } from "./userInfo"; const mapping = { ...profile, ...sync }; // ## Dispatch requests // // The `content_script` needs to communicate to the `background` page to send // and receive information, e.g.: // // - Get information about the current user. // - Send the scraped post. // - ... // // Here we connect the "backend functions" (where *backend* here is intended as // the **background page**) to a dispatcher. // // It's **not** a good practice to plug an async fuction as a listener. // The Mozilla documentation [says][1]: // // > Do not call addListener using the async function [...] as the listener // will consume every message it receives, effectively blocking all other // listeners from receiving and processing messages. // // You may notice that there is no `sendMessage` in the `addListener` callback. // Returning a Promise is now preferred as sendResponse will be removed from // the [W3C spec][2]. The popular [webextension-polyfill library][3] has // already removed the sendResponse function from its implementation. browser.runtime.onMessage.addListener(({ method, params }, sender) => { const func = mapping[method]; params = params === undefined ? [] : params; console.debug(`Dispatch "${method}" from ${sender.url}`); if (!func) { const message = `Method "${method}" not supported.`; console.error(message); return Promise.reject(new Error(message)); } return func(...params); }); // ## Alarms // // Alarms are a neat way to schedule code to run at a specific time. // Here we set a listener to refresh some user info every hour. // browser.alarms.onAlarm.addListener(refreshUserInfo); // browser.alarms.create("refreshUserInfo", { // periodInMinutes: 60 // }); // ## Extra stuff // // We also want to refresh the user info when the extension boots. // refreshUserInfo(); // [1]: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage // [2]: https://github.com/mozilla/webextension-polyfill/issues/16#issuecomment-296693219 // [3]: https://github.com/mozilla/webextension-polyfill // [4]: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/alarms
Wrap backend calls to log failures
src/domains/facebook.com/background/index.js
Wrap backend calls to log failures
<ide><path>rc/domains/facebook.com/background/index.js <ide> // <ide> // Here we connect the "backend functions" (where *backend* here is intended as <ide> // the **background page**) to a dispatcher. <add> <add>// ### Log errors <ide> // <add>// To understand better what happens when calling a "backend function", here we <add>// wrap its call and log errors for better debugging. <add>async function wrapAndLog(func, params) { <add> try { <add> return await func(...params); <add> } catch (e) { <add> console.error(`Error dispatching "${func.name}"`, e); <add> throw e; <add> } <add>} <add> <add>// ### Global listener <ide> // It's **not** a good practice to plug an async fuction as a listener. <ide> // The Mozilla documentation [says][1]: <ide> // <ide> <ide> params = params === undefined ? [] : params; <ide> <del> console.debug(`Dispatch "${method}" from ${sender.url}`); <del> <ide> if (!func) { <ide> const message = `Method "${method}" not supported.`; <ide> console.error(message); <ide> return Promise.reject(new Error(message)); <ide> } <ide> <del> return func(...params); <add> console.log(`Dispatch "${method}" from ${sender.url}`); <add> <add> return wrapAndLog(func, params); <ide> }); <ide> <ide> // ## Alarms
JavaScript
apache-2.0
912373a389d02c4d113125533d655f38ce16e798
0
resin-io/etcher,resin-io/etcher,cedricve/etcher,resin-io/etcher,cedricve/etcher,resin-io/herostratus,cedricve/etcher,resin-io/resin-etcher,resin-io/resin-etcher,resin-io/etcher,resin-io/herostratus,resin-io/etcher
/* * Copyright 2016 Resin.io * * 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. */ 'use strict'; /** * @module Etcher.analytics */ const _ = require('lodash'); const angular = require('angular'); const username = require('username'); const app = require('electron').remote.app; const packageJSON = require('../../../package.json'); // Force Mixpanel snippet to load Mixpanel locally // instead of using a CDN for performance reasons window.MIXPANEL_CUSTOM_LIB_URL = '../bower_components/mixpanel/mixpanel.js'; require('../../../bower_components/mixpanel/mixpanel-jslib-snippet.js'); require('../../../bower_components/angular-mixpanel/src/angular-mixpanel'); require('../models/settings'); const analytics = angular.module('Etcher.analytics', [ 'analytics.mixpanel', 'Etcher.Models.Settings' ]); analytics.config(function($mixpanelProvider) { $mixpanelProvider.apiKey('63e5fc4563e00928da67d1226364dd4c'); $mixpanelProvider.superProperties({ // jscs:disable requireCamelCaseOrUpperCaseIdentifiers distinct_id: username.sync(), // jscs:enable requireCamelCaseOrUpperCaseIdentifiers electron: app.getVersion(), node: process.version, arch: process.arch, version: packageJSON.version }); }); // TrackJS integration // http://docs.trackjs.com/tracker/framework-integrations analytics.run(function($window) { $window.trackJs.configure({ userId: username.sync(), version: packageJSON.version }); }); analytics.config(function($provide) { $provide.decorator('$exceptionHandler', function($delegate, $window, $injector) { return function(exception, cause) { const SettingsModel = $injector.get('SettingsModel'); if (SettingsModel.data.errorReporting) { $window.trackJs.track(exception); } $delegate(exception, cause); }; }); $provide.decorator('$log', function($delegate, $window, $injector) { // Save the original $log.debug() let debugFn = $delegate.debug; $delegate.debug = function(message) { message = new Date() + ' ' + message; const SettingsModel = $injector.get('SettingsModel'); if (SettingsModel.data.errorReporting) { $window.trackJs.console.debug(message); } debugFn.call(null, message); }; return $delegate; }); }); analytics.service('AnalyticsService', function($log, $mixpanel, SettingsModel) { let self = this; /** * @summary Log a debug message * @function * @public * * @description * This function sends the debug message to TrackJS only. * * @param {String} message - message * * @example * AnalyticsService.log('Hello World'); */ this.log = function(message) { $log.debug(message); }; /** * @summary Log an event * @function * @public * * @description * This function sends the debug message to TrackJS and Mixpanel. * * @param {String} message - message * @param {Object} [data] - event data * * @example * AnalyticsService.logEvent('Select image', { * image: '/dev/disk2' * }); */ this.logEvent = function(message, data) { if (SettingsModel.data.errorReporting) { // Clone data before passing it to `mixpanel.track` // since this function mutates the object adding // some custom private Mixpanel properties. $mixpanel.track(message, _.clone(data)); } if (data) { message += ` (${JSON.stringify(data)})`; } self.log(message); }; });
lib/browser/modules/analytics.js
/* * Copyright 2016 Resin.io * * 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. */ 'use strict'; /** * @module Etcher.analytics */ const _ = require('lodash'); const angular = require('angular'); const username = require('username'); const app = require('electron').remote.app; // Force Mixpanel snippet to load Mixpanel locally // instead of using a CDN for performance reasons window.MIXPANEL_CUSTOM_LIB_URL = '../bower_components/mixpanel/mixpanel.js'; require('../../../bower_components/mixpanel/mixpanel-jslib-snippet.js'); require('../../../bower_components/angular-mixpanel/src/angular-mixpanel'); require('../models/settings'); const analytics = angular.module('Etcher.analytics', [ 'analytics.mixpanel', 'Etcher.Models.Settings' ]); analytics.config(function($mixpanelProvider) { $mixpanelProvider.apiKey('63e5fc4563e00928da67d1226364dd4c'); $mixpanelProvider.superProperties({ // jscs:disable requireCamelCaseOrUpperCaseIdentifiers distinct_id: username.sync(), // jscs:enable requireCamelCaseOrUpperCaseIdentifiers electron: app.getVersion(), node: process.version, arch: process.arch }); }); // TrackJS integration // http://docs.trackjs.com/tracker/framework-integrations analytics.run(function($window) { $window.trackJs.configure({ userId: username.sync() }); }); analytics.config(function($provide) { $provide.decorator('$exceptionHandler', function($delegate, $window, $injector) { return function(exception, cause) { const SettingsModel = $injector.get('SettingsModel'); if (SettingsModel.data.errorReporting) { $window.trackJs.track(exception); } $delegate(exception, cause); }; }); $provide.decorator('$log', function($delegate, $window, $injector) { // Save the original $log.debug() let debugFn = $delegate.debug; $delegate.debug = function(message) { message = new Date() + ' ' + message; const SettingsModel = $injector.get('SettingsModel'); if (SettingsModel.data.errorReporting) { $window.trackJs.console.debug(message); } debugFn.call(null, message); }; return $delegate; }); }); analytics.service('AnalyticsService', function($log, $mixpanel, SettingsModel) { let self = this; /** * @summary Log a debug message * @function * @public * * @description * This function sends the debug message to TrackJS only. * * @param {String} message - message * * @example * AnalyticsService.log('Hello World'); */ this.log = function(message) { $log.debug(message); }; /** * @summary Log an event * @function * @public * * @description * This function sends the debug message to TrackJS and Mixpanel. * * @param {String} message - message * @param {Object} [data] - event data * * @example * AnalyticsService.logEvent('Select image', { * image: '/dev/disk2' * }); */ this.logEvent = function(message, data) { if (SettingsModel.data.errorReporting) { // Clone data before passing it to `mixpanel.track` // since this function mutates the object adding // some custom private Mixpanel properties. $mixpanel.track(message, _.clone(data)); } if (data) { message += ` (${JSON.stringify(data)})`; } self.log(message); }; });
Log Etcher version in Mixpanel and TrackJS Its hard to attempt to debug or reproduce an issue if we don't know the version the user is running. Signed-off-by: Juan Cruz Viotti <[email protected]>
lib/browser/modules/analytics.js
Log Etcher version in Mixpanel and TrackJS
<ide><path>ib/browser/modules/analytics.js <ide> const angular = require('angular'); <ide> const username = require('username'); <ide> const app = require('electron').remote.app; <add>const packageJSON = require('../../../package.json'); <ide> <ide> // Force Mixpanel snippet to load Mixpanel locally <ide> // instead of using a CDN for performance reasons <ide> <ide> electron: app.getVersion(), <ide> node: process.version, <del> arch: process.arch <add> arch: process.arch, <add> version: packageJSON.version <ide> }); <ide> }); <ide> <ide> <ide> analytics.run(function($window) { <ide> $window.trackJs.configure({ <del> userId: username.sync() <add> userId: username.sync(), <add> version: packageJSON.version <ide> }); <ide> }); <ide>
JavaScript
mit
ec785a936efcc558635428ca9b274b1d62c21e4f
0
wq/wq.app,wq/wq.app,wq/wq.app
/*! * wq.app - app.js * Utilizes store and pages to dynamically load and render * content from a wq.db-compatible REST service * (c) 2012 S. Andrew Sheppard * http://wq.io/license */ define(['./lib/jquery', './lib/jquery.mobile', './store', './pages', './template', './spinner', './lib/es5-shim'], function($, jqm, ds, pages, tmpl, spin) { var app = {}; app.init = function(config, templates, baseurl, svc) { if (baseurl === undefined) baseurl = ''; if (svc === undefined) svc = baseurl; app.config = app.default_config = config; app['native'] = !!window.cordova; app.can_login = !!config.pages.login; ds.init(svc, {'format':'json'}, {'applyResult': _applyResult}); app.service = ds.service; pages.init(baseurl); app.base_url = pages.info.base_url; tmpl.init(templates, templates.partials, config.defaults); tmpl.setDefault('native', app['native']); tmpl.setDefault('app_config', app.config); if (app.can_login) { var user = ds.get('user'); var csrftoken = ds.get('csrftoken'); if (user) { app.user = user; tmpl.setDefault('user', user); tmpl.setDefault('is_authenticated', true); tmpl.setDefault('csrftoken', csrftoken); app.config = ds.get({'url': 'config'}); tmpl.setDefault('app_config', app.config); $('body').trigger('login'); } app.check_login(); pages.register('logout\/?', app.logout); } if (config.transitions) { var def = "default"; if (config.transitions[def]) jqm.defaultPageTransition = config.transitions[def]; if (config.transitions.dialog) jqm.defaultDialogTransition = config.transitions.dialog; if (config.transitions.save) _saveTransition = config.transitions.save; jqm.maxTransitionWidth = config.transitions.maxwidth || 800; } for (var page in app.config.pages) { var conf = _getConf(page); if (conf.list) { _registerList(page); _registerDetail(page); _registerEdit(page); } else if (conf) { _registerOther(page); } } $(document).on('submit', 'form', _handleForm); } app.logout = function() { if (!app.can_login) return; delete app.user; ds.set('user', null); tmpl.setDefault('user', null); tmpl.setDefault('is_authenticated', false); tmpl.setDefault('csrftoken', null); app.config = app.default_config; tmpl.setDefault('app_config', app.config); ds.fetch({'url': 'logout'}, true, undefined, true); $('body').trigger('logout'); }; app.save_login = function(result) { var config = result.config, user = result.user, csrftoken = result.csrftoken; if (!app.can_login) return; app.config = config; ds.set({'url': 'config'}, config); tmpl.setDefault('app_config', config); app.user = user; tmpl.setDefault('user', user); tmpl.setDefault('is_authenticated', true); tmpl.setDefault('csrftoken', csrftoken); ds.set('user', user); ds.set('csrftoken', csrftoken); $('body').trigger('login'); }; app.check_login = function() { if (!app.can_login) return; ds.fetch({'url': 'login'}, true, function(result) { if (result && result.user && result.config) { app.save_login(result); } else if (result && app.user) { app.logout(); } }, true); }; // Internal variables and functions var _saveTransition = "none"; // Wrappers for pages.register & pages.go to handle common use cases // Determine appropriate context & template for pages.go app.go = function(page, ui, params, itemid, edit, url, context) { if (ui && ui.options && ui.options.data) return; // Ignore form actions var conf = _getConf(page); if (!conf.list) { _renderOther(page, ui, params, url, context); return; } spin.start(); ds.getList({'url': conf.url}, function(list) { spin.stop(); if (itemid) { if (edit) _renderEdit(page, list, ui, params, itemid, url, context); else _renderDetail(page, list, ui, params, itemid, url, context); } else { _renderList(page, list, ui, params, url, context); } }); } app.attachmentTypes = { annotation: { 'predicate': 'annotated', 'type': 'annotationtype', 'getTypeFilter': function(page, context) { return {'for': page}; } }, identifier: { 'predicate': 'identified', 'type': 'authority', 'getTypeFilter': function(page, context) { return {}; } }, location: { 'predicate': 'located', 'type': null } }; // Generate list view context and render with [url]_list template; // handles requests for [url] and [url]/ function _registerList(page) { var conf = _getConf(page); pages.register(conf.url, go); pages.register(conf.url + '/', go); function go(match, ui, params) { app.go(page, ui, params); } (conf.parents || []).forEach(function(ppage) { var pconf = _getConf(ppage); var url = pconf.url; if (url) url += '/'; url += '<slug>/' + conf.url; pages.register(url, goUrl(ppage, url)) pages.register(url + '/', goUrl(ppage, url)) }); function goUrl(ppage, url) { return function(match, ui, params) { var pconf = _getConf(ppage); if (!params) params = {}; if (ppage.indexOf(page) == 0) params[ppage.replace(page, '')] = match[1]; else params[ppage] = match[1]; var pageurl = url.replace('<slug>', match[1]); spin.start(); ds.getList({'url': pconf.url}, function(plist) { spin.stop(); var pitem = plist.find(match[1]); app.go(page, ui, params, undefined, false, pageurl, { 'parent_id': match[1], 'parent_url': pitem && (pconf.url + '/' + pitem.id), 'parent_label': pitem && pitem.label }); }); } } } function _renderList(page, list, ui, params, url, context) { var conf = _getConf(page); var pnum = 1, next = null, prev = null, filter; if (url === undefined) { url = conf.url; if (url) url += '/'; } if (params) { if (url == conf.url || url == conf.url + '/') url += "?" + $.param(params); if (params['page']) { pnum = params['page']; } else { filter = {}; for (var key in params) { filter[key] = params[key]; } (conf.parents || []).forEach(function(p) { if (p.indexOf(page) == 0) p = p.replace(page, ''); if (filter[p]) { filter[p + '_id'] = filter[p]; delete filter[p]; } }); } } if (pnum > conf.max_local_pages || filter && conf.partial) { // Set max_local_pages to avoid filling up local storage and // instead attempt to load HTML directly from the server // (using built-in jQM loader) var jqmurl = '/' + url; spin.start(); jqm.loadPage(jqmurl).then(function() { spin.stop(); $page = $(":jqmData(url='" + jqmurl + "')"); if ($page.length > 0) jqm.changePage($page); else pages.notFound(url); }); return; } var data = filter ? list.filter(filter) : list.page(pnum); if (pnum > 1) { var prevp = {'page': parseInt(pnum) - 1}; prev = conf.url + '/?' + $.param(prevp); } if (pnum < data.info.pages) { var nextp = {'page': parseInt(pnum) + 1}; next = conf.url + '/?' + $.param(nextp); } context = $.extend({}, conf, { 'list': data, 'page': pnum, 'pages': data.info.pages, 'per_page': data.info.per_page, 'total': data.info.total, 'previous': prev ? '/' + prev : null, 'next': next ? '/' + next : null, 'multiple': data.info.pages > 1 }, context); _addLookups(page, context, false, function(context) { pages.go(url, page + '_list', context, ui, conf.once ? true : false); }); } // Generate item detail view context and render with [url]_detail template; // handles requests for [url]/[id] function _registerDetail(page) { var conf = _getConf(page); var url = conf.url; var reserved = ["new"]; if (url) { url += "/"; } else { // This list is bound to the root URL, don't mistake other lists for items for (var key in app.config.pages) reserved.push(app.config.pages[key].url); } pages.register(url + '<slug>', function(match, ui, params) { if (reserved.indexOf(match[1]) > -1) return; app.go(page, ui, params, match[1]); }); } function _renderDetail(page, list, ui, params, itemid, url, context) { var conf = _getConf(page); if (url === undefined) { url = conf.url; if (url) url += '/'; url += itemid; } var item = list.find(itemid, undefined, undefined, conf.max_local_pages); if (!item) { // Item not found in stored list... if (!conf.partial) { // If partial is not set, locally stored list is assumed to // contain the entire dataset, so the item probably does not exist. pages.notFound(url); } else { // Set partial to indicate local list does not represent entire // dataset; if an item is not found will attempt to load HTML // directly from the server (using built-in jQM loader) var jqmurl = '/' + url; spin.start(); jqm.loadPage(jqmurl).then(function() { spin.stop(); $page = $(":jqmData(url='" + jqmurl + "')"); if ($page.length > 0) jqm.changePage($page); else pages.notFound(url); }); } return; } context = $.extend({}, conf, item, context); _addLookups(page, context, false, function(context) { pages.go(url, page + '_detail', context, ui, conf.once ? true : false); }); } // Generate item edit context and render with [url]_edit template; // handles requests for [url]/[id]/edit and [url]/new function _registerEdit(page) { var conf = _getConf(page); pages.register(conf.url + '/<slug>/edit', go); pages.register(conf.url + '/(new)', go); function go(match, ui, params) { app.go(page, ui, params, match[1], true); } } function _renderEdit(page, list, ui, params, itemid, url, context) { var conf = _getConf(page); if (itemid != "new") { // Edit existing item if (url === undefined) url = itemid + '/edit'; var item = list.find(itemid, undefined, undefined, conf.max_local_pages); if (!item) { pages.notFound(url); return; } context = $.extend({}, conf, item, context); _addLookups(page, context, true, done); } else { // Create new item context = $.extend({}, conf, params, context); //FIXME: defaults if (url === undefined) { url = 'new'; if (params && $.param(params)) url += '?' + $.param(params); } _addLookups(page, context, "new", done); } function done(context) { var divid = page + '_' + itemid + '-page'; pages.go(conf.url + '/' + url, page + '_edit', context, ui, false, divid); } } // Render non-list pages with with [url] template; // handles requests for [url] and [url]/ function _registerOther(page) { var conf = _getConf(page); pages.register(conf.url, go); pages.register(conf.url + '/', go); function go(match, ui, params) { app.go(page, ui, params); } } function _renderOther(page, ui, params, url, context) { var conf = _getConf(page); if (url === undefined) url = conf.url; context = $.extend({}, conf, params, context); pages.go(url, page, context, ui, conf.once ? true : false); } // Handle form submit from [url]_edit views function _handleForm(evt) { var $form = $(this); if ($form.data('json') !== undefined && $form.data('json') == false) return; // Defer to default (HTML-based) handler var url = $form.attr('action').substring(1); var conf = _getConfByUrl(url); var vals = {}; var $files = $form.find('input[type=file]'); var has_files = ($files.length > 0 && $files.val().length > 0); if (!app['native'] && has_files) { // Files present and we're not running in Cordova. if (window.FormData && window.Blob) // Modern browser; use FormData to upload files via AJAX. // FIXME: localStorage version of outbox item will be unusable. // Can we serialize this object somehow? vals.data = new FormData(this); else // Looks like we're in a an old browser and we can't upload files // via AJAX or Cordova... Bypass store and assume server is // configured to accept regular form posts. return; } else { // No files, or we're running in Cordova. // Use a simple dictionary for values, which is better for outbox // serialization. store will automatically use Cordova FileUpload iff // there is a form field named 'fileupload'. $.each($form.serializeArray(), function(i, v) { vals[v.name] = v.value; }); } // Skip regular form submission, we're saving this via store evt.preventDefault(); vals.url = url; if (url == conf.url + "/" || !conf.list) vals.method = "POST"; // REST API uses POST for new records else vals.method = "PUT"; // .. but PUT to update existing records vals.csrftoken = ds.get('csrftoken'); $('.error').html(''); spin.start(); ds.save(vals, undefined, function(item) { spin.stop(); if (item && item.saved) { // Save was successful var options = {'reverse': true, 'transition': _saveTransition}; if (conf.list) jqm.changePage('/' + conf.url + '/' + item.newid, options); else jqm.changePage('/' + conf.url + '/', options); return; } if (!item || !item.error) { // Save failed for some unknown reason showError("Error saving data."); return; } // REST API provided general error information if (typeof(item.error) === 'string') { showError(item.error); return; } // REST API provided per-field error information var errs = Object.keys(item.error); // General API errors have a single "detail" attribute if (errs.length == 1 && errs[0] == 'detail') { showError(item.error.detail); } else { // Form errors (other than non_field_errors) are keyed by field name for (f in item.error) { // FIXME: there may be multiple errors per field var err = item.error[f][0]; if (f == 'non_field_errors') showError(err); else showError(err, f); } if (!item.error.non_field_errors) showError('One or more errors were found.'); } function showError(err, field) { var sel = '.' + conf.page + '-' + (field ? field + '-' : '') + 'errors'; $form.find(sel).html(err); } }); } // Successful results from REST API contain the newly saved object function _applyResult(item, result) { if (result && result.id) { var conf = _getConfByUrl(item.data.url); item.saved = true; item.newid = result.id; ds.getList({'url': conf.url}, function(list) { var res = $.extend({}, result); for (aname in app.attachmentTypes) _updateAttachments(conf, res, aname); list.update([res], 'id', conf.reversed); }); } else if (app.can_login && result && result.user && result.config) { app.save_login(result); pages.go("login", "login"); } } function _updateAttachments(conf, res, aname) { var info = app.attachmentTypes[aname]; var aconf = _getConf(aname); if (!conf[info.predicate] || !res[aconf.url]) return; var attachments = res[aconf.url]; attachments.forEach(function(a) { a[conf.page + '_id'] = res.id; }); ds.getList({'url': aconf.url}, function(list) { list.update(attachments, 'id'); }); delete res[aconf.url]; } // Add various callback functions to context object to automate foreign key // lookups within templates function _addLookups(page, context, editable, callback) { var conf = _getConf(page); var lookups = {}; $.each(conf.parents || [], function(i, v) { var pconf = _getConf(v); var col; if (v.indexOf(page) == 0) col = v.replace(page, '') + '_id'; else col = v + '_id'; lookups[v] = _parent_lookup(v, col) if (editable) { lookups[v + '_list'] = _parent_dropdown_lookup(v, col); if (pconf.url) lookups[pconf.url] = lookups[v + '_list']; } }); $.each(conf.children || [], function(i, v) { var cconf = _getConf(v); lookups[cconf.url] = _children_lookup(page, v) }); // Load annotations and identifiers for (aname in app.attachmentTypes) { var info = app.attachmentTypes[aname]; var aconf = _getConf(aname); if (!conf[info.predicate]) continue; if (info.type) lookups[info.type] = _parent_lookup(info.type); if (editable == "new") lookups[aconf.url] = _default_attachments(page, aname); else lookups[aconf.url] = _children_lookup(page, aname); } if (conf.related) { lookups['relationships'] = _relationship_lookup(page); lookups['inverserelationships'] = _relationship_lookup(page, true); lookups['relationshiptype'] = _parent_lookup('relationshiptype'); } var queue = []; for (key in lookups) queue.push(key); spin.start(); step(); function step() { if (queue.length == 0) { spin.stop(); callback(context); return; } var key = queue.shift(); lookups[key](context, key, step); } } function _make_lookup(page, fn) { return function(context, key, callback) { var conf = _getConf(page); ds.getList({'url': conf.url}, function(list) { context[key] = fn(list, context); callback(context); }); } } // Simple foreign key lookup function _parent_lookup(page, column) { if (!column) column = page + '_id'; return _make_lookup(page, function(list) { return function() { return list.find(this[column]); } }); } // List of all potential foreign key values (useful for generating dropdowns) function _parent_dropdown_lookup(page, column) { if (!column) column = page + '_id'; return _make_lookup(page, function(list) { return function() { var obj = this; var parents = []; list.forEach(function(v) { var item = $.extend({}, v); if (item.id == obj[column]) item.selected = true; // Currently selected item parents.push(item); }); return parents; }; }); } // List of objects with a foreign key pointing to this one function _children_lookup(ppage, cpage) { return _make_lookup(cpage, function(list) { return function() { var filter = {}; filter[ppage + '_id'] = this.id; return list.filter(filter); } }); } // List of empty annotations for new objects function _default_attachments(ppage, apage) { var info = app.attachmentTypes[apage]; if (!info.type) return []; return _make_lookup(info.type, function(list, context) { var filter = info.getTypeFilter(ppage, context); var types = list.filter(filter); var attachments = []; types.forEach(function(t) { attachments.push({ 'type_id': t.id }); }); return attachments; }); } // List of relationships for this object // (grouped by type) function _relationship_lookup(page, inverse) { var name = inverse ? 'inverserelationship' : 'relationship'; return _make_lookup(name, function(list) { return function() { var filter = {}, groups = {}; filter[page + '_id'] = this.id; list.filter(filter).forEach(function(rel) { if (!groups[rel.type]) groups[rel.type] = { 'type': rel.type, 'list': [] } groups[rel.type].list.push(rel) }); var garray = []; for (group in groups) { garray.push(groups[group]); } return garray; } }); } // Load configuration based on page id function _getConf(page) { var conf = app.config.pages[page]; if (!conf) throw 'Configuration for "' + page + '" not found!'; if (conf.alias) return _getConf(conf.alias); return $.extend({'page': page}, conf); } // Helper to load configuration based on URL function _getConfByUrl(url) { var parts = url.split('/'); var conf; for (var p in app.config.pages) if (app.config.pages[p].url == parts[0]) { conf = $.extend({}, app.config.pages[p]); conf.page = p; } if (!conf) throw 'Configuration for "/' + url + '" not found!'; return conf; } return app; });
js/app.js
/*! * wq.app - app.js * Utilizes store and pages to dynamically load and render * content from a wq.db-compatible REST service * (c) 2012 S. Andrew Sheppard * http://wq.io/license */ define(['./lib/jquery', './lib/jquery.mobile', './store', './pages', './template', './spinner', './lib/es5-shim'], function($, jqm, ds, pages, tmpl, spin) { var app = {}; app.init = function(config, templates, baseurl, svc) { if (baseurl === undefined) baseurl = ''; if (svc === undefined) svc = baseurl; app.config = app.default_config = config; app['native'] = !!window.cordova; app.can_login = !!config.pages.login; ds.init(svc, {'format':'json'}, {'applyResult': _applyResult}); app.service = ds.service; pages.init(baseurl); app.base_url = pages.info.base_url; tmpl.init(templates, templates.partials, config.defaults); tmpl.setDefault('native', app['native']); tmpl.setDefault('app_config', app.config); if (app.can_login) { var user = ds.get('user'); var csrftoken = ds.get('csrftoken'); if (user) { app.user = user; tmpl.setDefault('user', user); tmpl.setDefault('is_authenticated', true); tmpl.setDefault('csrftoken', csrftoken); app.config = ds.get({'url': 'config'}); tmpl.setDefault('app_config', app.config); $('body').trigger('login'); } app.check_login(); pages.register('logout\/?', app.logout); } if (config.transitions) { var def = "default"; if (config.transitions[def]) jqm.defaultPageTransition = config.transitions[def]; if (config.transitions.dialog) jqm.defaultDialogTransition = config.transitions.dialog; if (config.transitions.save) _saveTransition = config.transitions.save; jqm.maxTransitionWidth = config.transitions.maxwidth || 800; } for (var page in app.config.pages) { var conf = _getConf(page); if (conf.list) { _registerList(page); _registerDetail(page); _registerEdit(page); } else if (conf) { _registerOther(page); } } $(document).on('submit', 'form', _handleForm); } app.logout = function() { if (!app.can_login) return; delete app.user; ds.set('user', null); tmpl.setDefault('user', null); tmpl.setDefault('is_authenticated', false); tmpl.setDefault('csrftoken', null); app.config = app.default_config; tmpl.setDefault('app_config', app.config); ds.fetch({'url': 'logout'}, true, undefined, true); $('body').trigger('logout'); }; app.save_login = function(result) { var config = result.config, user = result.user, csrftoken = result.csrftoken; if (!app.can_login) return; app.config = config; ds.set({'url': 'config'}, config); tmpl.setDefault('app_config', config); app.user = user; tmpl.setDefault('user', user); tmpl.setDefault('is_authenticated', true); tmpl.setDefault('csrftoken', csrftoken); ds.set('user', user); ds.set('csrftoken', csrftoken); $('body').trigger('login'); }; app.check_login = function() { if (!app.can_login) return; ds.fetch({'url': 'login'}, true, function(result) { if (result && result.user && result.config) { app.save_login(result); } else if (result && app.user) { app.logout(); } }, true); }; // Internal variables and functions var _saveTransition = "none"; // Wrappers for pages.register & pages.go to handle common use cases // Determine appropriate context & template for pages.go app.go = function(page, ui, params, itemid, edit, url, context) { if (ui && ui.options && ui.options.data) return; // Ignore form actions var conf = _getConf(page); if (!conf.list) { _renderOther(page, ui, params, url, context); return; } spin.start(); ds.getList({'url': conf.url}, function(list) { spin.stop(); if (itemid) { if (edit) _renderEdit(page, list, ui, params, itemid, url, context); else _renderDetail(page, list, ui, params, itemid, url, context); } else { _renderList(page, list, ui, params, url, context); } }); } app.attachmentTypes = { annotation: { 'predicate': 'annotated', 'type': 'annotationtype', 'getTypeFilter': function(page, context) { return {'for': page}; } }, identifier: { 'predicate': 'identified', 'type': 'authority', 'getTypeFilter': function(page, context) { return {}; } }, location: { 'predicate': 'located', 'type': null } }; // Generate list view context and render with [url]_list template; // handles requests for [url] and [url]/ function _registerList(page) { var conf = _getConf(page); pages.register(conf.url, go); pages.register(conf.url + '/', go); function go(match, ui, params) { app.go(page, ui, params); } (conf.parents || []).forEach(function(ppage) { var pconf = _getConf(ppage); var url = pconf.url; if (url) url += '/'; url += '<slug>/' + conf.url; pages.register(url, goUrl(ppage, url)) pages.register(url + '/', goUrl(ppage, url)) }); function goUrl(ppage, url) { return function(match, ui, params) { if (!params) params = {}; if (ppage.indexOf(page) == 0) params[ppage.replace(page, '')] = match[1]; else params[ppage] = match[1]; url = url.replace('<slug>', match[1]); spin.start(); ds.getList({'url': _getConf(ppage).url}, function(plist) { spin.stop(); var pitem = plist.find(match[1]); app.go(page, ui, params, undefined, false, url, { 'parent_id': match[1], 'parent_label': pitem && pitem.label }); }); } } } function _renderList(page, list, ui, params, url, context) { var conf = _getConf(page); var pnum = 1, next = null, prev = null, filter; if (url === undefined) { url = conf.url; if (url) url += '/'; } if (params) { if (url == conf.url || url == conf.url + '/') url += "?" + $.param(params); if (params['page']) { pnum = params['page']; } else { filter = {}; for (var key in params) { filter[key] = params[key]; } (conf.parents || []).forEach(function(p) { if (p.indexOf(page) == 0) p = p.replace(page, ''); if (filter[p]) { filter[p + '_id'] = filter[p]; delete filter[p]; } }); } } if (pnum > conf.max_local_pages) { // Set max_local_pages to avoid filling up local storage and // instead attempt to load HTML directly from the server // (using built-in jQM loader) var jqmurl = '/' + url; spin.start(); jqm.loadPage(jqmurl).then(function() { spin.stop(); $page = $(":jqmData(url='" + jqmurl + "')"); if ($page.length > 0) jqm.changePage($page); else pages.notFound(url); }); return; } var data = filter ? list.filter(filter) : list.page(pnum); if (pnum > 1) { var prevp = {'page': parseInt(pnum) - 1}; prev = conf.url + '/?' + $.param(prevp); } if (pnum < data.info.pages) { var nextp = {'page': parseInt(pnum) + 1}; next = conf.url + '/?' + $.param(nextp); } context = $.extend({}, conf, { 'list': data, 'page': pnum, 'pages': data.info.pages, 'per_page': data.info.per_page, 'total': data.info.total, 'previous': prev ? '/' + prev : null, 'next': next ? '/' + next : null, 'multiple': data.info.pages > 1 }, context); _addLookups(page, context, false, function(context) { pages.go(url, page + '_list', context, ui, conf.once ? true : false); }); } // Generate item detail view context and render with [url]_detail template; // handles requests for [url]/[id] function _registerDetail(page) { var conf = _getConf(page); var url = conf.url; var reserved = ["new"]; if (url) { url += "/"; } else { // This list is bound to the root URL, don't mistake other lists for items for (var key in app.config.pages) reserved.push(app.config.pages[key].url); } pages.register(url + '<slug>', function(match, ui, params) { if (reserved.indexOf(match[1]) > -1) return; app.go(page, ui, params, match[1]); }); } function _renderDetail(page, list, ui, params, itemid, url, context) { var conf = _getConf(page); if (url === undefined) { url = conf.url; if (url) url += '/'; url += itemid; } var item = list.find(itemid, undefined, undefined, conf.max_local_pages); if (!item) { // Item not found in stored list... if (!conf.partial) { // If partial is not set, locally stored list is assumed to // contain the entire dataset, so the item probably does not exist. pages.notFound(url); } else { // Set partial to indicate local list does not represent entire // dataset; if an item is not found will attempt to load HTML // directly from the server (using built-in jQM loader) var jqmurl = '/' + url; spin.start(); jqm.loadPage(jqmurl).then(function() { spin.stop(); $page = $(":jqmData(url='" + jqmurl + "')"); if ($page.length > 0) jqm.changePage($page); else pages.notFound(url); }); } return; } context = $.extend({}, conf, item, context); _addLookups(page, context, false, function(context) { pages.go(url, page + '_detail', context, ui, conf.once ? true : false); }); } // Generate item edit context and render with [url]_edit template; // handles requests for [url]/[id]/edit and [url]/new function _registerEdit(page) { var conf = _getConf(page); pages.register(conf.url + '/<slug>/edit', go); pages.register(conf.url + '/(new)', go); function go(match, ui, params) { app.go(page, ui, params, match[1], true); } } function _renderEdit(page, list, ui, params, itemid, url, context) { var conf = _getConf(page); if (itemid != "new") { // Edit existing item if (url === undefined) url = itemid + '/edit'; var item = list.find(itemid, undefined, undefined, conf.max_local_pages); if (!item) { pages.notFound(url); return; } context = $.extend({}, conf, item, context); _addLookups(page, context, true, done); } else { // Create new item context = $.extend({}, conf, params, context); //FIXME: defaults if (url === undefined) { url = 'new'; if (params && $.param(params)) url += '?' + $.param(params); } _addLookups(page, context, "new", done); } function done(context) { var divid = page + '_' + itemid + '-page'; pages.go(conf.url + '/' + url, page + '_edit', context, ui, false, divid); } } // Render non-list pages with with [url] template; // handles requests for [url] and [url]/ function _registerOther(page) { var conf = _getConf(page); pages.register(conf.url, go); pages.register(conf.url + '/', go); function go(match, ui, params) { app.go(page, ui, params); } } function _renderOther(page, ui, params, url, context) { var conf = _getConf(page); if (url === undefined) url = conf.url; context = $.extend({}, conf, params, context); pages.go(url, page, context, ui, conf.once ? true : false); } // Handle form submit from [url]_edit views function _handleForm(evt) { var $form = $(this); if ($form.data('json') !== undefined && $form.data('json') == false) return; // Defer to default (HTML-based) handler var url = $form.attr('action').substring(1); var conf = _getConfByUrl(url); var vals = {}; var $files = $form.find('input[type=file]'); var has_files = ($files.length > 0 && $files.val().length > 0); if (!app['native'] && has_files) { // Files present and we're not running in Cordova. if (window.FormData && window.Blob) // Modern browser; use FormData to upload files via AJAX. // FIXME: localStorage version of outbox item will be unusable. // Can we serialize this object somehow? vals.data = new FormData(this); else // Looks like we're in a an old browser and we can't upload files // via AJAX or Cordova... Bypass store and assume server is // configured to accept regular form posts. return; } else { // No files, or we're running in Cordova. // Use a simple dictionary for values, which is better for outbox // serialization. store will automatically use Cordova FileUpload iff // there is a form field named 'fileupload'. $.each($form.serializeArray(), function(i, v) { vals[v.name] = v.value; }); } // Skip regular form submission, we're saving this via store evt.preventDefault(); vals.url = url; if (url == conf.url + "/" || !conf.list) vals.method = "POST"; // REST API uses POST for new records else vals.method = "PUT"; // .. but PUT to update existing records vals.csrftoken = ds.get('csrftoken'); $('.error').html(''); spin.start(); ds.save(vals, undefined, function(item) { spin.stop(); if (item && item.saved) { // Save was successful var options = {'reverse': true, 'transition': _saveTransition}; if (conf.list) jqm.changePage('/' + conf.url + '/' + item.newid, options); else jqm.changePage('/' + conf.url + '/', options); return; } if (!item || !item.error) { // Save failed for some unknown reason showError("Error saving data."); return; } // REST API provided general error information if (typeof(item.error) === 'string') { showError(item.error); return; } // REST API provided per-field error information var errs = Object.keys(item.error); // General API errors have a single "detail" attribute if (errs.length == 1 && errs[0] == 'detail') { showError(item.error.detail); } else { // Form errors (other than non_field_errors) are keyed by field name for (f in item.error) { // FIXME: there may be multiple errors per field var err = item.error[f][0]; if (f == 'non_field_errors') showError(err); else showError(err, f); } if (!item.error.non_field_errors) showError('One or more errors were found.'); } function showError(err, field) { var sel = '.' + conf.page + '-' + (field ? field + '-' : '') + 'errors'; $form.find(sel).html(err); } }); } // Successful results from REST API contain the newly saved object function _applyResult(item, result) { if (result && result.id) { var conf = _getConfByUrl(item.data.url); item.saved = true; item.newid = result.id; ds.getList({'url': conf.url}, function(list) { var res = $.extend({}, result); for (aname in app.attachmentTypes) _updateAttachments(conf, res, aname); list.update([res], 'id', conf.reversed); }); } else if (app.can_login && result && result.user && result.config) { app.save_login(result); pages.go("login", "login"); } } function _updateAttachments(conf, res, aname) { var info = app.attachmentTypes[aname]; var aconf = _getConf(aname); if (!conf[info.predicate] || !res[aconf.url]) return; var attachments = res[aconf.url]; attachments.forEach(function(a) { a[conf.page + '_id'] = res.id; }); ds.getList({'url': aconf.url}, function(list) { list.update(attachments, 'id'); }); delete res[aconf.url]; } // Add various callback functions to context object to automate foreign key // lookups within templates function _addLookups(page, context, editable, callback) { var conf = _getConf(page); var lookups = {}; $.each(conf.parents || [], function(i, v) { var pconf = _getConf(v); var col; if (v.indexOf(page) == 0) col = v.replace(page, '') + '_id'; else col = v + '_id'; lookups[v] = _parent_lookup(v, col) if (editable) { lookups[v + '_list'] = _parent_dropdown_lookup(v, col); if (pconf.url) lookups[pconf.url] = lookups[v + '_list']; } }); $.each(conf.children || [], function(i, v) { var cconf = _getConf(v); lookups[cconf.url] = _children_lookup(page, v) }); // Load annotations and identifiers for (aname in app.attachmentTypes) { var info = app.attachmentTypes[aname]; var aconf = _getConf(aname); if (!conf[info.predicate]) continue; if (info.type) lookups[info.type] = _parent_lookup(info.type); if (editable == "new") lookups[aconf.url] = _default_attachments(page, aname); else lookups[aconf.url] = _children_lookup(page, aname); } if (conf.related) { lookups['relationships'] = _relationship_lookup(page); lookups['inverserelationships'] = _relationship_lookup(page, true); lookups['relationshiptype'] = _parent_lookup('relationshiptype'); } var queue = []; for (key in lookups) queue.push(key); spin.start(); step(); function step() { if (queue.length == 0) { spin.stop(); callback(context); return; } var key = queue.shift(); lookups[key](context, key, step); } } function _make_lookup(page, fn) { return function(context, key, callback) { var conf = _getConf(page); ds.getList({'url': conf.url}, function(list) { context[key] = fn(list, context); callback(context); }); } } // Simple foreign key lookup function _parent_lookup(page, column) { if (!column) column = page + '_id'; return _make_lookup(page, function(list) { return function() { return list.find(this[column]); } }); } // List of all potential foreign key values (useful for generating dropdowns) function _parent_dropdown_lookup(page, column) { if (!column) column = page + '_id'; return _make_lookup(page, function(list) { return function() { var obj = this; var parents = []; list.forEach(function(v) { var item = $.extend({}, v); if (item.id == obj[column]) item.selected = true; // Currently selected item parents.push(item); }); return parents; }; }); } // List of objects with a foreign key pointing to this one function _children_lookup(ppage, cpage) { return _make_lookup(cpage, function(list) { return function() { var filter = {}; filter[ppage + '_id'] = this.id; return list.filter(filter); } }); } // List of empty annotations for new objects function _default_attachments(ppage, apage) { var info = app.attachmentTypes[apage]; if (!info.type) return []; return _make_lookup(info.type, function(list, context) { var filter = info.getTypeFilter(ppage, context); var types = list.filter(filter); var attachments = []; types.forEach(function(t) { attachments.push({ 'type_id': t.id }); }); return attachments; }); } // List of relationships for this object // (grouped by type) function _relationship_lookup(page, inverse) { var name = inverse ? 'inverserelationship' : 'relationship'; return _make_lookup(name, function(list) { return function() { var filter = {}, groups = {}; filter[page + '_id'] = this.id; list.filter(filter).forEach(function(rel) { if (!groups[rel.type]) groups[rel.type] = { 'type': rel.type, 'list': [] } groups[rel.type].list.push(rel) }); var garray = []; for (group in groups) { garray.push(groups[group]); } return garray; } }); } // Load configuration based on page id function _getConf(page) { var conf = app.config.pages[page]; if (!conf) throw 'Configuration for "' + page + '" not found!'; if (conf.alias) return _getConf(conf.alias); return $.extend({'page': page}, conf); } // Helper to load configuration based on URL function _getConfByUrl(url) { var parts = url.split('/'); var conf; for (var p in app.config.pages) if (app.config.pages[p].url == parts[0]) { conf = $.extend({}, app.config.pages[p]); conf.page = p; } if (!conf) throw 'Configuration for "/' + url + '" not found!'; return conf; } return app; });
better filtered list handling
js/app.js
better filtered list handling
<ide><path>s/app.js <ide> }); <ide> function goUrl(ppage, url) { <ide> return function(match, ui, params) { <add> var pconf = _getConf(ppage); <ide> if (!params) params = {}; <ide> if (ppage.indexOf(page) == 0) <ide> params[ppage.replace(page, '')] = match[1]; <ide> else <ide> params[ppage] = match[1]; <del> url = url.replace('<slug>', match[1]); <add> var pageurl = url.replace('<slug>', match[1]); <ide> spin.start(); <del> ds.getList({'url': _getConf(ppage).url}, function(plist) { <add> ds.getList({'url': pconf.url}, function(plist) { <ide> spin.stop(); <ide> var pitem = plist.find(match[1]); <del> app.go(page, ui, params, undefined, false, url, { <add> app.go(page, ui, params, undefined, false, pageurl, { <ide> 'parent_id': match[1], <add> 'parent_url': pitem && (pconf.url + '/' + pitem.id), <ide> 'parent_label': pitem && pitem.label <ide> }); <ide> }); <ide> } <ide> } <ide> <del> if (pnum > conf.max_local_pages) { <add> if (pnum > conf.max_local_pages || filter && conf.partial) { <ide> // Set max_local_pages to avoid filling up local storage and <ide> // instead attempt to load HTML directly from the server <ide> // (using built-in jQM loader)
Java
apache-2.0
0c9288ad7368e1f383e2787e6c79fbf5b10665fe
0
stupidnetizen/selenium,mojwang/selenium,alb-i986/selenium,customcommander/selenium,carsonmcdonald/selenium,thanhpete/selenium,Jarob22/selenium,clavery/selenium,bmannix/selenium,jerome-jacob/selenium,gorlemik/selenium,xsyntrex/selenium,knorrium/selenium,zenefits/selenium,Sravyaksr/selenium,carsonmcdonald/selenium,jabbrwcky/selenium,amikey/selenium,bayandin/selenium,blueyed/selenium,clavery/selenium,eric-stanley/selenium,o-schneider/selenium,davehunt/selenium,manuelpirez/selenium,davehunt/selenium,bartolkaruza/selenium,Tom-Trumper/selenium,s2oBCN/selenium,lrowe/selenium,gotcha/selenium,kalyanjvn1/selenium,soundcloud/selenium,Herst/selenium,blackboarddd/selenium,mojwang/selenium,chrisblock/selenium,pulkitsinghal/selenium,gotcha/selenium,i17c/selenium,xmhubj/selenium,gotcha/selenium,asashour/selenium,amikey/selenium,jerome-jacob/selenium,carlosroh/selenium,blackboarddd/selenium,customcommander/selenium,Dude-X/selenium,o-schneider/selenium,AutomatedTester/selenium,tbeadle/selenium,kalyanjvn1/selenium,pulkitsinghal/selenium,SouWilliams/selenium,o-schneider/selenium,GorK-ChO/selenium,rrussell39/selenium,joshmgrant/selenium,krmahadevan/selenium,krosenvold/selenium,Appdynamics/selenium,sevaseva/selenium,dibagga/selenium,gregerrag/selenium,tbeadle/selenium,wambat/selenium,slongwang/selenium,dcjohnson1989/selenium,Dude-X/selenium,MCGallaspy/selenium,dbo/selenium,lrowe/selenium,denis-vilyuzhanin/selenium-fastview,rovner/selenium,pulkitsinghal/selenium,wambat/selenium,dcjohnson1989/selenium,valfirst/selenium,joshbruning/selenium,skurochkin/selenium,juangj/selenium,gabrielsimas/selenium,HtmlUnit/selenium,i17c/selenium,HtmlUnit/selenium,carlosroh/selenium,AutomatedTester/selenium,BlackSmith/selenium,asolntsev/selenium,BlackSmith/selenium,asashour/selenium,doungni/selenium,bartolkaruza/selenium,mach6/selenium,meksh/selenium,dcjohnson1989/selenium,Herst/selenium,alb-i986/selenium,bartolkaruza/selenium,MCGallaspy/selenium,rplevka/selenium,SeleniumHQ/selenium,tkurnosova/selenium,amar-sharma/selenium,lilredindy/selenium,gorlemik/selenium,gorlemik/selenium,clavery/selenium,oddui/selenium,rovner/selenium,rovner/selenium,titusfortner/selenium,houchj/selenium,dibagga/selenium,houchj/selenium,jsakamoto/selenium,HtmlUnit/selenium,denis-vilyuzhanin/selenium-fastview,JosephCastro/selenium,dimacus/selenium,gemini-testing/selenium,denis-vilyuzhanin/selenium-fastview,clavery/selenium,yukaReal/selenium,Tom-Trumper/selenium,tarlabs/selenium,petruc/selenium,stupidnetizen/selenium,gabrielsimas/selenium,gorlemik/selenium,amar-sharma/selenium,rrussell39/selenium,amikey/selenium,gregerrag/selenium,AutomatedTester/selenium,bayandin/selenium,Appdynamics/selenium,o-schneider/selenium,customcommander/selenium,lilredindy/selenium,TikhomirovSergey/selenium,misttechnologies/selenium,joshuaduffy/selenium,krmahadevan/selenium,s2oBCN/selenium,mestihudson/selenium,Tom-Trumper/selenium,rovner/selenium,vveliev/selenium,joshuaduffy/selenium,doungni/selenium,sankha93/selenium,titusfortner/selenium,SouWilliams/selenium,juangj/selenium,HtmlUnit/selenium,HtmlUnit/selenium,sankha93/selenium,titusfortner/selenium,AutomatedTester/selenium,bayandin/selenium,skurochkin/selenium,jabbrwcky/selenium,bmannix/selenium,meksh/selenium,rrussell39/selenium,zenefits/selenium,petruc/selenium,valfirst/selenium,joshmgrant/selenium,wambat/selenium,mach6/selenium,slongwang/selenium,skurochkin/selenium,tbeadle/selenium,dandv/selenium,Dude-X/selenium,minhthuanit/selenium,arunsingh/selenium,carsonmcdonald/selenium,TheBlackTuxCorp/selenium,joshbruning/selenium,titusfortner/selenium,sri85/selenium,MCGallaspy/selenium,minhthuanit/selenium,i17c/selenium,jerome-jacob/selenium,joshuaduffy/selenium,bayandin/selenium,pulkitsinghal/selenium,anshumanchatterji/selenium,chrisblock/selenium,AutomatedTester/selenium,GorK-ChO/selenium,GorK-ChO/selenium,Dude-X/selenium,SeleniumHQ/selenium,krmahadevan/selenium,oddui/selenium,gurayinan/selenium,mach6/selenium,manuelpirez/selenium,p0deje/selenium,lukeis/selenium,AutomatedTester/selenium,krmahadevan/selenium,oddui/selenium,dimacus/selenium,dbo/selenium,juangj/selenium,yukaReal/selenium,Herst/selenium,markodolancic/selenium,SeleniumHQ/selenium,doungni/selenium,lrowe/selenium,tarlabs/selenium,Ardesco/selenium,gregerrag/selenium,eric-stanley/selenium,MeetMe/selenium,lmtierney/selenium,Sravyaksr/selenium,chrisblock/selenium,xsyntrex/selenium,JosephCastro/selenium,xmhubj/selenium,tkurnosova/selenium,bayandin/selenium,twalpole/selenium,Ardesco/selenium,misttechnologies/selenium,asashour/selenium,dimacus/selenium,denis-vilyuzhanin/selenium-fastview,doungni/selenium,knorrium/selenium,TikhomirovSergey/selenium,alb-i986/selenium,o-schneider/selenium,dbo/selenium,GorK-ChO/selenium,quoideneuf/selenium,quoideneuf/selenium,davehunt/selenium,sag-enorman/selenium,mojwang/selenium,markodolancic/selenium,anshumanchatterji/selenium,DrMarcII/selenium,SouWilliams/selenium,soundcloud/selenium,asolntsev/selenium,quoideneuf/selenium,tarlabs/selenium,arunsingh/selenium,twalpole/selenium,stupidnetizen/selenium,gregerrag/selenium,lilredindy/selenium,amar-sharma/selenium,juangj/selenium,dibagga/selenium,lmtierney/selenium,asashour/selenium,gorlemik/selenium,jsakamoto/selenium,houchj/selenium,SouWilliams/selenium,blackboarddd/selenium,lukeis/selenium,amikey/selenium,soundcloud/selenium,joshmgrant/selenium,uchida/selenium,petruc/selenium,Ardesco/selenium,BlackSmith/selenium,rrussell39/selenium,davehunt/selenium,joshbruning/selenium,gurayinan/selenium,anshumanchatterji/selenium,Sravyaksr/selenium,eric-stanley/selenium,krmahadevan/selenium,joshuaduffy/selenium,Jarob22/selenium,lukeis/selenium,arunsingh/selenium,MeetMe/selenium,soundcloud/selenium,dandv/selenium,bartolkaruza/selenium,HtmlUnit/selenium,jerome-jacob/selenium,5hawnknight/selenium,valfirst/selenium,misttechnologies/selenium,mojwang/selenium,JosephCastro/selenium,blackboarddd/selenium,dbo/selenium,dkentw/selenium,blackboarddd/selenium,dimacus/selenium,SeleniumHQ/selenium,carlosroh/selenium,jabbrwcky/selenium,skurochkin/selenium,stupidnetizen/selenium,actmd/selenium,soundcloud/selenium,dkentw/selenium,amikey/selenium,dandv/selenium,gregerrag/selenium,misttechnologies/selenium,jabbrwcky/selenium,valfirst/selenium,gotcha/selenium,Herst/selenium,markodolancic/selenium,wambat/selenium,soundcloud/selenium,thanhpete/selenium,uchida/selenium,DrMarcII/selenium,lrowe/selenium,tkurnosova/selenium,Dude-X/selenium,tkurnosova/selenium,xsyntrex/selenium,bayandin/selenium,dkentw/selenium,sri85/selenium,vveliev/selenium,jabbrwcky/selenium,tarlabs/selenium,amar-sharma/selenium,alexec/selenium,i17c/selenium,alexec/selenium,customcommander/selenium,mach6/selenium,quoideneuf/selenium,Jarob22/selenium,dbo/selenium,rplevka/selenium,sag-enorman/selenium,chrisblock/selenium,JosephCastro/selenium,asolntsev/selenium,gorlemik/selenium,5hawnknight/selenium,jsakamoto/selenium,manuelpirez/selenium,gemini-testing/selenium,asolntsev/selenium,uchida/selenium,amar-sharma/selenium,houchj/selenium,sri85/selenium,joshbruning/selenium,soundcloud/selenium,doungni/selenium,twalpole/selenium,i17c/selenium,mojwang/selenium,jsakamoto/selenium,slongwang/selenium,yukaReal/selenium,misttechnologies/selenium,lilredindy/selenium,customcommander/selenium,joshbruning/selenium,HtmlUnit/selenium,dimacus/selenium,blackboarddd/selenium,kalyanjvn1/selenium,gurayinan/selenium,chrisblock/selenium,sankha93/selenium,DrMarcII/selenium,lilredindy/selenium,sankha93/selenium,sag-enorman/selenium,sevaseva/selenium,dibagga/selenium,dibagga/selenium,xmhubj/selenium,oddui/selenium,kalyanjvn1/selenium,meksh/selenium,petruc/selenium,anshumanchatterji/selenium,yukaReal/selenium,arunsingh/selenium,dkentw/selenium,sri85/selenium,dbo/selenium,dcjohnson1989/selenium,markodolancic/selenium,blueyed/selenium,sri85/selenium,arunsingh/selenium,sag-enorman/selenium,wambat/selenium,Ardesco/selenium,davehunt/selenium,oddui/selenium,juangj/selenium,houchj/selenium,manuelpirez/selenium,GorK-ChO/selenium,jsakamoto/selenium,uchida/selenium,markodolancic/selenium,bmannix/selenium,tarlabs/selenium,DrMarcII/selenium,tarlabs/selenium,anshumanchatterji/selenium,asolntsev/selenium,quoideneuf/selenium,tkurnosova/selenium,xmhubj/selenium,s2oBCN/selenium,actmd/selenium,xsyntrex/selenium,soundcloud/selenium,markodolancic/selenium,MeetMe/selenium,mestihudson/selenium,SeleniumHQ/selenium,HtmlUnit/selenium,gregerrag/selenium,MCGallaspy/selenium,rplevka/selenium,sankha93/selenium,GorK-ChO/selenium,gemini-testing/selenium,sankha93/selenium,rplevka/selenium,dibagga/selenium,jerome-jacob/selenium,carsonmcdonald/selenium,markodolancic/selenium,eric-stanley/selenium,titusfortner/selenium,denis-vilyuzhanin/selenium-fastview,i17c/selenium,arunsingh/selenium,jerome-jacob/selenium,alb-i986/selenium,xmhubj/selenium,Sravyaksr/selenium,carlosroh/selenium,knorrium/selenium,thanhpete/selenium,carsonmcdonald/selenium,krmahadevan/selenium,sevaseva/selenium,mach6/selenium,SeleniumHQ/selenium,gregerrag/selenium,titusfortner/selenium,alexec/selenium,SouWilliams/selenium,arunsingh/selenium,TheBlackTuxCorp/selenium,p0deje/selenium,krosenvold/selenium,houchj/selenium,manuelpirez/selenium,joshbruning/selenium,Appdynamics/selenium,stupidnetizen/selenium,joshmgrant/selenium,bartolkaruza/selenium,pulkitsinghal/selenium,petruc/selenium,mestihudson/selenium,customcommander/selenium,Sravyaksr/selenium,clavery/selenium,krosenvold/selenium,MCGallaspy/selenium,Sravyaksr/selenium,uchida/selenium,tkurnosova/selenium,juangj/selenium,Dude-X/selenium,gurayinan/selenium,AutomatedTester/selenium,joshmgrant/selenium,SouWilliams/selenium,actmd/selenium,petruc/selenium,lilredindy/selenium,carsonmcdonald/selenium,dkentw/selenium,knorrium/selenium,SouWilliams/selenium,BlackSmith/selenium,bartolkaruza/selenium,juangj/selenium,GorK-ChO/selenium,joshmgrant/selenium,rplevka/selenium,blueyed/selenium,customcommander/selenium,p0deje/selenium,thanhpete/selenium,yukaReal/selenium,Appdynamics/selenium,Ardesco/selenium,zenefits/selenium,gabrielsimas/selenium,joshuaduffy/selenium,thanhpete/selenium,yukaReal/selenium,MeetMe/selenium,actmd/selenium,denis-vilyuzhanin/selenium-fastview,zenefits/selenium,misttechnologies/selenium,lrowe/selenium,bartolkaruza/selenium,rrussell39/selenium,jsakamoto/selenium,gemini-testing/selenium,uchida/selenium,MeetMe/selenium,Dude-X/selenium,sri85/selenium,skurochkin/selenium,amikey/selenium,AutomatedTester/selenium,mojwang/selenium,doungni/selenium,joshuaduffy/selenium,s2oBCN/selenium,valfirst/selenium,s2oBCN/selenium,rrussell39/selenium,lukeis/selenium,clavery/selenium,DrMarcII/selenium,eric-stanley/selenium,vveliev/selenium,twalpole/selenium,valfirst/selenium,twalpole/selenium,TheBlackTuxCorp/selenium,lilredindy/selenium,oddui/selenium,TheBlackTuxCorp/selenium,vveliev/selenium,carsonmcdonald/selenium,carsonmcdonald/selenium,stupidnetizen/selenium,5hawnknight/selenium,tbeadle/selenium,actmd/selenium,o-schneider/selenium,TheBlackTuxCorp/selenium,o-schneider/selenium,dcjohnson1989/selenium,AutomatedTester/selenium,TheBlackTuxCorp/selenium,gorlemik/selenium,rovner/selenium,eric-stanley/selenium,asolntsev/selenium,gregerrag/selenium,zenefits/selenium,o-schneider/selenium,dbo/selenium,bayandin/selenium,jabbrwcky/selenium,mestihudson/selenium,eric-stanley/selenium,customcommander/selenium,rplevka/selenium,chrisblock/selenium,tkurnosova/selenium,alexec/selenium,slongwang/selenium,minhthuanit/selenium,markodolancic/selenium,blueyed/selenium,stupidnetizen/selenium,TheBlackTuxCorp/selenium,MeetMe/selenium,dbo/selenium,BlackSmith/selenium,gemini-testing/selenium,actmd/selenium,slongwang/selenium,clavery/selenium,gabrielsimas/selenium,DrMarcII/selenium,manuelpirez/selenium,amar-sharma/selenium,davehunt/selenium,carlosroh/selenium,denis-vilyuzhanin/selenium-fastview,rovner/selenium,alexec/selenium,manuelpirez/selenium,Tom-Trumper/selenium,slongwang/selenium,quoideneuf/selenium,titusfortner/selenium,clavery/selenium,TikhomirovSergey/selenium,Herst/selenium,mestihudson/selenium,Herst/selenium,alb-i986/selenium,blackboarddd/selenium,dimacus/selenium,BlackSmith/selenium,gorlemik/selenium,kalyanjvn1/selenium,oddui/selenium,anshumanchatterji/selenium,joshuaduffy/selenium,5hawnknight/selenium,bmannix/selenium,lilredindy/selenium,chrisblock/selenium,rrussell39/selenium,kalyanjvn1/selenium,alb-i986/selenium,lukeis/selenium,lmtierney/selenium,blackboarddd/selenium,titusfortner/selenium,i17c/selenium,sag-enorman/selenium,chrisblock/selenium,jerome-jacob/selenium,p0deje/selenium,twalpole/selenium,mestihudson/selenium,Dude-X/selenium,meksh/selenium,jerome-jacob/selenium,xsyntrex/selenium,SouWilliams/selenium,asolntsev/selenium,slongwang/selenium,joshuaduffy/selenium,tbeadle/selenium,BlackSmith/selenium,titusfortner/selenium,JosephCastro/selenium,asolntsev/selenium,joshmgrant/selenium,dkentw/selenium,asashour/selenium,Sravyaksr/selenium,i17c/selenium,tbeadle/selenium,misttechnologies/selenium,houchj/selenium,wambat/selenium,minhthuanit/selenium,jsakamoto/selenium,Appdynamics/selenium,lrowe/selenium,blueyed/selenium,chrisblock/selenium,TikhomirovSergey/selenium,p0deje/selenium,gotcha/selenium,5hawnknight/selenium,tbeadle/selenium,slongwang/selenium,davehunt/selenium,lmtierney/selenium,bayandin/selenium,vveliev/selenium,blackboarddd/selenium,dandv/selenium,blueyed/selenium,rplevka/selenium,Jarob22/selenium,xmhubj/selenium,thanhpete/selenium,gabrielsimas/selenium,zenefits/selenium,gabrielsimas/selenium,skurochkin/selenium,minhthuanit/selenium,MeetMe/selenium,lmtierney/selenium,Appdynamics/selenium,mestihudson/selenium,customcommander/selenium,kalyanjvn1/selenium,joshmgrant/selenium,krosenvold/selenium,carlosroh/selenium,blueyed/selenium,vveliev/selenium,yukaReal/selenium,doungni/selenium,sri85/selenium,alb-i986/selenium,krosenvold/selenium,amikey/selenium,dandv/selenium,Jarob22/selenium,SeleniumHQ/selenium,Herst/selenium,krosenvold/selenium,dandv/selenium,SeleniumHQ/selenium,xmhubj/selenium,xmhubj/selenium,dibagga/selenium,bartolkaruza/selenium,jabbrwcky/selenium,gemini-testing/selenium,JosephCastro/selenium,mojwang/selenium,valfirst/selenium,sevaseva/selenium,p0deje/selenium,xmhubj/selenium,JosephCastro/selenium,gemini-testing/selenium,gabrielsimas/selenium,lmtierney/selenium,TheBlackTuxCorp/selenium,titusfortner/selenium,TikhomirovSergey/selenium,lilredindy/selenium,MeetMe/selenium,rrussell39/selenium,mestihudson/selenium,lmtierney/selenium,5hawnknight/selenium,Appdynamics/selenium,dcjohnson1989/selenium,dimacus/selenium,joshbruning/selenium,sevaseva/selenium,rovner/selenium,gabrielsimas/selenium,DrMarcII/selenium,dimacus/selenium,GorK-ChO/selenium,bmannix/selenium,sevaseva/selenium,p0deje/selenium,minhthuanit/selenium,mojwang/selenium,dcjohnson1989/selenium,asashour/selenium,BlackSmith/selenium,mestihudson/selenium,krosenvold/selenium,eric-stanley/selenium,lrowe/selenium,Ardesco/selenium,dkentw/selenium,xsyntrex/selenium,asolntsev/selenium,amar-sharma/selenium,clavery/selenium,bmannix/selenium,dibagga/selenium,valfirst/selenium,gabrielsimas/selenium,stupidnetizen/selenium,mach6/selenium,bmannix/selenium,juangj/selenium,Appdynamics/selenium,tbeadle/selenium,p0deje/selenium,Ardesco/selenium,DrMarcII/selenium,gotcha/selenium,SeleniumHQ/selenium,rplevka/selenium,davehunt/selenium,dandv/selenium,davehunt/selenium,SouWilliams/selenium,yukaReal/selenium,s2oBCN/selenium,slongwang/selenium,joshmgrant/selenium,joshuaduffy/selenium,gurayinan/selenium,5hawnknight/selenium,sankha93/selenium,Dude-X/selenium,Tom-Trumper/selenium,o-schneider/selenium,quoideneuf/selenium,lrowe/selenium,asashour/selenium,pulkitsinghal/selenium,asashour/selenium,SeleniumHQ/selenium,meksh/selenium,xsyntrex/selenium,twalpole/selenium,sri85/selenium,misttechnologies/selenium,minhthuanit/selenium,carsonmcdonald/selenium,blueyed/selenium,joshbruning/selenium,dandv/selenium,gregerrag/selenium,uchida/selenium,pulkitsinghal/selenium,alexec/selenium,bartolkaruza/selenium,Sravyaksr/selenium,sri85/selenium,jsakamoto/selenium,knorrium/selenium,sag-enorman/selenium,mojwang/selenium,s2oBCN/selenium,vveliev/selenium,5hawnknight/selenium,xsyntrex/selenium,markodolancic/selenium,arunsingh/selenium,i17c/selenium,houchj/selenium,Sravyaksr/selenium,zenefits/selenium,dimacus/selenium,zenefits/selenium,wambat/selenium,denis-vilyuzhanin/selenium-fastview,bmannix/selenium,tarlabs/selenium,gurayinan/selenium,JosephCastro/selenium,Jarob22/selenium,thanhpete/selenium,dandv/selenium,alexec/selenium,rrussell39/selenium,gemini-testing/selenium,joshbruning/selenium,denis-vilyuzhanin/selenium-fastview,soundcloud/selenium,skurochkin/selenium,JosephCastro/selenium,twalpole/selenium,TikhomirovSergey/selenium,amikey/selenium,amar-sharma/selenium,oddui/selenium,Tom-Trumper/selenium,Appdynamics/selenium,sankha93/selenium,Herst/selenium,bayandin/selenium,xsyntrex/selenium,joshmgrant/selenium,p0deje/selenium,kalyanjvn1/selenium,doungni/selenium,alexec/selenium,knorrium/selenium,BlackSmith/selenium,tarlabs/selenium,krmahadevan/selenium,thanhpete/selenium,vveliev/selenium,jsakamoto/selenium,dibagga/selenium,krosenvold/selenium,Jarob22/selenium,mach6/selenium,gorlemik/selenium,dcjohnson1989/selenium,quoideneuf/selenium,knorrium/selenium,manuelpirez/selenium,tkurnosova/selenium,wambat/selenium,lukeis/selenium,sevaseva/selenium,tarlabs/selenium,houchj/selenium,MCGallaspy/selenium,gotcha/selenium,Jarob22/selenium,actmd/selenium,titusfortner/selenium,lrowe/selenium,sag-enorman/selenium,bmannix/selenium,knorrium/selenium,lukeis/selenium,petruc/selenium,gurayinan/selenium,yukaReal/selenium,Ardesco/selenium,misttechnologies/selenium,rovner/selenium,blueyed/selenium,DrMarcII/selenium,TikhomirovSergey/selenium,petruc/selenium,knorrium/selenium,quoideneuf/selenium,gurayinan/selenium,mach6/selenium,carlosroh/selenium,asashour/selenium,manuelpirez/selenium,rplevka/selenium,Herst/selenium,twalpole/selenium,sankha93/selenium,valfirst/selenium,arunsingh/selenium,dkentw/selenium,alexec/selenium,lmtierney/selenium,gotcha/selenium,meksh/selenium,carlosroh/selenium,amar-sharma/selenium,petruc/selenium,jabbrwcky/selenium,meksh/selenium,krosenvold/selenium,alb-i986/selenium,alb-i986/selenium,tbeadle/selenium,lukeis/selenium,minhthuanit/selenium,eric-stanley/selenium,dkentw/selenium,s2oBCN/selenium,TikhomirovSergey/selenium,s2oBCN/selenium,anshumanchatterji/selenium,actmd/selenium,HtmlUnit/selenium,lmtierney/selenium,actmd/selenium,lukeis/selenium,dcjohnson1989/selenium,TheBlackTuxCorp/selenium,jerome-jacob/selenium,rovner/selenium,sevaseva/selenium,TikhomirovSergey/selenium,tkurnosova/selenium,doungni/selenium,dbo/selenium,pulkitsinghal/selenium,MCGallaspy/selenium,joshmgrant/selenium,uchida/selenium,krmahadevan/selenium,Tom-Trumper/selenium,meksh/selenium,stupidnetizen/selenium,sag-enorman/selenium,meksh/selenium,MeetMe/selenium,thanhpete/selenium,skurochkin/selenium,amikey/selenium,Tom-Trumper/selenium,vveliev/selenium,sevaseva/selenium,gotcha/selenium,MCGallaspy/selenium,wambat/selenium,gemini-testing/selenium,oddui/selenium,krmahadevan/selenium,GorK-ChO/selenium,Ardesco/selenium,SeleniumHQ/selenium,zenefits/selenium,valfirst/selenium,HtmlUnit/selenium,gurayinan/selenium,minhthuanit/selenium,sag-enorman/selenium,juangj/selenium,Jarob22/selenium,skurochkin/selenium,carlosroh/selenium,jabbrwcky/selenium,kalyanjvn1/selenium,uchida/selenium,anshumanchatterji/selenium,MCGallaspy/selenium,5hawnknight/selenium,valfirst/selenium,anshumanchatterji/selenium,pulkitsinghal/selenium,mach6/selenium,Tom-Trumper/selenium
/* Copyright 2015 Software Freedom Conservancy Copyright 2009-2015 Selenium committers 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.openqa.selenium; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.JUnit4TestBase; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Ignore.Driver.CHROME; import static org.openqa.selenium.testing.Ignore.Driver.FIREFOX; import static org.openqa.selenium.testing.Ignore.Driver.IE; import static org.openqa.selenium.testing.Ignore.Driver.MARIONETTE; import static org.openqa.selenium.testing.Ignore.Driver.PHANTOMJS; import static org.openqa.selenium.testing.Ignore.Driver.SAFARI; import com.google.common.collect.Sets; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import javax.imageio.ImageIO; /** * Test screenshot feature. * * 1. check output for all possible types * * 2. check screenshot image * * Logic of screenshot check test is simple: * - open page with fixed amount of fixed sized and coloured areas * - take screenshot * - calculate expected colors as in tested HTML page * - scan screenshot for actual colors * compare * */ // TODO(user): verify expected behaviour after frame switching // TODO(user): test screenshots at guaranteed maximized browsers // TODO(user): test screenshots at guaranteed non maximized browsers // TODO(user): test screenshots at guaranteed minimized browsers // TODO(user): test screenshots at guaranteed fullscreened/kiosked browsers (WINDOWS platform specific) @Ignore(value = {IE}, reason = "IE: strange colors appeared") public class TakesScreenshotTest extends JUnit4TestBase { private TakesScreenshot screenshoter; private File tempFile = null; @Before public void setUp() throws Exception { assumeTrue(driver instanceof TakesScreenshot); screenshoter = (TakesScreenshot) driver; } @After public void tearDown() { if (tempFile != null) { tempFile.delete(); tempFile = null; } } @Test @Ignore(MARIONETTE) public void testGetScreenshotAsFile() throws Exception { driver.get(pages.simpleTestPage); tempFile = screenshoter.getScreenshotAs(OutputType.FILE); assertTrue(tempFile.exists()); assertTrue(tempFile.length() > 0); } @Test public void testGetScreenshotAsBase64() throws Exception { driver.get(pages.simpleTestPage); String screenshot = screenshoter.getScreenshotAs(OutputType.BASE64); assertTrue(screenshot.length() > 0); } @Test public void testGetScreenshotAsBinary() throws Exception { driver.get(pages.simpleTestPage); byte[] screenshot = screenshoter.getScreenshotAs(OutputType.BYTES); assertTrue(screenshot.length > 0); } @Test public void testShouldCaptureScreenshotOfCurrentViewport() throws Exception { driver.get(appServer.whereIs("screen/screen.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step */ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore(value = {SAFARI, CHROME, MARIONETTE}, reason = " SAFARI: takes only visible viewport." + " CHROME: takes only visible viewport.") public void testShouldCaptureScreenshotOfPageWithLongX() throws Exception { driver.get(appServer.whereIs("screen/screen_x_long.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 50, /* stepY in pixels */ 5); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore(value = {SAFARI, CHROME, MARIONETTE}, reason = " SAFARI: takes only visible viewport." + " CHROME: takes only visible viewport.") public void testShouldCaptureScreenshotOfPageWithLongY() throws Exception { driver.get(appServer.whereIs("screen/screen_y_long.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 50); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore(value = {PHANTOMJS, SAFARI, CHROME, IE, FIREFOX, MARIONETTE}, reason = " IE: cuts captured image at driver level." + " FF: captured image is cat at driver level." + " SAFARI: takes only visible viewport." + " CHROME: takes only visible viewport." + " PHANTOMJS: diffs at colors - small dimensions or coloring problem.") public void testShouldCaptureScreenshotOfPageWithTooLongX() throws Exception { driver.get(appServer.whereIs("screen/screen_x_too_long.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 5); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore(value = {PHANTOMJS, SAFARI, CHROME, IE, FIREFOX, MARIONETTE}, reason = " IE: cuts captured image at driver level." + " FF: captured image is cat at driver level." + " SAFARI: takes only visible viewport." + " CHROME: takes only visible viewport." + " PHANTOMJS: diffs at colors - small dimensions or coloring problem.") public void testShouldCaptureScreenshotOfPageWithTooLongY() throws Exception { driver.get(appServer.whereIs("screen/screen_y_too_long.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 100); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore(value = {PHANTOMJS, SAFARI, CHROME, IE, FIREFOX, MARIONETTE}, reason = " IE: returns null." + " FF: failed due NS_ERROR_FAILURE at context.drawWindow." + " SAFARI: takes only visible viewport." + " CHROME: takes only visible viewport." + " PHANTOMJS: takes empty data of byte[], no errors. ") public void testShouldCaptureScreenshotOfPageWithTooLongXandY() throws Exception { driver.get(appServer.whereIs("screen/screen_too_long.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 100); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore( value = {IE, MARIONETTE}, reason = " IE: v9 shows strange border which broke color comparison" ) public void testShouldCaptureScreenshotAtFramePage() throws Exception { driver.get(appServer.whereIs("screen/screen_frames.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); Set<String> expectedColors = new HashSet<String>(); expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames will be taken for full page compareColors(expectedColors, actualColors); } @Test @Ignore(value = {CHROME, MARIONETTE}, reason = " CHROME: Unknown actual colors are presented at screenshot") public void testShouldCaptureScreenshotAtIFramePage() throws Exception { driver.get(appServer.whereIs("screen/screen_iframes.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); Set<String> expectedColors = new HashSet<String>(); expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes will be taken for full page compareColors(expectedColors, actualColors); } @Test @Ignore( value = {IE, MARIONETTE}, reason = "IE: v9 shows strange border which broke color comparison" ) public void testShouldCaptureScreenshotAtFramePageAfterSwitching() throws Exception { driver.get(appServer.whereIs("screen/screen_frames.html")); driver.switchTo().frame(driver.findElement(By.id("frame2"))); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); Set<String> expectedColors = new HashSet<String>(); expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames after switching to a frame // will be taken for full page compareColors(expectedColors, actualColors); } @Test @Ignore( value = {IE, CHROME, MARIONETTE}, reason = " IE: v9 takes screesnhot only of switched-in frame area " + " CHROME: Unknown actual colors are presented at screenshot" ) public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() throws Exception { driver.get(appServer.whereIs("screen/screen_iframes.html")); driver.switchTo().frame(driver.findElement(By.id("iframe2"))); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); Set<String> expectedColors = new HashSet<String>(); expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes after switching to a Iframe // will be taken for full page compareColors(expectedColors, actualColors); } /** * get actual image screenshot * * @return Image object */ private BufferedImage getImage() { BufferedImage image = null; try { byte[] imageData = screenshoter.getScreenshotAs(OutputType.BYTES); assertTrue(imageData != null); assertTrue(imageData.length > 0); image = ImageIO.read(new ByteArrayInputStream(imageData)); assertTrue(image != null); } catch (IOException e) { fail("Image screenshot file is invalid: " + e.getMessage()); } //saveImageToTmpFile(image); return image; } /** * generate expected colors as in checked page. * * @param initialColor - initial color of first (right top) cell of grid * @param stepColor - step b/w grid colors as number * @param nX - grid size at X dimension * @param nY - grid size at Y dimension * @return set of colors in string hex presentation */ private Set<String> generateExpectedColors(final int initialColor, final int stepColor, final int nX, final int nY) { Set<String> colors = new TreeSet<String>(); int cnt = 1; for (int i = 1; i < nX; i++) { for (int j = 1; j < nY; j++) { int color = initialColor + (cnt * stepColor); String hex = String.format("#%02x%02x%02x", ((color & 0xFF0000) >> 16), ((color & 0x00FF00) >> 8), ((color & 0x0000FF))); colors.add(hex); cnt++; } } return colors; } /** * Get colors from image from each point at grid defined by stepX/stepY. * * @param image - image * @param stepX - interval in pixels b/w point in X dimension * @param stepY - interval in pixels b/w point in Y dimension * @return set of colors in string hex presentation */ private Set<String> scanActualColors(BufferedImage image, final int stepX, final int stepY) { Set<String> colors = new TreeSet<String>(); try { int height = image.getHeight(); int width = image.getWidth(); assertTrue(width > 0); assertTrue(height > 0); Raster raster = image.getRaster(); for (int i = 0; i < width; i = i + stepX) { for (int j = 0; j < height; j = j + stepY) { String hex = String.format("#%02x%02x%02x", (raster.getSample(i, j, 0)), (raster.getSample(i, j, 1)), (raster.getSample(i, j, 2))); colors.add(hex); } } } catch (Exception e) { fail("Unable to get actual colors from screenshot: " + e.getMessage()); } assertTrue(colors.size() > 0); return colors; } /** * Compares sets of colors are same. * * @param expectedColors - set of expected colors * @param actualColors - set of actual colors */ private void compareColors(Set<String> expectedColors, Set<String> actualColors) { assertFalse("Actual image has only black color", onlyBlack(actualColors)); assertFalse("Actual image has only white color", onlyWhite(actualColors)); // Ignore black and white for further comparison Set<String> cleanActualColors = Sets.newHashSet(actualColors); cleanActualColors.remove("#000000"); cleanActualColors.remove("#ffffff"); if (! expectedColors.containsAll(cleanActualColors)) { fail("There are unexpected colors on the screenshot: " + Sets.difference(cleanActualColors, expectedColors)); } if (! cleanActualColors.containsAll(expectedColors)) { fail("There are expected colors not present on the screenshot: " + Sets.difference(expectedColors, cleanActualColors)); } } private boolean onlyBlack(Set<String> colors) { return colors.size() == 1 && "#000000".equals(colors.toArray()[0]); } private boolean onlyWhite(Set<String> colors) { return colors.size() == 1 && "#ffffff".equals(colors.toArray()[0]); } /** * Simple helper to save screenshot to tmp file. For debug purposes. * * @param im image */ private void saveImageToTmpFile(BufferedImage im) { File outputfile = new File( testName.getMethodName() + "_image.png"); System.out.println("Image file is at " + outputfile.getAbsolutePath()); System.out.println("Sizes -> " + im.getWidth() + "x" + im.getHeight()); try { ImageIO.write(im, "png", outputfile); } catch (IOException e) { fail("Unable to write image to file: " + e.getMessage()); } } }
java/client/test/org/openqa/selenium/TakesScreenshotTest.java
/* Copyright 2015 Software Freedom Conservancy Copyright 2009-2015 Selenium committers 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.openqa.selenium; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.testing.Ignore; import org.openqa.selenium.testing.JUnit4TestBase; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; import static org.openqa.selenium.testing.Ignore.Driver.CHROME; import static org.openqa.selenium.testing.Ignore.Driver.FIREFOX; import static org.openqa.selenium.testing.Ignore.Driver.IE; import static org.openqa.selenium.testing.Ignore.Driver.MARIONETTE; import static org.openqa.selenium.testing.Ignore.Driver.PHANTOMJS; import static org.openqa.selenium.testing.Ignore.Driver.SAFARI; import com.google.common.collect.Sets; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import javax.imageio.ImageIO; /** * Test screenshot feature. * * 1. check output for all possible types * * 2. check screenshot image * * Logic of screenshot check test is simple: * - open page with fixed amount of fixed sized and coloured areas * - take screenshot * - calculate expected colors as in tested HTML page * - scan screenshot for actual colors * compare * */ // TODO(user): verify expected behaviour after frame switching // TODO(user): test screenshots at guaranteed maximized browsers // TODO(user): test screenshots at guaranteed non maximized browsers // TODO(user): test screenshots at guaranteed minimized browsers // TODO(user): test screenshots at guaranteed fullscreened/kiosked browsers (WINDOWS platform specific) @Ignore(value = {IE}, reason = "IE: strange colors appeared") public class TakesScreenshotTest extends JUnit4TestBase { private TakesScreenshot screenshoter; private File tempFile = null; @Before public void setUp() throws Exception { assumeTrue(driver instanceof TakesScreenshot); screenshoter = (TakesScreenshot) driver; } @After public void tearDown() { if (tempFile != null) { tempFile.delete(); tempFile = null; } } @Test @Ignore(MARIONETTE) public void testGetScreenshotAsFile() throws Exception { driver.get(pages.simpleTestPage); tempFile = screenshoter.getScreenshotAs(OutputType.FILE); assertTrue(tempFile.exists()); assertTrue(tempFile.length() > 0); } @Test public void testGetScreenshotAsBase64() throws Exception { driver.get(pages.simpleTestPage); String screenshot = screenshoter.getScreenshotAs(OutputType.BASE64); assertTrue(screenshot.length() > 0); } @Test public void testGetScreenshotAsBinary() throws Exception { driver.get(pages.simpleTestPage); byte[] screenshot = screenshoter.getScreenshotAs(OutputType.BYTES); assertTrue(screenshot.length > 0); } @Test public void testShouldCaptureScreenshotOfCurrentViewport() throws Exception { driver.get(appServer.whereIs("screen/screen.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step */ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore(value = {SAFARI, CHROME, MARIONETTE}, reason = " SAFARI: takes only visible viewport." + " CHROME: takes only visible viewport.") public void testShouldCaptureScreenshotOfPageWithLongX() throws Exception { driver.get(appServer.whereIs("screen/screen_x_long.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 50, /* stepY in pixels */ 5); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore(value = {SAFARI, CHROME, MARIONETTE}, reason = " SAFARI: takes only visible viewport." + " CHROME: takes only visible viewport.") public void testShouldCaptureScreenshotOfPageWithLongY() throws Exception { driver.get(appServer.whereIs("screen/screen_y_long.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 50); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore(value = {PHANTOMJS, SAFARI, CHROME, IE, FIREFOX, MARIONETTE}, reason = " IE: cuts captured image at driver level." + " FF: captured image is cat at driver level." + " SAFARI: takes only visible viewport." + " CHROME: takes only visible viewport." + " PHANTOMJS: diffs at colors - small dimensions or coloring problem.") public void testShouldCaptureScreenshotOfPageWithTooLongX() throws Exception { driver.get(appServer.whereIs("screen/screen_x_too_long.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 5); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore(value = {PHANTOMJS, SAFARI, CHROME, IE, FIREFOX, MARIONETTE}, reason = " IE: cuts captured image at driver level." + " FF: captured image is cat at driver level." + " SAFARI: takes only visible viewport." + " CHROME: takes only visible viewport." + " PHANTOMJS: diffs at colors - small dimensions or coloring problem.") public void testShouldCaptureScreenshotOfPageWithTooLongY() throws Exception { driver.get(appServer.whereIs("screen/screen_y_too_long.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 100); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore(value = {PHANTOMJS, SAFARI, CHROME, IE, FIREFOX, MARIONETTE}, reason = " IE: returns null." + " FF: failed due NS_ERROR_FAILURE at context.drawWindow." + " SAFARI: takes only visible viewport." + " CHROME: takes only visible viewport." + " PHANTOMJS: takes empty data of byte[], no errors. ") ) public void testShouldCaptureScreenshotOfPageWithTooLongXandY() throws Exception { driver.get(appServer.whereIs("screen/screen_too_long.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 100, /* stepY in pixels */ 100); Set<String> expectedColors = generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6); compareColors(expectedColors, actualColors); } @Test @Ignore( value = {IE, MARIONETTE}, reason = " IE: v9 shows strange border which broke color comparison" ) public void testShouldCaptureScreenshotAtFramePage() throws Exception { driver.get(appServer.whereIs("screen/screen_frames.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); Set<String> expectedColors = new HashSet<String>(); expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames will be taken for full page compareColors(expectedColors, actualColors); } @Test @Ignore(value = {CHROME, MARIONETTE}, reason = " CHROME: Unknown actual colors are presented at screenshot") public void testShouldCaptureScreenshotAtIFramePage() throws Exception { driver.get(appServer.whereIs("screen/screen_iframes.html")); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); Set<String> expectedColors = new HashSet<String>(); expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes will be taken for full page compareColors(expectedColors, actualColors); } @Test @Ignore( value = {IE, MARIONETTE}, reason = "IE: v9 shows strange border which broke color comparison" ) public void testShouldCaptureScreenshotAtFramePageAfterSwitching() throws Exception { driver.get(appServer.whereIs("screen/screen_frames.html")); driver.switchTo().frame(driver.findElement(By.id("frame2"))); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); Set<String> expectedColors = new HashSet<String>(); expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with frames after switching to a frame // will be taken for full page compareColors(expectedColors, actualColors); } @Test @Ignore( value = {IE, CHROME, MARIONETTE}, reason = " IE: v9 takes screesnhot only of switched-in frame area " + " CHROME: Unknown actual colors are presented at screenshot" ) public void testShouldCaptureScreenshotAtIFramePageAfterSwitching() throws Exception { driver.get(appServer.whereIs("screen/screen_iframes.html")); driver.switchTo().frame(driver.findElement(By.id("iframe2"))); BufferedImage screenshot = getImage(); Set<String> actualColors = scanActualColors(screenshot, /* stepX in pixels */ 5, /* stepY in pixels */ 5); Set<String> expectedColors = new HashSet<String>(); expectedColors.addAll(generateExpectedColors( /* initial color */ 0x0F0F0F, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); expectedColors.addAll(generateExpectedColors( /* initial color */ 0xDFDFDF, /* color step*/ 1000, /* grid X size */ 6, /* grid Y size */ 6)); // expectation is that screenshot at page with Iframes after switching to a Iframe // will be taken for full page compareColors(expectedColors, actualColors); } /** * get actual image screenshot * * @return Image object */ private BufferedImage getImage() { BufferedImage image = null; try { byte[] imageData = screenshoter.getScreenshotAs(OutputType.BYTES); assertTrue(imageData != null); assertTrue(imageData.length > 0); image = ImageIO.read(new ByteArrayInputStream(imageData)); assertTrue(image != null); } catch (IOException e) { fail("Image screenshot file is invalid: " + e.getMessage()); } //saveImageToTmpFile(image); return image; } /** * generate expected colors as in checked page. * * @param initialColor - initial color of first (right top) cell of grid * @param stepColor - step b/w grid colors as number * @param nX - grid size at X dimension * @param nY - grid size at Y dimension * @return set of colors in string hex presentation */ private Set<String> generateExpectedColors(final int initialColor, final int stepColor, final int nX, final int nY) { Set<String> colors = new TreeSet<String>(); int cnt = 1; for (int i = 1; i < nX; i++) { for (int j = 1; j < nY; j++) { int color = initialColor + (cnt * stepColor); String hex = String.format("#%02x%02x%02x", ((color & 0xFF0000) >> 16), ((color & 0x00FF00) >> 8), ((color & 0x0000FF))); colors.add(hex); cnt++; } } return colors; } /** * Get colors from image from each point at grid defined by stepX/stepY. * * @param image - image * @param stepX - interval in pixels b/w point in X dimension * @param stepY - interval in pixels b/w point in Y dimension * @return set of colors in string hex presentation */ private Set<String> scanActualColors(BufferedImage image, final int stepX, final int stepY) { Set<String> colors = new TreeSet<String>(); try { int height = image.getHeight(); int width = image.getWidth(); assertTrue(width > 0); assertTrue(height > 0); Raster raster = image.getRaster(); for (int i = 0; i < width; i = i + stepX) { for (int j = 0; j < height; j = j + stepY) { String hex = String.format("#%02x%02x%02x", (raster.getSample(i, j, 0)), (raster.getSample(i, j, 1)), (raster.getSample(i, j, 2))); colors.add(hex); } } } catch (Exception e) { fail("Unable to get actual colors from screenshot: " + e.getMessage()); } assertTrue(colors.size() > 0); return colors; } /** * Compares sets of colors are same. * * @param expectedColors - set of expected colors * @param actualColors - set of actual colors */ private void compareColors(Set<String> expectedColors, Set<String> actualColors) { assertFalse("Actual image has only black color", onlyBlack(actualColors)); assertFalse("Actual image has only white color", onlyWhite(actualColors)); // Ignore black and white for further comparison Set<String> cleanActualColors = Sets.newHashSet(actualColors); cleanActualColors.remove("#000000"); cleanActualColors.remove("#ffffff"); if (! expectedColors.containsAll(cleanActualColors)) { fail("There are unexpected colors on the screenshot: " + Sets.difference(cleanActualColors, expectedColors)); } if (! cleanActualColors.containsAll(expectedColors)) { fail("There are expected colors not present on the screenshot: " + Sets.difference(expectedColors, cleanActualColors)); } } private boolean onlyBlack(Set<String> colors) { return colors.size() == 1 && "#000000".equals(colors.toArray()[0]); } private boolean onlyWhite(Set<String> colors) { return colors.size() == 1 && "#ffffff".equals(colors.toArray()[0]); } /** * Simple helper to save screenshot to tmp file. For debug purposes. * * @param im image */ private void saveImageToTmpFile(BufferedImage im) { File outputfile = new File( testName.getMethodName() + "_image.png"); System.out.println("Image file is at " + outputfile.getAbsolutePath()); System.out.println("Sizes -> " + im.getWidth() + "x" + im.getHeight()); try { ImageIO.write(im, "png", outputfile); } catch (IOException e) { fail("Unable to write image to file: " + e.getMessage()); } } }
java: fix compile error
java/client/test/org/openqa/selenium/TakesScreenshotTest.java
java: fix compile error
<ide><path>ava/client/test/org/openqa/selenium/TakesScreenshotTest.java <ide> " SAFARI: takes only visible viewport." + <ide> " CHROME: takes only visible viewport." + <ide> " PHANTOMJS: takes empty data of byte[], no errors. ") <del> ) <ide> public void testShouldCaptureScreenshotOfPageWithTooLongXandY() throws Exception { <ide> driver.get(appServer.whereIs("screen/screen_too_long.html")); <ide>
JavaScript
unlicense
a04ed5611f8111effec80cf168b45d6814f3b90e
0
twolfson/react-playground
// Disable ES5 lint warnings /* eslint-disable no-restricted-globals,global-require */ // Define our webpack config let jsLoaders; module.exports = { entry: [__dirname + '/browser/js/posts.jsx'], output: { path: __dirname + '/browser-dist/js', filename: 'posts.js' }, module: { rules: [ {test: /(\.js|\.jsx)$/, use: jsLoaders = ['babel-loader'], exclude: /node_modules/} ] }, plugins: [] }; // If we are in development, then enable LiveReload // TODO: Explore switching to React hot loader // https://github.com/statianzo/webpack-livereload-plugin/tree/v0.11.0 if (process.env.ENV === 'development') { module.exports.entry.unshift('react-hot-loader/patch'); jsLoaders.unshift('react-hot-loader/webpack'); module.exports.devServer = { host: 'localhost', port: 3000, hot: true }; }
webpack.config.js
// Disable ES5 lint warnings /* eslint-disable no-restricted-globals,global-require */ // Define our webpack config let jsLoaders; module.exports = { entry: [__dirname + '/browser/js/posts.jsx'], output: { path: __dirname + '/browser-dist/js', filename: 'posts.js' }, module: { rules: [ {test: /(\.js|\.jsx)$/, use: jsLoaders = ['babel-loader']} ] }, plugins: [] }; // If we are in development, then enable LiveReload // TODO: Explore switching to React hot loader // https://github.com/statianzo/webpack-livereload-plugin/tree/v0.11.0 if (process.env.ENV === 'development') { module.exports.entry.unshift('react-hot-loader/patch'); jsLoaders.unshift('react-hot-loader/webpack'); module.exports.devServer = { host: 'localhost', port: 3000, hot: true }; }
Added smart exclude for Webpack
webpack.config.js
Added smart exclude for Webpack
<ide><path>ebpack.config.js <ide> }, <ide> module: { <ide> rules: [ <del> {test: /(\.js|\.jsx)$/, use: jsLoaders = ['babel-loader']} <add> {test: /(\.js|\.jsx)$/, use: jsLoaders = ['babel-loader'], exclude: /node_modules/} <ide> ] <ide> }, <ide> plugins: []
Java
apache-2.0
484e9c025d559dda4b5e4765d2d0980a66218e8b
0
xiaolongzuo/niubi-job,xiaolongzuo/niubi-job,xiaolongzuo/niubi-job,xiaolongzuo/niubi-job
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zuoxiaolong.niubi.job.scanner; import com.zuoxiaolong.niubi.job.core.helper.AssertHelper; import com.zuoxiaolong.niubi.job.core.helper.IOHelper; import com.zuoxiaolong.niubi.job.core.helper.ListHelper; import com.zuoxiaolong.niubi.job.core.helper.LoggerHelper; import java.io.File; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; import java.util.Map; /** * @author Xiaolong Zuo * @since 0.9.3 */ public class ApplicationClassLoader extends URLClassLoader { private Map<String, Class<?>> classMap = new HashMap<>(); private ClassLoader javaClassLoader; private boolean entrust; ApplicationClassLoader(ClassLoader parent, boolean entrust) { super(new URL[]{}, parent); AssertHelper.notNull(getParent(), "parent can't be null."); this.entrust = entrust; ClassLoader classLoader = String.class.getClassLoader(); if (classLoader == null) { classLoader = getSystemClassLoader(); while (classLoader.getParent() != null) { classLoader = classLoader.getParent(); } } this.javaClassLoader = classLoader; } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> clazz = classMap.get(name); if (clazz != null) { return clazz; } synchronized (getClassLoadingLock(name)) { try { clazz = findLoadedClass(name); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } } catch (Throwable e) { //ignored } try { clazz = javaClassLoader.loadClass(name); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } } catch (Throwable e) { //ignored } try { if (entrust) { clazz = super.loadClass(name, resolve); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } } } catch (Throwable e) { //ignored } try { InputStream resource = getResourceAsStream(binaryNameToPath(name, false)); byte[] bytes = IOHelper.readStreamBytesAndClose(resource); clazz = defineClass(name, bytes, 0, bytes.length); if (clazz != null) { classMap.put(name, clazz); if (resolve) { resolveClass(clazz); } return clazz; } } catch (Throwable e) { //ignored } try { if (!entrust) { clazz = super.loadClass(name, resolve); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } } } catch (Throwable e) { //ignored } throw new ClassNotFoundException(); } } private String binaryNameToPath(String binaryName, boolean withLeadingSlash) { // 1 for leading '/', 6 for ".class" StringBuilder path = new StringBuilder(7 + binaryName.length()); if (withLeadingSlash) { path.append('/'); } path.append(binaryName.replace('.', '/')); path.append(".class"); return path.toString(); } @Override public URL getResource(String name) { URL url = javaClassLoader.getResource(name); if (url != null) { return url; } if (entrust) { ClassLoader parent = getParent(); if (parent instanceof URLClassLoader) { url = ((URLClassLoader)parent).findResource(name); } else { url = parent.getResource(name); } if (url != null) { return url; } } url = findResource(name); if (url != null) { return url; } if (!entrust) { ClassLoader parent = getParent(); if (parent instanceof URLClassLoader) { url = ((URLClassLoader)parent).findResource(name); } else { url = parent.getResource(name); } if (url != null) { return url; } } return null; } @Override protected void addURL(URL url) { super.addURL(url); } public synchronized void addFiles(Object... filePaths) { if (ListHelper.isEmpty(filePaths)) { return; } for (Object filePath : filePaths) { File file = new File(filePath.toString()); if (file.exists()) { try { addURL(file.toURI().toURL()); } catch (Throwable e) { LoggerHelper.warn("jar file [" + filePath + "] can't be add."); } } else { LoggerHelper.warn("jar file [" + filePath + "] can't be found."); } } } public synchronized void addJarFiles(String... jarFilePaths) { if (ListHelper.isEmpty(jarFilePaths)) { return; } for (String jarFilePath : jarFilePaths) { File file = new File(jarFilePath); if (file.exists()) { try { addURL(file.toURI().toURL()); } catch (Throwable e) { LoggerHelper.warn("jar file [" + jarFilePath + "] can't be add."); } } else { LoggerHelper.warn("jar file [" + jarFilePath + "] can't be found."); } } } }
niubi-job-scanner/src/main/java/com/zuoxiaolong/niubi/job/scanner/ApplicationClassLoader.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.zuoxiaolong.niubi.job.scanner; import com.zuoxiaolong.niubi.job.core.helper.AssertHelper; import com.zuoxiaolong.niubi.job.core.helper.IOHelper; import com.zuoxiaolong.niubi.job.core.helper.ListHelper; import com.zuoxiaolong.niubi.job.core.helper.LoggerHelper; import java.io.File; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.HashMap; import java.util.Map; /** * @author Xiaolong Zuo * @since 0.9.3 */ public class ApplicationClassLoader extends URLClassLoader { private Map<String, Class<?>> classMap = new HashMap<>(); private ClassLoader javaClassLoader; private boolean entrust; ApplicationClassLoader(ClassLoader parent, boolean entrust) { super(new URL[]{}, parent); AssertHelper.notNull(getParent(), "parent can't be null."); this.entrust = entrust; ClassLoader classLoader = String.class.getClassLoader(); if (classLoader == null) { classLoader = getSystemClassLoader(); while (classLoader.getParent() != null) { classLoader = classLoader.getParent(); } } this.javaClassLoader = classLoader; } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> clazz = classMap.get(name); if (clazz != null) { return clazz; } synchronized (getClassLoadingLock(name)) { try { clazz = findLoadedClass(name); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } } catch (Throwable e) { //ignored } try { clazz = javaClassLoader.loadClass(name); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } } catch (Throwable e) { //ignored } try { if (entrust) { clazz = super.loadClass(name, resolve); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } } } catch (Throwable e) { //ignored } try { InputStream resource = getResourceAsStream(binaryNameToPath(name, false)); byte[] bytes = IOHelper.readStreamBytesAndClose(resource); clazz = defineClass(name, bytes, 0, bytes.length); if (clazz != null) { classMap.put(name, clazz); if (resolve) { resolveClass(clazz); } return clazz; } } catch (Throwable e) { //ignored } try { if (!entrust) { clazz = super.loadClass(name, resolve); if (clazz != null) { if (resolve) { resolveClass(clazz); } return clazz; } } } catch (Throwable e) { //ignored } throw new ClassNotFoundException(); } } private String binaryNameToPath(String binaryName, boolean withLeadingSlash) { // 1 for leading '/', 6 for ".class" StringBuilder path = new StringBuilder(7 + binaryName.length()); if (withLeadingSlash) { path.append('/'); } path.append(binaryName.replace('.', '/')); path.append(".class"); return path.toString(); } @Override public URL getResource(String name) { URL url = javaClassLoader.getResource(name); if (url != null) { return url; } if (entrust) { ClassLoader parent = getParent(); if (parent instanceof URLClassLoader) { url = ((URLClassLoader)parent).findResource(name); } else { url = parent.getResource(name); } if (url != null) { return url; } } url = findResource(name); if (url != null) { return url; } if (entrust) { ClassLoader parent = getParent(); if (parent instanceof URLClassLoader) { url = ((URLClassLoader)parent).findResource(name); } else { url = parent.getResource(name); } if (url != null) { return url; } } return null; } @Override protected void addURL(URL url) { super.addURL(url); } public synchronized void addFiles(Object... filePaths) { if (ListHelper.isEmpty(filePaths)) { return; } for (Object filePath : filePaths) { File file = new File(filePath.toString()); if (file.exists()) { try { addURL(file.toURI().toURL()); } catch (Throwable e) { LoggerHelper.warn("jar file [" + filePath + "] can't be add."); } } else { LoggerHelper.warn("jar file [" + filePath + "] can't be found."); } } } public synchronized void addJarFiles(String... jarFilePaths) { if (ListHelper.isEmpty(jarFilePaths)) { return; } for (String jarFilePath : jarFilePaths) { File file = new File(jarFilePath); if (file.exists()) { try { addURL(file.toURI().toURL()); } catch (Throwable e) { LoggerHelper.warn("jar file [" + jarFilePath + "] can't be add."); } } else { LoggerHelper.warn("jar file [" + jarFilePath + "] can't be found."); } } } }
polishing.
niubi-job-scanner/src/main/java/com/zuoxiaolong/niubi/job/scanner/ApplicationClassLoader.java
polishing.
<ide><path>iubi-job-scanner/src/main/java/com/zuoxiaolong/niubi/job/scanner/ApplicationClassLoader.java <ide> if (url != null) { <ide> return url; <ide> } <del> if (entrust) { <add> if (!entrust) { <ide> ClassLoader parent = getParent(); <ide> if (parent instanceof URLClassLoader) { <ide> url = ((URLClassLoader)parent).findResource(name);
Java
apache-2.0
a460b0af322e50a2aeffcd6bcd5424227d8ae792
0
aharin/inproctester
package com.thoughtworks.inproctester.htmlunit; import com.gargoylesoftware.htmlunit.WebRequest; import com.thoughtworks.inproctester.core.InProcRequest; import com.thoughtworks.inproctester.core.UrlHelper; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.Set; class HtmlUnitInProcRequest implements InProcRequest { private WebRequest request; private Map<String, String> headers = new HashMap<>(); public HtmlUnitInProcRequest(WebRequest request) { this.request = request; headers.put("Host", UrlHelper.getRequestHost(request.getUrl())); headers.put("Content-Type", request.getEncodingType().getName() + ";" + request.getCharset()); headers.putAll(request.getAdditionalHeaders()); } @Override public String getHttpMethod() { return request.getHttpMethod().name(); } @Override public URI getUri() { try { return request.getUrl().toURI(); } catch (URISyntaxException e) { throw new RuntimeException(e); } } @Override public String getContent() { if (request.getRequestParameters().size() > 0) { return new UrlEncodedContent(request.getRequestParameters()).generateFormDataAsString(); } return request.getRequestBody(); } @Override public String getHeader(String headerName) { return headers.get(headerName); } @Override public Set<String> getHeaderNames() { return headers.keySet(); } @Override public void addHeader(String headerName, String header) { headers.put(headerName, header); } }
inproctester-htmlunit/src/main/java/com/thoughtworks/inproctester/htmlunit/HtmlUnitInprocRequest.java
package com.thoughtworks.inproctester.htmlunit; import com.gargoylesoftware.htmlunit.WebRequest; import com.thoughtworks.inproctester.core.InProcRequest; import com.thoughtworks.inproctester.core.UrlHelper; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.Set; class HtmlUnitInProcRequest implements InProcRequest { private WebRequest request; private Map<String, String> headers = new HashMap<String, String>(); public HtmlUnitInProcRequest(WebRequest request) { this.request = request; headers.put("Host", UrlHelper.getRequestHost(request.getUrl())); headers.put("Content-Type", request.getEncodingType().getName() + ";" + request.getCharset()); headers.putAll(request.getAdditionalHeaders()); } @Override public String getHttpMethod() { return request.getHttpMethod().name(); } @Override public URI getUri() { try { return request.getUrl().toURI(); } catch (URISyntaxException e) { throw new RuntimeException(e); } } @Override public String getContent() { if (request.getRequestParameters().size() > 0) { return new UrlEncodedContent(request.getRequestParameters()).generateFormDataAsString(); } return request.getRequestBody(); } @Override public String getHeader(String headerName) { return headers.get(headerName); } @Override public Set<String> getHeaderNames() { return headers.keySet(); } @Override public void addHeader(String headerName, String header) { headers.put(headerName, header); } }
fixed capitalisation
inproctester-htmlunit/src/main/java/com/thoughtworks/inproctester/htmlunit/HtmlUnitInprocRequest.java
fixed capitalisation
<ide><path>nproctester-htmlunit/src/main/java/com/thoughtworks/inproctester/htmlunit/HtmlUnitInprocRequest.java <ide> <ide> class HtmlUnitInProcRequest implements InProcRequest { <ide> private WebRequest request; <del> private Map<String, String> headers = new HashMap<String, String>(); <add> private Map<String, String> headers = new HashMap<>(); <ide> <ide> public HtmlUnitInProcRequest(WebRequest request) { <ide> this.request = request;
Java
agpl-3.0
6fb2153e4c08b44e3c150c933e14b6f257053306
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
6108f326-2e62-11e5-9284-b827eb9e62be
hello.java
610379dc-2e62-11e5-9284-b827eb9e62be
6108f326-2e62-11e5-9284-b827eb9e62be
hello.java
6108f326-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>610379dc-2e62-11e5-9284-b827eb9e62be <add>6108f326-2e62-11e5-9284-b827eb9e62be
Java
apache-2.0
f5fe72ae2ae61c4b355176e7e9d35890f8e99992
0
garybentley/quollwriter,garybentley/quollwriter
package com.quollwriter.exporter; import java.awt.Color; import java.awt.event.*; import java.io.*; import java.text.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.tree.*; import com.gentlyweb.utils.*; import com.jgoodies.forms.builder.*; import com.jgoodies.forms.factories.*; import com.jgoodies.forms.layout.*; import nl.siegmann.epublib.epub.*; import nl.siegmann.epublib.domain.Author; import nl.siegmann.epublib.domain.Resource; import com.quollwriter.*; import com.quollwriter.data.*; import com.quollwriter.data.comparators.*; import com.quollwriter.ui.*; import com.quollwriter.ui.components.Markup; import com.quollwriter.ui.renderers.*; import com.quollwriter.text.*; public class EPUBDocumentExporter extends AbstractDocumentExporter { // private ExportSettings settings = null; private ZipOutputStream zout = null; private JTextField author = null; private JTextField id = null; public EPUBDocumentExporter() { } public String getStartStage () { return "select-items"; } public WizardStep getStage (String stage) { final EPUBDocumentExporter _this = this; WizardStep ws = new WizardStep (); if (stage.equals ("select-items")) { ws.title = "Select the items you wish to export"; ws.helpText = "Select the items you wish to export, if you select any {chapters} then any associated {notes} and {outlineitems} will also be exported. {Locations}, {characters}, {objects} and {researchitems} will be added as appendices."; this.initItemsTree (null); JScrollPane sp = new JScrollPane (this.itemsTree); sp.setOpaque (false); sp.getViewport ().setOpaque (false); sp.setAlignmentX (JComponent.LEFT_ALIGNMENT); sp.setBorder (new LineBorder (new Color (127, 127, 127), 1)); ws.panel = sp; } if (stage.equals ("details")) { ws.title = "Enter the details about the book"; ws.helpText = "You should provide either the ISBN of your book or a unique url for the book as the ID."; FormLayout fl = new FormLayout ("10px, right:p, 6px, 200px, fill:10px", "p, 6px, p"); PanelBuilder builder = new PanelBuilder (fl); CellConstraints cc = new CellConstraints (); this.author = UIUtils.createTextField (); builder.addLabel ("Author Name", cc.xy (2, 1)); builder.add (this.author, cc.xy (4, 1)); this.author.setText (this.proj.getProperty (Constants.AUTHOR_NAME_PROPERTY_NAME)); builder.addLabel ("ID (ISBN/URL)", cc.xy (2, 3)); this.id = UIUtils.createTextField (); builder.add (this.id, cc.xy (4, 3)); this.id.setText (this.proj.getProperty (Constants.BOOK_ID_PROPERTY_NAME)); ws.panel = builder.getPanel (); } return ws; } public String getNextStage (String currStage) { if (currStage == null) { return "select-items"; } if (currStage.equals ("select-items")) { return "details"; } return null; } public String getPreviousStage (String currStage) { if (currStage == null) { return null; } if (currStage.equals ("details")) { return "select-items"; } return null; } private void addEntry (String name, String content) throws Exception { byte[] bytes = content.getBytes ("utf-8"); ZipEntry ze = new ZipEntry (name); if (name.equals ("mimetype")) { this.zout.setLevel (ZipEntry.STORED); } else { this.zout.setLevel (ZipEntry.DEFLATED); } this.zout.putNextEntry (ze); this.zout.write (bytes, 0, bytes.length); } private String sanitizeName (String name) { name = Utils.sanitizeForFilename (name); return name; } public void exportProject (File dir) throws GeneralException { try { Project p = ExportUtils.getSelectedItems (this.itemsTree, this.proj); // Create new Book nl.siegmann.epublib.domain.Book book = new nl.siegmann.epublib.domain.Book (); // Set the title book.getMetadata ().addTitle (this.proj.getName ()); // Add an Author book.getMetadata ().addAuthor (new Author (this.author.getText ())); // Set cover image //book.getMetadata().setCoverImage(new Resource(Simple1.class.getResourceAsStream("/book1/test_cover.png"), "cover.png")); String css = Environment.getResourceFileAsString ("/data/export/epub/css-template.xml"); css = StringUtils.replaceString (css, "[[FONT_NAME]]", this.proj.getProperty (Constants.EDITOR_FONT_PROPERTY_NAME)); css = StringUtils.replaceString (css, "[[FONT_SIZE]]", this.proj.getPropertyAsInt (Constants.EDITOR_FONT_SIZE_PROPERTY_NAME) + "pt"); css = StringUtils.replaceString (css, "[[LINE_SPACING]]", (100 * this.proj.getPropertyAsFloat (Constants.EDITOR_LINE_SPACING_PROPERTY_NAME)) + "%"); css = StringUtils.replaceString (css, "[[ALIGN]]", this.proj.getProperty (Constants.EDITOR_ALIGNMENT_PROPERTY_NAME).toLowerCase ()); String indent = "0px"; if (this.proj.getPropertyAsBoolean (Constants.EDITOR_INDENT_FIRST_LINE_PROPERTY_NAME)) { indent = "5em"; } css = StringUtils.replaceString (css, "[[INDENT]]", indent); book.getResources ().add (new Resource (new ByteArrayInputStream (css.getBytes ()), "main.css")); Book b = p.getBook (0); String cTemp = Environment.getResourceFileAsString ("/data/export/epub/chapter-template.xml"); List<Chapter> chapters = b.getChapters (); int count = 0; for (Chapter c : chapters) { count++; String chapterText = StringUtils.replaceString (cTemp, "[[TITLE]]", c.getName ()); String t = (c.getText () != null ? c.getText ().getMarkedUpText () : ""); // Split the text on new line, for each one output a p tag if not empty. // Get the text and split it. TextIterator ti = new TextIterator (t); StringBuilder ct = new StringBuilder (); for (Paragraph para : ti.getParagraphs ()) { ct.append (String.format ("<p>%s</p>", para.getText ())); } chapterText = StringUtils.replaceString (chapterText, "[[CONTENT]]", ct.toString ()); book.addSection (c.getName (), new Resource (new ByteArrayInputStream (chapterText.getBytes ()), "chapter" + count + ".html")); } String appendixTemp = Environment.getResourceFileAsString ("/data/export/epub/appendix-template.xml"); // Get the characters. List<QCharacter> characters = p.getCharacters (); if (characters.size () > 0) { String cid = "appendix-a-characters"; String title = "Appendix A - Characters"; String t = StringUtils.replaceString (appendixTemp, "[[TITLE]]", title); t = StringUtils.replaceString (t, "[[CONTENT]]", this.getAssetsPage (characters)); book.addSection (title, new Resource (new ByteArrayInputStream (t.getBytes ()), cid + ".html")); } // Get the locations. List<Location> locs = p.getLocations (); if (locs.size () > 0) { String cid = "appendix-b-locations"; String title = "Appendix B - Locations"; String t = StringUtils.replaceString (appendixTemp, "[[TITLE]]", title); t = StringUtils.replaceString (t, "[[CONTENT]]", this.getAssetsPage (locs)); book.addSection (title, new Resource (new ByteArrayInputStream (t.getBytes ()), cid + ".html")); } // Get the objects. List<QObject> objs = p.getQObjects (); if (objs.size () > 0) { String cid = "appendix-c-items"; String title = "Appendix C - Items"; String t = StringUtils.replaceString (appendixTemp, "[[TITLE]]", title); t = StringUtils.replaceString (t, "[[CONTENT]]", this.getAssetsPage (objs)); book.addSection (title, new Resource (new ByteArrayInputStream (t.getBytes ()), cid + ".html")); } // Get the research items. List<ResearchItem> res = p.getResearchItems (); if (res.size () > 0) { String cid = "appendix-d-research"; String title = "Appendix D - Research"; String t = StringUtils.replaceString (appendixTemp, "[[TITLE]]", title); t = StringUtils.replaceString (t, "[[CONTENT]]", this.getAssetsPage (res)); book.addSection (title, new Resource (new ByteArrayInputStream (t.getBytes ()), cid + ".html")); } // Create EpubWriter EpubWriter epubWriter = new EpubWriter (); // Write the Book as Epub epubWriter.write (book, new FileOutputStream (new File (dir.getPath () + "/" + this.sanitizeName (this.proj.getName ()) + Constants.EPUB_FILE_EXTENSION))); } catch (Exception e) { throw new GeneralException ("Unable to export project: " + this.proj, e); } } private String getAssetsPage (List<? extends Asset> assets) { StringBuilder buf = new StringBuilder (); for (Asset a : assets) { buf.append ("<h2>"); buf.append (a.getName ()); buf.append ("</h2>"); if (a instanceof QObject) { QObject q = (QObject) a; buf.append ("<h3>Type: " + q.getType () + "</h3>"); } if (a instanceof ResearchItem) { ResearchItem r = (ResearchItem) a; if (r.getUrl () != null) { buf.append ("<h3>Web page: <a href='" + r.getUrl () + "'>" + r.getUrl () + "</a></h3>"); } } // TODO: Change to use a textiterator. String at = (a.getDescription () != null ? a.getDescription ().getText () : ""); // Get the text and split it. StringTokenizer t = new StringTokenizer (at, String.valueOf ('\n') + String.valueOf ('\n')); while (t.hasMoreTokens ()) { buf.append ("<p>" + t.nextToken ().trim () + "</p>"); } } return buf.toString (); } }
src/com/quollwriter/exporter/EPUBDocumentExporter.java
package com.quollwriter.exporter; import java.awt.Color; import java.awt.event.*; import java.io.*; import java.text.*; import java.util.*; import java.util.zip.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.tree.*; import com.gentlyweb.utils.*; import com.jgoodies.forms.builder.*; import com.jgoodies.forms.factories.*; import com.jgoodies.forms.layout.*; import nl.siegmann.epublib.epub.*; import nl.siegmann.epublib.domain.Author; import nl.siegmann.epublib.domain.Resource; import com.quollwriter.*; import com.quollwriter.data.*; import com.quollwriter.data.comparators.*; import com.quollwriter.ui.*; import com.quollwriter.ui.components.Markup; import com.quollwriter.ui.renderers.*; import com.quollwriter.text.*; public class EPUBDocumentExporter extends AbstractDocumentExporter { // private ExportSettings settings = null; private ZipOutputStream zout = null; private JTextField author = null; private JTextField id = null; public EPUBDocumentExporter() { } public String getStartStage () { return "select-items"; } public WizardStep getStage (String stage) { final EPUBDocumentExporter _this = this; WizardStep ws = new WizardStep (); if (stage.equals ("select-items")) { ws.title = "Select the items you wish to export"; ws.helpText = "Select the items you wish to export, if you select any {chapters} then any associated {notes} and {outlineitems} will also be exported. {Locations}, {characters}, {objects} and {researchitems} will be added as appendices."; this.initItemsTree (null); JScrollPane sp = new JScrollPane (this.itemsTree); sp.setOpaque (false); sp.getViewport ().setOpaque (false); sp.setAlignmentX (JComponent.LEFT_ALIGNMENT); sp.setBorder (new LineBorder (new Color (127, 127, 127), 1)); ws.panel = sp; } if (stage.equals ("details")) { ws.title = "Enter the details about the book"; ws.helpText = "You should provide either the ISBN of your book or a unique url for the book as the ID."; FormLayout fl = new FormLayout ("10px, right:p, 6px, 200px, fill:10px", "p, 6px, p"); PanelBuilder builder = new PanelBuilder (fl); CellConstraints cc = new CellConstraints (); this.author = UIUtils.createTextField (); builder.addLabel ("Author Name", cc.xy (2, 1)); builder.add (this.author, cc.xy (4, 1)); this.author.setText (this.proj.getProperty (Constants.AUTHOR_NAME_PROPERTY_NAME)); builder.addLabel ("ID (ISBN/URL)", cc.xy (2, 3)); this.id = UIUtils.createTextField (); builder.add (this.id, cc.xy (4, 3)); this.id.setText (this.proj.getProperty (Constants.BOOK_ID_PROPERTY_NAME)); ws.panel = builder.getPanel (); } return ws; } public String getNextStage (String currStage) { if (currStage == null) { return "select-items"; } if (currStage.equals ("select-items")) { return "details"; } return null; } public String getPreviousStage (String currStage) { if (currStage == null) { return null; } if (currStage.equals ("details")) { return "select-items"; } return null; } private void addEntry (String name, String content) throws Exception { byte[] bytes = content.getBytes ("utf-8"); ZipEntry ze = new ZipEntry (name); if (name.equals ("mimetype")) { this.zout.setLevel (ZipEntry.STORED); } else { this.zout.setLevel (ZipEntry.DEFLATED); } this.zout.putNextEntry (ze); this.zout.write (bytes, 0, bytes.length); } private String sanitizeName (String name) { name = Utils.sanitizeForFilename (name); return name; } public void exportProject (File dir) throws GeneralException { try { Project p = ExportUtils.getSelectedItems (this.itemsTree, this.proj); // Create new Book nl.siegmann.epublib.domain.Book book = new nl.siegmann.epublib.domain.Book (); // Set the title book.getMetadata ().addTitle (this.proj.getName ()); // Add an Author book.getMetadata ().addAuthor (new Author (this.author.getText ())); // Set cover image //book.getMetadata().setCoverImage(new Resource(Simple1.class.getResourceAsStream("/book1/test_cover.png"), "cover.png")); String css = Environment.getResourceFileAsString ("/data/export/epub/css-template.xml"); css = StringUtils.replaceString (css, "[[FONT_NAME]]", this.proj.getProperty (Constants.EDITOR_FONT_PROPERTY_NAME)); css = StringUtils.replaceString (css, "[[FONT_SIZE]]", this.proj.getPropertyAsInt (Constants.EDITOR_FONT_SIZE_PROPERTY_NAME) + "pt"); css = StringUtils.replaceString (css, "[[LINE_SPACING]]", (100 * this.proj.getPropertyAsFloat (Constants.EDITOR_LINE_SPACING_PROPERTY_NAME)) + "%"); css = StringUtils.replaceString (css, "[[ALIGN]]", this.proj.getProperty (Constants.EDITOR_ALIGNMENT_PROPERTY_NAME).toLowerCase ()); String indent = "0px"; if (this.proj.getPropertyAsBoolean (Constants.EDITOR_INDENT_FIRST_LINE_PROPERTY_NAME)) { indent = "5em"; } css = StringUtils.replaceString (css, "[[INDENT]]", indent); book.getResources ().add (new Resource (new ByteArrayInputStream (css.getBytes ()), "main.css")); Book b = this.proj.getBook (0); String cTemp = Environment.getResourceFileAsString ("/data/export/epub/chapter-template.xml"); List<Chapter> chapters = b.getChapters (); int count = 0; for (Chapter c : chapters) { count++; String chapterText = StringUtils.replaceString (cTemp, "[[TITLE]]", c.getName ()); String t = (c.getText () != null ? c.getText ().getMarkedUpText () : ""); // Split the text on new line, for each one output a p tag if not empty. // Get the text and split it. TextIterator ti = new TextIterator (t); StringBuilder ct = new StringBuilder (); for (Paragraph para : ti.getParagraphs ()) { ct.append (String.format ("<p>%s</p>", para.getText ())); } chapterText = StringUtils.replaceString (chapterText, "[[CONTENT]]", ct.toString ()); book.addSection (c.getName (), new Resource (new ByteArrayInputStream (chapterText.getBytes ()), "chapter" + count + ".html")); } String appendixTemp = Environment.getResourceFileAsString ("/data/export/epub/appendix-template.xml"); // Get the characters. List<QCharacter> characters = this.proj.getCharacters (); if (characters.size () > 0) { String cid = "appendix-a-characters"; String title = "Appendix A - Characters"; String t = StringUtils.replaceString (appendixTemp, "[[TITLE]]", title); t = StringUtils.replaceString (t, "[[CONTENT]]", this.getAssetsPage (characters)); book.addSection (title, new Resource (new ByteArrayInputStream (t.getBytes ()), cid + ".html")); } // Get the locations. List<Location> locs = this.proj.getLocations (); if (locs.size () > 0) { String cid = "appendix-b-locations"; String title = "Appendix B - Locations"; String t = StringUtils.replaceString (appendixTemp, "[[TITLE]]", title); t = StringUtils.replaceString (t, "[[CONTENT]]", this.getAssetsPage (locs)); book.addSection (title, new Resource (new ByteArrayInputStream (t.getBytes ()), cid + ".html")); } // Get the objects. List<QObject> objs = this.proj.getQObjects (); if (objs.size () > 0) { String cid = "appendix-c-items"; String title = "Appendix C - Items"; String t = StringUtils.replaceString (appendixTemp, "[[TITLE]]", title); t = StringUtils.replaceString (t, "[[CONTENT]]", this.getAssetsPage (objs)); book.addSection (title, new Resource (new ByteArrayInputStream (t.getBytes ()), cid + ".html")); } // Get the research items. List<ResearchItem> res = this.proj.getResearchItems (); if (res.size () > 0) { String cid = "appendix-d-research"; String title = "Appendix D - Research"; String t = StringUtils.replaceString (appendixTemp, "[[TITLE]]", title); t = StringUtils.replaceString (t, "[[CONTENT]]", this.getAssetsPage (res)); book.addSection (title, new Resource (new ByteArrayInputStream (t.getBytes ()), cid + ".html")); } // Create EpubWriter EpubWriter epubWriter = new EpubWriter (); // Write the Book as Epub epubWriter.write (book, new FileOutputStream (new File (dir.getPath () + "/" + this.sanitizeName (this.proj.getName ()) + Constants.EPUB_FILE_EXTENSION))); } catch (Exception e) { throw new GeneralException ("Unable to export project: " + this.proj, e); } } private String getAssetsPage (List<? extends Asset> assets) { StringBuilder buf = new StringBuilder (); for (Asset a : assets) { buf.append ("<h2>"); buf.append (a.getName ()); buf.append ("</h2>"); if (a instanceof QObject) { QObject q = (QObject) a; buf.append ("<h3>Type: " + q.getType () + "</h3>"); } if (a instanceof ResearchItem) { ResearchItem r = (ResearchItem) a; if (r.getUrl () != null) { buf.append ("<h3>Web page: <a href='" + r.getUrl () + "'>" + r.getUrl () + "</a></h3>"); } } // TODO: Change to use a textiterator. String at = (a.getDescription () != null ? a.getDescription ().getText () : ""); // Get the text and split it. StringTokenizer t = new StringTokenizer (at, String.valueOf ('\n') + String.valueOf ('\n')); while (t.hasMoreTokens ()) { buf.append ("<p>" + t.nextToken ().trim () + "</p>"); } } return buf.toString (); } }
Fix to allow selected chapters and assets to be exported to epub format.
src/com/quollwriter/exporter/EPUBDocumentExporter.java
Fix to allow selected chapters and assets to be exported to epub format.
<ide><path>rc/com/quollwriter/exporter/EPUBDocumentExporter.java <ide> book.getResources ().add (new Resource (new ByteArrayInputStream (css.getBytes ()), <ide> "main.css")); <ide> <del> Book b = this.proj.getBook (0); <add> Book b = p.getBook (0); <ide> <ide> String cTemp = Environment.getResourceFileAsString ("/data/export/epub/chapter-template.xml"); <ide> <ide> String appendixTemp = Environment.getResourceFileAsString ("/data/export/epub/appendix-template.xml"); <ide> <ide> // Get the characters. <del> List<QCharacter> characters = this.proj.getCharacters (); <add> List<QCharacter> characters = p.getCharacters (); <ide> <ide> if (characters.size () > 0) <ide> { <ide> } <ide> <ide> // Get the locations. <del> List<Location> locs = this.proj.getLocations (); <add> List<Location> locs = p.getLocations (); <ide> <ide> if (locs.size () > 0) <ide> { <ide> } <ide> <ide> // Get the objects. <del> List<QObject> objs = this.proj.getQObjects (); <add> List<QObject> objs = p.getQObjects (); <ide> <ide> if (objs.size () > 0) <ide> { <ide> } <ide> <ide> // Get the research items. <del> List<ResearchItem> res = this.proj.getResearchItems (); <add> List<ResearchItem> res = p.getResearchItems (); <ide> <ide> if (res.size () > 0) <ide> {
Java
bsd-3-clause
4c41c3ab5306212cb1d35dc0546bf86aaed3f9cf
0
eoinsha/JavaPhoenixChannels,metalwihen/JavaPhoenixChannels,eoinsha/JavaPhoenixChannels,bryanjos/JavaPhoenixChannels,bryanjos/JavaPhoenixChannels,Mobbit/JavaPhoenixChannels,Mobbit/JavaPhoenixChannels,metalwihen/JavaPhoenixChannels
package org.phoenixframework.channels; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import com.squareup.okhttp.ResponseBody; import com.squareup.okhttp.ws.WebSocket; import com.squareup.okhttp.ws.WebSocketCall; import com.squareup.okhttp.ws.WebSocketListener; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSocketFactory; import okio.Buffer; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.logging.Level; import java.util.logging.Logger; public class Socket { private static final Logger LOG = Logger.getLogger(Socket.class.getName()); public static final int RECONNECT_INTERVAL_MS = 5000; private static final int DEFAULT_HEARTBEAT_INTERVAL = 7000; private final ObjectMapper objectMapper = new ObjectMapper(); private final OkHttpClient httpClient = new OkHttpClient(); private WebSocket webSocket = null; private String endpointUri = null; private final List<Channel> channels = new ArrayList<>(); private int heartbeatInterval; private Timer timer = null; private TimerTask reconnectTimerTask = null; private TimerTask heartbeatTimerTask = null; private Set<ISocketOpenCallback> socketOpenCallbacks = Collections.newSetFromMap(new WeakHashMap<ISocketOpenCallback, Boolean>()); private Set<ISocketCloseCallback> socketCloseCallbacks = Collections.newSetFromMap(new WeakHashMap<ISocketCloseCallback, Boolean>()); private Set<IErrorCallback> errorCallbacks = Collections.newSetFromMap(new WeakHashMap<IErrorCallback, Boolean>()); private Set<IMessageCallback> messageCallbacks = Collections.newSetFromMap(new WeakHashMap<IMessageCallback, Boolean>()); private int refNo = 1; /** * Annotated WS Endpoint. Private member to prevent confusion with "onConn*" registration methods. */ private PhoenixWSListener wsListener = new PhoenixWSListener(); private ConcurrentLinkedDeque<RequestBody> sendBuffer = new ConcurrentLinkedDeque<>(); public class PhoenixWSListener implements WebSocketListener { private PhoenixWSListener() { } @Override public void onOpen(final WebSocket webSocket, final Response response) { LOG.log(Level.FINE, "WebSocket onOpen: {0}", webSocket); Socket.this.webSocket = webSocket; cancelReconnectTimer(); startHeartbeatTimer(); for (final ISocketOpenCallback callback : socketOpenCallbacks) { callback.onOpen(); } Socket.this.flushSendBuffer(); } @Override public void onMessage(final ResponseBody payload) throws IOException { LOG.log(Level.FINE, "Envelope received: {0}", payload); try { if (payload.contentType() == WebSocket.TEXT) { final Envelope envelope = objectMapper.readValue(payload.byteStream(), Envelope.class); for (final Channel channel : channels) { if (channel.isMember(envelope.getTopic())) { channel.trigger(envelope.getEvent(), envelope); } } for (final IMessageCallback callback : messageCallbacks) { callback.onMessage(envelope); } } } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to read message payload", e); } finally { payload.close(); } } @Override public void onPong(final Buffer payload) { LOG.log(Level.INFO, "PONG received: {0}", payload); } @Override public void onClose(final int code, final String reason) { LOG.log(Level.FINE, "WebSocket onClose {0}/{1}", new Object[]{code, reason}); Socket.this.webSocket = null; scheduleReconnectTimer(); for (final ISocketCloseCallback callback : socketCloseCallbacks) { callback.onClose(); } } @Override public void onFailure(final IOException e, final Response response) { LOG.log(Level.WARNING, "WebSocket connection error", e); try { for (final IErrorCallback callback : errorCallbacks) { triggerChannelError(); callback.onError(e.toString()); } } finally { // Assume closed on failure if(Socket.this.webSocket != null) { try { Socket.this.webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "EOF received"); } catch (IOException ioe) { LOG.log(Level.WARNING, "Failed to explicitly close following failure"); } finally { Socket.this.webSocket = null; } } scheduleReconnectTimer(); } } } private void startHeartbeatTimer(){ Socket.this.heartbeatTimerTask = new TimerTask() { @Override public void run() { LOG.log(Level.FINE, "heartbeatTimerTask run"); if(Socket.this.isConnected()) { try { Envelope envelope = new Envelope("phoenix", "heartbeat", new ObjectNode(JsonNodeFactory.instance), Socket.this.makeRef()); Socket.this.push(envelope); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to send heartbeat", e); } } } }; timer.schedule(Socket.this.heartbeatTimerTask, Socket.this.heartbeatInterval, Socket.this.heartbeatInterval); } private void cancelHeartbeatTimer(){ if (Socket.this.heartbeatTimerTask != null) { Socket.this.heartbeatTimerTask.cancel(); } } /** * Sets up and schedules a timer task to make repeated reconnect attempts at configured intervals */ private void scheduleReconnectTimer() { cancelReconnectTimer(); cancelHeartbeatTimer(); Socket.this.reconnectTimerTask = new TimerTask() { @Override public void run() { LOG.log(Level.FINE, "reconnectTimerTask run"); try { Socket.this.connect(); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to reconnect to " + Socket.this.wsListener, e); } } }; timer.schedule(Socket.this.reconnectTimerTask, RECONNECT_INTERVAL_MS ); } private void cancelReconnectTimer() { if (Socket.this.reconnectTimerTask != null) { Socket.this.reconnectTimerTask.cancel(); } } public Socket(final String endpointUri) throws IOException { LOG.log(Level.FINE, "PhoenixSocket({0})", endpointUri); this.endpointUri = endpointUri; this.heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL; this.timer = new Timer("Reconnect Timer for " + endpointUri); } public Socket(final String endpointUri, final int heartbeatIntervalInMs) throws IOException { LOG.log(Level.FINE, "PhoenixSocket({0})", endpointUri); this.endpointUri = endpointUri; this.heartbeatInterval = heartbeatIntervalInMs; this.timer = new Timer("Reconnect Timer for " + endpointUri); } public void disconnect() throws IOException { LOG.log(Level.FINE, "disconnect"); if (webSocket != null) { webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "Disconnected by client"); cancelHeartbeatTimer(); } } public void connect() throws IOException { LOG.log(Level.FINE, "connect"); disconnect(); // No support for ws:// or ws:// in okhttp. See https://github.com/square/okhttp/issues/1652 final String httpUrl = this.endpointUri.replaceFirst("^ws:", "http:").replaceFirst("^wss:", "https:"); final Request request = new Request.Builder().url(httpUrl).build(); final WebSocketCall wsCall = WebSocketCall.create(httpClient, request); wsCall.enqueue(wsListener); } /** * @return true if the socket connection is connected */ public boolean isConnected() { return webSocket != null; } /** * Retrieve a channel instance for the specified topic * * @param topic The channel topic * @param payload The message payload * @return A Channel instance to be used for sending and receiving events for the topic */ public Channel chan(final String topic, final JsonNode payload) { LOG.log(Level.FINE, "chan: {0}, {1}", new Object[]{topic, payload}); final Channel channel = new Channel(topic, payload, Socket.this); synchronized (channels) { channels.add(channel); } return channel; } /** * Removes the specified channel if it is known to the socket * * @param channel The channel to be removed */ public void remove(final Channel channel) { synchronized (channels) { for (final Iterator chanIter = channels.iterator(); chanIter.hasNext(); ) { if (chanIter.next() == channel) { chanIter.remove(); break; } } } } /** * Sends a message envelope on this socket * * @param envelope The message envelope * @return This socket instance * @throws IOException Thrown if the message cannot be sent */ public Socket push(final Envelope envelope) throws IOException { LOG.log(Level.FINE, "Pushing envelope: {0}", envelope); final ObjectNode node = objectMapper.createObjectNode(); node.put("topic", envelope.getTopic()); node.put("event", envelope.getEvent()); node.put("ref", envelope.getRef()); node.set("payload", envelope.getPayload() == null ? objectMapper.createObjectNode() : envelope.getPayload()); final String json = objectMapper.writeValueAsString(node); LOG.log(Level.FINE, "Sending JSON: {0}", json); RequestBody body = RequestBody.create(WebSocket.TEXT, json); if (this.isConnected()) { try { webSocket.sendMessage(body); } catch(IllegalStateException e) { LOG.log(Level.SEVERE, "Attempted to send push when socket is not open", e); } } else { this.sendBuffer.add(body); } return this; } /** * Register a callback for SocketEvent.OPEN events * * @param callback The callback to receive OPEN events * @return This Socket instance */ public Socket onOpen(final ISocketOpenCallback callback) { cancelReconnectTimer(); this.socketOpenCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.ERROR events * * @param callback The callback to receive CLOSE events * @return This Socket instance */ public Socket onClose(final ISocketCloseCallback callback) { this.socketCloseCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.ERROR events * * @param callback The callback to receive ERROR events * @return This Socket instance */ public Socket onError(final IErrorCallback callback) { this.errorCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.MESSAGE events * * @param callback The callback to receive MESSAGE events * @return This Socket instance */ public Socket onMessage(final IMessageCallback callback) { this.messageCallbacks.add(callback); return this; } @Override public String toString() { return "PhoenixSocket{" + "endpointUri='" + endpointUri + '\'' + ", channels=" + channels + ", refNo=" + refNo + ", webSocket=" + webSocket + '}'; } synchronized String makeRef() { int val = refNo++; if (refNo == Integer.MAX_VALUE) { refNo = 0; } return Integer.toString(val); } private void triggerChannelError() { for (final Channel channel : channels) { channel.trigger(ChannelEvent.ERROR.getPhxEvent(), null); } } public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) { httpClient.setSslSocketFactory(sslSocketFactory); } public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { httpClient.setHostnameVerifier(hostnameVerifier); } private void flushSendBuffer() { while (this.isConnected() && !this.sendBuffer.isEmpty()) { final RequestBody body = this.sendBuffer.removeFirst(); try { this.webSocket.sendMessage(body); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to send payload {0}", body); } } } static String replyEventName(final String ref) { return "chan_reply_" + ref; } }
src/main/java/org/phoenixframework/channels/Socket.java
package org.phoenixframework.channels; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import com.squareup.okhttp.ResponseBody; import com.squareup.okhttp.ws.WebSocket; import com.squareup.okhttp.ws.WebSocketCall; import com.squareup.okhttp.ws.WebSocketListener; import javax.net.ssl.SSLSocketFactory; import okio.Buffer; import java.io.IOException; import java.util.*; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.logging.Level; import java.util.logging.Logger; public class Socket { private static final Logger LOG = Logger.getLogger(Socket.class.getName()); public static final int RECONNECT_INTERVAL_MS = 5000; private static final int DEFAULT_HEARTBEAT_INTERVAL = 7000; private final ObjectMapper objectMapper = new ObjectMapper(); private final OkHttpClient httpClient = new OkHttpClient(); private WebSocket webSocket = null; private String endpointUri = null; private final List<Channel> channels = new ArrayList<>(); private int heartbeatInterval; private Timer timer = null; private TimerTask reconnectTimerTask = null; private TimerTask heartbeatTimerTask = null; private Set<ISocketOpenCallback> socketOpenCallbacks = Collections.newSetFromMap(new WeakHashMap<ISocketOpenCallback, Boolean>()); private Set<ISocketCloseCallback> socketCloseCallbacks = Collections.newSetFromMap(new WeakHashMap<ISocketCloseCallback, Boolean>()); private Set<IErrorCallback> errorCallbacks = Collections.newSetFromMap(new WeakHashMap<IErrorCallback, Boolean>()); private Set<IMessageCallback> messageCallbacks = Collections.newSetFromMap(new WeakHashMap<IMessageCallback, Boolean>()); private int refNo = 1; /** * Annotated WS Endpoint. Private member to prevent confusion with "onConn*" registration methods. */ private PhoenixWSListener wsListener = new PhoenixWSListener(); private ConcurrentLinkedDeque<RequestBody> sendBuffer = new ConcurrentLinkedDeque<>(); public class PhoenixWSListener implements WebSocketListener { private PhoenixWSListener() { } @Override public void onOpen(final WebSocket webSocket, final Response response) { LOG.log(Level.FINE, "WebSocket onOpen: {0}", webSocket); Socket.this.webSocket = webSocket; cancelReconnectTimer(); startHeartbeatTimer(); for (final ISocketOpenCallback callback : socketOpenCallbacks) { callback.onOpen(); } Socket.this.flushSendBuffer(); } @Override public void onMessage(final ResponseBody payload) throws IOException { LOG.log(Level.FINE, "Envelope received: {0}", payload); try { if (payload.contentType() == WebSocket.TEXT) { final Envelope envelope = objectMapper.readValue(payload.byteStream(), Envelope.class); for (final Channel channel : channels) { if (channel.isMember(envelope.getTopic())) { channel.trigger(envelope.getEvent(), envelope); } } for (final IMessageCallback callback : messageCallbacks) { callback.onMessage(envelope); } } } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to read message payload", e); } finally { payload.close(); } } @Override public void onPong(final Buffer payload) { LOG.log(Level.INFO, "PONG received: {0}", payload); } @Override public void onClose(final int code, final String reason) { LOG.log(Level.FINE, "WebSocket onClose {0}/{1}", new Object[]{code, reason}); Socket.this.webSocket = null; scheduleReconnectTimer(); for (final ISocketCloseCallback callback : socketCloseCallbacks) { callback.onClose(); } } @Override public void onFailure(final IOException e, final Response response) { LOG.log(Level.WARNING, "WebSocket connection error", e); try { for (final IErrorCallback callback : errorCallbacks) { triggerChannelError(); callback.onError(e.toString()); } } finally { // Assume closed on failure if(Socket.this.webSocket != null) { try { Socket.this.webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "EOF received"); } catch (IOException ioe) { LOG.log(Level.WARNING, "Failed to explicitly close following failure"); } finally { Socket.this.webSocket = null; } } scheduleReconnectTimer(); } } } private void startHeartbeatTimer(){ Socket.this.heartbeatTimerTask = new TimerTask() { @Override public void run() { LOG.log(Level.FINE, "heartbeatTimerTask run"); if(Socket.this.isConnected()) { try { Envelope envelope = new Envelope("phoenix", "heartbeat", new ObjectNode(JsonNodeFactory.instance), Socket.this.makeRef()); Socket.this.push(envelope); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to send heartbeat", e); } } } }; timer.schedule(Socket.this.heartbeatTimerTask, Socket.this.heartbeatInterval, Socket.this.heartbeatInterval); } private void cancelHeartbeatTimer(){ if (Socket.this.heartbeatTimerTask != null) { Socket.this.heartbeatTimerTask.cancel(); } } /** * Sets up and schedules a timer task to make repeated reconnect attempts at configured intervals */ private void scheduleReconnectTimer() { cancelReconnectTimer(); cancelHeartbeatTimer(); Socket.this.reconnectTimerTask = new TimerTask() { @Override public void run() { LOG.log(Level.FINE, "reconnectTimerTask run"); try { Socket.this.connect(); } catch (Exception e) { LOG.log(Level.SEVERE, "Failed to reconnect to " + Socket.this.wsListener, e); } } }; timer.schedule(Socket.this.reconnectTimerTask, RECONNECT_INTERVAL_MS ); } private void cancelReconnectTimer() { if (Socket.this.reconnectTimerTask != null) { Socket.this.reconnectTimerTask.cancel(); } } public Socket(final String endpointUri) throws IOException { LOG.log(Level.FINE, "PhoenixSocket({0})", endpointUri); this.endpointUri = endpointUri; this.heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL; this.timer = new Timer("Reconnect Timer for " + endpointUri); } public Socket(final String endpointUri, final int heartbeatIntervalInMs) throws IOException { LOG.log(Level.FINE, "PhoenixSocket({0})", endpointUri); this.endpointUri = endpointUri; this.heartbeatInterval = heartbeatIntervalInMs; this.timer = new Timer("Reconnect Timer for " + endpointUri); } public void disconnect() throws IOException { LOG.log(Level.FINE, "disconnect"); if (webSocket != null) { webSocket.close(1001 /*CLOSE_GOING_AWAY*/, "Disconnected by client"); cancelHeartbeatTimer(); } } public void connect() throws IOException { LOG.log(Level.FINE, "connect"); disconnect(); // No support for ws:// or ws:// in okhttp. See https://github.com/square/okhttp/issues/1652 final String httpUrl = this.endpointUri.replaceFirst("^ws:", "http:").replaceFirst("^wss:", "https:"); final Request request = new Request.Builder().url(httpUrl).build(); final WebSocketCall wsCall = WebSocketCall.create(httpClient, request); wsCall.enqueue(wsListener); } /** * @return true if the socket connection is connected */ public boolean isConnected() { return webSocket != null; } /** * Retrieve a channel instance for the specified topic * * @param topic The channel topic * @param payload The message payload * @return A Channel instance to be used for sending and receiving events for the topic */ public Channel chan(final String topic, final JsonNode payload) { LOG.log(Level.FINE, "chan: {0}, {1}", new Object[]{topic, payload}); final Channel channel = new Channel(topic, payload, Socket.this); synchronized (channels) { channels.add(channel); } return channel; } /** * Removes the specified channel if it is known to the socket * * @param channel The channel to be removed */ public void remove(final Channel channel) { synchronized (channels) { for (final Iterator chanIter = channels.iterator(); chanIter.hasNext(); ) { if (chanIter.next() == channel) { chanIter.remove(); break; } } } } /** * Sends a message envelope on this socket * * @param envelope The message envelope * @return This socket instance * @throws IOException Thrown if the message cannot be sent */ public Socket push(final Envelope envelope) throws IOException { LOG.log(Level.FINE, "Pushing envelope: {0}", envelope); final ObjectNode node = objectMapper.createObjectNode(); node.put("topic", envelope.getTopic()); node.put("event", envelope.getEvent()); node.put("ref", envelope.getRef()); node.set("payload", envelope.getPayload() == null ? objectMapper.createObjectNode() : envelope.getPayload()); final String json = objectMapper.writeValueAsString(node); LOG.log(Level.FINE, "Sending JSON: {0}", json); RequestBody body = RequestBody.create(WebSocket.TEXT, json); if (this.isConnected()) { try { webSocket.sendMessage(body); } catch(IllegalStateException e) { LOG.log(Level.SEVERE, "Attempted to send push when socket is not open", e); } } else { this.sendBuffer.add(body); } return this; } /** * Register a callback for SocketEvent.OPEN events * * @param callback The callback to receive OPEN events * @return This Socket instance */ public Socket onOpen(final ISocketOpenCallback callback) { cancelReconnectTimer(); this.socketOpenCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.ERROR events * * @param callback The callback to receive CLOSE events * @return This Socket instance */ public Socket onClose(final ISocketCloseCallback callback) { this.socketCloseCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.ERROR events * * @param callback The callback to receive ERROR events * @return This Socket instance */ public Socket onError(final IErrorCallback callback) { this.errorCallbacks.add(callback); return this; } /** * Register a callback for SocketEvent.MESSAGE events * * @param callback The callback to receive MESSAGE events * @return This Socket instance */ public Socket onMessage(final IMessageCallback callback) { this.messageCallbacks.add(callback); return this; } @Override public String toString() { return "PhoenixSocket{" + "endpointUri='" + endpointUri + '\'' + ", channels=" + channels + ", refNo=" + refNo + ", webSocket=" + webSocket + '}'; } synchronized String makeRef() { int val = refNo++; if (refNo == Integer.MAX_VALUE) { refNo = 0; } return Integer.toString(val); } private void triggerChannelError() { for (final Channel channel : channels) { channel.trigger(ChannelEvent.ERROR.getPhxEvent(), null); } } public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) { httpClient.setSslSocketFactory(sslSocketFactory); } private void flushSendBuffer() { while (this.isConnected() && !this.sendBuffer.isEmpty()) { final RequestBody body = this.sendBuffer.removeFirst(); try { this.webSocket.sendMessage(body); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to send payload {0}", body); } } } static String replyEventName(final String ref) { return "chan_reply_" + ref; } }
added hostVerifier setter
src/main/java/org/phoenixframework/channels/Socket.java
added hostVerifier setter
<ide><path>rc/main/java/org/phoenixframework/channels/Socket.java <ide> import com.squareup.okhttp.ws.WebSocket; <ide> import com.squareup.okhttp.ws.WebSocketCall; <ide> import com.squareup.okhttp.ws.WebSocketListener; <add>import javax.net.ssl.HostnameVerifier; <ide> import javax.net.ssl.SSLSocketFactory; <ide> import okio.Buffer; <ide> <ide> httpClient.setSslSocketFactory(sslSocketFactory); <ide> } <ide> <add> public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { <add> httpClient.setHostnameVerifier(hostnameVerifier); <add> } <add> <ide> private void flushSendBuffer() { <ide> while (this.isConnected() && !this.sendBuffer.isEmpty()) { <ide> final RequestBody body = this.sendBuffer.removeFirst();
JavaScript
mit
648bce5b0e098e9af54957bf6d7fa48ad2834f49
0
FruitieX/nodifier,FruitieX/nodifier
#!/usr/bin/env node var auth = require('http-auth'); var htpasswd = require('./htpasswd.json'); var basic = auth.basic({ realm: "nodifier" }, function (username, password, callback) { callback(username === htpasswd.username && password === htpasswd.password); }); var https = require('https'); var url = require('url'); var querystring = require('querystring'); var clc = require('cli-color'); var config = require('./config.json'); var fs = require('fs'); var path = require('path'); var options = { key: fs.readFileSync(path.resolve(__dirname, config['ssl-key'])), cert: fs.readFileSync(path.resolve(__dirname, config['ssl-cert'])) }; /* Notification handling */ var n = []; // array containing unread notifications var read_n = []; // array containing read notifications var read_n_limit = config.numReadToKeep; // keep only this many read notifications // find index for new notification based on its timestamp // assumes 'array' is sorted in ascending order according to .date fields var n_findId = function(date, array) { for (var i = 0; i < array.length; i++) { if(array[i].date >= date) return i; } return array.length; }; // store unread notification in correct slot according to timestamp var n_store_unread = function(data_json) { // get rid of weird characters data_json.text = data_json.text.replace('\t',' '); // convert tabs to single spaces data_json.text = data_json.text.replace(/^\s*/, ""); // get rid of leading spaces data_json.text = data_json.text.replace(/\s*$/, ""); // get rid of trailing spaces delete data_json.method; data_json.read = false; // plugin did not provide timestamp, create one from current time if(!data_json.date) data_json.date = new Date().valueOf(); // replace old notification if duplicate UID with matching source found var uid_dupe_found = false; if(data_json.uid) { var i; for(i = 0; i < n.length; i++) { if(n[i].uid === data_json.uid && (!data_json.source || (n[i].source === data_json.source)) && (!data_json.context || (n[i].context === data_json.context))) { // TODO: for now keep date same so we don't mess up sorting! data_json.date = n[i].date; n[i] = data_json; uid_dupe_found = true; } } // look in read array too, if duplicate UID found there, remove it for(i = read_n.length - 1; i >= 0; i--) { if(read_n[i].uid === data_json.uid && (!data_json.source || (read_n[i].source === data_json.source)) && (!data_json.context || (read_n[i].context === data_json.context))) read_n.splice(i, 1); } } if (!uid_dupe_found) { var id = n_findId(data_json.date, n); // insert notification to "n" n at pos "id" n.splice(id, 0, data_json); } }; var n_store_read = function(data_json) { delete data_json.method; data_json.read = true; data_json.text = data_json.text.replace('\t',' '); // convert tabs to single spaces data_json.text = data_json.text.replace(/^\s*/, ""); // get rid of leading spaces data_json.text = data_json.text.replace(/\s*$/, ""); // get rid of trailing spaces // plugin did not provide timestamp, create one from current time if(!data_json.date) data_json.date = new Date().valueOf(); // replace old notification if duplicate UID with matching source found var uid_dupe_found = false; if(data_json.uid) { var i; for(i = 0; i < read_n.length; i++) { if(read_n[i].uid === data_json.uid && (!data_json.source || (read_n[i].source === data_json.source)) && (!data_json.context || (read_n[i].context === data_json.context))) { // TODO: for now keep date same so we don't mess up sorting! data_json.date = read_n[i].date; read_n[i] = data_json; uid_dupe_found = true; } } // look in unread array too, if duplicate UID found there, remove it for(i = n.length - 1; i >= 0; i--) { if(n[i].uid === data_json.uid && (!data_json.source || (n[i].source === data_json.source)) && (!data_json.context || (n[i].context === data_json.context))) n.splice(i, 1); } } if (!uid_dupe_found) { // insert notification at end of read_n array read_n.push(data_json); // if read_n is full, pop from start if(read_n.length == read_n_limit) { read_n.splice(0, 1); } } }; var range_re = /(.*)\.\.(.*)/; var n_id_fetch = function(id, array) { var range = id.match(range_re); if(range) { var min = range[1] || 0; var max = range[2] || 9999999999999; if (min > max) { var temp = min; min = max; max = temp; } return array.filter(function (notification, i) { return (i >= min && i <= max); }); } else { return array.filter(function (notification, i) { return i == id; })[0]; } }; // fetch notifications with matching uid, source, context // (if any of these fields are left undefined, the field will not be included in search) var n_search_fetch = function(uid, source, context, array) { return array.filter(function (notification) { return (!uid || (notification.uid == uid)) && (!source || (notification.source == source)) && (!context || (notification.context == context)); }); }; var plugin_setReadStatus = function(notification, read) { if(notification.uid && notification.response_host && notification.response_port) { var options = { hostname: notification.response_host, port: notification.response_port, path: '/' + read + '/' + notification.uid, method: 'GET', rejectUnauthorized: false, auth: htpasswd.username + ':' + htpasswd.password }; var req = https.request(options); req.end(); } }; // mark notifications as (un)read // move notifications between "n" and "read_n" arrays accordingly var n_mark_as = function(notifications, noSendResponse, state) { var msg = ""; // check if arg is object, then make it into an array if(Object.prototype.toString.call(notifications) === '[object Object]') { notifications = [notifications]; } var i; var notification; // update read boolean field of every given notification for (i = 0; i < notifications.length; i++) { // toggle read status if(state === "read") notifications[i].read = true; else notifications[i].read = false; // if plugin supports updating read status, send update if(!noSendResponse) plugin_setReadStatus(notifications[i], state); } if(update) { // loop through unread notifications // see if we can find any that were marked as read // remove and move these to "read_n" if(state === "read") { for(i = n.length - 1; i >= 0; i--) { if(n[i].read) { notification = n[i]; n.splice(i, 1); n_store_read(notification); } } } else if (state === "unread") { for(i = read_n.length - 1; i >= 0; i--) { if(!read_n[i].read) { notification = read_n[i]; read_n.splice(i, 1); n_store_unread(notification); } } } } }; /* HTTP server */ // regex for matching getprev urls, remembers the digit var url_re_all = /all.*/; var url_re_longpoll = /longpoll.*/; var url_re_read = /read.*/; var resMsg = function(res, statusCode, msg) { res.writeHead(statusCode, msg, { 'Content-Type': 'text/html', 'Content-Length': Buffer.byteLength(msg, 'utf8') }); res.end(msg); }; var resWriteJSON = function(res, data) { var data_json = JSON.stringify(data); res.writeHead(200, "OK", { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data_json, 'utf8') }); res.end(data_json); }; var handlePOST = function(req, res) { var msg, notifications; req.on('data', function(data) { var data_json = querystring.parse(data.toString()); if (data_json.method === 'newNotification') { // store POST in notifications array, note: make copy of object n_store_unread(data_json); resLongpolls(); resMsg(res, 200, "Notification added."); } else if (data_json.method === 'setUnread') { if (data_json.uid || data_json.source || data_json.context) { notifications = n_search_fetch(data_json.uid, data_json.source, data_json.context, read_n); } else { notifications = n_id_fetch(data_json.id, read_n); } if (!notifications) { resMsg(res, 404, "Notification not found."); return; } n_mark_as(notifications, data_json.noSendResponse, "unread"); resLongpolls(); resWriteJSON(res, notifications); } else if (data_json.method === 'setRead') { if (data_json.uid || data_json.source || data_json.context) { notifications = n_search_fetch(data_json.uid, data_json.source, data_json.context, n); } else { notifications = n_id_fetch(data_json.id, n); } if (!notifications) { resMsg(res, 404, "Notification not found."); return; } n_mark_as(notifications, data_json.noSendResponse, "read"); resLongpolls(); resWriteJSON(res, notifications); } else { resMsg(res, 404, "Unknown method in POST (should be 'newNotification', 'setUnread' or 'setRead')"); } }); req.on('end', function() { resMsg(res, 200, "OK"); }); }; var longpolls = []; var resLongpolls = function() { while(longpolls.length) resWriteJSON(longpolls.pop(), n); }; var handleGET = function(req, res) { var resource = url.parse(req.url).pathname; resource = resource.substr(1); // remove first slash var notifications; var all = resource.match(url_re_all); var longpoll = resource.match(url_re_longpoll); var read = resource.match(url_re_read); if(all) { // fetch all unread notifications notifications = n; resWriteJSON(res, notifications); } else if (longpoll) { longpolls.push(res); } else if (read) { notifications = read_n; resWriteJSON(res, notifications); } else { // fetch one notification or a range of notifications notifications = n_id_fetch(resource, n); if(notifications) resWriteJSON(res, notifications); else resMsg(res, 404, "Notification with id " + resource + " not found."); } }; s = https.createServer(basic, options, function (req, res) { if (req.method == 'POST') { handlePOST(req, res); } else { // GET request handleGET(req, res); } }); console.log(clc.green('nodifier server listening on port ' + config.port)); s.listen(config.port); process.on('uncaughtException', function (err) { console.error(err.stack); console.log("ERROR! Node not exiting."); });
nodifier_sv.js
#!/usr/bin/env node var auth = require('http-auth'); var htpasswd = require('./htpasswd.json'); var basic = auth.basic({ realm: "nodifier" }, function (username, password, callback) { callback(username === htpasswd.username && password === htpasswd.password); }); var https = require('https'); var url = require('url'); var querystring = require('querystring'); var clc = require('cli-color'); var config = require('./config.json'); var fs = require('fs'); var path = require('path'); var options = { key: fs.readFileSync(path.resolve(__dirname, config['ssl-key'])), cert: fs.readFileSync(path.resolve(__dirname, config['ssl-cert'])) }; /* Notification handling */ var n = []; // array containing unread notifications var read_n = []; // array containing read notifications var read_n_limit = config.numReadToKeep; // keep only this many read notifications // find index for new notification based on its timestamp // assumes 'array' is sorted in ascending order according to .date fields var n_findId = function(date, array) { for (var i = 0; i < array.length; i++) { if(array[i].date >= date) return i; } return array.length; }; // store unread notification in correct slot according to timestamp var n_store_unread = function(data_json) { // get rid of weird characters data_json.text = data_json.text.replace('\t',' '); // convert tabs to single spaces data_json.text = data_json.text.replace(/^\s*/, ""); // get rid of leading spaces data_json.text = data_json.text.replace(/\s*$/, ""); // get rid of trailing spaces delete data_json.method; data_json.read = false; // plugin did not provide timestamp, create one from current time if(!data_json.date) data_json.date = new Date().valueOf(); // replace old notification if duplicate UID with matching source found var uid_dupe_found = false; if(data_json.uid) { var i; for(i = 0; i < n.length; i++) { if(n[i].uid === data_json.uid && (!data_json.source || (n[i].source === data_json.source)) && (!data_json.context || (n[i].context === data_json.context))) { // TODO: for now keep date same so we don't mess up sorting! data_json.date = n[i].date; n[i] = data_json; uid_dupe_found = true; } } // look in read array too, if duplicate UID found there, remove it for(i = read_n.length - 1; i >= 0; i--) { if(read_n[i].uid === data_json.uid && (!data_json.source || (read_n[i].source === data_json.source)) && (!data_json.context || (read_n[i].context === data_json.context))) read_n.splice(i, 1); } } if (!uid_dupe_found) { var id = n_findId(data_json.date, n); // insert notification to "n" n at pos "id" n.splice(id, 0, data_json); } }; var n_store_read = function(data_json) { delete data_json.method; data_json.read = true; data_json.text = data_json.text.replace('\t',' '); // convert tabs to single spaces data_json.text = data_json.text.replace(/^\s*/, ""); // get rid of leading spaces data_json.text = data_json.text.replace(/\s*$/, ""); // get rid of trailing spaces // plugin did not provide timestamp, create one from current time if(!data_json.date) data_json.date = new Date().valueOf(); // replace old notification if duplicate UID with matching source found var uid_dupe_found = false; if(data_json.uid) { var i; for(i = 0; i < read_n.length; i++) { if(read_n[i].uid === data_json.uid && (!data_json.source || (read_n[i].source === data_json.source)) && (!data_json.context || (read_n[i].context === data_json.context))) { // TODO: for now keep date same so we don't mess up sorting! data_json.date = read_n[i].date; read_n[i] = data_json; uid_dupe_found = true; } } // look in unread array too, if duplicate UID found there, remove it for(i = n.length - 1; i >= 0; i--) { if(n[i].uid === data_json.uid && (!data_json.source || (n[i].source === data_json.source)) && (!data_json.context || (n[i].context === data_json.context))) n.splice(i, 1); } } if (!uid_dupe_found) { // insert notification at end of read_n array read_n.push(data_json); // if read_n is full, pop from start if(read_n.length == read_n_limit) { read_n.splice(0, 1); } } }; var range_re = /(.*)\.\.(.*)/; var n_id_fetch = function(id, array) { var range = id.match(range_re); if(range) { var min = range[1] || 0; var max = range[2] || 9999999999999; if (min > max) { var temp = min; min = max; max = temp; } return array.filter(function (notification, i) { return (i >= min && i <= max); }); } else { return array.filter(function (notification, i) { return i == id; })[0]; } }; // fetch notifications with matching uid, source, context // (if any of these fields are left undefined, the field will not be included in search) var n_search_fetch = function(uid, source, context, array) { return array.filter(function (notification) { return (!uid || (notification.uid == uid)) && (!source || (notification.source == source)) && (!context || (notification.context == context)); }); }; var plugin_setReadStatus = function(notification, read) { if(notification.uid && notification.response_host && notification.response_port) { var options = { hostname: notification.response_host, port: notification.response_port, path: '/' + read + '/' + notification.uid, method: 'GET', rejectUnauthorized: false, auth: htpasswd.username + ':' + htpasswd.password }; var req = https.request(options); req.end(); } }; // mark notifications as (un)read // move notifications between "n" and "read_n" arrays accordingly var n_mark_as = function(notifications, noSendResponse, state) { var msg = ""; // check if arg is object, then make it into an array if(Object.prototype.toString.call(notifications) === '[object Object]') { notifications = [notifications]; } // keep track if any notification was actually changed var update = false; var i; var notification; // update read boolean field of every given notification for (i = 0; i < notifications.length; i++) { if((state === "read" && !notifications[i].read) || (state === "unread" && notifications[i].read)) { // toggle read status notifications[i].read = !notifications[i].read; update = true; // if plugin supports updating read status, send update if(!noSendResponse) plugin_setReadStatus(notifications[i], state); } } if(update) { // loop through unread notifications // see if we can find any that were marked as read // remove and move these to "read_n" if(state === "read") { for(i = n.length - 1; i >= 0; i--) { if(n[i].read) { notification = n[i]; n.splice(i, 1); n_store_read(notification); } } } else if (state === "unread") { for(i = read_n.length - 1; i >= 0; i--) { if(!read_n[i].read) { notification = read_n[i]; read_n.splice(i, 1); n_store_unread(notification); } } } if(notifications.length > 1) msg = "Notifications set as " + state + "."; else msg = "Notification set as " + state + "."; } else { if(notifications.length > 1) msg = "All notifications already marked as " + state + "."; else msg = "Notification already marked as " + state + "."; } return msg; }; /* HTTP server */ // regex for matching getprev urls, remembers the digit var url_re_all = /all.*/; var url_re_longpoll = /longpoll.*/; var url_re_read = /read.*/; var resMsg = function(res, statusCode, msg) { res.writeHead(statusCode, msg, { 'Content-Type': 'text/html', 'Content-Length': Buffer.byteLength(msg, 'utf8') }); res.end(msg); }; var resWriteJSON = function(res, data) { var data_json = JSON.stringify(data); res.writeHead(200, "OK", { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data_json, 'utf8') }); res.end(data_json); }; var handlePOST = function(req, res) { var msg, notifications; req.on('data', function(data) { var data_json = querystring.parse(data.toString()); if (data_json.method === 'newNotification') { // store POST in notifications array, note: make copy of object n_store_unread(data_json); resLongpolls(); resMsg(res, 200, "Notification added."); } else if (data_json.method === 'setUnread') { if (data_json.uid || data_json.source || data_json.context) { notifications = n_search_fetch(data_json.uid, data_json.source, data_json.context, n); } else { notifications = n_id_fetch(data_json.id, read_n); } if (!notifications) { resMsg(res, 404, "Notification not found."); return; } msg = n_mark_as(notifications, data_json.noSendResponse, "unread"); resLongpolls(); resMsg(res, 200, msg); } else if (data_json.method === 'setRead') { if (data_json.uid || data_json.source || data_json.context) { notifications = n_search_fetch(data_json.uid, data_json.source, data_json.context, n); } else { notifications = n_id_fetch(data_json.id, n); } if (!notifications) { resMsg(res, 404, "Notification not found."); return; } msg = n_mark_as(notifications, data_json.noSendResponse, "read"); resLongpolls(); resMsg(res, 200, msg); } else { resMsg(res, 404, "Unknown method in POST (should be 'newNotification', 'setUnread' or 'setRead')"); } }); req.on('end', function() { resMsg(res, 200, "OK"); }); }; var longpolls = []; var resLongpolls = function() { while(longpolls.length) resWriteJSON(longpolls.pop(), n); }; var handleGET = function(req, res) { var resource = url.parse(req.url).pathname; resource = resource.substr(1); // remove first slash var notifications; var all = resource.match(url_re_all); var longpoll = resource.match(url_re_longpoll); var read = resource.match(url_re_read); if(all) { // fetch all unread notifications notifications = n; resWriteJSON(res, notifications); } else if (longpoll) { longpolls.push(res); } else if (read) { notifications = read_n; resWriteJSON(res, notifications); } else { // fetch one notification or a range of notifications notifications = n_id_fetch(resource, n); if(notifications) resWriteJSON(res, notifications); else resMsg(res, 404, "Notification with id " + resource + " not found."); } }; s = https.createServer(basic, options, function (req, res) { if (req.method == 'POST') { handlePOST(req, res); } else { // GET request handleGET(req, res); } }); console.log(clc.green('nodifier server listening on port ' + config.port)); s.listen(config.port); process.on('uncaughtException', function (err) { console.error(err.stack); console.log("ERROR! Node not exiting."); });
attempt to clean n_mark_as() a little bit
nodifier_sv.js
attempt to clean n_mark_as() a little bit
<ide><path>odifier_sv.js <ide> notifications = [notifications]; <ide> } <ide> <del> // keep track if any notification was actually changed <del> var update = false; <del> <ide> var i; <ide> var notification; <ide> <ide> // update read boolean field of every given notification <ide> for (i = 0; i < notifications.length; i++) { <del> if((state === "read" && !notifications[i].read) || (state === "unread" && notifications[i].read)) { <del> // toggle read status <del> notifications[i].read = !notifications[i].read; <del> update = true; <del> <del> // if plugin supports updating read status, send update <del> if(!noSendResponse) <del> plugin_setReadStatus(notifications[i], state); <del> <del> } <add> // toggle read status <add> if(state === "read") <add> notifications[i].read = true; <add> else <add> notifications[i].read = false; <add> <add> // if plugin supports updating read status, send update <add> if(!noSendResponse) <add> plugin_setReadStatus(notifications[i], state); <ide> } <ide> <ide> if(update) { <ide> } <ide> } <ide> } <del> <del> if(notifications.length > 1) <del> msg = "Notifications set as " + state + "."; <del> else <del> msg = "Notification set as " + state + "."; <del> } else { <del> if(notifications.length > 1) <del> msg = "All notifications already marked as " + state + "."; <del> else <del> msg = "Notification already marked as " + state + "."; <del> } <del> <del> return msg; <add> } <ide> }; <ide> <ide> /* HTTP server */ <ide> resMsg(res, 200, "Notification added."); <ide> } else if (data_json.method === 'setUnread') { <ide> if (data_json.uid || data_json.source || data_json.context) { <del> notifications = n_search_fetch(data_json.uid, data_json.source, data_json.context, n); <add> notifications = n_search_fetch(data_json.uid, data_json.source, data_json.context, read_n); <ide> } else { <ide> notifications = n_id_fetch(data_json.id, read_n); <ide> } <ide> return; <ide> } <ide> <del> msg = n_mark_as(notifications, data_json.noSendResponse, "unread"); <add> n_mark_as(notifications, data_json.noSendResponse, "unread"); <ide> resLongpolls(); <ide> <del> resMsg(res, 200, msg); <add> resWriteJSON(res, notifications); <ide> } else if (data_json.method === 'setRead') { <ide> if (data_json.uid || data_json.source || data_json.context) { <ide> notifications = n_search_fetch(data_json.uid, data_json.source, data_json.context, n); <ide> return; <ide> } <ide> <del> msg = n_mark_as(notifications, data_json.noSendResponse, "read"); <add> n_mark_as(notifications, data_json.noSendResponse, "read"); <ide> resLongpolls(); <ide> <del> resMsg(res, 200, msg); <add> resWriteJSON(res, notifications); <ide> } else { <ide> resMsg(res, 404, "Unknown method in POST (should be 'newNotification', 'setUnread' or 'setRead')"); <ide> }
Java
bsd-3-clause
error: pathspec 'test/src/org/lockss/daemon/TestTitleConfig.java' did not match any file(s) known to git
cf3b43382b8661217bf5523a3132efef698c09b3
1
edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon
/* * $Id: TestTitleConfig.java,v 1.1 2004-01-04 06:22:49 tlipkis Exp $ */ /* Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, all rights reserved. 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 STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.daemon; import java.util.*; import org.lockss.test.*; import org.lockss.util.*; /** * This is the test class for org.lockss.daemon.TitleConfig */ public class TestTitleConfig extends LockssTestCase { public void setUp() { } public void testConstructors() { String id = "pid"; String name = "foo 2"; MockPlugin mp = new MockPlugin(); mp.setPluginId(id); TitleConfig tc1 = new TitleConfig(name, mp); TitleConfig tc2 = new TitleConfig(name, id); assertSame(id, tc1.getPluginName()); assertSame(id, tc2.getPluginName()); assertEquals(name, tc1.getDisplayName()); } public void testAccessors1() { TitleConfig tc1 = new TitleConfig("a", "b"); tc1.setPluginVersion("4"); assertEquals("4", tc1.getPluginVersion()); List foo = new ArrayList(); tc1.setParams(foo); assertSame(foo, tc1.getParams()); } public void testGetConfig() { ConfigParamDescr d1 = new ConfigParamDescr("key1"); ConfigParamDescr d2 = new ConfigParamDescr("key2"); ConfigParamAssignment a1 = new ConfigParamAssignment(d1, "a"); ConfigParamAssignment a2 = new ConfigParamAssignment(d2, "foo"); TitleConfig tc1 = new TitleConfig("a", "b"); tc1.setParams(ListUtil.list(a1, a2)); Configuration config = tc1.getConfig(); Configuration exp = ConfigManager.newConfiguration(); exp.put("key1", "a"); exp.put("key2", "foo"); assertEquals(exp, config); } public void testGetNoEditKeys() { ConfigParamDescr d1 = new ConfigParamDescr("key1"); ConfigParamDescr d2 = new ConfigParamDescr("key2"); ConfigParamAssignment a1 = new ConfigParamAssignment(d1, "a"); ConfigParamAssignment a2 = new ConfigParamAssignment(d2, "foo"); a2.setEditable(true); TitleConfig tc1 = new TitleConfig("a", "b"); tc1.setParams(ListUtil.list(a1, a2)); Collection u1 = tc1.getUnEditableKeys(); assertIsomorphic(ListUtil.list("key1"), u1); } }
test/src/org/lockss/daemon/TestTitleConfig.java
Added tests. git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@2288 4f837ed2-42f5-46e7-a7a5-fa17313484d4
test/src/org/lockss/daemon/TestTitleConfig.java
Added tests.
<ide><path>est/src/org/lockss/daemon/TestTitleConfig.java <add>/* <add> * $Id: TestTitleConfig.java,v 1.1 2004-01-04 06:22:49 tlipkis Exp $ <add> */ <add> <add>/* <add> <add>Copyright (c) 2000-2003 Board of Trustees of Leland Stanford Jr. University, <add>all rights reserved. <add> <add>Permission is hereby granted, free of charge, to any person obtaining a copy <add>of this software and associated documentation files (the "Software"), to deal <add>in the Software without restriction, including without limitation the rights <add>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <add>copies of the Software, and to permit persons to whom the Software is <add>furnished to do so, subject to the following conditions: <add> <add>The above copyright notice and this permission notice shall be included in <add>all copies or substantial portions of the Software. <add> <add>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <add>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <add>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL <add>STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, <add>WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR <add>IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>Except as contained in this notice, the name of Stanford University shall not <add>be used in advertising or otherwise to promote the sale, use or other dealings <add>in this Software without prior written authorization from Stanford University. <add> <add>*/ <add> <add>package org.lockss.daemon; <add> <add>import java.util.*; <add>import org.lockss.test.*; <add>import org.lockss.util.*; <add> <add>/** <add> * This is the test class for org.lockss.daemon.TitleConfig <add> */ <add> <add>public class TestTitleConfig extends LockssTestCase { <add> <add> public void setUp() { <add> } <add> <add> public void testConstructors() { <add> String id = "pid"; <add> String name = "foo 2"; <add> MockPlugin mp = new MockPlugin(); <add> mp.setPluginId(id); <add> TitleConfig tc1 = new TitleConfig(name, mp); <add> TitleConfig tc2 = new TitleConfig(name, id); <add> assertSame(id, tc1.getPluginName()); <add> assertSame(id, tc2.getPluginName()); <add> assertEquals(name, tc1.getDisplayName()); <add> } <add> <add> public void testAccessors1() { <add> TitleConfig tc1 = new TitleConfig("a", "b"); <add> tc1.setPluginVersion("4"); <add> assertEquals("4", tc1.getPluginVersion()); <add> List foo = new ArrayList(); <add> tc1.setParams(foo); <add> assertSame(foo, tc1.getParams()); <add> } <add> <add> public void testGetConfig() { <add> ConfigParamDescr d1 = new ConfigParamDescr("key1"); <add> ConfigParamDescr d2 = new ConfigParamDescr("key2"); <add> ConfigParamAssignment a1 = new ConfigParamAssignment(d1, "a"); <add> ConfigParamAssignment a2 = new ConfigParamAssignment(d2, "foo"); <add> TitleConfig tc1 = new TitleConfig("a", "b"); <add> tc1.setParams(ListUtil.list(a1, a2)); <add> Configuration config = tc1.getConfig(); <add> Configuration exp = ConfigManager.newConfiguration(); <add> exp.put("key1", "a"); <add> exp.put("key2", "foo"); <add> assertEquals(exp, config); <add> } <add> <add> public void testGetNoEditKeys() { <add> ConfigParamDescr d1 = new ConfigParamDescr("key1"); <add> ConfigParamDescr d2 = new ConfigParamDescr("key2"); <add> ConfigParamAssignment a1 = new ConfigParamAssignment(d1, "a"); <add> ConfigParamAssignment a2 = new ConfigParamAssignment(d2, "foo"); <add> a2.setEditable(true); <add> TitleConfig tc1 = new TitleConfig("a", "b"); <add> tc1.setParams(ListUtil.list(a1, a2)); <add> Collection u1 = tc1.getUnEditableKeys(); <add> assertIsomorphic(ListUtil.list("key1"), u1); <add> } <add>}
Java
mit
d45c7337ccb0edcd10fe5dc541f637228f75a88e
0
mnipper/AndroidSurvey,mnipper/AndroidSurvey,mnipper/AndroidSurvey,DukeMobileTech/AndroidSurvey
package org.adaptlab.chpir.android.survey; import java.util.UUID; import org.adaptlab.chpir.android.activerecordcloudsync.ActiveRecordCloudSync; import org.adaptlab.chpir.android.activerecordcloudsync.PollService; import org.adaptlab.chpir.android.survey.Models.AdminSettings; import org.adaptlab.chpir.android.survey.Models.Instrument; import org.adaptlab.chpir.android.survey.Models.Option; import org.adaptlab.chpir.android.survey.Models.Question; import org.adaptlab.chpir.android.survey.Models.Response; import org.adaptlab.chpir.android.survey.Models.Survey; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import com.crashlytics.android.Crashlytics; import android.app.AlertDialog; import android.app.admin.DevicePolicyManager; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.util.Log; public class AppUtil { private final static String TAG = "AppUtil"; public final static boolean REQUIRE_SECURITY_CHECKS = false; public static String ADMIN_PASSWORD_HASH; public static String ACCESS_TOKEN; /* * Get the version code from the AndroidManifest */ public static int getVersionCode(Context context) { try { PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return pInfo.versionCode; } catch (NameNotFoundException nnfe) { Log.e(TAG, "Error finding version code: " + nnfe); } return -1; } public static final void appInit(Context context) { if (AppUtil.REQUIRE_SECURITY_CHECKS) { if (!AppUtil.runDeviceSecurityChecks(context)) { // Device has failed security checks return; } } Log.i(TAG, "Initializing application..."); ADMIN_PASSWORD_HASH = context.getResources().getString(R.string.admin_password_hash); ACCESS_TOKEN = context.getResources().getString(R.string.backend_api_key); if (!BuildConfig.DEBUG) Crashlytics.start(context); DatabaseSeed.seed(context); if (AdminSettings.getInstance().getDeviceIdentifier() == null) { AdminSettings.getInstance().setDeviceIdentifier(UUID.randomUUID().toString()); } ActiveRecordCloudSync.setAccessToken(ACCESS_TOKEN); ActiveRecordCloudSync.setVersionCode(AppUtil.getVersionCode(context)); ActiveRecordCloudSync.setEndPoint(AdminSettings.getInstance().getApiUrl()); ActiveRecordCloudSync.addReceiveTable("instruments", Instrument.class); ActiveRecordCloudSync.addReceiveTable("questions", Question.class); ActiveRecordCloudSync.addReceiveTable("options", Option.class); ActiveRecordCloudSync.addSendTable("surveys", Survey.class); ActiveRecordCloudSync.addSendTable("responses", Response.class); PollService.setServiceAlarm(context.getApplicationContext(), true); } /* * Security checks that must pass for the application to start. * * If the application fails any security checks, display * AlertDialog indicating why and immediately stop execution * of the application. * * Current security checks: require encryption */ public static final boolean runDeviceSecurityChecks(Context context) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context .getSystemService(Context.DEVICE_POLICY_SERVICE); if (devicePolicyManager.getStorageEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE) { new AlertDialog.Builder(context) .setTitle(R.string.encryption_required_title) .setMessage(R.string.encryption_required_text) .setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .show(); return false; } return true; } /* * Hash the entered password and compare it with admin password hash */ public static boolean checkAdminPassword(String password) { String hash = new String(Hex.encodeHex(DigestUtils.sha256(password))); return hash.equals(ADMIN_PASSWORD_HASH); } }
src/org/adaptlab/chpir/android/survey/AppUtil.java
package org.adaptlab.chpir.android.survey; import java.util.UUID; import org.adaptlab.chpir.android.activerecordcloudsync.ActiveRecordCloudSync; import org.adaptlab.chpir.android.activerecordcloudsync.PollService; import org.adaptlab.chpir.android.survey.Models.AdminSettings; import org.adaptlab.chpir.android.survey.Models.Instrument; import org.adaptlab.chpir.android.survey.Models.Option; import org.adaptlab.chpir.android.survey.Models.Question; import org.adaptlab.chpir.android.survey.Models.Response; import org.adaptlab.chpir.android.survey.Models.Survey; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import com.crashlytics.android.Crashlytics; import android.app.AlertDialog; import android.app.admin.DevicePolicyManager; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.util.Log; public class AppUtil { private final static String TAG = "AppUtil"; public final static boolean REQUIRE_SECURITY_CHECKS = false; public static String ADMIN_PASSWORD_HASH; public static String ACCESS_TOKEN; /* * Get the version code from the AndroidManifest */ public static int getVersionCode(Context context) { try { PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return pInfo.versionCode; } catch (NameNotFoundException nnfe) { Log.e(TAG, "Error finding version code: " + nnfe); } return -1; } public static final void appInit(Context context) { if (AppUtil.REQUIRE_SECURITY_CHECKS) { if (!AppUtil.runDeviceSecurityChecks(context)) { // Device has failed security checks return; } } Log.i(TAG, "Initializing application..."); ADMIN_PASSWORD_HASH = context.getResources().getString(R.string.admin_password_hash); ACCESS_TOKEN = context.getResources().getString(R.string.backend_api_key); Crashlytics.start(context); DatabaseSeed.seed(context); if (AdminSettings.getInstance().getDeviceIdentifier() == null) { AdminSettings.getInstance().setDeviceIdentifier(UUID.randomUUID().toString()); } ActiveRecordCloudSync.setAccessToken(ACCESS_TOKEN); ActiveRecordCloudSync.setVersionCode(AppUtil.getVersionCode(context)); ActiveRecordCloudSync.setEndPoint(AdminSettings.getInstance().getApiUrl()); ActiveRecordCloudSync.addReceiveTable("instruments", Instrument.class); ActiveRecordCloudSync.addReceiveTable("questions", Question.class); ActiveRecordCloudSync.addReceiveTable("options", Option.class); ActiveRecordCloudSync.addSendTable("surveys", Survey.class); ActiveRecordCloudSync.addSendTable("responses", Response.class); PollService.setServiceAlarm(context.getApplicationContext(), true); } /* * Security checks that must pass for the application to start. * * If the application fails any security checks, display * AlertDialog indicating why and immediately stop execution * of the application. * * Current security checks: require encryption */ public static final boolean runDeviceSecurityChecks(Context context) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) context .getSystemService(Context.DEVICE_POLICY_SERVICE); if (devicePolicyManager.getStorageEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE) { new AlertDialog.Builder(context) .setTitle(R.string.encryption_required_title) .setMessage(R.string.encryption_required_text) .setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .show(); return false; } return true; } /* * Hash the entered password and compare it with admin password hash */ public static boolean checkAdminPassword(String password) { String hash = new String(Hex.encodeHex(DigestUtils.sha256(password))); return hash.equals(ADMIN_PASSWORD_HASH); } }
Only start Crashlytics if not in debug mode
src/org/adaptlab/chpir/android/survey/AppUtil.java
Only start Crashlytics if not in debug mode
<ide><path>rc/org/adaptlab/chpir/android/survey/AppUtil.java <ide> ADMIN_PASSWORD_HASH = context.getResources().getString(R.string.admin_password_hash); <ide> ACCESS_TOKEN = context.getResources().getString(R.string.backend_api_key); <ide> <del> Crashlytics.start(context); <add> if (!BuildConfig.DEBUG) <add> Crashlytics.start(context); <ide> <ide> DatabaseSeed.seed(context); <ide>