diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/ChangeUtil.java b/gerrit-server/src/main/java/com/google/gerrit/server/ChangeUtil.java
index 54bfe60d7..132a4997a 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/ChangeUtil.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/ChangeUtil.java
@@ -1,565 +1,565 @@
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server;
import com.google.common.base.CharMatcher;
import com.google.gerrit.common.ChangeHooks;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.ChangeMessage;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.PatchSetAncestor;
import com.google.gerrit.reviewdb.client.PatchSetInfo;
import com.google.gerrit.reviewdb.client.RevId;
import com.google.gerrit.reviewdb.client.TrackingId;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.config.TrackingFooter;
import com.google.gerrit.server.config.TrackingFooters;
import com.google.gerrit.server.extensions.events.GitReferenceUpdated;
import com.google.gerrit.server.git.GitRepositoryManager;
import com.google.gerrit.server.git.MergeOp;
import com.google.gerrit.server.mail.EmailException;
import com.google.gerrit.server.mail.ReplyToChangeSender;
import com.google.gerrit.server.mail.RevertedSender;
import com.google.gerrit.server.patch.PatchSetInfoFactory;
import com.google.gerrit.server.patch.PatchSetInfoNotAvailableException;
import com.google.gerrit.server.project.InvalidChangeOperationException;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.util.IdGenerator;
import com.google.gwtorm.server.AtomicUpdate;
import com.google.gwtorm.server.OrmConcurrencyException;
import com.google.gwtorm.server.OrmException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.FooterLine;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.util.Base64;
import org.eclipse.jgit.util.ChangeIdUtil;
import org.eclipse.jgit.util.NB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
public class ChangeUtil {
private static final Logger log = LoggerFactory.getLogger(ChangeUtil.class);
private static int uuidPrefix;
private static int uuidSeq;
/**
* Generate a new unique identifier for change message entities.
*
* @param db the database connection, used to increment the change message
* allocation sequence.
* @return the new unique identifier.
* @throws OrmException the database couldn't be incremented.
*/
public static String messageUUID(final ReviewDb db) throws OrmException {
final byte[] raw = new byte[8];
fill(raw, db);
// Make the resulting base64 string more URL friendly.
return CharMatcher.is('A').trimLeadingFrom(
CharMatcher.is('=').trimTrailingFrom(Base64.encodeBytes(raw)))
.replace('+', '.')
.replace('/', '-');
}
private static synchronized void fill(byte[] raw, ReviewDb db)
throws OrmException {
if (uuidSeq == 0) {
uuidPrefix = db.nextChangeMessageId();
uuidSeq = Integer.MAX_VALUE;
}
NB.encodeInt32(raw, 0, uuidPrefix);
NB.encodeInt32(raw, 4, IdGenerator.mix(uuidPrefix, uuidSeq--));
}
public static void touch(final Change change, ReviewDb db)
throws OrmException {
try {
updated(change);
db.changes().update(Collections.singleton(change));
} catch (OrmConcurrencyException e) {
// Ignore a concurrent update, we just wanted to tag it as newer.
}
}
public static void updated(final Change c) {
c.resetLastUpdatedOn();
computeSortKey(c);
}
public static void updateTrackingIds(ReviewDb db, Change change,
TrackingFooters trackingFooters, List<FooterLine> footerLines)
throws OrmException {
if (trackingFooters.getTrackingFooters().isEmpty() || footerLines.isEmpty()) {
return;
}
final Set<TrackingId> want = new HashSet<TrackingId>();
final Set<TrackingId> have = new HashSet<TrackingId>( //
db.trackingIds().byChange(change.getId()).toList());
for (final TrackingFooter footer : trackingFooters.getTrackingFooters()) {
for (final FooterLine footerLine : footerLines) {
if (footerLine.matches(footer.footerKey())) {
// supporting multiple tracking-ids on a single line
final Matcher m = footer.match().matcher(footerLine.getValue());
while (m.find()) {
if (m.group().isEmpty()) {
continue;
}
String idstr;
if (m.groupCount() > 0) {
idstr = m.group(1);
} else {
idstr = m.group();
}
if (idstr.isEmpty()) {
continue;
}
if (idstr.length() > TrackingId.TRACKING_ID_MAX_CHAR) {
continue;
}
want.add(new TrackingId(change.getId(), idstr, footer.system()));
}
}
}
}
// Only insert the rows we don't have, and delete rows we don't match.
//
final Set<TrackingId> toInsert = new HashSet<TrackingId>(want);
final Set<TrackingId> toDelete = new HashSet<TrackingId>(have);
toInsert.removeAll(have);
toDelete.removeAll(want);
db.trackingIds().insert(toInsert);
db.trackingIds().delete(toDelete);
}
public static void testMerge(MergeOp.Factory opFactory, Change change) {
opFactory.create(change.getDest()).verifyMergeability(change);
}
public static void insertAncestors(ReviewDb db, PatchSet.Id id, RevCommit src)
throws OrmException {
final int cnt = src.getParentCount();
List<PatchSetAncestor> toInsert = new ArrayList<PatchSetAncestor>(cnt);
for (int p = 0; p < cnt; p++) {
PatchSetAncestor a =
new PatchSetAncestor(new PatchSetAncestor.Id(id, p + 1));
a.setAncestorRevision(new RevId(src.getParent(p).getId().getName()));
toInsert.add(a);
}
db.patchSetAncestors().insert(toInsert);
}
public static Change.Id revert(final PatchSet.Id patchSetId,
final IdentifiedUser user, final String message, final ReviewDb db,
final RevertedSender.Factory revertedSenderFactory,
final ChangeHooks hooks, GitRepositoryManager gitManager,
final PatchSetInfoFactory patchSetInfoFactory,
final GitReferenceUpdated replication, PersonIdent myIdent)
throws NoSuchChangeException, EmailException, OrmException,
MissingObjectException, IncorrectObjectTypeException, IOException {
final Change.Id changeId = patchSetId.getParentKey();
final PatchSet patch = db.patchSets().get(patchSetId);
if (patch == null) {
throw new NoSuchChangeException(changeId);
}
final Change changeToRevert = db.changes().get(changeId);
final Repository git;
try {
git = gitManager.openRepository(changeToRevert.getProject());
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
}
final RevWalk revWalk = new RevWalk(git);
try {
RevCommit commitToRevert =
revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get()));
PersonIdent authorIdent =
user.newCommitterIdent(myIdent.getWhen(), myIdent.getTimeZone());
RevCommit parentToCommitToRevert = commitToRevert.getParent(0);
revWalk.parseHeaders(parentToCommitToRevert);
CommitBuilder revertCommitBuilder = new CommitBuilder();
revertCommitBuilder.addParentId(commitToRevert);
revertCommitBuilder.setTreeId(parentToCommitToRevert.getTree());
revertCommitBuilder.setAuthor(authorIdent);
revertCommitBuilder.setCommitter(myIdent);
final ObjectId computedChangeId =
ChangeIdUtil.computeChangeId(parentToCommitToRevert.getTree(),
commitToRevert, authorIdent, myIdent, message);
revertCommitBuilder.setMessage(ChangeIdUtil.insertId(message, computedChangeId, true));
RevCommit revertCommit;
final ObjectInserter oi = git.newObjectInserter();
try {
ObjectId id = oi.insert(revertCommitBuilder);
oi.flush();
revertCommit = revWalk.parseCommit(id);
} finally {
oi.release();
}
final Change change = new Change(
new Change.Key("I" + computedChangeId.name()),
new Change.Id(db.nextChangeId()),
user.getAccountId(),
changeToRevert.getDest());
change.nextPatchSetId();
change.setTopic(changeToRevert.getTopic());
final PatchSet ps = new PatchSet(change.currPatchSetId());
ps.setCreatedOn(change.getCreatedOn());
ps.setUploader(change.getOwner());
ps.setRevision(new RevId(revertCommit.name()));
change.setCurrentPatchSet(patchSetInfoFactory.get(revertCommit, ps.getId()));
ChangeUtil.updated(change);
final RefUpdate ru = git.updateRef(ps.getRefName());
ru.setExpectedOldObjectId(ObjectId.zeroId());
ru.setNewObjectId(revertCommit);
ru.disableRefLog();
if (ru.update(revWalk) != RefUpdate.Result.NEW) {
throw new IOException(String.format(
"Failed to create ref %s in %s: %s", ps.getRefName(),
change.getDest().getParentKey().get(), ru.getResult()));
}
replication.fire(change.getProject(), ru.getName());
db.changes().beginTransaction(change.getId());
try {
insertAncestors(db, ps.getId(), revertCommit);
db.patchSets().insert(Collections.singleton(ps));
db.changes().insert(Collections.singleton(change));
db.commit();
} finally {
db.rollback();
}
final ChangeMessage cmsg =
new ChangeMessage(new ChangeMessage.Key(changeId,
ChangeUtil.messageUUID(db)), user.getAccountId(), patchSetId);
final StringBuilder msgBuf =
new StringBuilder("Patch Set " + patchSetId.get() + ": Reverted");
msgBuf.append("\n\n");
msgBuf.append("This patchset was reverted in change: " + change.getKey().get());
cmsg.setMessage(msgBuf.toString());
db.changeMessages().insert(Collections.singleton(cmsg));
final RevertedSender cm = revertedSenderFactory.create(change);
cm.setFrom(user.getAccountId());
cm.setChangeMessage(cmsg);
cm.send();
hooks.doPatchsetCreatedHook(change, ps, db);
return change.getId();
} finally {
revWalk.release();
git.close();
}
}
public static Change.Id editCommitMessage(final PatchSet.Id patchSetId,
final IdentifiedUser user, final String message, final ReviewDb db,
final ChangeHooks hooks, GitRepositoryManager gitManager,
final PatchSetInfoFactory patchSetInfoFactory,
final GitReferenceUpdated replication, PersonIdent myIdent)
throws NoSuchChangeException, EmailException, OrmException,
MissingObjectException, IncorrectObjectTypeException, IOException,
InvalidChangeOperationException, PatchSetInfoNotAvailableException {
final Change.Id changeId = patchSetId.getParentKey();
final PatchSet patch = db.patchSets().get(patchSetId);
if (patch == null) {
throw new NoSuchChangeException(changeId);
}
if (message == null || message.length() == 0) {
throw new InvalidChangeOperationException("The commit message cannot be empty");
}
final Repository git;
try {
git = gitManager.openRepository(db.changes().get(changeId).getProject());
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
}
try {
final RevWalk revWalk = new RevWalk(git);
try {
Change change = db.changes().get(changeId);
RevCommit commit =
revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get()));
PersonIdent authorIdent =
user.newCommitterIdent(myIdent.getWhen(), myIdent.getTimeZone());
CommitBuilder commitBuilder = new CommitBuilder();
- commitBuilder.addParentId(commit);
commitBuilder.setTreeId(commit.getTree());
+ commitBuilder.setParentIds(commit.getParents());
commitBuilder.setAuthor(authorIdent);
commitBuilder.setCommitter(myIdent);
commitBuilder.setMessage(message);
RevCommit newCommit;
final ObjectInserter oi = git.newObjectInserter();
try {
ObjectId id = oi.insert(commitBuilder);
oi.flush();
newCommit = revWalk.parseCommit(id);
} finally {
oi.release();
}
change.nextPatchSetId();
final PatchSet originalPS = db.patchSets().get(patchSetId);
final PatchSet newPatchSet = new PatchSet(change.currPatchSetId());
newPatchSet.setCreatedOn(change.getCreatedOn());
newPatchSet.setUploader(change.getOwner());
newPatchSet.setRevision(new RevId(newCommit.name()));
newPatchSet.setDraft(originalPS.isDraft());
final PatchSetInfo info =
patchSetInfoFactory.get(newCommit, newPatchSet.getId());
final RefUpdate ru = git.updateRef(newPatchSet.getRefName());
ru.setExpectedOldObjectId(ObjectId.zeroId());
ru.setNewObjectId(newCommit);
ru.disableRefLog();
if (ru.update(revWalk) != RefUpdate.Result.NEW) {
throw new IOException(String.format(
"Failed to create ref %s in %s: %s", newPatchSet.getRefName(),
change.getDest().getParentKey().get(), ru.getResult()));
}
replication.fire(change.getProject(), ru.getName());
db.changes().beginTransaction(change.getId());
try {
Change updatedChange =
db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
if (change.getStatus().isOpen()) {
change.updateNumberOfPatchSets(newPatchSet.getPatchSetId());
return change;
} else {
return null;
}
}
});
if (updatedChange != null) {
change = updatedChange;
} else {
throw new InvalidChangeOperationException(String.format(
"Change %s is closed", change.getId()));
}
ChangeUtil.insertAncestors(db, newPatchSet.getId(), commit);
db.patchSets().insert(Collections.singleton(newPatchSet));
updatedChange =
db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
if (change.getStatus().isClosed()) {
return null;
}
if (!change.currentPatchSetId().equals(patchSetId)) {
return null;
}
if (change.getStatus() != Change.Status.DRAFT) {
change.setStatus(Change.Status.NEW);
}
change.setLastSha1MergeTested(null);
change.setCurrentPatchSet(info);
ChangeUtil.updated(change);
return change;
}
});
if (updatedChange != null) {
change = updatedChange;
} else {
throw new InvalidChangeOperationException(String.format(
"Change %s was modified", change.getId()));
}
final ChangeMessage cmsg =
new ChangeMessage(new ChangeMessage.Key(changeId,
ChangeUtil.messageUUID(db)), user.getAccountId(), patchSetId);
final String msg = "Patch Set " + newPatchSet.getPatchSetId() + ": Commit message was updated";
cmsg.setMessage(msg);
db.changeMessages().insert(Collections.singleton(cmsg));
db.commit();
} finally {
db.rollback();
}
hooks.doPatchsetCreatedHook(change, newPatchSet, db);
return change.getId();
} finally {
revWalk.release();
}
} finally {
git.close();
}
}
public static void deleteDraftChange(final PatchSet.Id patchSetId,
GitRepositoryManager gitManager,
final GitReferenceUpdated replication, final ReviewDb db)
throws NoSuchChangeException, OrmException, IOException {
final Change.Id changeId = patchSetId.getParentKey();
final Change change = db.changes().get(changeId);
if (change == null || change.getStatus() != Change.Status.DRAFT) {
throw new NoSuchChangeException(changeId);
}
for (PatchSet ps : db.patchSets().byChange(changeId)) {
// These should all be draft patch sets.
deleteOnlyDraftPatchSet(ps, change, gitManager, replication, db);
}
db.changeMessages().delete(db.changeMessages().byChange(changeId));
db.starredChanges().delete(db.starredChanges().byChange(changeId));
db.trackingIds().delete(db.trackingIds().byChange(changeId));
db.changes().delete(Collections.singleton(change));
}
public static void deleteOnlyDraftPatchSet(final PatchSet patch,
final Change change, GitRepositoryManager gitManager,
final GitReferenceUpdated replication, final ReviewDb db)
throws NoSuchChangeException, OrmException, IOException {
final PatchSet.Id patchSetId = patch.getId();
if (patch == null || !patch.isDraft()) {
throw new NoSuchChangeException(patchSetId.getParentKey());
}
Repository repo = gitManager.openRepository(change.getProject());
try {
RefUpdate update = repo.updateRef(patch.getRefName());
update.setForceUpdate(true);
update.disableRefLog();
switch (update.delete()) {
case NEW:
case FAST_FORWARD:
case FORCED:
case NO_CHANGE:
// Successful deletion.
break;
default:
throw new IOException("Failed to delete ref " + patch.getRefName() +
" in " + repo.getDirectory() + ": " + update.getResult());
}
replication.fire(change.getProject(), update.getName());
} finally {
repo.close();
}
db.accountPatchReviews().delete(db.accountPatchReviews().byPatchSet(patchSetId));
db.changeMessages().delete(db.changeMessages().byPatchSet(patchSetId));
db.patchComments().delete(db.patchComments().byPatchSet(patchSetId));
db.patchSetApprovals().delete(db.patchSetApprovals().byPatchSet(patchSetId));
db.patchSetAncestors().delete(db.patchSetAncestors().byPatchSet(patchSetId));
db.patchSets().delete(Collections.singleton(patch));
}
public static <T extends ReplyToChangeSender> void updatedChange(
final ReviewDb db, final IdentifiedUser user, final Change change,
final ChangeMessage cmsg, ReplyToChangeSender.Factory<T> senderFactory)
throws OrmException {
db.changeMessages().insert(Collections.singleton(cmsg));
new ApprovalsUtil(db, null).syncChangeStatus(change);
// Email the reviewers
try {
final ReplyToChangeSender cm = senderFactory.create(change);
cm.setFrom(user.getAccountId());
cm.setChangeMessage(cmsg);
cm.send();
} catch (Exception e) {
log.error("Cannot email update for change " + change.getChangeId(), e);
}
}
public static String sortKey(long lastUpdated, int id){
// The encoding uses minutes since Wed Oct 1 00:00:00 2008 UTC.
// We overrun approximately 4,085 years later, so ~6093.
//
final long lastUpdatedOn = (lastUpdated / 1000L) - 1222819200L;
final StringBuilder r = new StringBuilder(16);
r.setLength(16);
formatHexInt(r, 0, (int) (lastUpdatedOn / 60));
formatHexInt(r, 8, id);
return r.toString();
}
public static void computeSortKey(final Change c) {
long lastUpdated = c.getLastUpdatedOn().getTime();
int id = c.getId().get();
c.setSortKey(sortKey(lastUpdated, id));
}
private static final char[] hexchar =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', //
'a', 'b', 'c', 'd', 'e', 'f'};
private static void formatHexInt(final StringBuilder dst, final int p, int w) {
int o = p + 7;
while (o >= p && w != 0) {
dst.setCharAt(o--, hexchar[w & 0xf]);
w >>>= 4;
}
while (o >= p) {
dst.setCharAt(o--, '0');
}
}
}
| false | true | public static Change.Id editCommitMessage(final PatchSet.Id patchSetId,
final IdentifiedUser user, final String message, final ReviewDb db,
final ChangeHooks hooks, GitRepositoryManager gitManager,
final PatchSetInfoFactory patchSetInfoFactory,
final GitReferenceUpdated replication, PersonIdent myIdent)
throws NoSuchChangeException, EmailException, OrmException,
MissingObjectException, IncorrectObjectTypeException, IOException,
InvalidChangeOperationException, PatchSetInfoNotAvailableException {
final Change.Id changeId = patchSetId.getParentKey();
final PatchSet patch = db.patchSets().get(patchSetId);
if (patch == null) {
throw new NoSuchChangeException(changeId);
}
if (message == null || message.length() == 0) {
throw new InvalidChangeOperationException("The commit message cannot be empty");
}
final Repository git;
try {
git = gitManager.openRepository(db.changes().get(changeId).getProject());
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
}
try {
final RevWalk revWalk = new RevWalk(git);
try {
Change change = db.changes().get(changeId);
RevCommit commit =
revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get()));
PersonIdent authorIdent =
user.newCommitterIdent(myIdent.getWhen(), myIdent.getTimeZone());
CommitBuilder commitBuilder = new CommitBuilder();
commitBuilder.addParentId(commit);
commitBuilder.setTreeId(commit.getTree());
commitBuilder.setAuthor(authorIdent);
commitBuilder.setCommitter(myIdent);
commitBuilder.setMessage(message);
RevCommit newCommit;
final ObjectInserter oi = git.newObjectInserter();
try {
ObjectId id = oi.insert(commitBuilder);
oi.flush();
newCommit = revWalk.parseCommit(id);
} finally {
oi.release();
}
change.nextPatchSetId();
final PatchSet originalPS = db.patchSets().get(patchSetId);
final PatchSet newPatchSet = new PatchSet(change.currPatchSetId());
newPatchSet.setCreatedOn(change.getCreatedOn());
newPatchSet.setUploader(change.getOwner());
newPatchSet.setRevision(new RevId(newCommit.name()));
newPatchSet.setDraft(originalPS.isDraft());
final PatchSetInfo info =
patchSetInfoFactory.get(newCommit, newPatchSet.getId());
final RefUpdate ru = git.updateRef(newPatchSet.getRefName());
ru.setExpectedOldObjectId(ObjectId.zeroId());
ru.setNewObjectId(newCommit);
ru.disableRefLog();
if (ru.update(revWalk) != RefUpdate.Result.NEW) {
throw new IOException(String.format(
"Failed to create ref %s in %s: %s", newPatchSet.getRefName(),
change.getDest().getParentKey().get(), ru.getResult()));
}
replication.fire(change.getProject(), ru.getName());
db.changes().beginTransaction(change.getId());
try {
Change updatedChange =
db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
if (change.getStatus().isOpen()) {
change.updateNumberOfPatchSets(newPatchSet.getPatchSetId());
return change;
} else {
return null;
}
}
});
if (updatedChange != null) {
change = updatedChange;
} else {
throw new InvalidChangeOperationException(String.format(
"Change %s is closed", change.getId()));
}
ChangeUtil.insertAncestors(db, newPatchSet.getId(), commit);
db.patchSets().insert(Collections.singleton(newPatchSet));
updatedChange =
db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
if (change.getStatus().isClosed()) {
return null;
}
if (!change.currentPatchSetId().equals(patchSetId)) {
return null;
}
if (change.getStatus() != Change.Status.DRAFT) {
change.setStatus(Change.Status.NEW);
}
change.setLastSha1MergeTested(null);
change.setCurrentPatchSet(info);
ChangeUtil.updated(change);
return change;
}
});
if (updatedChange != null) {
change = updatedChange;
} else {
throw new InvalidChangeOperationException(String.format(
"Change %s was modified", change.getId()));
}
final ChangeMessage cmsg =
new ChangeMessage(new ChangeMessage.Key(changeId,
ChangeUtil.messageUUID(db)), user.getAccountId(), patchSetId);
final String msg = "Patch Set " + newPatchSet.getPatchSetId() + ": Commit message was updated";
cmsg.setMessage(msg);
db.changeMessages().insert(Collections.singleton(cmsg));
db.commit();
} finally {
db.rollback();
}
hooks.doPatchsetCreatedHook(change, newPatchSet, db);
return change.getId();
} finally {
revWalk.release();
}
} finally {
git.close();
}
}
| public static Change.Id editCommitMessage(final PatchSet.Id patchSetId,
final IdentifiedUser user, final String message, final ReviewDb db,
final ChangeHooks hooks, GitRepositoryManager gitManager,
final PatchSetInfoFactory patchSetInfoFactory,
final GitReferenceUpdated replication, PersonIdent myIdent)
throws NoSuchChangeException, EmailException, OrmException,
MissingObjectException, IncorrectObjectTypeException, IOException,
InvalidChangeOperationException, PatchSetInfoNotAvailableException {
final Change.Id changeId = patchSetId.getParentKey();
final PatchSet patch = db.patchSets().get(patchSetId);
if (patch == null) {
throw new NoSuchChangeException(changeId);
}
if (message == null || message.length() == 0) {
throw new InvalidChangeOperationException("The commit message cannot be empty");
}
final Repository git;
try {
git = gitManager.openRepository(db.changes().get(changeId).getProject());
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
}
try {
final RevWalk revWalk = new RevWalk(git);
try {
Change change = db.changes().get(changeId);
RevCommit commit =
revWalk.parseCommit(ObjectId.fromString(patch.getRevision().get()));
PersonIdent authorIdent =
user.newCommitterIdent(myIdent.getWhen(), myIdent.getTimeZone());
CommitBuilder commitBuilder = new CommitBuilder();
commitBuilder.setTreeId(commit.getTree());
commitBuilder.setParentIds(commit.getParents());
commitBuilder.setAuthor(authorIdent);
commitBuilder.setCommitter(myIdent);
commitBuilder.setMessage(message);
RevCommit newCommit;
final ObjectInserter oi = git.newObjectInserter();
try {
ObjectId id = oi.insert(commitBuilder);
oi.flush();
newCommit = revWalk.parseCommit(id);
} finally {
oi.release();
}
change.nextPatchSetId();
final PatchSet originalPS = db.patchSets().get(patchSetId);
final PatchSet newPatchSet = new PatchSet(change.currPatchSetId());
newPatchSet.setCreatedOn(change.getCreatedOn());
newPatchSet.setUploader(change.getOwner());
newPatchSet.setRevision(new RevId(newCommit.name()));
newPatchSet.setDraft(originalPS.isDraft());
final PatchSetInfo info =
patchSetInfoFactory.get(newCommit, newPatchSet.getId());
final RefUpdate ru = git.updateRef(newPatchSet.getRefName());
ru.setExpectedOldObjectId(ObjectId.zeroId());
ru.setNewObjectId(newCommit);
ru.disableRefLog();
if (ru.update(revWalk) != RefUpdate.Result.NEW) {
throw new IOException(String.format(
"Failed to create ref %s in %s: %s", newPatchSet.getRefName(),
change.getDest().getParentKey().get(), ru.getResult()));
}
replication.fire(change.getProject(), ru.getName());
db.changes().beginTransaction(change.getId());
try {
Change updatedChange =
db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
if (change.getStatus().isOpen()) {
change.updateNumberOfPatchSets(newPatchSet.getPatchSetId());
return change;
} else {
return null;
}
}
});
if (updatedChange != null) {
change = updatedChange;
} else {
throw new InvalidChangeOperationException(String.format(
"Change %s is closed", change.getId()));
}
ChangeUtil.insertAncestors(db, newPatchSet.getId(), commit);
db.patchSets().insert(Collections.singleton(newPatchSet));
updatedChange =
db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
if (change.getStatus().isClosed()) {
return null;
}
if (!change.currentPatchSetId().equals(patchSetId)) {
return null;
}
if (change.getStatus() != Change.Status.DRAFT) {
change.setStatus(Change.Status.NEW);
}
change.setLastSha1MergeTested(null);
change.setCurrentPatchSet(info);
ChangeUtil.updated(change);
return change;
}
});
if (updatedChange != null) {
change = updatedChange;
} else {
throw new InvalidChangeOperationException(String.format(
"Change %s was modified", change.getId()));
}
final ChangeMessage cmsg =
new ChangeMessage(new ChangeMessage.Key(changeId,
ChangeUtil.messageUUID(db)), user.getAccountId(), patchSetId);
final String msg = "Patch Set " + newPatchSet.getPatchSetId() + ": Commit message was updated";
cmsg.setMessage(msg);
db.changeMessages().insert(Collections.singleton(cmsg));
db.commit();
} finally {
db.rollback();
}
hooks.doPatchsetCreatedHook(change, newPatchSet, db);
return change.getId();
} finally {
revWalk.release();
}
} finally {
git.close();
}
}
|
diff --git a/src/edu/jhu/nlp/wikipedia/WikiTextParser.java b/src/edu/jhu/nlp/wikipedia/WikiTextParser.java
index 7f4c762..d9716fe 100644
--- a/src/edu/jhu/nlp/wikipedia/WikiTextParser.java
+++ b/src/edu/jhu/nlp/wikipedia/WikiTextParser.java
@@ -1,177 +1,180 @@
package edu.jhu.nlp.wikipedia;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* For internal use only -- Used by the {@link WikiPage} class.
* Can also be used as a stand alone class to parse wiki formatted text.
* @author Delip Rao
*
*/
public class WikiTextParser {
private String wikiText = null;
private Vector<String> pageCats = null;
private Vector<String> pageLinks = null;
private boolean redirect = false;
private String redirectString = null;
private static Pattern redirectPattern =
Pattern.compile("#REDIRECT\\s+\\[\\[(.*?)\\]\\]");
private boolean stub = false;
private boolean disambiguation = false;
private static Pattern stubPattern = Pattern.compile("\\-stub\\}\\}");
private static Pattern disambCatPattern = Pattern.compile("\\{\\{disambig\\}\\}");
private InfoBox infoBox = null;
public WikiTextParser(String wtext) {
wikiText = wtext;
Matcher matcher = redirectPattern.matcher(wikiText);
if(matcher.find()) {
redirect = true;
if(matcher.groupCount() == 1)
redirectString = matcher.group(1);
}
matcher = stubPattern.matcher(wikiText);
stub = matcher.find();
matcher = disambCatPattern.matcher(wikiText);
disambiguation = matcher.find();
}
public boolean isRedirect() {
return redirect;
}
public boolean isStub() {
return stub;
}
public String getRedirectText() {
return redirectString;
}
public String getText() {
return wikiText;
}
public Vector<String> getCategories() {
if(pageCats == null) parseCategories();
return pageCats;
}
public Vector<String> getLinks() {
if(pageLinks == null) parseLinks();
return pageLinks;
}
private void parseCategories() {
pageCats = new Vector<String>();
Pattern catPattern = Pattern.compile("\\[\\[Category:(.*?)\\]\\]", Pattern.MULTILINE);
Matcher matcher = catPattern.matcher(wikiText);
while(matcher.find()) {
String [] temp = matcher.group(1).split("\\|");
pageCats.add(temp[0]);
}
}
private void parseLinks() {
pageLinks = new Vector<String>();
Pattern catPattern = Pattern.compile("\\[\\[(.*?)\\]\\]", Pattern.MULTILINE);
Matcher matcher = catPattern.matcher(wikiText);
while(matcher.find()) {
String [] temp = matcher.group(1).split("\\|");
if(temp == null || temp.length == 0) continue;
String link = temp[0];
if(link.contains(":") == false) {
pageLinks.add(link);
}
}
}
public String getPlainText() {
String text = wikiText.replaceAll(">", ">");
text = text.replaceAll("<", "<");
text = text.replaceAll("<ref>.*?</ref>", " ");
text = text.replaceAll("</?.*?>", " ");
text = text.replaceAll("\\{\\{.*?\\}\\}", " ");
text = text.replaceAll("\\[\\[.*?:.*?\\]\\]", " ");
text = text.replaceAll("\\[\\[(.*?)\\]\\]", "$1");
text = text.replaceAll("\\s(.*?)\\|(\\w+\\s)", " $2");
text = text.replaceAll("\\[.*?\\]", " ");
text = text.replaceAll("\\'+", "");
return text;
}
public InfoBox getInfoBox() {
//parseInfoBox is expensive. Doing it only once like other parse* methods
if(infoBox == null)
infoBox = parseInfoBox();
return infoBox;
}
private InfoBox parseInfoBox() {
String INFOBOX_CONST_STR = "{{Infobox";
int startPos = wikiText.indexOf(INFOBOX_CONST_STR);
if(startPos < 0) return null;
int bracketCount = 2;
int endPos = startPos + INFOBOX_CONST_STR.length();
for(; endPos < wikiText.length(); endPos++) {
switch(wikiText.charAt(endPos)) {
case '}':
bracketCount--;
break;
case '{':
bracketCount++;
break;
default:
}
if(bracketCount == 0) break;
}
+ if(endPos+1 >= wikiText.length()) return null;
+ // This happens due to malformed Infoboxes in wiki text. See Issue #10
+ // Giving up parsing is the easier thing to do.
String infoBoxText = wikiText.substring(startPos, endPos+1);
infoBoxText = stripCite(infoBoxText); // strip clumsy {{cite}} tags
// strip any html formatting
infoBoxText = infoBoxText.replaceAll(">", ">");
infoBoxText = infoBoxText.replaceAll("<", "<");
infoBoxText = infoBoxText.replaceAll("<ref.*?>.*?</ref>", " ");
infoBoxText = infoBoxText.replaceAll("</?.*?>", " ");
return new InfoBox(infoBoxText);
}
private String stripCite(String text) {
String CITE_CONST_STR = "{{cite";
int startPos = text.indexOf(CITE_CONST_STR);
if(startPos < 0) return text;
int bracketCount = 2;
int endPos = startPos + CITE_CONST_STR.length();
for(; endPos < text.length(); endPos++) {
switch(text.charAt(endPos)) {
case '}':
bracketCount--;
break;
case '{':
bracketCount++;
break;
default:
}
if(bracketCount == 0) break;
}
text = text.substring(0, startPos-1) + text.substring(endPos);
return stripCite(text);
}
public boolean isDisambiguationPage() {
return disambiguation;
}
public String getTranslatedTitle(String languageCode) {
Pattern pattern = Pattern.compile("^\\[\\[" + languageCode + ":(.*?)\\]\\]$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(wikiText);
if(matcher.find()) {
return matcher.group(1);
}
return null;
}
}
| true | true | private InfoBox parseInfoBox() {
String INFOBOX_CONST_STR = "{{Infobox";
int startPos = wikiText.indexOf(INFOBOX_CONST_STR);
if(startPos < 0) return null;
int bracketCount = 2;
int endPos = startPos + INFOBOX_CONST_STR.length();
for(; endPos < wikiText.length(); endPos++) {
switch(wikiText.charAt(endPos)) {
case '}':
bracketCount--;
break;
case '{':
bracketCount++;
break;
default:
}
if(bracketCount == 0) break;
}
String infoBoxText = wikiText.substring(startPos, endPos+1);
infoBoxText = stripCite(infoBoxText); // strip clumsy {{cite}} tags
// strip any html formatting
infoBoxText = infoBoxText.replaceAll(">", ">");
infoBoxText = infoBoxText.replaceAll("<", "<");
infoBoxText = infoBoxText.replaceAll("<ref.*?>.*?</ref>", " ");
infoBoxText = infoBoxText.replaceAll("</?.*?>", " ");
return new InfoBox(infoBoxText);
}
| private InfoBox parseInfoBox() {
String INFOBOX_CONST_STR = "{{Infobox";
int startPos = wikiText.indexOf(INFOBOX_CONST_STR);
if(startPos < 0) return null;
int bracketCount = 2;
int endPos = startPos + INFOBOX_CONST_STR.length();
for(; endPos < wikiText.length(); endPos++) {
switch(wikiText.charAt(endPos)) {
case '}':
bracketCount--;
break;
case '{':
bracketCount++;
break;
default:
}
if(bracketCount == 0) break;
}
if(endPos+1 >= wikiText.length()) return null;
// This happens due to malformed Infoboxes in wiki text. See Issue #10
// Giving up parsing is the easier thing to do.
String infoBoxText = wikiText.substring(startPos, endPos+1);
infoBoxText = stripCite(infoBoxText); // strip clumsy {{cite}} tags
// strip any html formatting
infoBoxText = infoBoxText.replaceAll(">", ">");
infoBoxText = infoBoxText.replaceAll("<", "<");
infoBoxText = infoBoxText.replaceAll("<ref.*?>.*?</ref>", " ");
infoBoxText = infoBoxText.replaceAll("</?.*?>", " ");
return new InfoBox(infoBoxText);
}
|
diff --git a/src/test/java/org/jboss/threads/ThreadPoolTestCase.java b/src/test/java/org/jboss/threads/ThreadPoolTestCase.java
index a977013..b29324d 100644
--- a/src/test/java/org/jboss/threads/ThreadPoolTestCase.java
+++ b/src/test/java/org/jboss/threads/ThreadPoolTestCase.java
@@ -1,214 +1,217 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt 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.jboss.threads;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import junit.framework.TestCase;
/**
*
*/
public final class ThreadPoolTestCase extends TestCase {
private final JBossThreadFactory threadFactory = new JBossThreadFactory(null, null, null, "test thread %p %t", null, null);
private static final class SimpleTask implements Runnable {
private final CountDownLatch taskUnfreezer;
private final CountDownLatch taskFinishLine;
private SimpleTask(final CountDownLatch taskUnfreezer, final CountDownLatch taskFinishLine) {
this.taskUnfreezer = taskUnfreezer;
this.taskFinishLine = taskFinishLine;
}
public void run() {
try {
assertTrue(taskUnfreezer.await(800L, TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
fail("interrupted");
}
taskFinishLine.countDown();
}
}
public void testBasic() throws InterruptedException {
// Start some tasks, let them run, then shut down the executor
final int cnt = 100;
final CountDownLatch taskUnfreezer = new CountDownLatch(1);
final CountDownLatch taskFinishLine = new CountDownLatch(cnt);
final ExecutorService simpleQueueExecutor = new QueueExecutor(5, 5, 500L, TimeUnit.MILLISECONDS, 1000, threadFactory, true, null);
for (int i = 0; i < cnt; i ++) {
simpleQueueExecutor.execute(new SimpleTask(taskUnfreezer, taskFinishLine));
}
taskUnfreezer.countDown();
final boolean finished = taskFinishLine.await(800L, TimeUnit.MILLISECONDS);
assertTrue(finished);
simpleQueueExecutor.shutdown();
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task not rejected after shutdown");
} catch (Throwable t) {
assertTrue(t instanceof RejectedExecutionException);
}
assertTrue(simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
}
public void testShutdownNow() throws InterruptedException {
final AtomicBoolean interrupted = new AtomicBoolean();
final AtomicBoolean ran = new AtomicBoolean();
final CountDownLatch startLatch = new CountDownLatch(1);
final CountDownLatch finLatch = new CountDownLatch(1);
final ExecutorService simpleQueueExecutor = new QueueExecutor(5, 5, 500L, TimeUnit.MILLISECONDS, 1000, threadFactory, true, null);
simpleQueueExecutor.execute(new Runnable() {
public void run() {
try {
ran.set(true);
startLatch.countDown();
Thread.sleep(5000L);
} catch (InterruptedException e) {
interrupted.set(true);
} finally {
finLatch.countDown();
}
}
});
assertTrue("Task not started", startLatch.await(300L, TimeUnit.MILLISECONDS));
assertTrue("Task returned", simpleQueueExecutor.shutdownNow().isEmpty());
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task not rejected after shutdown");
} catch (RejectedExecutionException t) {
}
assertTrue("Task not finished", finLatch.await(300L, TimeUnit.MILLISECONDS));
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
assertTrue("Task wasn't run", ran.get());
assertTrue("Worker wasn't interrupted", interrupted.get());
}
private static class Holder<T> {
private T instance;
public Holder(T instance) {
this.instance = instance;
}
public T get() { return instance; }
public void set(T instance) {this.instance = instance;}
}
public void testBlocking() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final CountDownLatch taskUnfreezer = new CountDownLatch(1);
final CountDownLatch taskFinishLine = new CountDownLatch(cnt);
final ExecutorService simpleQueueExecutor = new QueueExecutor(coreThreads, coreThreads + extraThreads, 500L, TimeUnit.MILLISECONDS, new ArrayQueue<Runnable>(queueSize), threadFactory, true, null);
for (int i = 0; i < cnt; i ++) {
simpleQueueExecutor.execute(new SimpleTask(taskUnfreezer, taskFinishLine));
}
Thread.currentThread().interrupt();
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task was accepted");
} catch (RejectedExecutionException t) {
}
Thread.interrupted();
final CountDownLatch latch = new CountDownLatch(1);
final Thread otherThread = threadFactory.newThread(new Runnable() {
public void run() {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
latch.countDown();
}
});
}
});
otherThread.start();
assertFalse("Task executed without wait", latch.await(100L, TimeUnit.MILLISECONDS));
// safe to say the other thread is blocking...?
taskUnfreezer.countDown();
assertTrue("Task never ran", latch.await(800L, TimeUnit.MILLISECONDS));
otherThread.join(500L);
assertTrue("Simple Tasks never ran", taskFinishLine.await(800L, TimeUnit.MILLISECONDS));
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
+ final CountDownLatch shutdownLatch = new CountDownLatch(1);
((QueueExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
+ shutdownLatch.countDown();
} } , null);
+ shutdownLatch.await(100L, TimeUnit.MILLISECONDS);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
}
public void testBlockingEmpty() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final ExecutorService simpleQueueExecutor = new QueueExecutor(coreThreads, coreThreads + extraThreads, 500L, TimeUnit.MILLISECONDS, new ArrayQueue<Runnable>(queueSize), threadFactory, true, null);
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
((QueueExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
} } , null);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
Thread.interrupted();
}
public void testQueuelessEmpty() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final ExecutorService simpleQueueExecutor = new QueuelessExecutor(threadFactory, SimpleDirectExecutor.INSTANCE, null, 500L);
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
((QueuelessExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
} } , null);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
Thread.interrupted();
}
}
| false | true | public void testBlocking() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final CountDownLatch taskUnfreezer = new CountDownLatch(1);
final CountDownLatch taskFinishLine = new CountDownLatch(cnt);
final ExecutorService simpleQueueExecutor = new QueueExecutor(coreThreads, coreThreads + extraThreads, 500L, TimeUnit.MILLISECONDS, new ArrayQueue<Runnable>(queueSize), threadFactory, true, null);
for (int i = 0; i < cnt; i ++) {
simpleQueueExecutor.execute(new SimpleTask(taskUnfreezer, taskFinishLine));
}
Thread.currentThread().interrupt();
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task was accepted");
} catch (RejectedExecutionException t) {
}
Thread.interrupted();
final CountDownLatch latch = new CountDownLatch(1);
final Thread otherThread = threadFactory.newThread(new Runnable() {
public void run() {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
latch.countDown();
}
});
}
});
otherThread.start();
assertFalse("Task executed without wait", latch.await(100L, TimeUnit.MILLISECONDS));
// safe to say the other thread is blocking...?
taskUnfreezer.countDown();
assertTrue("Task never ran", latch.await(800L, TimeUnit.MILLISECONDS));
otherThread.join(500L);
assertTrue("Simple Tasks never ran", taskFinishLine.await(800L, TimeUnit.MILLISECONDS));
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
((QueueExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
} } , null);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
}
| public void testBlocking() throws InterruptedException {
final int queueSize = 20;
final int coreThreads = 5;
final int extraThreads = 5;
final int cnt = queueSize + coreThreads + extraThreads;
final CountDownLatch taskUnfreezer = new CountDownLatch(1);
final CountDownLatch taskFinishLine = new CountDownLatch(cnt);
final ExecutorService simpleQueueExecutor = new QueueExecutor(coreThreads, coreThreads + extraThreads, 500L, TimeUnit.MILLISECONDS, new ArrayQueue<Runnable>(queueSize), threadFactory, true, null);
for (int i = 0; i < cnt; i ++) {
simpleQueueExecutor.execute(new SimpleTask(taskUnfreezer, taskFinishLine));
}
Thread.currentThread().interrupt();
try {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
}
});
fail("Task was accepted");
} catch (RejectedExecutionException t) {
}
Thread.interrupted();
final CountDownLatch latch = new CountDownLatch(1);
final Thread otherThread = threadFactory.newThread(new Runnable() {
public void run() {
simpleQueueExecutor.execute(new Runnable() {
public void run() {
latch.countDown();
}
});
}
});
otherThread.start();
assertFalse("Task executed without wait", latch.await(100L, TimeUnit.MILLISECONDS));
// safe to say the other thread is blocking...?
taskUnfreezer.countDown();
assertTrue("Task never ran", latch.await(800L, TimeUnit.MILLISECONDS));
otherThread.join(500L);
assertTrue("Simple Tasks never ran", taskFinishLine.await(800L, TimeUnit.MILLISECONDS));
simpleQueueExecutor.shutdown();
final Holder<Boolean> callback = new Holder<Boolean>(false);
final CountDownLatch shutdownLatch = new CountDownLatch(1);
((QueueExecutor)simpleQueueExecutor).addShutdownListener(new EventListener<Object>() {
@Override
public void handleEvent(Object attachment) {
callback.set(true);
shutdownLatch.countDown();
} } , null);
shutdownLatch.await(100L, TimeUnit.MILLISECONDS);
assertTrue("Calback not called", callback.get());
assertTrue("Executor not shut down in 800ms", simpleQueueExecutor.awaitTermination(800L, TimeUnit.MILLISECONDS));
}
|
diff --git a/source/de/anomic/crawler/robotsParser.java b/source/de/anomic/crawler/robotsParser.java
index bb87e01f2..97b9648f0 100644
--- a/source/de/anomic/crawler/robotsParser.java
+++ b/source/de/anomic/crawler/robotsParser.java
@@ -1,224 +1,224 @@
//robotsParser.java
//-------------------------------------
//part of YACY
//
//(C) 2005, 2006 by Alexander Schier
// Martin Thelian
//
//last change: $LastChangedDate$ by $LastChangedBy$
//Revision: $LastChangedRevision$
//
//This program is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 2 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// extended to return structured objects instead of a Object[] and
// extended to return a Allow-List by Michael Christen, 21.07.2008
package de.anomic.crawler;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
/*
* A class for Parsing robots.txt files.
* It only parses the Deny Part, yet.
*
* Robots RFC
* http://www.robotstxt.org/wc/norobots-rfc.html
*
* TODO:
* - On the request attempt resulted in temporary failure a robot
* should defer visits to the site until such time as the resource
* can be retrieved.
*
* - Extended Standard for Robot Exclusion
* See: http://www.conman.org/people/spc/robots2.html
*
* - Robot Exclusion Standard Revisited
* See: http://www.kollar.com/robots.html
*/
public final class robotsParser {
public static final String ROBOTS_USER_AGENT = "User-agent:".toUpperCase();
public static final String ROBOTS_DISALLOW = "Disallow:".toUpperCase();
public static final String ROBOTS_ALLOW = "Allow:".toUpperCase();
public static final String ROBOTS_COMMENT = "#";
public static final String ROBOTS_SITEMAP = "Sitemap:".toUpperCase();
public static final String ROBOTS_CRAWL_DELAY = "Crawl-Delay:".toUpperCase();
private ArrayList<String> allowList;
private ArrayList<String> denyList;
private String sitemap;
private long crawlDelayMillis;
public robotsParser(final byte[] robotsTxt) {
if ((robotsTxt == null)||(robotsTxt.length == 0)) {
allowList = new ArrayList<String>(0);
denyList = new ArrayList<String>(0);
sitemap = "";
crawlDelayMillis = 0;
} else {
final ByteArrayInputStream bin = new ByteArrayInputStream(robotsTxt);
final BufferedReader reader = new BufferedReader(new InputStreamReader(bin));
parse(reader);
}
}
public robotsParser(final BufferedReader reader) {
if (reader == null) {
allowList = new ArrayList<String>(0);
denyList = new ArrayList<String>(0);
sitemap = "";
crawlDelayMillis = 0;
} else {
parse(reader);
}
}
private void parse(final BufferedReader reader) {
final ArrayList<String> deny4AllAgents = new ArrayList<String>();
final ArrayList<String> deny4YaCyAgent = new ArrayList<String>();
final ArrayList<String> allow4AllAgents = new ArrayList<String>();
final ArrayList<String> allow4YaCyAgent = new ArrayList<String>();
int pos;
String line = null, lineUpper = null;
sitemap = null;
crawlDelayMillis = 0;
boolean isRule4AllAgents = false,
isRule4YaCyAgent = false,
rule4YaCyFound = false,
inBlock = false;
try {
while ((line = reader.readLine()) != null) {
// replacing all tabs with spaces
- line = line.replaceAll("\t"," ").replaceAll(":"," ").trim();
+ line = line.replaceAll("\t"," ").trim();
lineUpper = line.toUpperCase();
if (line.length() == 0) {
// OLD: we have reached the end of the rule block
// rule4Yacy = false; inBlock = false;
// NEW: just ignore it
} else if (line.startsWith(ROBOTS_COMMENT)) {
// we can ignore this. Just a comment line
} else if (lineUpper.startsWith(ROBOTS_SITEMAP)) {
pos = line.indexOf(" ");
if (pos != -1) {
sitemap = line.substring(pos).trim();
}
} else if (lineUpper.startsWith(ROBOTS_USER_AGENT)) {
if (inBlock) {
// we have detected the start of a new block
inBlock = false;
isRule4AllAgents = false;
isRule4YaCyAgent = false;
crawlDelayMillis = 0; // each block has a separate delay
}
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// getting out the robots name
pos = line.indexOf(" ");
if (pos != -1) {
final String userAgent = line.substring(pos).trim();
isRule4AllAgents |= userAgent.equals("*");
isRule4YaCyAgent |= userAgent.toLowerCase().indexOf("yacy") >=0;
if (isRule4YaCyAgent) rule4YaCyFound = true;
}
} else if (lineUpper.startsWith(ROBOTS_CRAWL_DELAY)) {
pos = line.indexOf(" ");
if (pos != -1) {
try {
// the crawl delay can be a float number and means number of seconds
crawlDelayMillis = (long) (1000.0 * Float.parseFloat(line.substring(pos).trim()));
} catch (final NumberFormatException e) {
// invalid crawling delay
}
}
} else if (lineUpper.startsWith(ROBOTS_DISALLOW) ||
lineUpper.startsWith(ROBOTS_ALLOW)) {
inBlock = true;
final boolean isDisallowRule = lineUpper.startsWith(ROBOTS_DISALLOW);
if (isRule4YaCyAgent || isRule4AllAgents) {
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// cutting of tailing *
if (line.endsWith("*")) line = line.substring(0,line.length()-1);
// getting the path
pos = line.indexOf(" ");
if (pos != -1) {
// getting the path
String path = line.substring(pos).trim();
// unencoding all special charsx
try {
path = URLDecoder.decode(path,"UTF-8");
} catch (final Exception e) {
/*
* url decoding failed. E.g. because of
* "Incomplete trailing escape (%) pattern"
*/
}
// escaping all occurences of ; because this char is used as special char in the Robots DB
path = path.replaceAll(RobotsTxt.ROBOTS_DB_PATH_SEPARATOR,"%3B");
// adding it to the pathlist
if (isDisallowRule) {
if (isRule4AllAgents) deny4AllAgents.add(path);
if (isRule4YaCyAgent) deny4YaCyAgent.add(path);
} else {
if (isRule4AllAgents) allow4AllAgents.add(path);
if (isRule4YaCyAgent) allow4YaCyAgent.add(path);
}
}
}
}
}
} catch (final IOException e) {}
allowList = (rule4YaCyFound) ? allow4YaCyAgent : allow4AllAgents;
denyList = (rule4YaCyFound) ? deny4YaCyAgent : deny4AllAgents;
}
public long crawlDelayMillis() {
return this.crawlDelayMillis;
}
public String sitemap() {
return this.sitemap;
}
public ArrayList<String> allowList() {
return this.allowList;
}
public ArrayList<String> denyList() {
return this.denyList;
}
}
| true | true | private void parse(final BufferedReader reader) {
final ArrayList<String> deny4AllAgents = new ArrayList<String>();
final ArrayList<String> deny4YaCyAgent = new ArrayList<String>();
final ArrayList<String> allow4AllAgents = new ArrayList<String>();
final ArrayList<String> allow4YaCyAgent = new ArrayList<String>();
int pos;
String line = null, lineUpper = null;
sitemap = null;
crawlDelayMillis = 0;
boolean isRule4AllAgents = false,
isRule4YaCyAgent = false,
rule4YaCyFound = false,
inBlock = false;
try {
while ((line = reader.readLine()) != null) {
// replacing all tabs with spaces
line = line.replaceAll("\t"," ").replaceAll(":"," ").trim();
lineUpper = line.toUpperCase();
if (line.length() == 0) {
// OLD: we have reached the end of the rule block
// rule4Yacy = false; inBlock = false;
// NEW: just ignore it
} else if (line.startsWith(ROBOTS_COMMENT)) {
// we can ignore this. Just a comment line
} else if (lineUpper.startsWith(ROBOTS_SITEMAP)) {
pos = line.indexOf(" ");
if (pos != -1) {
sitemap = line.substring(pos).trim();
}
} else if (lineUpper.startsWith(ROBOTS_USER_AGENT)) {
if (inBlock) {
// we have detected the start of a new block
inBlock = false;
isRule4AllAgents = false;
isRule4YaCyAgent = false;
crawlDelayMillis = 0; // each block has a separate delay
}
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// getting out the robots name
pos = line.indexOf(" ");
if (pos != -1) {
final String userAgent = line.substring(pos).trim();
isRule4AllAgents |= userAgent.equals("*");
isRule4YaCyAgent |= userAgent.toLowerCase().indexOf("yacy") >=0;
if (isRule4YaCyAgent) rule4YaCyFound = true;
}
} else if (lineUpper.startsWith(ROBOTS_CRAWL_DELAY)) {
pos = line.indexOf(" ");
if (pos != -1) {
try {
// the crawl delay can be a float number and means number of seconds
crawlDelayMillis = (long) (1000.0 * Float.parseFloat(line.substring(pos).trim()));
} catch (final NumberFormatException e) {
// invalid crawling delay
}
}
} else if (lineUpper.startsWith(ROBOTS_DISALLOW) ||
lineUpper.startsWith(ROBOTS_ALLOW)) {
inBlock = true;
final boolean isDisallowRule = lineUpper.startsWith(ROBOTS_DISALLOW);
if (isRule4YaCyAgent || isRule4AllAgents) {
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// cutting of tailing *
if (line.endsWith("*")) line = line.substring(0,line.length()-1);
// getting the path
pos = line.indexOf(" ");
if (pos != -1) {
// getting the path
String path = line.substring(pos).trim();
// unencoding all special charsx
try {
path = URLDecoder.decode(path,"UTF-8");
} catch (final Exception e) {
/*
* url decoding failed. E.g. because of
* "Incomplete trailing escape (%) pattern"
*/
}
// escaping all occurences of ; because this char is used as special char in the Robots DB
path = path.replaceAll(RobotsTxt.ROBOTS_DB_PATH_SEPARATOR,"%3B");
// adding it to the pathlist
if (isDisallowRule) {
if (isRule4AllAgents) deny4AllAgents.add(path);
if (isRule4YaCyAgent) deny4YaCyAgent.add(path);
} else {
if (isRule4AllAgents) allow4AllAgents.add(path);
if (isRule4YaCyAgent) allow4YaCyAgent.add(path);
}
}
}
}
}
} catch (final IOException e) {}
allowList = (rule4YaCyFound) ? allow4YaCyAgent : allow4AllAgents;
denyList = (rule4YaCyFound) ? deny4YaCyAgent : deny4AllAgents;
}
| private void parse(final BufferedReader reader) {
final ArrayList<String> deny4AllAgents = new ArrayList<String>();
final ArrayList<String> deny4YaCyAgent = new ArrayList<String>();
final ArrayList<String> allow4AllAgents = new ArrayList<String>();
final ArrayList<String> allow4YaCyAgent = new ArrayList<String>();
int pos;
String line = null, lineUpper = null;
sitemap = null;
crawlDelayMillis = 0;
boolean isRule4AllAgents = false,
isRule4YaCyAgent = false,
rule4YaCyFound = false,
inBlock = false;
try {
while ((line = reader.readLine()) != null) {
// replacing all tabs with spaces
line = line.replaceAll("\t"," ").trim();
lineUpper = line.toUpperCase();
if (line.length() == 0) {
// OLD: we have reached the end of the rule block
// rule4Yacy = false; inBlock = false;
// NEW: just ignore it
} else if (line.startsWith(ROBOTS_COMMENT)) {
// we can ignore this. Just a comment line
} else if (lineUpper.startsWith(ROBOTS_SITEMAP)) {
pos = line.indexOf(" ");
if (pos != -1) {
sitemap = line.substring(pos).trim();
}
} else if (lineUpper.startsWith(ROBOTS_USER_AGENT)) {
if (inBlock) {
// we have detected the start of a new block
inBlock = false;
isRule4AllAgents = false;
isRule4YaCyAgent = false;
crawlDelayMillis = 0; // each block has a separate delay
}
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// getting out the robots name
pos = line.indexOf(" ");
if (pos != -1) {
final String userAgent = line.substring(pos).trim();
isRule4AllAgents |= userAgent.equals("*");
isRule4YaCyAgent |= userAgent.toLowerCase().indexOf("yacy") >=0;
if (isRule4YaCyAgent) rule4YaCyFound = true;
}
} else if (lineUpper.startsWith(ROBOTS_CRAWL_DELAY)) {
pos = line.indexOf(" ");
if (pos != -1) {
try {
// the crawl delay can be a float number and means number of seconds
crawlDelayMillis = (long) (1000.0 * Float.parseFloat(line.substring(pos).trim()));
} catch (final NumberFormatException e) {
// invalid crawling delay
}
}
} else if (lineUpper.startsWith(ROBOTS_DISALLOW) ||
lineUpper.startsWith(ROBOTS_ALLOW)) {
inBlock = true;
final boolean isDisallowRule = lineUpper.startsWith(ROBOTS_DISALLOW);
if (isRule4YaCyAgent || isRule4AllAgents) {
// cutting off comments at the line end
pos = line.indexOf(ROBOTS_COMMENT);
if (pos != -1) line = line.substring(0,pos).trim();
// cutting of tailing *
if (line.endsWith("*")) line = line.substring(0,line.length()-1);
// getting the path
pos = line.indexOf(" ");
if (pos != -1) {
// getting the path
String path = line.substring(pos).trim();
// unencoding all special charsx
try {
path = URLDecoder.decode(path,"UTF-8");
} catch (final Exception e) {
/*
* url decoding failed. E.g. because of
* "Incomplete trailing escape (%) pattern"
*/
}
// escaping all occurences of ; because this char is used as special char in the Robots DB
path = path.replaceAll(RobotsTxt.ROBOTS_DB_PATH_SEPARATOR,"%3B");
// adding it to the pathlist
if (isDisallowRule) {
if (isRule4AllAgents) deny4AllAgents.add(path);
if (isRule4YaCyAgent) deny4YaCyAgent.add(path);
} else {
if (isRule4AllAgents) allow4AllAgents.add(path);
if (isRule4YaCyAgent) allow4YaCyAgent.add(path);
}
}
}
}
}
} catch (final IOException e) {}
allowList = (rule4YaCyFound) ? allow4YaCyAgent : allow4AllAgents;
denyList = (rule4YaCyFound) ? deny4YaCyAgent : deny4AllAgents;
}
|
diff --git a/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/internal/context/core/CompositeInteractionContext.java b/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/internal/context/core/CompositeInteractionContext.java
index f12bdf8a9..a881e074a 100644
--- a/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/internal/context/core/CompositeInteractionContext.java
+++ b/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/internal/context/core/CompositeInteractionContext.java
@@ -1,174 +1,174 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.context.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.mylyn.context.core.IInteractionContext;
import org.eclipse.mylyn.context.core.IInteractionContextScaling;
import org.eclipse.mylyn.context.core.IInteractionElement;
import org.eclipse.mylyn.monitor.core.InteractionEvent;
/**
* Delegates to contained contexts.
*
* TODO: should info be propagated proportionally to number of taskscapes?
*
* @author Mik Kersten
* @author Shawn Minto
*/
public class CompositeInteractionContext implements IInteractionContext {
protected Map<String, InteractionContext> contexts = new HashMap<String, InteractionContext>();
protected IInteractionElement activeNode = null;
private final IInteractionContextScaling contextScaling;
public String contentLimitedTo = null;
public CompositeInteractionContext(IInteractionContextScaling contextScaling) {
this.contextScaling = contextScaling;
}
public IInteractionElement addEvent(InteractionEvent event) {
List<InteractionContextElement> nodes = new ArrayList<InteractionContextElement>();
for (InteractionContext context : contexts.values()) {
InteractionContextElement info = (InteractionContextElement) context.parseEvent(event);
nodes.add(info);
}
CompositeContextElement compositeNode = new CompositeContextElement(event.getStructureHandle(), nodes,
contextScaling);
return compositeNode;
}
public IInteractionElement get(String handle) {
- if (contexts.values().size() == 0) {
+ if (handle == null || contexts.values().size() == 0) {
return null;
}
List<InteractionContextElement> nodes = new ArrayList<InteractionContextElement>();
for (InteractionContext taskscape : contexts.values()) {
InteractionContextElement node = (InteractionContextElement) taskscape.get(handle);
if (node != null) {
nodes.add(node);
}
}
CompositeContextElement composite = new CompositeContextElement(handle, nodes, contextScaling);
return composite;
}
public List<IInteractionElement> getLandmarks() {
Set<IInteractionElement> landmarks = new HashSet<IInteractionElement>();
for (InteractionContext taskscape : contexts.values()) {
for (IInteractionElement concreteNode : taskscape.getLandmarks()) {
if (concreteNode != null) {
landmarks.add(get(concreteNode.getHandleIdentifier()));
}
}
}
return new ArrayList<IInteractionElement>(landmarks);
}
public List<IInteractionElement> getInteresting() {
Set<IInteractionElement> landmarks = new HashSet<IInteractionElement>();
for (InteractionContext context : contexts.values()) {
for (IInteractionElement concreteNode : context.getInteresting()) {
if (concreteNode != null) {
landmarks.add(get(concreteNode.getHandleIdentifier()));
}
}
}
return new ArrayList<IInteractionElement>(landmarks);
}
public void setActiveElement(IInteractionElement activeElement) {
this.activeNode = activeElement;
}
public IInteractionElement getActiveNode() {
return activeNode;
}
public void delete(IInteractionElement node) {
for (InteractionContext taskscape : contexts.values()) {
taskscape.delete(node);
}
}
public void clear() {
for (InteractionContext taskscape : contexts.values()) {
taskscape.reset();
}
}
public Map<String, InteractionContext> getContextMap() {
return contexts;
}
public List<IInteractionElement> getAllElements() {
Set<IInteractionElement> nodes = new HashSet<IInteractionElement>();
for (InteractionContext context : contexts.values()) {
for (IInteractionElement concreteNode : context.getAllElements()) {
nodes.add(get(concreteNode.getHandleIdentifier()));
}
}
return new ArrayList<IInteractionElement>(nodes);
}
/**
* TODO: sort by date?
*/
public List<InteractionEvent> getInteractionHistory() {
Set<InteractionEvent> events = new HashSet<InteractionEvent>();
for (InteractionContext taskscape : contexts.values()) {
events.addAll(taskscape.getInteractionHistory());
}
return new ArrayList<InteractionEvent>(events);
}
public void updateElementHandle(IInteractionElement element, String newHandle) {
for (InteractionContext context : contexts.values()) {
context.updateElementHandle(element, newHandle);
}
element.setHandleIdentifier(newHandle);
}
/**
* Composite contexts do not have a unique handle identifier.
*
* @return null if no unique handle
*/
public String getHandleIdentifier() {
if (contexts.values().size() == 1) {
return contexts.keySet().iterator().next();
} else {
return null;
}
}
public IInteractionContextScaling getScaling() {
return contextScaling;
}
public String getContentLimitedTo() {
return contentLimitedTo;
}
public void setContentLimitedTo(String contentLimitedTo) {
this.contentLimitedTo = contentLimitedTo;
}
}
| true | true | public IInteractionElement get(String handle) {
if (contexts.values().size() == 0) {
return null;
}
List<InteractionContextElement> nodes = new ArrayList<InteractionContextElement>();
for (InteractionContext taskscape : contexts.values()) {
InteractionContextElement node = (InteractionContextElement) taskscape.get(handle);
if (node != null) {
nodes.add(node);
}
}
CompositeContextElement composite = new CompositeContextElement(handle, nodes, contextScaling);
return composite;
}
| public IInteractionElement get(String handle) {
if (handle == null || contexts.values().size() == 0) {
return null;
}
List<InteractionContextElement> nodes = new ArrayList<InteractionContextElement>();
for (InteractionContext taskscape : contexts.values()) {
InteractionContextElement node = (InteractionContextElement) taskscape.get(handle);
if (node != null) {
nodes.add(node);
}
}
CompositeContextElement composite = new CompositeContextElement(handle, nodes, contextScaling);
return composite;
}
|
diff --git a/dashboard/src/main/java/com/appnomic/appsone/dashboard/action/config/ConfigUtilityAction.java b/dashboard/src/main/java/com/appnomic/appsone/dashboard/action/config/ConfigUtilityAction.java
index 81d09f9..82b2e0f 100644
--- a/dashboard/src/main/java/com/appnomic/appsone/dashboard/action/config/ConfigUtilityAction.java
+++ b/dashboard/src/main/java/com/appnomic/appsone/dashboard/action/config/ConfigUtilityAction.java
@@ -1,164 +1,164 @@
package com.appnomic.appsone.dashboard.action.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import com.appnomic.appsone.dashboard.action.ActionConstants;
import com.appnomic.appsone.dashboard.action.noc.AbstractNocAction;
import com.appnomic.appsone.dashboard.config.AlertGridConfigManager;
import com.appnomic.appsone.dashboard.config.ConfigType;
import com.appnomic.appsone.dashboard.config.LevelDBManager;
import com.appnomic.appsone.dashboard.config.attribute.*;
import com.appnomic.appsone.dashboard.config.entity.AlertGridEntity;
import com.appnomic.appsone.dashboard.viewobject.config.AlertGridConfigVO;
import com.appnomic.appsone.dashboard.viewobject.config.PageListVO;
import com.appnomic.appsone.dashboard.viewobject.config.TabListVO;
import com.appnomic.appsone.dashboard.viewobject.config.base.BooleanAttributeVO;
import com.appnomic.appsone.dashboard.viewobject.config.base.IntegerAttributeVO;
import com.appnomic.appsone.dashboard.viewobject.config.base.StringAttributeVO;
@ParentPackage("json-default")
@Namespace("/config")
public class ConfigUtilityAction extends AbstractNocAction {
private PageListVO [] pageListVO;
private Map<String, String[]> param;
private Map<String, String> levelDbMap;
public Map<String, String> getLevelDbMap() {
return levelDbMap;
}
public void setLevelDbMap(Map<String, String> levelDbMap) {
this.levelDbMap = levelDbMap;
}
public PageListVO[] getPageListVO() {
return pageListVO;
}
public void setPageListVO(PageListVO[] pageListVO) {
this.pageListVO = pageListVO;
}
public Map<String, String[]> getParam() {
return param;
}
public void setParam(Map<String, String[]> param) {
this.param = param;
}
@Action(value="/config/pages", results = {
@Result(name="success", type="json", params = {
"excludeProperties",
"parameters,session,SUCCESS,ERROR,agcVO,levelDbMap",
"enableGZIP", "true",
"encoding", "UTF-8",
"noCache","true",
"excludeNullProperties","true"
})})
public String pagesAction() {
param = getParameters();
pageListVO = getDummyList();
return SUCCESS;
}
private PageListVO[] getDummyList() {
List<PageListVO> pageList = new ArrayList<PageListVO>();
PageListVO pageListVO = new PageListVO();
pageListVO.setName("Alerts Grid");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);
/*pageListVO = new PageListVO();
pageListVO.setName("Clusters Grid");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);*/
pageListVO = new PageListVO();
pageListVO.setName("Transactions Grid");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);
- pageListVO = new PageListVO();
+ /*pageListVO = new PageListVO();
pageListVO.setName("Topology View");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);
pageListVO = new PageListVO();
pageListVO.setName("Global Config");
pageListVO.setId(UUID.randomUUID().toString());
- pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
+ pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());*/
pageList.add(pageListVO);
PageListVO [] pageArray = pageList.toArray(new PageListVO[pageList.size()]);
return pageArray;
}
////////////////////////////////////////////////////////////////////////////////////////////////
public static Integer getInteger(String name, Map<String, String[]> parameters) {
Integer myint = null;
try {
myint = Integer.parseInt(parameters.get(name)[0]);
} catch(Exception e) {
//e.printStackTrace();
}
return myint;
}
public static Boolean getBoolean(String name, Map<String, String[]> parameters) {
Boolean mybool = null;
try {
mybool = Boolean.parseBoolean(parameters.get(name)[0]);
} catch(Exception e) {
//e.printStackTrace();
}
return mybool;
}
////////////////////////////////////////////////////////////////////////////////////////////////
@Action(value="/config/allConfigDump", results = {
@Result(name="success", type="json", params = {
"excludeProperties",
"parameters,session,SUCCESS,ERROR,age,agcVO,pageListVO",
"enableGZIP", "true",
"encoding", "UTF-8",
"noCache","true",
"excludeNullProperties","true"
})})
public String allConfigDumpAction() {
LevelDBManager instance = null;
try {
instance = LevelDBManager.getInstance();
//instance.init();
levelDbMap = instance.getAllKeyValues();
} catch(Exception e) {
e.printStackTrace();
} finally {
if(instance!=null) {
//instance.shutdown();
}
}
return SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////////////////////
}
| false | true | private PageListVO[] getDummyList() {
List<PageListVO> pageList = new ArrayList<PageListVO>();
PageListVO pageListVO = new PageListVO();
pageListVO.setName("Alerts Grid");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);
/*pageListVO = new PageListVO();
pageListVO.setName("Clusters Grid");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);*/
pageListVO = new PageListVO();
pageListVO.setName("Transactions Grid");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);
pageListVO = new PageListVO();
pageListVO.setName("Topology View");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);
pageListVO = new PageListVO();
pageListVO.setName("Global Config");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);
PageListVO [] pageArray = pageList.toArray(new PageListVO[pageList.size()]);
return pageArray;
}
| private PageListVO[] getDummyList() {
List<PageListVO> pageList = new ArrayList<PageListVO>();
PageListVO pageListVO = new PageListVO();
pageListVO.setName("Alerts Grid");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);
/*pageListVO = new PageListVO();
pageListVO.setName("Clusters Grid");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);*/
pageListVO = new PageListVO();
pageListVO.setName("Transactions Grid");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);
/*pageListVO = new PageListVO();
pageListVO.setName("Topology View");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());
pageList.add(pageListVO);
pageListVO = new PageListVO();
pageListVO.setName("Global Config");
pageListVO.setId(UUID.randomUUID().toString());
pageListVO.setType(ActionConstants.ACCTYPE.GRID.name());*/
pageList.add(pageListVO);
PageListVO [] pageArray = pageList.toArray(new PageListVO[pageList.size()]);
return pageArray;
}
|
diff --git a/src/org/goldclone/converter/areaConverter.java b/src/org/goldclone/converter/areaConverter.java
index fc44e52..970176e 100644
--- a/src/org/goldclone/converter/areaConverter.java
+++ b/src/org/goldclone/converter/areaConverter.java
@@ -1,52 +1,52 @@
package org.goldclone.converter;
public class areaConverter {
private static areaConverter instance = null;
protected areaConverter() {
// Exists only to defeat instantiation.
}
public static areaConverter getInstance() {
if (instance == null) {
instance = new areaConverter();
}
return instance;
}
// <item>Squaremillimeters</item>
// <item>Squarecentimeters</item>
// <item>Squarefeet</item>
// <item>Squareinches</item>
// <item>Squareyards</item>
public double convert(double input, int from, int to) {
double sqMMeter;
if (from == 0) {// Squaremillimeters
sqMMeter = input;
} else if (from == 1) { // Squarecentimeters
sqMMeter = input * 100;
} else if (from == 2) {// Squarefeet
sqMMeter = input * 92903;
} else if (from == 3) { // Squareinches
sqMMeter = input * 645.2;
} else { // Squareyards
sqMMeter = input * 836127;
}
if (to == 0) {// Squaremillimeters
- return input;
+ return sqMMeter;
} else if (to == 1) { // Squarecentimeters
- return input / 100;
+ return sqMMeter / 100;
} else if (to == 2) {// Squarefeet
- return input / 92903;
+ return sqMMeter / 92903;
} else if (to == 3) { // Squareinches
- return input / 645.2;
+ return sqMMeter / 645.2;
} else { // Squareyards
- return input / 836127;
+ return sqMMeter / 836127;
}
}
}
| false | true | public double convert(double input, int from, int to) {
double sqMMeter;
if (from == 0) {// Squaremillimeters
sqMMeter = input;
} else if (from == 1) { // Squarecentimeters
sqMMeter = input * 100;
} else if (from == 2) {// Squarefeet
sqMMeter = input * 92903;
} else if (from == 3) { // Squareinches
sqMMeter = input * 645.2;
} else { // Squareyards
sqMMeter = input * 836127;
}
if (to == 0) {// Squaremillimeters
return input;
} else if (to == 1) { // Squarecentimeters
return input / 100;
} else if (to == 2) {// Squarefeet
return input / 92903;
} else if (to == 3) { // Squareinches
return input / 645.2;
} else { // Squareyards
return input / 836127;
}
}
| public double convert(double input, int from, int to) {
double sqMMeter;
if (from == 0) {// Squaremillimeters
sqMMeter = input;
} else if (from == 1) { // Squarecentimeters
sqMMeter = input * 100;
} else if (from == 2) {// Squarefeet
sqMMeter = input * 92903;
} else if (from == 3) { // Squareinches
sqMMeter = input * 645.2;
} else { // Squareyards
sqMMeter = input * 836127;
}
if (to == 0) {// Squaremillimeters
return sqMMeter;
} else if (to == 1) { // Squarecentimeters
return sqMMeter / 100;
} else if (to == 2) {// Squarefeet
return sqMMeter / 92903;
} else if (to == 3) { // Squareinches
return sqMMeter / 645.2;
} else { // Squareyards
return sqMMeter / 836127;
}
}
|
diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/commit/CompositeEditorProvider.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/commit/CompositeEditorProvider.java
index 95348589be..0fd18fb410 100644
--- a/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/commit/CompositeEditorProvider.java
+++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/spi/commit/CompositeEditorProvider.java
@@ -1,87 +1,87 @@
/*
* 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.jackrabbit.oak.spi.commit;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Arrays.asList;
import java.util.Collection;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import com.google.common.collect.Lists;
/**
* Aggregation of a list of editor providers into a single provider.
*/
public class CompositeEditorProvider implements EditorProvider {
private static final EditorProvider EMPTY_PROVIDER =
new EditorProvider() {
@Override @CheckForNull
public Editor getRootEditor(
NodeState before, NodeState after, NodeBuilder builder) {
return null;
}
};
@Nonnull
public static EditorProvider compose(
@Nonnull Collection<? extends EditorProvider> providers) {
checkNotNull(providers);
switch (providers.size()) {
- case 0:
- return EMPTY_PROVIDER;
- case 1:
- return providers.iterator().next();
- default:
- return new CompositeEditorProvider(providers);
+ case 0:
+ return EMPTY_PROVIDER;
+ case 1:
+ return providers.iterator().next();
+ default:
+ return new CompositeEditorProvider(providers);
}
}
private final Collection<? extends EditorProvider> providers;
private CompositeEditorProvider(
Collection<? extends EditorProvider> providers) {
this.providers = providers;
}
public CompositeEditorProvider(EditorProvider... providers) {
this(asList(providers));
}
@Override @CheckForNull
public Editor getRootEditor(
NodeState before, NodeState after, NodeBuilder builder)
throws CommitFailedException {
List<Editor> list = Lists.newArrayListWithCapacity(providers.size());
for (EditorProvider provider : providers) {
Editor editor = provider.getRootEditor(before, after, builder);
if (editor != null) {
list.add(editor);
}
}
return CompositeEditor.compose(list);
}
}
| true | true | public static EditorProvider compose(
@Nonnull Collection<? extends EditorProvider> providers) {
checkNotNull(providers);
switch (providers.size()) {
case 0:
return EMPTY_PROVIDER;
case 1:
return providers.iterator().next();
default:
return new CompositeEditorProvider(providers);
}
}
| public static EditorProvider compose(
@Nonnull Collection<? extends EditorProvider> providers) {
checkNotNull(providers);
switch (providers.size()) {
case 0:
return EMPTY_PROVIDER;
case 1:
return providers.iterator().next();
default:
return new CompositeEditorProvider(providers);
}
}
|
diff --git a/src/com/zand/areaguard/Area.java b/src/com/zand/areaguard/Area.java
index 84dbb60..c555b22 100644
--- a/src/com/zand/areaguard/Area.java
+++ b/src/com/zand/areaguard/Area.java
@@ -1,148 +1,148 @@
package com.zand.areaguard;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Area {
private static AreaDatabase ad = AreaDatabase.getInstance();
public static Area getArea(int id) {
return ad.getArea(id);
}
public static Area getArea(int x, int y, int z) {
return ad.getArea(ad.getAreaId(x, y, z));
}
public static Area getArea(String name) {
return ad.getArea(ad.getAreaId(name));
}
public static Area getOwnedArea(String owner, String name) {
for (int id : ad.getAreaIdsFromListValues("owners", owner)) {
Area area = ad.getArea(id);
if (area != null)
if (area.getName().equals(name))
return area;
}
return null;
}
public static boolean remove(int id) {
return ad.removeArea(id);
}
private Integer id = -1;
// Cache
private String name = "NOT FOUND";
private int priority = 0;
private int[] coords = new int[6];
protected Area(int id, String name, int priority, int[] coords) {
this.id = id;
this.name = name;
this.priority = priority;
if (coords.length == 6)
this.coords = coords;
}
public Area(String name, int[] coords) {
this.name = name;
if (coords.length == 6)
this.coords = coords;
this.id = ad.addArea(name, coords);
}
public boolean setMsg(String name, String msg) {
return ad.setMsg(id, name, msg);
}
public boolean addList(String list, HashSet<String> values) {
return ad.addList(id, list, values);
}
public int[] getCoords() {
return coords;
}
public int getId() {
return id;
}
public String getMsg(String name) {
return ad.getMsg(id, name);
}
public Set<String> getLists() {
return ad.getLists(id);
}
public ArrayList<String> getList(String list) {
return ad.getList(id, list);
}
public String getName() {
return name;
}
public boolean remove() {
return remove(id);
}
public boolean removeList(String list) {
return ad.removeList(id, list);
}
public boolean removeList(String list, HashSet<String> values) {
return ad.removeList(id, list, values);
}
public boolean setCoords(int[] coords) {
if (id == -1) return false;
if (coords.length != 6) return false;
this.coords = coords;
return ad.updateArea(this);
}
public boolean setName(String name) {
if (id == -1) return false;
this.name = name;
return ad.updateArea(this);
}
public String toString() {
return "[" + id + "] \t" + name + " \t@ (" +
coords[0] + ", " + coords[1] + ", " + coords[2] + ")-(" +
coords[3] + ", " + coords[4] + ", " + coords[5] + ")";
}
public boolean listHas(String list, String value) {
return ad.listHas(id, list, value);
}
public boolean playerCan(String player, String name, boolean checkAllow) {
- if (checkAllow || listHas("owners", player)) return true;
+ if (checkAllow && listHas("owners", player)) return true;
if (listHas("restrict", name)) {
- if (checkAllow || listHas("allow", player)) return true;
+ if (checkAllow && listHas("allow", player)) return true;
if (listHas(name, player)) return true;
return false;
}
if (listHas("no-allow", player)) return false;
if (listHas("no-"+name, player)) return false;
return true;
}
public HashMap<String, String> getMsgs() {
return ad.getMsgs(id);
}
public int getPriority() {
return priority;
}
public boolean setPriority(int priority) {
if (id == -1) return false;
this.priority = priority;
return ad.updateArea(this);
}
}
| false | true | public boolean playerCan(String player, String name, boolean checkAllow) {
if (checkAllow || listHas("owners", player)) return true;
if (listHas("restrict", name)) {
if (checkAllow || listHas("allow", player)) return true;
if (listHas(name, player)) return true;
return false;
}
if (listHas("no-allow", player)) return false;
if (listHas("no-"+name, player)) return false;
return true;
}
| public boolean playerCan(String player, String name, boolean checkAllow) {
if (checkAllow && listHas("owners", player)) return true;
if (listHas("restrict", name)) {
if (checkAllow && listHas("allow", player)) return true;
if (listHas(name, player)) return true;
return false;
}
if (listHas("no-allow", player)) return false;
if (listHas("no-"+name, player)) return false;
return true;
}
|
diff --git a/xwiki-platform-editor-tool-autocomplete/xwiki-platform-editor-tool-autocomplete-api/src/main/java/org/xwiki/editor/tool/autocomplete/internal/AutoCompletionResource.java b/xwiki-platform-editor-tool-autocomplete/xwiki-platform-editor-tool-autocomplete-api/src/main/java/org/xwiki/editor/tool/autocomplete/internal/AutoCompletionResource.java
index 06c63c0..891e4f5 100644
--- a/xwiki-platform-editor-tool-autocomplete/xwiki-platform-editor-tool-autocomplete-api/src/main/java/org/xwiki/editor/tool/autocomplete/internal/AutoCompletionResource.java
+++ b/xwiki-platform-editor-tool-autocomplete/xwiki-platform-editor-tool-autocomplete-api/src/main/java/org/xwiki/editor/tool/autocomplete/internal/AutoCompletionResource.java
@@ -1,350 +1,350 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.xwiki.editor.tool.autocomplete.internal;
import java.util.Collections;
import javax.inject.Inject;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.editor.tool.autocomplete.AutoCompletionMethodFinder;
import org.xwiki.editor.tool.autocomplete.TargetContent;
import org.xwiki.editor.tool.autocomplete.TargetContentLocator;
import org.xwiki.editor.tool.autocomplete.TargetContentType;
import org.xwiki.rest.XWikiRestComponent;
import org.xwiki.velocity.VelocityManager;
import org.xwiki.velocity.internal.util.InvalidVelocityException;
import org.xwiki.velocity.internal.util.VelocityParser;
import org.xwiki.velocity.internal.util.VelocityParserContext;
/**
* REST Resource for returning autocompletion hints. The content to autocomplete is passed in the request body, the
* position of the cursor and the syntax in which the content is written in are passed as request parameters.
*
* @version $Id$
* @since 4.2M2
*/
@Component("org.xwiki.editor.tool.autocomplete.internal.AutoCompletionResource")
@Path("/autocomplete")
public class AutoCompletionResource implements XWikiRestComponent
{
/**
* Used to get the Velocity Context from which we retrieve the list of bound variables that are used for
* autocompletion.
*/
@Inject
private VelocityManager velocityManager;
/**
* Used to dynamically find Autocompletion Method finder to handle specific cases.
*
* @see AutoCompletionMethodFinder
*/
@Inject
private ComponentManager componentManager;
/**
* Used to autodiscover method hints.
*/
@Inject
private AutoCompletionMethodFinder defaultAutoCompletionMethodFinder;
/**
* Used to extract the content and the type under the cursor position.
*/
@Inject
private TargetContentLocator targetContentLocator;
/**
* Logging framework.
*/
@Inject
private Logger logger;
/**
* A Velocity Parser that we use to help parse Velocity content for figuring out autocompletion.
*/
private VelocityParser parser = new VelocityParser();
/**
* Main REST entry point for getting Autocompletion hints.
*
* @param offset the position of the cursor in the full content
* @param syntaxId the syntax in which the content is written in
* @param content the full wiki content
* @return the list of autocompletion hints
*/
@POST
public Hints getAutoCompletionHints(@QueryParam("offset") int offset, @QueryParam("syntax") String syntaxId,
String content)
{
Hints hints = new Hints();
// Only support autocompletion on Velocity ATM
TargetContent targetContent = this.targetContentLocator.locate(content, syntaxId, offset);
if (targetContent.getType() == TargetContentType.VELOCITY) {
hints = getHints(targetContent.getContent(), targetContent.getPosition());
}
// Subtract the temporary user input size from the initial offset to get the absolute start offset of the user's
// input.
hints.withStartOffset(offset - hints.getStartOffset());
return hints;
}
/**
* @param content the Velocity content to autocomplete
* @param offset the position of the cursor relative to the Velocity content
* @return the list of autocompletion hints
*/
private Hints getHints(String content, int offset)
{
Hints results = new Hints();
char[] chars = content.toCharArray();
VelocityContext velocityContext = this.velocityManager.getVelocityContext();
// Find the dollar sign before the current position
int dollarPos = StringUtils.lastIndexOf(content, '$', offset);
if (dollarPos > -1) {
// Special case for when there's no variable after the dollar position since the Velocity Parser doesn't
// support parsing this case.
if (isCursorDirectlyAfterDollar(chars, dollarPos, offset)) {
// Find all objects bound to the Velocity Context. We need to also look in the chained context since
// this is where we store Velocity Tools
results = getVelocityContextKeys("", velocityContext);
} else {
StringBuffer velocityBlock = new StringBuffer();
VelocityParserContext context = new VelocityParserContext();
try {
// Get the block after the dollar
int blockPos = this.parser.getVar(chars, dollarPos, velocityBlock, context);
// if newPos matches the current position then it means we have a valid block for autocompletion
// Note: we need to handle the special case where the cursor is just after the dot since getVar
// will not return it!
if (blockPos + 1 == offset && chars[blockPos] == '.') {
blockPos++;
velocityBlock.append('.');
}
if (blockPos == offset) {
results = getMethodsOrVariableHints(chars, dollarPos, blockPos, offset, velocityContext);
}
} catch (InvalidVelocityException e) {
- this.logger.debug("Failed to get autocomplete hints for content [{}] at offset [{}]", new Object[] {
- content, offset, e});
+ this.logger.debug("Failed to get autocomplete hints for content [{}] at offset [{}]",
+ new Object[] {content, offset, e});
}
}
}
// Sort hints
Collections.sort(results.getHints());
return results;
}
/**
* @param chars the content to parse
* @param dollarPos the position of the dollar symbol
* @param offset the position in the whole content of the cursor
* @return false if there's a velocity variable after the dollar sign
*/
private boolean isCursorDirectlyAfterDollar(char[] chars, int dollarPos, int offset)
{
boolean result = true;
for (int i = dollarPos; i < offset; i++) {
if (chars[i] != '$' && chars[i] != '!' && chars[i] != '{') {
result = false;
break;
}
}
return result;
}
/**
* @param chars the content to parse
* @param dollarPos the position of the dollar symbol
* @param blockPos the position in the content after the whole fragment starting with the dollar symbol
* @param offset the position in the whole content of the cursor
* @param velocityContext the velocity context used to get the variables bound in the Velocity Context
* @return the list of hints
* @throws InvalidVelocityException when the code to parse is not what's expected
*/
private Hints getMethodsOrVariableHints(char[] chars, int dollarPos, int blockPos, int offset,
VelocityContext velocityContext) throws InvalidVelocityException
{
Hints results = new Hints();
// Get the property before the first dot.
int methodPos = -1;
for (int i = dollarPos; i < offset; i++) {
if (chars[i] == '.') {
methodPos = i;
break;
}
}
// Get the variable name without any leading '$', '!' or '{'
int endPos = (methodPos == -1) ? offset : methodPos;
int variableStartPos = -1;
for (int i = dollarPos; i < endPos; i++) {
if (chars[i] != '$' && chars[i] != '!' && chars[i] != '{') {
variableStartPos = i;
break;
}
}
if (variableStartPos > -1) {
String variableName = new String(chars, variableStartPos, endPos - variableStartPos);
if (methodPos > -1) {
results = getMethods(chars, variableName, blockPos, methodPos, offset, velocityContext);
// Set the temporary start offset as the size of the user's input.
results.withStartOffset(blockPos - methodPos - 1);
} else {
results = getVelocityContextKeys(variableName, velocityContext);
// Set the temporary start offset as the size of the user's input.
results.withStartOffset(variableName.length());
}
}
return results;
}
/**
* @param chars the content to parse
* @param propertyName the name of the property on which we want to find methods
* @param blockPos the position in the content after the whole fragment starting with the dollar symbol
* @param methodPos the position in the content after the whole fragment starting with the dollar symbol
* @param offset the position in the whole content of the cursor
* @param velocityContext the velocity context used to get the variables bound in the Velocity Context
* @return the list of hints
* @throws InvalidVelocityException when the code to parse is not what's expected
*/
private Hints getMethods(char[] chars, String propertyName, int blockPos, int methodPos, int offset,
VelocityContext velocityContext) throws InvalidVelocityException
{
Hints results = new Hints();
VelocityParserContext context = new VelocityParserContext();
String fragment = "";
boolean autoCompleteMethods = false;
// Handle the case where the cursor is just after the dot
if (methodPos + 1 == offset) {
autoCompleteMethods = true;
} else {
StringBuffer propertyBlock = new StringBuffer();
int newMethodPos = this.parser.getMethodOrProperty(chars, methodPos, propertyBlock, context);
if (newMethodPos == blockPos) {
autoCompleteMethods = true;
fragment = propertyBlock.toString().substring(1);
}
}
if (autoCompleteMethods) {
// Find methods using Reflection
results = getMethods(propertyName, fragment, velocityContext);
}
return results;
}
/**
* Find out all Velocity variable names bound in the Velocity Context.
*
* @param fragmentToMatch the prefix to filter with in order to return only variable whose names start with the
* passed string
* @param velocityContext the Velocity Context from which to get the bound variables
* @return the Velocity variables
*/
private Hints getVelocityContextKeys(String fragmentToMatch, VelocityContext velocityContext)
{
Hints hints = new Hints();
addVelocityKeys(hints, velocityContext.getKeys(), fragmentToMatch);
if (velocityContext.getChainedContext() != null) {
addVelocityKeys(hints, velocityContext.getChainedContext().getKeys(), fragmentToMatch);
}
return hints;
}
/**
* Add variables to the passed results list.
*
* @param results the list of variable names
* @param keys the keys containing the variables to add
* @param fragmentToMatch the filter in order to only add variable whose names start with the passed string
*/
private void addVelocityKeys(Hints results, Object[] keys, String fragmentToMatch)
{
for (Object key : keys) {
if (key instanceof String && ((String) key).startsWith(fragmentToMatch)) {
results.withHints(new HintData((String) key, (String) key));
}
}
}
/**
* @param variableName the variable name corresponding to the class for which to find the methods
* @param fragmentToMatch the filter to only return methods matching the passed string
* @param velocityContext the Velocity Context from which to get the Class corresponding to the variable name
* @return the method names found in the Class pointed to by the passed variableName name
*/
private Hints getMethods(String variableName, String fragmentToMatch, VelocityContext velocityContext)
{
Hints hints = new Hints();
Object propertyClass = velocityContext.get(variableName);
if (propertyClass != null) {
// Allow special handling for classes that have registered a custom introspection handler
if (this.componentManager.hasComponent(AutoCompletionMethodFinder.class, variableName)) {
try {
AutoCompletionMethodFinder finder =
this.componentManager.getInstance(AutoCompletionMethodFinder.class, variableName);
hints.withHints(finder.findMethods(propertyClass.getClass(), fragmentToMatch));
} catch (ComponentLookupException e) {
// Component not found, continue with default finder...
}
}
if (hints.isEmpty()) {
hints.withHints(this.defaultAutoCompletionMethodFinder.findMethods(propertyClass.getClass(),
fragmentToMatch));
}
}
return hints;
}
}
| true | true | private Hints getHints(String content, int offset)
{
Hints results = new Hints();
char[] chars = content.toCharArray();
VelocityContext velocityContext = this.velocityManager.getVelocityContext();
// Find the dollar sign before the current position
int dollarPos = StringUtils.lastIndexOf(content, '$', offset);
if (dollarPos > -1) {
// Special case for when there's no variable after the dollar position since the Velocity Parser doesn't
// support parsing this case.
if (isCursorDirectlyAfterDollar(chars, dollarPos, offset)) {
// Find all objects bound to the Velocity Context. We need to also look in the chained context since
// this is where we store Velocity Tools
results = getVelocityContextKeys("", velocityContext);
} else {
StringBuffer velocityBlock = new StringBuffer();
VelocityParserContext context = new VelocityParserContext();
try {
// Get the block after the dollar
int blockPos = this.parser.getVar(chars, dollarPos, velocityBlock, context);
// if newPos matches the current position then it means we have a valid block for autocompletion
// Note: we need to handle the special case where the cursor is just after the dot since getVar
// will not return it!
if (blockPos + 1 == offset && chars[blockPos] == '.') {
blockPos++;
velocityBlock.append('.');
}
if (blockPos == offset) {
results = getMethodsOrVariableHints(chars, dollarPos, blockPos, offset, velocityContext);
}
} catch (InvalidVelocityException e) {
this.logger.debug("Failed to get autocomplete hints for content [{}] at offset [{}]", new Object[] {
content, offset, e});
}
}
}
// Sort hints
Collections.sort(results.getHints());
return results;
}
| private Hints getHints(String content, int offset)
{
Hints results = new Hints();
char[] chars = content.toCharArray();
VelocityContext velocityContext = this.velocityManager.getVelocityContext();
// Find the dollar sign before the current position
int dollarPos = StringUtils.lastIndexOf(content, '$', offset);
if (dollarPos > -1) {
// Special case for when there's no variable after the dollar position since the Velocity Parser doesn't
// support parsing this case.
if (isCursorDirectlyAfterDollar(chars, dollarPos, offset)) {
// Find all objects bound to the Velocity Context. We need to also look in the chained context since
// this is where we store Velocity Tools
results = getVelocityContextKeys("", velocityContext);
} else {
StringBuffer velocityBlock = new StringBuffer();
VelocityParserContext context = new VelocityParserContext();
try {
// Get the block after the dollar
int blockPos = this.parser.getVar(chars, dollarPos, velocityBlock, context);
// if newPos matches the current position then it means we have a valid block for autocompletion
// Note: we need to handle the special case where the cursor is just after the dot since getVar
// will not return it!
if (blockPos + 1 == offset && chars[blockPos] == '.') {
blockPos++;
velocityBlock.append('.');
}
if (blockPos == offset) {
results = getMethodsOrVariableHints(chars, dollarPos, blockPos, offset, velocityContext);
}
} catch (InvalidVelocityException e) {
this.logger.debug("Failed to get autocomplete hints for content [{}] at offset [{}]",
new Object[] {content, offset, e});
}
}
}
// Sort hints
Collections.sort(results.getHints());
return results;
}
|
diff --git a/src/net/aufdemrand/denizen/CommandExecuter.java b/src/net/aufdemrand/denizen/CommandExecuter.java
index ab709733f..fc99ebf4b 100644
--- a/src/net/aufdemrand/denizen/CommandExecuter.java
+++ b/src/net/aufdemrand/denizen/CommandExecuter.java
@@ -1,444 +1,444 @@
package net.aufdemrand.denizen;
import java.util.ArrayList;
import java.util.List;
import net.aufdemrand.denizen.ScriptEngine.Trigger;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.trait.LookClose;
import org.bukkit.Bukkit;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.craftbukkit.CraftWorld;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
public class CommandExecuter {
public static enum Command {
WAIT, ZAP, SPAWN, CHANGE, WEATHER, EFFECT, GIVE, TAKE, HEAL,
TELEPORT, STRIKE, WALK, REMEMBER, RESPAWN, PERMISS, EXECUTE, SHOUT,
WHISPER, CHAT, ANNOUNCE, GRANT, HINT, RETURN, LOOK, WALKTO, FINISH,
FOLLOW, CAST, NARRATE, ENGAGE, DISENGAGE,
SWITCH, PRESS, HURT, REFUSE, WAITING, RESET, FAIL, SPAWNMOB, EMOTE, ATTACK, PLAYERTASK, RUNTASK
}
private Denizen plugin;
/*
* Executes a command defined in theStep (not to be confused with currentStep ;)
*
* I am attempting to keep down the size of this method by branching out large
* sections of code into their own methods.
*
* These commands normally come from the playerQue or denizenQue, but don't have
* to necessarily, as long as the proper format is sent in theStep.
*
* Syntax of theStep -- elements are divided by semi-colons.
* 0 Denizen ID; 1 Script Name; 2 Step Number; 3 Time added to Queue; 4 Command
*/
public void execute(Player thePlayer, String theStep) {
// Syntax of theStep
//
plugin = (Denizen) Bukkit.getPluginManager().getPlugin("Denizen");
/* Break down information from theStep for use */
String[] executeArgs = theStep.split(";");
NPC theDenizen = null;
if (!executeArgs[0].equalsIgnoreCase("NONE")) theDenizen = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executeArgs[0]));
String theScript = executeArgs[1];
String currentStep = executeArgs[2];
/* Populate 25 command arguments with values, rest with null */
String[] commandArgs = new String[25];
String[] argumentPopulator = executeArgs[4].split(" ");
for (int count = 0; count < 25; count++) {
if (argumentPopulator.length > count) commandArgs[count] = argumentPopulator[count];
else commandArgs[count] = null;
}
if (commandArgs[0].startsWith("^")) commandArgs[0] = commandArgs[0].substring(1);
/* Now to execute the command... */
switch (Command.valueOf(commandArgs[0].toUpperCase())) {
/* commandArgs [0] [1] [2] [...] */
case ZAP: /* ZAP (Step #) */
Denizen.getScript.zap(thePlayer, theScript, currentStep, commandArgs[1]);
break;
case ENGAGE:
Denizen.engagedNPC.add(theDenizen);
break;
case DISENGAGE:
if (Denizen.engagedNPC.contains(theDenizen)) Denizen.engagedNPC.remove(theDenizen);
break;
case SPAWNMOB:
case SPAWN: /* SPAWN [ENTITY_TYPE] (AMOUNT) (Location Bookmark) */
Denizen.getWorld.spawnMob(commandArgs[1], commandArgs[2], commandArgs[3], theDenizen);
break;
case SWITCH: // SWITCH [Block Bookmark] ON|OFF
Location switchLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Block");
if (switchLoc.getBlock().getType() == Material.LEVER) {
World theWorld = switchLoc.getWorld();
net.minecraft.server.Block.LEVER.interact(((CraftWorld)theWorld).getHandle(), switchLoc.getBlockX(), switchLoc.getBlockY(), switchLoc.getBlockZ(), null);
}
break;
case PRESS: // SWITCH [Block Bookmark] ON|OFF
Location pressLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Block");
if (pressLoc.getBlock().getType() == Material.STONE_BUTTON) {
World theWorld = pressLoc.getWorld();
net.minecraft.server.Block.STONE_BUTTON.interact(((CraftWorld)theWorld).getHandle(), pressLoc.getBlockX(), pressLoc.getBlockY(), pressLoc.getBlockZ(), null);
}
break;
case WEATHER: // WEATHER [Sunny|Stormy|Precipitation] (Duration for Stormy/Rainy)
if (commandArgs[1].equalsIgnoreCase("sunny")) { thePlayer.getWorld().setStorm(false); }
else if (commandArgs[1].equalsIgnoreCase("stormy")) { thePlayer.getWorld().setThundering(true); }
else if (commandArgs[1].equalsIgnoreCase("precipitation")) { thePlayer.getWorld().setStorm(true); }
break;
case CAST: // CAST [POTION_TYPE] [DURATION] [AMPLIFIER]
thePlayer.addPotionEffect(new PotionEffect(
PotionEffectType.getByName(commandArgs[1].toUpperCase()), Integer.valueOf(commandArgs[2]) * 20, Integer.valueOf(commandArgs[3])));
break;
case EFFECT: // EFFECT [EFFECT_TYPE] (Location Bookmark)
break;
case LOOK: // ENG
if (commandArgs[1].equalsIgnoreCase("CLOSE")) {
if (!theDenizen.getTrait(LookClose.class).toggle())
theDenizen.getTrait(LookClose.class).toggle();
}
else if (commandArgs[1].equalsIgnoreCase("AWAY")) {
if (theDenizen.getTrait(LookClose.class).toggle())
theDenizen.getTrait(LookClose.class).toggle();
}
else if (!commandArgs[1].equalsIgnoreCase("AWAY") && !commandArgs[1].equalsIgnoreCase("CLOSE")) {
NPC denizenLooking = theDenizen;
Location lookLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Location");
denizenLooking.getBukkitEntity().getLocation().setPitch(lookLoc.getPitch());
denizenLooking.getBukkitEntity().getLocation().setYaw(lookLoc.getYaw());
}
break;
case GIVE: // GIVE [Item:Data] [Amount] [ENCHANTMENT_TYPE]
String[] theItem = Denizen.getRequirements.splitItem(commandArgs[1]);
ItemStack giveItem = new ItemStack(Material.AIR);
if (Character.isDigit(theItem[0].charAt(0))) {
giveItem.setTypeId(Integer.valueOf(theItem[0]));
giveItem.getData().setData(Byte.valueOf(theItem[1]));
}
else giveItem.setType(Material.getMaterial(commandArgs[1].toUpperCase()));
if (commandArgs[2] != null) giveItem.setAmount(Integer.valueOf(commandArgs[2]));
else giveItem.setAmount(1);
thePlayer.getWorld().dropItem(thePlayer.getLocation(), giveItem);
break;
case TAKE: // TAKE [Item] [Amount] or TAKE ITEM_IN_HAND or TAKE MONEY [Amount]
if (commandArgs[1].equalsIgnoreCase("MONEY")) {
double playerMoneyAmt = Denizen.denizenEcon.getBalance(thePlayer.getName());
double amtToTake = Double.valueOf(commandArgs[2]);
if (amtToTake > playerMoneyAmt) amtToTake = playerMoneyAmt;
Denizen.denizenEcon.withdrawPlayer(thePlayer.getName(), amtToTake);
}
else if (commandArgs[1].equalsIgnoreCase("ITEMINHAND")) {
thePlayer.setItemInHand(new ItemStack(Material.AIR));
}
else {
String[] theTakeItem = Denizen.getRequirements.splitItem(commandArgs[1]);
ItemStack itemToTake = new ItemStack(Material.AIR);
if (Character.isDigit(theTakeItem[0].charAt(0))) {
itemToTake.setTypeId(Integer.valueOf(theTakeItem[0]));
itemToTake.getData().setData(Byte.valueOf(theTakeItem[1]));
}
else itemToTake.setType(Material.getMaterial(commandArgs[1].toUpperCase()));
if (commandArgs[2] != null) itemToTake.setAmount(Integer.valueOf(commandArgs[2]));
else itemToTake.setAmount(1);
thePlayer.getInventory().removeItem(itemToTake);
}
break;
case HEAL: // HEAL (# of Health)
int health = 1;
if (commandArgs[1] != null) health = Integer.valueOf(commandArgs[1]);
((LivingEntity) thePlayer).setHealth(thePlayer.getHealth() + health);
break;
case HURT: // HURT (# of Health)
int damage = 1;
if (commandArgs[1] != null) damage = Integer.valueOf(commandArgs[1]);
if (theDenizen != null) thePlayer.damage(damage, theDenizen.getBukkitEntity());
else thePlayer.damage(damage);
break;
case TELEPORT: // TELEPORT [Location Notable]
thePlayer.teleport(Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "location"));
case STRIKE: // STRIKE Strikes lightning on the player, with damage.
thePlayer.getWorld().strikeLightning(thePlayer.getLocation());
break;
case WALK: // WALK Z(-NORTH(2)/+SOUTH(0)) X(-WEST(1)/+EAST(3)) Y (+UP/-DOWN)
Denizen.previousNPCLoc.put(theDenizen, theDenizen.getBukkitEntity().getLocation());
if (!commandArgs[1].isEmpty()) theDenizen.getAI().setDestination(theDenizen.getBukkitEntity().getLocation()
.add(Double.parseDouble(commandArgs[2]), Double.parseDouble(commandArgs[3]), Double.parseDouble(commandArgs[1])));
break;
case WALKTO: // WALKTO [Location Bookmark]
Location walkLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Location");
Denizen.previousNPCLoc.put(theDenizen, theDenizen.getBukkitEntity().getLocation());
theDenizen.getAI().setDestination(walkLoc);
break;
case RETURN:
if (Denizen.previousNPCLoc.containsKey(theDenizen))
theDenizen.getAI().setDestination(Denizen.previousNPCLoc.get(theDenizen));
break;
case FINISH:
int finishes = plugin.getAssignments().getInt("Players." + thePlayer.getName() + "." + executeArgs[1] + "." + "Completed", 0);
finishes++;
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeArgs[1] + "." + "Completed", finishes);
plugin.saveSaves();
break;
case FAIL:
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeArgs[1] + "." + "Failed", true);
plugin.saveSaves();
break;
case REMEMBER: // REMEMBER [CHAT|LOCATION|INVENTORY]
break;
case FOLLOW: // FOLLOW PLAYER|NOBODY
if (commandArgs[1].equalsIgnoreCase("PLAYER")) {
theDenizen.getAI().setTarget(thePlayer, false);
}
if (commandArgs[1].equalsIgnoreCase("NOBODY")) {
theDenizen.getAI().cancelDestination();
}
break;
case ATTACK: // FOLLOW PLAYER|NOBODY
if (commandArgs[1].equalsIgnoreCase("PLAYER")) {
theDenizen.getAI().setTarget(thePlayer, true);
}
if (commandArgs[1].equalsIgnoreCase("NOBODY")) {
theDenizen.getAI().cancelDestination();
}
break;
case RESPAWN: // RESPAWN [Location Notable]
Location respawnLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Location");
Denizen.previousNPCLoc.put(theDenizen, theDenizen.getBukkitEntity().getLocation());
theDenizen.getBukkitEntity().getWorld().playEffect(theDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2);
theDenizen.despawn();
theDenizen.spawn(respawnLoc);
theDenizen.getBukkitEntity().getWorld().playEffect(theDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2);
break;
case PERMISS: // PERMISS [Permission Node]
Denizen.denizenPerms.playerAdd(thePlayer, commandArgs[1]);
break;
case REFUSE: // PERMISS [Permission Node]
Denizen.denizenPerms.playerRemove(thePlayer, commandArgs[1]);
break;
case EXECUTE: // EXECUTE ASPLAYER [Command to Execute]
String[] executeCommand = executeArgs[4].split(" ", 3);
if (commandArgs[1].equalsIgnoreCase("ASPLAYER")) {
thePlayer.performCommand(executeCommand[2]
.replace("<PLAYER>", thePlayer.getName()
.replace("<WORLD>", thePlayer.getWorld().getName())));
}
if (commandArgs[1].equalsIgnoreCase("ASNPC")) {
((Player) theDenizen.getBukkitEntity()).setOp(true);
((Player) theDenizen.getBukkitEntity()).performCommand(executeCommand[2]
.replace("<PLAYER>", thePlayer.getName()
.replace("<WORLD>", thePlayer.getWorld().getName())));
((Player) theDenizen.getBukkitEntity()).setOp(false);
}
if (commandArgs[1].equalsIgnoreCase("ASSERVER")) {
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), executeCommand[2]
.replace("<PLAYER>", thePlayer.getName()
.replace("<WORLD>", thePlayer.getWorld().getName())));
}
break;
// TYPE BOOKMARK DURATION LEEWAY RUNSCRIPT
case PLAYERTASK: // LOCATION [Location Bookmark] [Duration] [Leeway] [Script to Trigger]
/* LOCATION Listener */
String theLocation = commandArgs[2];
int theDuration = Integer.valueOf(commandArgs[3]);
int theLeeway = Integer.valueOf(commandArgs[4]);
String triggerScript = executeArgs[4].split(" ", 6)[5];
Denizen.scriptEngine.newLocationTask(thePlayer, theDenizen, theLocation, theDuration, theLeeway, triggerScript);
break;
case RUNTASK:
Denizen.scriptEngine.parseScript(null, thePlayer, executeArgs[4].split(" ", 2)[1], null, Trigger.TASK);
break;
case ANNOUNCE:
break;
case NARRATE:
case WHISPER:
case EMOTE:
case SHOUT:
case CHAT: // CHAT|WHISPER|EMOTE|SHOUT|NARRATE [Message]
/*
* I had to take out the feature for multiline text following the script delay. It was getting too messy!
* Hopefully nobody will notice ;) ...but I'm sure they will, so I will put that off for another day.
*/
/* Format the text for player and bystander, and turn into multiline if necessary */
String[] formattedText = Denizen.scriptEngine.formatChatText(executeArgs[4].split(" ", 2)[1], commandArgs[0], thePlayer, theDenizen);
List<String> playerText = Denizen.scriptEngine.getMultilineText(formattedText[0]);
List<String> bystanderText = Denizen.scriptEngine.getMultilineText(formattedText[1]);
/* Spew the text to the world. */
if (!playerText.isEmpty()) {
for (String text : playerText) { /* First playerText */
Denizen.getDenizen.talkToPlayer(theDenizen, thePlayer, text, null, commandArgs[0]);
}
}
if (!bystanderText.isEmpty()) {
for (String text : bystanderText) { /* now bystanderText */
if (!playerText.isEmpty()) Denizen.getDenizen.talkToPlayer(theDenizen, thePlayer, "shhh...don't speak!", text, commandArgs[0]);
else Denizen.getDenizen.talkToPlayer(theDenizen, thePlayer, null, text, commandArgs[0]);
}
}
break;
case RESET: // RESET FINISH(ED) [Name of Script] or RESET FAIL(ED) [NAME OF SCRIPT]
String executeScript;
- if (commandArgs.length == 2) executeScript=theScript; else executeScript=executeArgs[4].split(" ", 3)[2];
+ if (commandArgs[2] == null) executeScript=theScript; else executeScript=executeArgs[4].split(" ", 3)[2];
if (commandArgs[1].equalsIgnoreCase("FINISH") || commandArgs[1].equalsIgnoreCase("FINISHED")) {
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeScript + "." + "Completed", 0);
plugin.saveSaves();
}
if (commandArgs[1].equalsIgnoreCase("FAIL") || commandArgs[1].equalsIgnoreCase("FAILED")) {
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeScript + "." + "Failed", false);
plugin.saveSaves();
}
break;
case CHANGE: // CHANGE [Block Bookmark] [#:#|MATERIAL_TYPE]
Location blockLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Block");
String[] theChangeItem = Denizen.getRequirements.splitItem(commandArgs[2]);
if (Character.isDigit(theChangeItem[0].charAt(0))) {
blockLoc.getBlock().setTypeId(Integer.valueOf(theChangeItem[0]));
blockLoc.getBlock().setData(Byte.valueOf(theChangeItem[1]));
}
else blockLoc.getBlock().setType(Material.getMaterial(commandArgs[2].toUpperCase()));
break;
case WAIT:
/*
* This may be a bit hack-y, at least it seems like it to me.
* but, if it isn't broken.. you know what they say.
*/
List<String> CurrentPlayerQue = new ArrayList<String>();
if (Denizen.playerQue.get(thePlayer) != null) CurrentPlayerQue = Denizen.playerQue.get(thePlayer);
Denizen.playerQue.remove(thePlayer); // Should keep the talk queue from triggering mid-add
Long timeDelay = Long.parseLong(commandArgs[1]) * 1000;
String timeWithDelay = String.valueOf(System.currentTimeMillis() + timeDelay);
CurrentPlayerQue.add(1, "0;none;0;" + timeWithDelay + ";WAITING");
Denizen.playerQue.put(thePlayer, CurrentPlayerQue);
break;
case WAITING:
// ...and we're waiting... mmmm... hack-y.
break;
default:
break;
}
return;
}
}
| true | true | public void execute(Player thePlayer, String theStep) {
// Syntax of theStep
//
plugin = (Denizen) Bukkit.getPluginManager().getPlugin("Denizen");
/* Break down information from theStep for use */
String[] executeArgs = theStep.split(";");
NPC theDenizen = null;
if (!executeArgs[0].equalsIgnoreCase("NONE")) theDenizen = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executeArgs[0]));
String theScript = executeArgs[1];
String currentStep = executeArgs[2];
/* Populate 25 command arguments with values, rest with null */
String[] commandArgs = new String[25];
String[] argumentPopulator = executeArgs[4].split(" ");
for (int count = 0; count < 25; count++) {
if (argumentPopulator.length > count) commandArgs[count] = argumentPopulator[count];
else commandArgs[count] = null;
}
if (commandArgs[0].startsWith("^")) commandArgs[0] = commandArgs[0].substring(1);
/* Now to execute the command... */
switch (Command.valueOf(commandArgs[0].toUpperCase())) {
/* commandArgs [0] [1] [2] [...] */
case ZAP: /* ZAP (Step #) */
Denizen.getScript.zap(thePlayer, theScript, currentStep, commandArgs[1]);
break;
case ENGAGE:
Denizen.engagedNPC.add(theDenizen);
break;
case DISENGAGE:
if (Denizen.engagedNPC.contains(theDenizen)) Denizen.engagedNPC.remove(theDenizen);
break;
case SPAWNMOB:
case SPAWN: /* SPAWN [ENTITY_TYPE] (AMOUNT) (Location Bookmark) */
Denizen.getWorld.spawnMob(commandArgs[1], commandArgs[2], commandArgs[3], theDenizen);
break;
case SWITCH: // SWITCH [Block Bookmark] ON|OFF
Location switchLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Block");
if (switchLoc.getBlock().getType() == Material.LEVER) {
World theWorld = switchLoc.getWorld();
net.minecraft.server.Block.LEVER.interact(((CraftWorld)theWorld).getHandle(), switchLoc.getBlockX(), switchLoc.getBlockY(), switchLoc.getBlockZ(), null);
}
break;
case PRESS: // SWITCH [Block Bookmark] ON|OFF
Location pressLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Block");
if (pressLoc.getBlock().getType() == Material.STONE_BUTTON) {
World theWorld = pressLoc.getWorld();
net.minecraft.server.Block.STONE_BUTTON.interact(((CraftWorld)theWorld).getHandle(), pressLoc.getBlockX(), pressLoc.getBlockY(), pressLoc.getBlockZ(), null);
}
break;
case WEATHER: // WEATHER [Sunny|Stormy|Precipitation] (Duration for Stormy/Rainy)
if (commandArgs[1].equalsIgnoreCase("sunny")) { thePlayer.getWorld().setStorm(false); }
else if (commandArgs[1].equalsIgnoreCase("stormy")) { thePlayer.getWorld().setThundering(true); }
else if (commandArgs[1].equalsIgnoreCase("precipitation")) { thePlayer.getWorld().setStorm(true); }
break;
case CAST: // CAST [POTION_TYPE] [DURATION] [AMPLIFIER]
thePlayer.addPotionEffect(new PotionEffect(
PotionEffectType.getByName(commandArgs[1].toUpperCase()), Integer.valueOf(commandArgs[2]) * 20, Integer.valueOf(commandArgs[3])));
break;
case EFFECT: // EFFECT [EFFECT_TYPE] (Location Bookmark)
break;
case LOOK: // ENG
if (commandArgs[1].equalsIgnoreCase("CLOSE")) {
if (!theDenizen.getTrait(LookClose.class).toggle())
theDenizen.getTrait(LookClose.class).toggle();
}
else if (commandArgs[1].equalsIgnoreCase("AWAY")) {
if (theDenizen.getTrait(LookClose.class).toggle())
theDenizen.getTrait(LookClose.class).toggle();
}
else if (!commandArgs[1].equalsIgnoreCase("AWAY") && !commandArgs[1].equalsIgnoreCase("CLOSE")) {
NPC denizenLooking = theDenizen;
Location lookLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Location");
denizenLooking.getBukkitEntity().getLocation().setPitch(lookLoc.getPitch());
denizenLooking.getBukkitEntity().getLocation().setYaw(lookLoc.getYaw());
}
break;
case GIVE: // GIVE [Item:Data] [Amount] [ENCHANTMENT_TYPE]
String[] theItem = Denizen.getRequirements.splitItem(commandArgs[1]);
ItemStack giveItem = new ItemStack(Material.AIR);
if (Character.isDigit(theItem[0].charAt(0))) {
giveItem.setTypeId(Integer.valueOf(theItem[0]));
giveItem.getData().setData(Byte.valueOf(theItem[1]));
}
else giveItem.setType(Material.getMaterial(commandArgs[1].toUpperCase()));
if (commandArgs[2] != null) giveItem.setAmount(Integer.valueOf(commandArgs[2]));
else giveItem.setAmount(1);
thePlayer.getWorld().dropItem(thePlayer.getLocation(), giveItem);
break;
case TAKE: // TAKE [Item] [Amount] or TAKE ITEM_IN_HAND or TAKE MONEY [Amount]
if (commandArgs[1].equalsIgnoreCase("MONEY")) {
double playerMoneyAmt = Denizen.denizenEcon.getBalance(thePlayer.getName());
double amtToTake = Double.valueOf(commandArgs[2]);
if (amtToTake > playerMoneyAmt) amtToTake = playerMoneyAmt;
Denizen.denizenEcon.withdrawPlayer(thePlayer.getName(), amtToTake);
}
else if (commandArgs[1].equalsIgnoreCase("ITEMINHAND")) {
thePlayer.setItemInHand(new ItemStack(Material.AIR));
}
else {
String[] theTakeItem = Denizen.getRequirements.splitItem(commandArgs[1]);
ItemStack itemToTake = new ItemStack(Material.AIR);
if (Character.isDigit(theTakeItem[0].charAt(0))) {
itemToTake.setTypeId(Integer.valueOf(theTakeItem[0]));
itemToTake.getData().setData(Byte.valueOf(theTakeItem[1]));
}
else itemToTake.setType(Material.getMaterial(commandArgs[1].toUpperCase()));
if (commandArgs[2] != null) itemToTake.setAmount(Integer.valueOf(commandArgs[2]));
else itemToTake.setAmount(1);
thePlayer.getInventory().removeItem(itemToTake);
}
break;
case HEAL: // HEAL (# of Health)
int health = 1;
if (commandArgs[1] != null) health = Integer.valueOf(commandArgs[1]);
((LivingEntity) thePlayer).setHealth(thePlayer.getHealth() + health);
break;
case HURT: // HURT (# of Health)
int damage = 1;
if (commandArgs[1] != null) damage = Integer.valueOf(commandArgs[1]);
if (theDenizen != null) thePlayer.damage(damage, theDenizen.getBukkitEntity());
else thePlayer.damage(damage);
break;
case TELEPORT: // TELEPORT [Location Notable]
thePlayer.teleport(Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "location"));
case STRIKE: // STRIKE Strikes lightning on the player, with damage.
thePlayer.getWorld().strikeLightning(thePlayer.getLocation());
break;
case WALK: // WALK Z(-NORTH(2)/+SOUTH(0)) X(-WEST(1)/+EAST(3)) Y (+UP/-DOWN)
Denizen.previousNPCLoc.put(theDenizen, theDenizen.getBukkitEntity().getLocation());
if (!commandArgs[1].isEmpty()) theDenizen.getAI().setDestination(theDenizen.getBukkitEntity().getLocation()
.add(Double.parseDouble(commandArgs[2]), Double.parseDouble(commandArgs[3]), Double.parseDouble(commandArgs[1])));
break;
case WALKTO: // WALKTO [Location Bookmark]
Location walkLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Location");
Denizen.previousNPCLoc.put(theDenizen, theDenizen.getBukkitEntity().getLocation());
theDenizen.getAI().setDestination(walkLoc);
break;
case RETURN:
if (Denizen.previousNPCLoc.containsKey(theDenizen))
theDenizen.getAI().setDestination(Denizen.previousNPCLoc.get(theDenizen));
break;
case FINISH:
int finishes = plugin.getAssignments().getInt("Players." + thePlayer.getName() + "." + executeArgs[1] + "." + "Completed", 0);
finishes++;
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeArgs[1] + "." + "Completed", finishes);
plugin.saveSaves();
break;
case FAIL:
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeArgs[1] + "." + "Failed", true);
plugin.saveSaves();
break;
case REMEMBER: // REMEMBER [CHAT|LOCATION|INVENTORY]
break;
case FOLLOW: // FOLLOW PLAYER|NOBODY
if (commandArgs[1].equalsIgnoreCase("PLAYER")) {
theDenizen.getAI().setTarget(thePlayer, false);
}
if (commandArgs[1].equalsIgnoreCase("NOBODY")) {
theDenizen.getAI().cancelDestination();
}
break;
case ATTACK: // FOLLOW PLAYER|NOBODY
if (commandArgs[1].equalsIgnoreCase("PLAYER")) {
theDenizen.getAI().setTarget(thePlayer, true);
}
if (commandArgs[1].equalsIgnoreCase("NOBODY")) {
theDenizen.getAI().cancelDestination();
}
break;
case RESPAWN: // RESPAWN [Location Notable]
Location respawnLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Location");
Denizen.previousNPCLoc.put(theDenizen, theDenizen.getBukkitEntity().getLocation());
theDenizen.getBukkitEntity().getWorld().playEffect(theDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2);
theDenizen.despawn();
theDenizen.spawn(respawnLoc);
theDenizen.getBukkitEntity().getWorld().playEffect(theDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2);
break;
case PERMISS: // PERMISS [Permission Node]
Denizen.denizenPerms.playerAdd(thePlayer, commandArgs[1]);
break;
case REFUSE: // PERMISS [Permission Node]
Denizen.denizenPerms.playerRemove(thePlayer, commandArgs[1]);
break;
case EXECUTE: // EXECUTE ASPLAYER [Command to Execute]
String[] executeCommand = executeArgs[4].split(" ", 3);
if (commandArgs[1].equalsIgnoreCase("ASPLAYER")) {
thePlayer.performCommand(executeCommand[2]
.replace("<PLAYER>", thePlayer.getName()
.replace("<WORLD>", thePlayer.getWorld().getName())));
}
if (commandArgs[1].equalsIgnoreCase("ASNPC")) {
((Player) theDenizen.getBukkitEntity()).setOp(true);
((Player) theDenizen.getBukkitEntity()).performCommand(executeCommand[2]
.replace("<PLAYER>", thePlayer.getName()
.replace("<WORLD>", thePlayer.getWorld().getName())));
((Player) theDenizen.getBukkitEntity()).setOp(false);
}
if (commandArgs[1].equalsIgnoreCase("ASSERVER")) {
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), executeCommand[2]
.replace("<PLAYER>", thePlayer.getName()
.replace("<WORLD>", thePlayer.getWorld().getName())));
}
break;
// TYPE BOOKMARK DURATION LEEWAY RUNSCRIPT
case PLAYERTASK: // LOCATION [Location Bookmark] [Duration] [Leeway] [Script to Trigger]
/* LOCATION Listener */
String theLocation = commandArgs[2];
int theDuration = Integer.valueOf(commandArgs[3]);
int theLeeway = Integer.valueOf(commandArgs[4]);
String triggerScript = executeArgs[4].split(" ", 6)[5];
Denizen.scriptEngine.newLocationTask(thePlayer, theDenizen, theLocation, theDuration, theLeeway, triggerScript);
break;
case RUNTASK:
Denizen.scriptEngine.parseScript(null, thePlayer, executeArgs[4].split(" ", 2)[1], null, Trigger.TASK);
break;
case ANNOUNCE:
break;
case NARRATE:
case WHISPER:
case EMOTE:
case SHOUT:
case CHAT: // CHAT|WHISPER|EMOTE|SHOUT|NARRATE [Message]
/*
* I had to take out the feature for multiline text following the script delay. It was getting too messy!
* Hopefully nobody will notice ;) ...but I'm sure they will, so I will put that off for another day.
*/
/* Format the text for player and bystander, and turn into multiline if necessary */
String[] formattedText = Denizen.scriptEngine.formatChatText(executeArgs[4].split(" ", 2)[1], commandArgs[0], thePlayer, theDenizen);
List<String> playerText = Denizen.scriptEngine.getMultilineText(formattedText[0]);
List<String> bystanderText = Denizen.scriptEngine.getMultilineText(formattedText[1]);
/* Spew the text to the world. */
if (!playerText.isEmpty()) {
for (String text : playerText) { /* First playerText */
Denizen.getDenizen.talkToPlayer(theDenizen, thePlayer, text, null, commandArgs[0]);
}
}
if (!bystanderText.isEmpty()) {
for (String text : bystanderText) { /* now bystanderText */
if (!playerText.isEmpty()) Denizen.getDenizen.talkToPlayer(theDenizen, thePlayer, "shhh...don't speak!", text, commandArgs[0]);
else Denizen.getDenizen.talkToPlayer(theDenizen, thePlayer, null, text, commandArgs[0]);
}
}
break;
case RESET: // RESET FINISH(ED) [Name of Script] or RESET FAIL(ED) [NAME OF SCRIPT]
String executeScript;
if (commandArgs.length == 2) executeScript=theScript; else executeScript=executeArgs[4].split(" ", 3)[2];
if (commandArgs[1].equalsIgnoreCase("FINISH") || commandArgs[1].equalsIgnoreCase("FINISHED")) {
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeScript + "." + "Completed", 0);
plugin.saveSaves();
}
if (commandArgs[1].equalsIgnoreCase("FAIL") || commandArgs[1].equalsIgnoreCase("FAILED")) {
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeScript + "." + "Failed", false);
plugin.saveSaves();
}
break;
case CHANGE: // CHANGE [Block Bookmark] [#:#|MATERIAL_TYPE]
Location blockLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Block");
String[] theChangeItem = Denizen.getRequirements.splitItem(commandArgs[2]);
if (Character.isDigit(theChangeItem[0].charAt(0))) {
blockLoc.getBlock().setTypeId(Integer.valueOf(theChangeItem[0]));
blockLoc.getBlock().setData(Byte.valueOf(theChangeItem[1]));
}
else blockLoc.getBlock().setType(Material.getMaterial(commandArgs[2].toUpperCase()));
break;
case WAIT:
/*
* This may be a bit hack-y, at least it seems like it to me.
* but, if it isn't broken.. you know what they say.
*/
List<String> CurrentPlayerQue = new ArrayList<String>();
if (Denizen.playerQue.get(thePlayer) != null) CurrentPlayerQue = Denizen.playerQue.get(thePlayer);
Denizen.playerQue.remove(thePlayer); // Should keep the talk queue from triggering mid-add
Long timeDelay = Long.parseLong(commandArgs[1]) * 1000;
String timeWithDelay = String.valueOf(System.currentTimeMillis() + timeDelay);
CurrentPlayerQue.add(1, "0;none;0;" + timeWithDelay + ";WAITING");
Denizen.playerQue.put(thePlayer, CurrentPlayerQue);
break;
case WAITING:
// ...and we're waiting... mmmm... hack-y.
break;
default:
break;
}
return;
}
| public void execute(Player thePlayer, String theStep) {
// Syntax of theStep
//
plugin = (Denizen) Bukkit.getPluginManager().getPlugin("Denizen");
/* Break down information from theStep for use */
String[] executeArgs = theStep.split(";");
NPC theDenizen = null;
if (!executeArgs[0].equalsIgnoreCase("NONE")) theDenizen = CitizensAPI.getNPCRegistry().getNPC(Integer.valueOf(executeArgs[0]));
String theScript = executeArgs[1];
String currentStep = executeArgs[2];
/* Populate 25 command arguments with values, rest with null */
String[] commandArgs = new String[25];
String[] argumentPopulator = executeArgs[4].split(" ");
for (int count = 0; count < 25; count++) {
if (argumentPopulator.length > count) commandArgs[count] = argumentPopulator[count];
else commandArgs[count] = null;
}
if (commandArgs[0].startsWith("^")) commandArgs[0] = commandArgs[0].substring(1);
/* Now to execute the command... */
switch (Command.valueOf(commandArgs[0].toUpperCase())) {
/* commandArgs [0] [1] [2] [...] */
case ZAP: /* ZAP (Step #) */
Denizen.getScript.zap(thePlayer, theScript, currentStep, commandArgs[1]);
break;
case ENGAGE:
Denizen.engagedNPC.add(theDenizen);
break;
case DISENGAGE:
if (Denizen.engagedNPC.contains(theDenizen)) Denizen.engagedNPC.remove(theDenizen);
break;
case SPAWNMOB:
case SPAWN: /* SPAWN [ENTITY_TYPE] (AMOUNT) (Location Bookmark) */
Denizen.getWorld.spawnMob(commandArgs[1], commandArgs[2], commandArgs[3], theDenizen);
break;
case SWITCH: // SWITCH [Block Bookmark] ON|OFF
Location switchLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Block");
if (switchLoc.getBlock().getType() == Material.LEVER) {
World theWorld = switchLoc.getWorld();
net.minecraft.server.Block.LEVER.interact(((CraftWorld)theWorld).getHandle(), switchLoc.getBlockX(), switchLoc.getBlockY(), switchLoc.getBlockZ(), null);
}
break;
case PRESS: // SWITCH [Block Bookmark] ON|OFF
Location pressLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Block");
if (pressLoc.getBlock().getType() == Material.STONE_BUTTON) {
World theWorld = pressLoc.getWorld();
net.minecraft.server.Block.STONE_BUTTON.interact(((CraftWorld)theWorld).getHandle(), pressLoc.getBlockX(), pressLoc.getBlockY(), pressLoc.getBlockZ(), null);
}
break;
case WEATHER: // WEATHER [Sunny|Stormy|Precipitation] (Duration for Stormy/Rainy)
if (commandArgs[1].equalsIgnoreCase("sunny")) { thePlayer.getWorld().setStorm(false); }
else if (commandArgs[1].equalsIgnoreCase("stormy")) { thePlayer.getWorld().setThundering(true); }
else if (commandArgs[1].equalsIgnoreCase("precipitation")) { thePlayer.getWorld().setStorm(true); }
break;
case CAST: // CAST [POTION_TYPE] [DURATION] [AMPLIFIER]
thePlayer.addPotionEffect(new PotionEffect(
PotionEffectType.getByName(commandArgs[1].toUpperCase()), Integer.valueOf(commandArgs[2]) * 20, Integer.valueOf(commandArgs[3])));
break;
case EFFECT: // EFFECT [EFFECT_TYPE] (Location Bookmark)
break;
case LOOK: // ENG
if (commandArgs[1].equalsIgnoreCase("CLOSE")) {
if (!theDenizen.getTrait(LookClose.class).toggle())
theDenizen.getTrait(LookClose.class).toggle();
}
else if (commandArgs[1].equalsIgnoreCase("AWAY")) {
if (theDenizen.getTrait(LookClose.class).toggle())
theDenizen.getTrait(LookClose.class).toggle();
}
else if (!commandArgs[1].equalsIgnoreCase("AWAY") && !commandArgs[1].equalsIgnoreCase("CLOSE")) {
NPC denizenLooking = theDenizen;
Location lookLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Location");
denizenLooking.getBukkitEntity().getLocation().setPitch(lookLoc.getPitch());
denizenLooking.getBukkitEntity().getLocation().setYaw(lookLoc.getYaw());
}
break;
case GIVE: // GIVE [Item:Data] [Amount] [ENCHANTMENT_TYPE]
String[] theItem = Denizen.getRequirements.splitItem(commandArgs[1]);
ItemStack giveItem = new ItemStack(Material.AIR);
if (Character.isDigit(theItem[0].charAt(0))) {
giveItem.setTypeId(Integer.valueOf(theItem[0]));
giveItem.getData().setData(Byte.valueOf(theItem[1]));
}
else giveItem.setType(Material.getMaterial(commandArgs[1].toUpperCase()));
if (commandArgs[2] != null) giveItem.setAmount(Integer.valueOf(commandArgs[2]));
else giveItem.setAmount(1);
thePlayer.getWorld().dropItem(thePlayer.getLocation(), giveItem);
break;
case TAKE: // TAKE [Item] [Amount] or TAKE ITEM_IN_HAND or TAKE MONEY [Amount]
if (commandArgs[1].equalsIgnoreCase("MONEY")) {
double playerMoneyAmt = Denizen.denizenEcon.getBalance(thePlayer.getName());
double amtToTake = Double.valueOf(commandArgs[2]);
if (amtToTake > playerMoneyAmt) amtToTake = playerMoneyAmt;
Denizen.denizenEcon.withdrawPlayer(thePlayer.getName(), amtToTake);
}
else if (commandArgs[1].equalsIgnoreCase("ITEMINHAND")) {
thePlayer.setItemInHand(new ItemStack(Material.AIR));
}
else {
String[] theTakeItem = Denizen.getRequirements.splitItem(commandArgs[1]);
ItemStack itemToTake = new ItemStack(Material.AIR);
if (Character.isDigit(theTakeItem[0].charAt(0))) {
itemToTake.setTypeId(Integer.valueOf(theTakeItem[0]));
itemToTake.getData().setData(Byte.valueOf(theTakeItem[1]));
}
else itemToTake.setType(Material.getMaterial(commandArgs[1].toUpperCase()));
if (commandArgs[2] != null) itemToTake.setAmount(Integer.valueOf(commandArgs[2]));
else itemToTake.setAmount(1);
thePlayer.getInventory().removeItem(itemToTake);
}
break;
case HEAL: // HEAL (# of Health)
int health = 1;
if (commandArgs[1] != null) health = Integer.valueOf(commandArgs[1]);
((LivingEntity) thePlayer).setHealth(thePlayer.getHealth() + health);
break;
case HURT: // HURT (# of Health)
int damage = 1;
if (commandArgs[1] != null) damage = Integer.valueOf(commandArgs[1]);
if (theDenizen != null) thePlayer.damage(damage, theDenizen.getBukkitEntity());
else thePlayer.damage(damage);
break;
case TELEPORT: // TELEPORT [Location Notable]
thePlayer.teleport(Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "location"));
case STRIKE: // STRIKE Strikes lightning on the player, with damage.
thePlayer.getWorld().strikeLightning(thePlayer.getLocation());
break;
case WALK: // WALK Z(-NORTH(2)/+SOUTH(0)) X(-WEST(1)/+EAST(3)) Y (+UP/-DOWN)
Denizen.previousNPCLoc.put(theDenizen, theDenizen.getBukkitEntity().getLocation());
if (!commandArgs[1].isEmpty()) theDenizen.getAI().setDestination(theDenizen.getBukkitEntity().getLocation()
.add(Double.parseDouble(commandArgs[2]), Double.parseDouble(commandArgs[3]), Double.parseDouble(commandArgs[1])));
break;
case WALKTO: // WALKTO [Location Bookmark]
Location walkLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Location");
Denizen.previousNPCLoc.put(theDenizen, theDenizen.getBukkitEntity().getLocation());
theDenizen.getAI().setDestination(walkLoc);
break;
case RETURN:
if (Denizen.previousNPCLoc.containsKey(theDenizen))
theDenizen.getAI().setDestination(Denizen.previousNPCLoc.get(theDenizen));
break;
case FINISH:
int finishes = plugin.getAssignments().getInt("Players." + thePlayer.getName() + "." + executeArgs[1] + "." + "Completed", 0);
finishes++;
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeArgs[1] + "." + "Completed", finishes);
plugin.saveSaves();
break;
case FAIL:
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeArgs[1] + "." + "Failed", true);
plugin.saveSaves();
break;
case REMEMBER: // REMEMBER [CHAT|LOCATION|INVENTORY]
break;
case FOLLOW: // FOLLOW PLAYER|NOBODY
if (commandArgs[1].equalsIgnoreCase("PLAYER")) {
theDenizen.getAI().setTarget(thePlayer, false);
}
if (commandArgs[1].equalsIgnoreCase("NOBODY")) {
theDenizen.getAI().cancelDestination();
}
break;
case ATTACK: // FOLLOW PLAYER|NOBODY
if (commandArgs[1].equalsIgnoreCase("PLAYER")) {
theDenizen.getAI().setTarget(thePlayer, true);
}
if (commandArgs[1].equalsIgnoreCase("NOBODY")) {
theDenizen.getAI().cancelDestination();
}
break;
case RESPAWN: // RESPAWN [Location Notable]
Location respawnLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Location");
Denizen.previousNPCLoc.put(theDenizen, theDenizen.getBukkitEntity().getLocation());
theDenizen.getBukkitEntity().getWorld().playEffect(theDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2);
theDenizen.despawn();
theDenizen.spawn(respawnLoc);
theDenizen.getBukkitEntity().getWorld().playEffect(theDenizen.getBukkitEntity().getLocation(), Effect.STEP_SOUND, 2);
break;
case PERMISS: // PERMISS [Permission Node]
Denizen.denizenPerms.playerAdd(thePlayer, commandArgs[1]);
break;
case REFUSE: // PERMISS [Permission Node]
Denizen.denizenPerms.playerRemove(thePlayer, commandArgs[1]);
break;
case EXECUTE: // EXECUTE ASPLAYER [Command to Execute]
String[] executeCommand = executeArgs[4].split(" ", 3);
if (commandArgs[1].equalsIgnoreCase("ASPLAYER")) {
thePlayer.performCommand(executeCommand[2]
.replace("<PLAYER>", thePlayer.getName()
.replace("<WORLD>", thePlayer.getWorld().getName())));
}
if (commandArgs[1].equalsIgnoreCase("ASNPC")) {
((Player) theDenizen.getBukkitEntity()).setOp(true);
((Player) theDenizen.getBukkitEntity()).performCommand(executeCommand[2]
.replace("<PLAYER>", thePlayer.getName()
.replace("<WORLD>", thePlayer.getWorld().getName())));
((Player) theDenizen.getBukkitEntity()).setOp(false);
}
if (commandArgs[1].equalsIgnoreCase("ASSERVER")) {
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), executeCommand[2]
.replace("<PLAYER>", thePlayer.getName()
.replace("<WORLD>", thePlayer.getWorld().getName())));
}
break;
// TYPE BOOKMARK DURATION LEEWAY RUNSCRIPT
case PLAYERTASK: // LOCATION [Location Bookmark] [Duration] [Leeway] [Script to Trigger]
/* LOCATION Listener */
String theLocation = commandArgs[2];
int theDuration = Integer.valueOf(commandArgs[3]);
int theLeeway = Integer.valueOf(commandArgs[4]);
String triggerScript = executeArgs[4].split(" ", 6)[5];
Denizen.scriptEngine.newLocationTask(thePlayer, theDenizen, theLocation, theDuration, theLeeway, triggerScript);
break;
case RUNTASK:
Denizen.scriptEngine.parseScript(null, thePlayer, executeArgs[4].split(" ", 2)[1], null, Trigger.TASK);
break;
case ANNOUNCE:
break;
case NARRATE:
case WHISPER:
case EMOTE:
case SHOUT:
case CHAT: // CHAT|WHISPER|EMOTE|SHOUT|NARRATE [Message]
/*
* I had to take out the feature for multiline text following the script delay. It was getting too messy!
* Hopefully nobody will notice ;) ...but I'm sure they will, so I will put that off for another day.
*/
/* Format the text for player and bystander, and turn into multiline if necessary */
String[] formattedText = Denizen.scriptEngine.formatChatText(executeArgs[4].split(" ", 2)[1], commandArgs[0], thePlayer, theDenizen);
List<String> playerText = Denizen.scriptEngine.getMultilineText(formattedText[0]);
List<String> bystanderText = Denizen.scriptEngine.getMultilineText(formattedText[1]);
/* Spew the text to the world. */
if (!playerText.isEmpty()) {
for (String text : playerText) { /* First playerText */
Denizen.getDenizen.talkToPlayer(theDenizen, thePlayer, text, null, commandArgs[0]);
}
}
if (!bystanderText.isEmpty()) {
for (String text : bystanderText) { /* now bystanderText */
if (!playerText.isEmpty()) Denizen.getDenizen.talkToPlayer(theDenizen, thePlayer, "shhh...don't speak!", text, commandArgs[0]);
else Denizen.getDenizen.talkToPlayer(theDenizen, thePlayer, null, text, commandArgs[0]);
}
}
break;
case RESET: // RESET FINISH(ED) [Name of Script] or RESET FAIL(ED) [NAME OF SCRIPT]
String executeScript;
if (commandArgs[2] == null) executeScript=theScript; else executeScript=executeArgs[4].split(" ", 3)[2];
if (commandArgs[1].equalsIgnoreCase("FINISH") || commandArgs[1].equalsIgnoreCase("FINISHED")) {
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeScript + "." + "Completed", 0);
plugin.saveSaves();
}
if (commandArgs[1].equalsIgnoreCase("FAIL") || commandArgs[1].equalsIgnoreCase("FAILED")) {
plugin.getSaves().set("Players." + thePlayer.getName() + "." + executeScript + "." + "Failed", false);
plugin.saveSaves();
}
break;
case CHANGE: // CHANGE [Block Bookmark] [#:#|MATERIAL_TYPE]
Location blockLoc = Denizen.getDenizen.getBookmark(theDenizen.getName(), commandArgs[1], "Block");
String[] theChangeItem = Denizen.getRequirements.splitItem(commandArgs[2]);
if (Character.isDigit(theChangeItem[0].charAt(0))) {
blockLoc.getBlock().setTypeId(Integer.valueOf(theChangeItem[0]));
blockLoc.getBlock().setData(Byte.valueOf(theChangeItem[1]));
}
else blockLoc.getBlock().setType(Material.getMaterial(commandArgs[2].toUpperCase()));
break;
case WAIT:
/*
* This may be a bit hack-y, at least it seems like it to me.
* but, if it isn't broken.. you know what they say.
*/
List<String> CurrentPlayerQue = new ArrayList<String>();
if (Denizen.playerQue.get(thePlayer) != null) CurrentPlayerQue = Denizen.playerQue.get(thePlayer);
Denizen.playerQue.remove(thePlayer); // Should keep the talk queue from triggering mid-add
Long timeDelay = Long.parseLong(commandArgs[1]) * 1000;
String timeWithDelay = String.valueOf(System.currentTimeMillis() + timeDelay);
CurrentPlayerQue.add(1, "0;none;0;" + timeWithDelay + ";WAITING");
Denizen.playerQue.put(thePlayer, CurrentPlayerQue);
break;
case WAITING:
// ...and we're waiting... mmmm... hack-y.
break;
default:
break;
}
return;
}
|
diff --git a/src/org/mozilla/javascript/Synchronizer.java b/src/org/mozilla/javascript/Synchronizer.java
index cef0fb5c..f2fca522 100644
--- a/src/org/mozilla/javascript/Synchronizer.java
+++ b/src/org/mozilla/javascript/Synchronizer.java
@@ -1,81 +1,81 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Delegator.java, released
* Sep 27, 2000.
*
* The Initial Developer of the Original Code is
* Matthias Radestock. <[email protected]>.
* Portions created by the Initial Developer are Copyright (C) 2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
// API class
package org.mozilla.javascript;
/**
* This class provides support for implementing Java-style synchronized
* methods in Javascript.
*
* Synchronized functions are created from ordinary Javascript
* functions by the <code>Synchronizer</code> constructor, e.g.
* <code>new Packages.org.mozilla.javascript.Synchronizer(fun)</code>.
* The resulting object is a function that establishes an exclusive
* lock on the <code>this</code> object of its invocation.
*
* The Rhino shell provides a short-cut for the creation of
* synchronized methods: <code>sync(fun)</code> has the same effect as
* calling the above constructor.
*
* @see org.mozilla.javascript.Delegator
* @author Matthias Radestock
*/
public class Synchronizer extends Delegator {
/**
* Create a new synchronized function from an existing one.
*
* @param obj the existing function
*/
public Synchronizer(Scriptable obj) {
super(obj);
}
/**
* @see org.mozilla.javascript.Function#call
*/
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
{
- synchronized(thisObj) {
+ synchronized(thisObj instanceof Wrapper ? ((Wrapper)thisObj).unwrap() : thisObj) {
return ((Function)obj).call(cx,scope,thisObj,args);
}
}
}
| true | true | public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
{
synchronized(thisObj) {
return ((Function)obj).call(cx,scope,thisObj,args);
}
}
| public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
{
synchronized(thisObj instanceof Wrapper ? ((Wrapper)thisObj).unwrap() : thisObj) {
return ((Function)obj).call(cx,scope,thisObj,args);
}
}
|
diff --git a/src/test/java/fr/jamgotchian/abcd/core/controlflow/RPSTTest.java b/src/test/java/fr/jamgotchian/abcd/core/controlflow/RPSTTest.java
index 3544106..98fbf08 100644
--- a/src/test/java/fr/jamgotchian/abcd/core/controlflow/RPSTTest.java
+++ b/src/test/java/fr/jamgotchian/abcd/core/controlflow/RPSTTest.java
@@ -1,137 +1,137 @@
/*
* Copyright (C) 2011 Geoffroy Jamgotchian <geoffroy.jamgotchian at gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.jamgotchian.abcd.core.controlflow;
import fr.jamgotchian.abcd.core.ABCDContext;
import fr.jamgotchian.abcd.core.util.SimplestFormatter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author Geoffroy Jamgotchian <geoffroy.jamgotchian at gmail.com>
*/
public class RPSTTest {
private static final Logger logger = Logger.getLogger(RPSTTest.class.getName());
public RPSTTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
// root logger configuration
Logger rootLogger = Logger.getLogger(ABCDContext.class.getPackage().getName());
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new SimplestFormatter());
handler.setLevel(Level.FINEST);
rootLogger.setLevel(Level.ALL);
rootLogger.addHandler(handler);
rootLogger.setUseParentHandlers(false);
}
@AfterClass
public static void tearDownClass() throws Exception {
Logger rootLogger = Logger.getLogger(ABCDContext.class.getPackage().getName());
for (Handler handler : rootLogger.getHandlers()) {
handler.close();
}
Thread.sleep(1000);
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testCase1() throws IOException {
BasicBlock a = new BasicBlockTestImpl("a");
BasicBlock b = new BasicBlockTestImpl("b");
BasicBlock c = new BasicBlockTestImpl("c");
BasicBlock d = new BasicBlockTestImpl("d");
BasicBlock e = new BasicBlockTestImpl("e");
BasicBlock f = new BasicBlockTestImpl("f");
BasicBlock g = new BasicBlockTestImpl("g");
BasicBlock h = new BasicBlockTestImpl("h");
BasicBlock i = new BasicBlockTestImpl("i");
BasicBlock j = new BasicBlockTestImpl("j");
BasicBlock k = new BasicBlockTestImpl("k");
BasicBlock l = new BasicBlockTestImpl("l");
ControlFlowGraphImpl cfg = new ControlFlowGraphImpl("Test", a, e);
cfg.addBasicBlock(b);
cfg.addBasicBlock(c);
cfg.addBasicBlock(d);
cfg.addBasicBlock(f);
cfg.addBasicBlock(g);
cfg.addBasicBlock(h);
cfg.addBasicBlock(i);
cfg.addBasicBlock(j);
cfg.addBasicBlock(k);
cfg.addBasicBlock(l);
cfg.addEdge(a, g);
cfg.addEdge(g, b);
cfg.addEdge(g, l);
cfg.addEdge(b, f);
cfg.addEdge(b, c);
cfg.addEdge(f, c);
cfg.addEdge(c, d);
cfg.addEdge(l, d);
cfg.addEdge(d, g);
cfg.addEdge(d, e);
cfg.addEdge(a, h);
cfg.addEdge(h, i);
cfg.addEdge(h, j);
cfg.addEdge(i, j);
cfg.addEdge(j, i);
cfg.addEdge(i, k);
cfg.addEdge(j, k);
cfg.addEdge(k, e);
- cfg.updateDomInfo();
+ cfg.updateDominatorInfo();
cfg.performDepthFirstSearch();
Writer writer = new FileWriter("/tmp/RPSTTest_CFG.dot");
try {
cfg.export(writer, new BasicBlockRangeAttributeFactory(),
new EdgeAttributeFactory(false));
} finally {
writer.close();
}
RPST rpst = new RPST(cfg);
writer = new FileWriter("/tmp/RPSTTest_RPST.dot");
try {
rpst.export(writer);
} finally {
writer.close();
}
}
}
| true | true | public void testCase1() throws IOException {
BasicBlock a = new BasicBlockTestImpl("a");
BasicBlock b = new BasicBlockTestImpl("b");
BasicBlock c = new BasicBlockTestImpl("c");
BasicBlock d = new BasicBlockTestImpl("d");
BasicBlock e = new BasicBlockTestImpl("e");
BasicBlock f = new BasicBlockTestImpl("f");
BasicBlock g = new BasicBlockTestImpl("g");
BasicBlock h = new BasicBlockTestImpl("h");
BasicBlock i = new BasicBlockTestImpl("i");
BasicBlock j = new BasicBlockTestImpl("j");
BasicBlock k = new BasicBlockTestImpl("k");
BasicBlock l = new BasicBlockTestImpl("l");
ControlFlowGraphImpl cfg = new ControlFlowGraphImpl("Test", a, e);
cfg.addBasicBlock(b);
cfg.addBasicBlock(c);
cfg.addBasicBlock(d);
cfg.addBasicBlock(f);
cfg.addBasicBlock(g);
cfg.addBasicBlock(h);
cfg.addBasicBlock(i);
cfg.addBasicBlock(j);
cfg.addBasicBlock(k);
cfg.addBasicBlock(l);
cfg.addEdge(a, g);
cfg.addEdge(g, b);
cfg.addEdge(g, l);
cfg.addEdge(b, f);
cfg.addEdge(b, c);
cfg.addEdge(f, c);
cfg.addEdge(c, d);
cfg.addEdge(l, d);
cfg.addEdge(d, g);
cfg.addEdge(d, e);
cfg.addEdge(a, h);
cfg.addEdge(h, i);
cfg.addEdge(h, j);
cfg.addEdge(i, j);
cfg.addEdge(j, i);
cfg.addEdge(i, k);
cfg.addEdge(j, k);
cfg.addEdge(k, e);
cfg.updateDomInfo();
cfg.performDepthFirstSearch();
Writer writer = new FileWriter("/tmp/RPSTTest_CFG.dot");
try {
cfg.export(writer, new BasicBlockRangeAttributeFactory(),
new EdgeAttributeFactory(false));
} finally {
writer.close();
}
RPST rpst = new RPST(cfg);
writer = new FileWriter("/tmp/RPSTTest_RPST.dot");
try {
rpst.export(writer);
} finally {
writer.close();
}
}
| public void testCase1() throws IOException {
BasicBlock a = new BasicBlockTestImpl("a");
BasicBlock b = new BasicBlockTestImpl("b");
BasicBlock c = new BasicBlockTestImpl("c");
BasicBlock d = new BasicBlockTestImpl("d");
BasicBlock e = new BasicBlockTestImpl("e");
BasicBlock f = new BasicBlockTestImpl("f");
BasicBlock g = new BasicBlockTestImpl("g");
BasicBlock h = new BasicBlockTestImpl("h");
BasicBlock i = new BasicBlockTestImpl("i");
BasicBlock j = new BasicBlockTestImpl("j");
BasicBlock k = new BasicBlockTestImpl("k");
BasicBlock l = new BasicBlockTestImpl("l");
ControlFlowGraphImpl cfg = new ControlFlowGraphImpl("Test", a, e);
cfg.addBasicBlock(b);
cfg.addBasicBlock(c);
cfg.addBasicBlock(d);
cfg.addBasicBlock(f);
cfg.addBasicBlock(g);
cfg.addBasicBlock(h);
cfg.addBasicBlock(i);
cfg.addBasicBlock(j);
cfg.addBasicBlock(k);
cfg.addBasicBlock(l);
cfg.addEdge(a, g);
cfg.addEdge(g, b);
cfg.addEdge(g, l);
cfg.addEdge(b, f);
cfg.addEdge(b, c);
cfg.addEdge(f, c);
cfg.addEdge(c, d);
cfg.addEdge(l, d);
cfg.addEdge(d, g);
cfg.addEdge(d, e);
cfg.addEdge(a, h);
cfg.addEdge(h, i);
cfg.addEdge(h, j);
cfg.addEdge(i, j);
cfg.addEdge(j, i);
cfg.addEdge(i, k);
cfg.addEdge(j, k);
cfg.addEdge(k, e);
cfg.updateDominatorInfo();
cfg.performDepthFirstSearch();
Writer writer = new FileWriter("/tmp/RPSTTest_CFG.dot");
try {
cfg.export(writer, new BasicBlockRangeAttributeFactory(),
new EdgeAttributeFactory(false));
} finally {
writer.close();
}
RPST rpst = new RPST(cfg);
writer = new FileWriter("/tmp/RPSTTest_RPST.dot");
try {
rpst.export(writer);
} finally {
writer.close();
}
}
|
diff --git a/src/minecraft/biomesoplenty/world/ChunkProviderBOP.java b/src/minecraft/biomesoplenty/world/ChunkProviderBOP.java
index aa3ac934d..57bcea514 100644
--- a/src/minecraft/biomesoplenty/world/ChunkProviderBOP.java
+++ b/src/minecraft/biomesoplenty/world/ChunkProviderBOP.java
@@ -1,731 +1,731 @@
package biomesoplenty.world;
import static net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.CAVE;
import static net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.MINESHAFT;
import static net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.RAVINE;
import static net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.SCATTERED_FEATURE;
import static net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.STRONGHOLD;
import static net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.VILLAGE;
import static net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType.DUNGEON;
import static net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType.ICE;
import static net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType.LAKE;
import static net.minecraftforge.event.terraingen.PopulateChunkEvent.Populate.EventType.LAVA;
import java.util.List;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockSand;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.util.IProgressUpdate;
import net.minecraft.util.MathHelper;
import net.minecraft.world.ChunkPosition;
import net.minecraft.world.SpawnerAnimals;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import net.minecraft.world.gen.MapGenBase;
import net.minecraft.world.gen.NoiseGeneratorOctaves;
import net.minecraft.world.gen.feature.WorldGenDungeons;
import net.minecraft.world.gen.feature.WorldGenLakes;
import net.minecraft.world.gen.structure.MapGenMineshaft;
import net.minecraft.world.gen.structure.MapGenStronghold;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.Event.Result;
import net.minecraftforge.event.terraingen.ChunkProviderEvent;
import net.minecraftforge.event.terraingen.PopulateChunkEvent;
import net.minecraftforge.event.terraingen.TerrainGen;
import biomesoplenty.api.Biomes;
import biomesoplenty.configuration.BOPConfiguration;
import biomesoplenty.world.map.MapGenCavesBOP;
import biomesoplenty.world.map.MapGenRavineBOP;
import biomesoplenty.world.noise.NoiseOctaves;
import biomesoplenty.worldgen.structure.BOPMapGenScatteredFeature;
import biomesoplenty.worldgen.structure.BOPMapGenVillage;
public class ChunkProviderBOP implements IChunkProvider
{
private Random rand;
private NoiseGeneratorOctaves noiseGen1;
private NoiseGeneratorOctaves noiseGen2;
private NoiseGeneratorOctaves noiseGen3;
private NoiseGeneratorOctaves noiseGen4;
public NoiseGeneratorOctaves noiseGen5;
public NoiseGeneratorOctaves noiseGen6;
public NoiseGeneratorOctaves mobSpawnerNoise;
private World worldObj;
private final boolean mapFeaturesEnabled;
private double[] noiseArray;
private double[] stoneNoise = new double[256];
private MapGenBase caveGenerator = new MapGenCavesBOP();
private MapGenStronghold strongholdGenerator = new MapGenStronghold();
private BOPMapGenVillage villageGenerator = new BOPMapGenVillage();
private MapGenMineshaft mineshaftGenerator = new MapGenMineshaft();
private BOPMapGenScatteredFeature scatteredFeatureGenerator = new BOPMapGenScatteredFeature();
private MapGenBase ravineGenerator = new MapGenRavineBOP();
private BiomeGenBase[] biomesForGeneration;
double[] noise3;
double[] noise1;
double[] noise2;
double[] noise5;
double[] noise6;
private NoiseOctaves beachnoise;
private double[] sandNoise = new double[256];
private double[] gravelNoise = new double[256];
float[] parabolicField;
int[][] field_73219_j = new int[32][32];
{
caveGenerator = TerrainGen.getModdedMapGen(caveGenerator, CAVE);
strongholdGenerator = (MapGenStronghold) TerrainGen.getModdedMapGen(strongholdGenerator, STRONGHOLD);
villageGenerator = (BOPMapGenVillage) TerrainGen.getModdedMapGen(villageGenerator, VILLAGE);
mineshaftGenerator = (MapGenMineshaft) TerrainGen.getModdedMapGen(mineshaftGenerator, MINESHAFT);
scatteredFeatureGenerator = (BOPMapGenScatteredFeature) TerrainGen.getModdedMapGen(scatteredFeatureGenerator, SCATTERED_FEATURE);
ravineGenerator = TerrainGen.getModdedMapGen(ravineGenerator, RAVINE);
}
public ChunkProviderBOP(World par1World, long par2, boolean par4)
{
worldObj = par1World;
mapFeaturesEnabled = par4;
rand = new Random(par2);
noiseGen1 = new NoiseGeneratorOctaves(rand, 16);
noiseGen2 = new NoiseGeneratorOctaves(rand, 16);
noiseGen3 = new NoiseGeneratorOctaves(rand, 8);
noiseGen4 = new NoiseGeneratorOctaves(rand, 4);
noiseGen5 = new NoiseGeneratorOctaves(rand, 10);
noiseGen6 = new NoiseGeneratorOctaves(rand, 16);
mobSpawnerNoise = new NoiseGeneratorOctaves(rand, 8);
beachnoise = new NoiseOctaves(rand, 4);
NoiseGeneratorOctaves[] noiseGens = {noiseGen1, noiseGen2, noiseGen3, noiseGen4, noiseGen5, noiseGen6, mobSpawnerNoise};
noiseGens = TerrainGen.getModdedNoiseGenerators(par1World, rand, noiseGens);
noiseGen1 = noiseGens[0];
noiseGen2 = noiseGens[1];
noiseGen3 = noiseGens[2];
noiseGen4 = noiseGens[3];
noiseGen5 = noiseGens[4];
noiseGen6 = noiseGens[5];
mobSpawnerNoise = noiseGens[6];
}
/**
* Generates the shape of the terrain for the chunk though its all stone though the water is frozen if the
* temperature is low enough
*/
public void generateTerrain(int par1, int par2, byte[] par3ArrayOfByte)
{
byte b0 = 4;
byte b1 = 32;
byte b2 = 63;
int k = b0 + 1;
byte b3 = 33;
int l = b0 + 1;
biomesForGeneration = worldObj.getWorldChunkManager().getBiomesForGeneration(biomesForGeneration, par1 * 4 - 2, par2 * 4 - 2, k + 5, l + 5);
noiseArray = this.initializeNoiseField(noiseArray, par1 * b0, 0, par2 * b0, k, b3, l);
for (int i1 = 0; i1 < b0; ++i1)
{
for (int j1 = 0; j1 < b0; ++j1)
{
for (int k1 = 0; k1 < b1; ++k1)
{
double d0 = 0.125D;
double d1 = noiseArray[((i1 + 0) * l + j1 + 0) * b3 + k1 + 0];
double d2 = noiseArray[((i1 + 0) * l + j1 + 1) * b3 + k1 + 0];
double d3 = noiseArray[((i1 + 1) * l + j1 + 0) * b3 + k1 + 0];
double d4 = noiseArray[((i1 + 1) * l + j1 + 1) * b3 + k1 + 0];
double d5 = (noiseArray[((i1 + 0) * l + j1 + 0) * b3 + k1 + 1] - d1) * d0;
double d6 = (noiseArray[((i1 + 0) * l + j1 + 1) * b3 + k1 + 1] - d2) * d0;
double d7 = (noiseArray[((i1 + 1) * l + j1 + 0) * b3 + k1 + 1] - d3) * d0;
double d8 = (noiseArray[((i1 + 1) * l + j1 + 1) * b3 + k1 + 1] - d4) * d0;
for (int l1 = 0; l1 < 8; ++l1)
{
double d9 = 0.25D;
double d10 = d1;
double d11 = d2;
double d12 = (d3 - d1) * d9;
double d13 = (d4 - d2) * d9;
for (int i2 = 0; i2 < 4; ++i2)
{
int j2 = i2 + i1 * 4 << 12 | 0 + j1 * 4 << 8 | k1 * 8 + l1;
short short1 = 256;
j2 -= short1;
double d14 = 0.25D;
double d15 = (d11 - d10) * d14;
double d16 = d10 - d15;
for (int k2 = 0; k2 < 4; ++k2)
{
if ((d16 += d15) > 0.0D)
{
par3ArrayOfByte[j2 += short1] = (byte)Block.stone.blockID;
}
else if (k1 * 8 + l1 < b2)
{
par3ArrayOfByte[j2 += short1] = (byte)Block.waterStill.blockID;
}
else
{
par3ArrayOfByte[j2 += short1] = 0;
}
}
d10 += d12;
d11 += d13;
}
d1 += d5;
d2 += d6;
d3 += d7;
d4 += d8;
}
}
}
}
}
/**
* Replaces the stone that was placed in with blocks that match the biome
*/
public void replaceBlocksForBiome(int par1, int par2, byte[] par3ArrayOfByte, BiomeGenBase[] par4ArrayOfBiomeGenBase)
{
ChunkProviderEvent.ReplaceBiomeBlocks event = new ChunkProviderEvent.ReplaceBiomeBlocks(this, par1, par2, par3ArrayOfByte, par4ArrayOfBiomeGenBase);
MinecraftForge.EVENT_BUS.post(event);
if (event.getResult() == Result.DENY) return;
byte b0 = 63;
double d0 = 0.03125D;
sandNoise = beachnoise.generateNoiseOctaves(sandNoise, par1 * 16, par2 * 16, 0.0D, 16, 16, 1, d0, d0, 1.0D);
gravelNoise = beachnoise.generateNoiseOctaves(gravelNoise, par1 * 16, 109.0134D, par2 * 16, 16, 1, 16, d0, 1.0D, d0);
stoneNoise = noiseGen4.generateNoiseOctaves(stoneNoise, par1 * 16, par2 * 16, 0, 16, 16, 1, d0 * 2.0D, d0 * 2.0D, d0 * 2.0D);
for (int k = 0; k < 16; ++k)
{
for (int l = 0; l < 16; ++l)
{
BiomeGenBase biomegenbase = par4ArrayOfBiomeGenBase[l + k * 16];
float f = biomegenbase.getFloatTemperature();
int i1 = (int)(stoneNoise[k + l * 16] / 3.0D + 3.0D + rand.nextDouble() * 0.25D);
boolean sandbeach = sandNoise[k + l * 16] + rand.nextDouble() * 0.20000000000000001D > 0.0D;
boolean gravelbeach = gravelNoise[k + l * 16] + rand.nextDouble() * 0.20000000000000001D > 3D;
int j1 = -1;
byte b1 = biomegenbase.topBlock;
byte b2 = biomegenbase.fillerBlock;
for (int k1 = 255; k1 >= 0; --k1)
{
int l1 = (l * 16 + k) * 256 + k1;
if (k1 <= 0 + rand.nextInt(5))
{
par3ArrayOfByte[l1] = (byte)Block.bedrock.blockID;
}
else
{
byte b3 = par3ArrayOfByte[l1];
if (b3 == 0)
{
j1 = -1;
}
else if (b3 == Block.stone.blockID)
{
if (j1 == -1)
{
if (i1 <= 0)
{
if (BOPConfiguration.TerrainGen.exposedStone)
{
b1 = 0;
b2 = (byte)Block.stone.blockID;
}
else
{
b1 = biomegenbase.topBlock;
b2 = biomegenbase.fillerBlock;
}
}
else if (k1 >= b0 - 4 && k1 <= b0 + 1)
{
if(biomegenbase.biomeID == BOPConfiguration.IDs.originValleyID)
{
if(gravelbeach)
{
b1 = 0;
b2 = (byte)Block.gravel.blockID;
}
else if(sandbeach)
{
b1 = (byte)Block.sand.blockID;
b2 = (byte)Block.sand.blockID;
}
else
{
b1 = biomegenbase.topBlock;
b2 = biomegenbase.fillerBlock;
}
}
else
{
b1 = biomegenbase.topBlock;
b2 = biomegenbase.fillerBlock;
}
}
if (k1 < b0 && b1 == 0)
{
if (f < 0.15F)
{
b1 = (byte)Block.ice.blockID;
}
else
{
b1 = (byte)Block.waterStill.blockID;
}
}
j1 = i1;
if (k1 >= b0 - 1)
{
par3ArrayOfByte[l1] = b1;
}
else
{
par3ArrayOfByte[l1] = b2;
}
}
else if (j1 > 0)
{
--j1;
par3ArrayOfByte[l1] = b2;
if (j1 == 0 && b2 == Block.sand.blockID)
{
j1 = rand.nextInt(4);
b2 = (byte)Block.sandStone.blockID;
}
}
}
}
}
}
}
}
/**
* loads or generates the chunk at the chunk location specified
*/
@Override
public Chunk loadChunk(int par1, int par2)
{
return this.provideChunk(par1, par2);
}
/**
* Will return back a chunk, if it doesn't exist and its not a MP client it will generates all the blocks for the
* specified chunk from the map seed and chunk seed
*/
@Override
public Chunk provideChunk(int par1, int par2)
{
rand.setSeed(par1 * 341873128712L + par2 * 132897987541L);
byte[] abyte = new byte[0x65536];
this.generateTerrain(par1, par2, abyte);
biomesForGeneration = worldObj.getWorldChunkManager().loadBlockGeneratorData(biomesForGeneration, par1 * 16, par2 * 16, 16, 16);
this.replaceBlocksForBiome(par1, par2, abyte, biomesForGeneration);
caveGenerator.generate(this, worldObj, par1, par2, abyte);
ravineGenerator.generate(this, worldObj, par1, par2, abyte);
if (mapFeaturesEnabled)
{
mineshaftGenerator.generate(this, worldObj, par1, par2, abyte);
villageGenerator.generate(this, worldObj, par1, par2, abyte);
strongholdGenerator.generate(this, worldObj, par1, par2, abyte);
scatteredFeatureGenerator.generate(this, worldObj, par1, par2, abyte);
}
Chunk chunk = new Chunk(worldObj, par1, par2);
ExtendedBlockStorage aextendedblockstorage[] = chunk.getBlockStorageArray();
byte[] abyte1 = chunk.getBiomeArray();
for (int k = 0; k < abyte1.length; ++k)
{
abyte1[k] = (byte)this.biomesForGeneration[k].biomeID;
}
for (int k = 0; k < 16; k++)
{
for (int l = 0; l < 16; l++)
{
for (int i1 = 0; i1 < 256; i1++)
{
byte byte0 = abyte[k << 12 | l << 8 | i1];
if (byte0 == 0)
{
continue;
}
int j1 = i1 >> 4;
if (aextendedblockstorage[j1] == null)
{
aextendedblockstorage[j1] = new ExtendedBlockStorage(j1 << 4, mapFeaturesEnabled);
}
aextendedblockstorage[j1].setExtBlockID(k, i1 & 0xf, l, byte0 & 0xff);
}
}
}
chunk.generateSkylightMap();
return chunk;
}
/**
* generates a subset of the level's terrain data. Takes 7 arguments: the [empty] noise array, the position, and the
* size.
*/
private double[] initializeNoiseField(double[] par1ArrayOfDouble, int par2, int par3, int par4, int par5, int par6, int par7)
{
ChunkProviderEvent.InitNoiseField event = new ChunkProviderEvent.InitNoiseField(this, par1ArrayOfDouble, par2, par3, par4, par5, par6, par7);
MinecraftForge.EVENT_BUS.post(event);
if (event.getResult() == Result.DENY) return event.noisefield;
if (par1ArrayOfDouble == null)
{
par1ArrayOfDouble = new double[par5 * par6 * par7];
}
if (parabolicField == null)
{
parabolicField = new float[25];
for (int k1 = -2; k1 <= 2; ++k1)
{
for (int l1 = -2; l1 <= 2; ++l1)
{
float f = 10.0F / MathHelper.sqrt_float(k1 * k1 + l1 * l1 + 0.2F);
parabolicField[k1 + 2 + (l1 + 2) * 5] = f;
}
}
}
double d0 = 684.412D;
double d1 = 684.412D;
noise5 = noiseGen5.generateNoiseOctaves(noise5, par2, par4, par5, par7, 1.121D, 1.121D, 0.5D);
noise6 = noiseGen6.generateNoiseOctaves(noise6, par2, par4, par5, par7, 200.0D, 200.0D, 0.5D);
noise3 = noiseGen3.generateNoiseOctaves(noise3, par2, par3, par4, par5, par6, par7, d0 / 80.0D, d1 / 160.0D, d0 / 80.0D);
noise1 = noiseGen1.generateNoiseOctaves(noise1, par2, par3, par4, par5, par6, par7, d0, d1, d0);
noise2 = noiseGen2.generateNoiseOctaves(noise2, par2, par3, par4, par5, par6, par7, d0, d1, d0);
boolean flag = false;
boolean flag1 = false;
int i2 = 0;
int j2 = 0;
for (int k2 = 0; k2 < par5; ++k2)
{
for (int l2 = 0; l2 < par7; ++l2)
{
float f1 = 0.0F;
float f2 = 0.0F;
float f3 = 0.0F;
byte b0 = 2;
BiomeGenBase biomegenbase = biomesForGeneration[k2 + 2 + (l2 + 2) * (par5 + 5)];
for (int i3 = -b0; i3 <= b0; ++i3)
{
for (int j3 = -b0; j3 <= b0; ++j3)
{
BiomeGenBase biomegenbase1 = biomesForGeneration[k2 + i3 + 2 + (l2 + j3 + 2) * (par5 + 5)];
float f4 = parabolicField[i3 + 2 + (j3 + 2) * 5] / (biomegenbase1.minHeight + 2.0F);
if (biomegenbase1.minHeight > biomegenbase.minHeight)
{
f4 /= 2.0F;
}
f1 += biomegenbase1.maxHeight * f4;
- f2 += biomegenbase1.minHeight * f4;
+ f2 += (biomegenbase1.minHeight - 2.0) * f4;
f3 += f4;
}
}
f1 /= f3;
f2 /= f3;
f1 = f1 * 0.9F + 0.1F;
f2 = (f2 * 4.0F - 1.0F) / 8.0F;
double d2 = noise6[j2] / 8000.0D;
if (d2 < 0.0D)
{
d2 = -d2 * 0.3D;
}
d2 = d2 * 3.0D - 2.0D;
if (d2 < 0.0D)
{
d2 /= 2.0D;
if (d2 < -1.0D)
{
d2 = -1.0D;
}
d2 /= 1.4D;
d2 /= 2.0D;
}
else
{
if (d2 > 1.0D)
{
d2 = 1.0D;
}
d2 /= 8.0D;
}
++j2;
for (int k3 = 0; k3 < par6; ++k3)
{
double d3 = f2;
double d4 = f1;
d3 += d2 * 0.2D;
d3 = d3 * par6 / 16.0D;
double d5 = par6 / 2.0D + d3 * 4.0D;
double d6 = 0.0D;
double d7 = (k3 - d5) * 12.0D * 128.0D / 128.0D / d4;
if (d7 < 0.0D)
{
d7 *= 4.0D;
}
double d8 = noise1[i2] / 512.0D;
double d9 = noise2[i2] / 512.0D;
double d10 = (noise3[i2] / 10.0D + 1.0D) / 2.0D;
if (d10 < 0.0D)
{
d6 = d8;
}
else if (d10 > 1.0D)
{
d6 = d9;
}
else
{
d6 = d8 + (d9 - d8) * d10;
}
d6 -= d7;
if (k3 > par6 - 4)
{
double d11 = (k3 - (par6 - 4)) / 3.0F;
d6 = d6 * (1.0D - d11) + -10.0D * d11;
}
par1ArrayOfDouble[i2] = d6;
++i2;
}
}
}
return par1ArrayOfDouble;
}
/**
* Checks to see if a chunk exists at x, y
*/
@Override
public boolean chunkExists(int par1, int par2)
{
return true;
}
/**
* Populates chunk with ores etc etc
*/
@Override
public void populate(IChunkProvider par1IChunkProvider, int par2, int par3)
{
BlockSand.fallInstantly = true;
int k = par2 * 16;
int l = par3 * 16;
BiomeGenBase biomegenbase = worldObj.getBiomeGenForCoords(k + 16, l + 16);
rand.setSeed(worldObj.getSeed());
long i1 = rand.nextLong() / 2L * 2L + 1L;
long j1 = rand.nextLong() / 2L * 2L + 1L;
rand.setSeed(par2 * i1 + par3 * j1 ^ worldObj.getSeed());
boolean flag = false;
MinecraftForge.EVENT_BUS.post(new PopulateChunkEvent.Pre(par1IChunkProvider, worldObj, rand, par2, par3, flag));
if (mapFeaturesEnabled)
{
mineshaftGenerator.generateStructuresInChunk(worldObj, rand, par2, par3);
flag = villageGenerator.generateStructuresInChunk(worldObj, rand, par2, par3);
strongholdGenerator.generateStructuresInChunk(worldObj, rand, par2, par3);
scatteredFeatureGenerator.generateStructuresInChunk(worldObj, rand, par2, par3);
}
int k1;
int l1;
int i2;
if (biomegenbase != BiomeGenBase.desert && biomegenbase != BiomeGenBase.desertHills && biomegenbase != Biomes.desertNew.get() && biomegenbase != Biomes.glacier.get() && biomegenbase != Biomes.volcano.get() && biomegenbase != Biomes.scrubland.get() && biomegenbase != Biomes.dunes.get() && biomegenbase != Biomes.arctic.get() && biomegenbase != Biomes.pasture.get() && biomegenbase != Biomes.silkglades.get() && !flag && this.rand.nextInt(4) == 0
&& TerrainGen.populate(par1IChunkProvider, worldObj, rand, par2, par3, flag, LAKE))
{
k1 = k + this.rand.nextInt(16) + 8;
l1 = this.rand.nextInt(128);
i2 = l + this.rand.nextInt(16) + 8;
(new WorldGenLakes(Block.waterStill.blockID)).generate(this.worldObj, this.rand, k1, l1, i2);
}
if (TerrainGen.populate(par1IChunkProvider, worldObj, rand, par2, par3, flag, LAVA) &&
!flag && rand.nextInt(8) == 0)
{
k1 = k + rand.nextInt(16) + 8;
l1 = rand.nextInt(rand.nextInt(120) + 8);
i2 = l + rand.nextInt(16) + 8;
if (l1 < 63 || rand.nextInt(10) == 0)
{
(new WorldGenLakes(Block.lavaStill.blockID)).generate(worldObj, rand, k1, l1, i2);
}
}
boolean doGen = TerrainGen.populate(par1IChunkProvider, worldObj, rand, par2, par3, flag, DUNGEON);
for (k1 = 0; doGen && k1 < 8; ++k1)
{
l1 = k + rand.nextInt(16) + 8;
i2 = rand.nextInt(128);
int j2 = l + rand.nextInt(16) + 8;
if ((new WorldGenDungeons()).generate(worldObj, rand, l1, i2, j2))
{
;
}
}
biomegenbase.decorate(worldObj, rand, k, l);
SpawnerAnimals.performWorldGenSpawning(worldObj, biomegenbase, k + 8, l + 8, 16, 16, rand);
k += 8;
l += 8;
doGen = TerrainGen.populate(par1IChunkProvider, worldObj, rand, par2, par3, flag, ICE);
for (k1 = 0; doGen && k1 < 16; ++k1)
{
for (l1 = 0; l1 < 16; ++l1)
{
i2 = worldObj.getPrecipitationHeight(k + k1, l + l1);
if (worldObj.isBlockFreezable(k1 + k, i2 - 1, l1 + l))
{
worldObj.setBlock(k1 + k, i2 - 1, l1 + l, Block.ice.blockID, 0, 2);
}
if (worldObj.canSnowAt(k1 + k, i2, l1 + l))
{
worldObj.setBlock(k1 + k, i2, l1 + l, Block.snow.blockID, 0, 2);
}
}
}
MinecraftForge.EVENT_BUS.post(new PopulateChunkEvent.Post(par1IChunkProvider, worldObj, rand, par2, par3, flag));
BlockSand.fallInstantly = false;
}
/**
* Two modes of operation: if passed true, save all Chunks in one go. If passed false, save up to two chunks.
* Return true if all chunks have been saved.
*/
@Override
public boolean saveChunks(boolean par1, IProgressUpdate par2IProgressUpdate)
{
return true;
}
/**
* Unloads chunks that are marked to be unloaded. This is not guaranteed to unload every such chunk.
*/
@Override
public boolean unloadQueuedChunks()
{
return false;
}
/**
* Returns if the IChunkProvider supports saving.
*/
@Override
public boolean canSave()
{
return true;
}
/**
* Converts the instance data to a readable string.
*/
@Override
public String makeString()
{
return "RandomLevelSource";
}
/**
* Returns a list of creatures of the specified type that can spawn at the given location.
*/
@Override
@SuppressWarnings("rawtypes")
public List getPossibleCreatures(EnumCreatureType par1EnumCreatureType, int par2, int par3, int par4)
{
BiomeGenBase biomegenbase = worldObj.getBiomeGenForCoords(par2, par4);
return biomegenbase == null ? null : (biomegenbase == BiomeGenBase.swampland && par1EnumCreatureType == EnumCreatureType.monster && scatteredFeatureGenerator.hasStructureAt(par2, par3, par4) ? scatteredFeatureGenerator.getScatteredFeatureSpawnList() : biomegenbase.getSpawnableList(par1EnumCreatureType));
}
/**
* Returns the location of the closest structure of the specified type. If not found returns null.
*/
@Override
public ChunkPosition findClosestStructure(World par1World, String par2Str, int par3, int par4, int par5)
{
return "Stronghold".equals(par2Str) && strongholdGenerator != null ? strongholdGenerator.getNearestInstance(par1World, par3, par4, par5) : null;
}
@Override
public int getLoadedChunkCount()
{
return 0;
}
@Override
public void recreateStructures(int par1, int par2)
{
if (mapFeaturesEnabled)
{
mineshaftGenerator.generate(this, worldObj, par1, par2, (byte[])null);
villageGenerator.generate(this, worldObj, par1, par2, (byte[])null);
strongholdGenerator.generate(this, worldObj, par1, par2, (byte[])null);
scatteredFeatureGenerator.generate(this, worldObj, par1, par2, (byte[])null);
}
}
@Override
public void func_104112_b() {}
}
| true | true | private double[] initializeNoiseField(double[] par1ArrayOfDouble, int par2, int par3, int par4, int par5, int par6, int par7)
{
ChunkProviderEvent.InitNoiseField event = new ChunkProviderEvent.InitNoiseField(this, par1ArrayOfDouble, par2, par3, par4, par5, par6, par7);
MinecraftForge.EVENT_BUS.post(event);
if (event.getResult() == Result.DENY) return event.noisefield;
if (par1ArrayOfDouble == null)
{
par1ArrayOfDouble = new double[par5 * par6 * par7];
}
if (parabolicField == null)
{
parabolicField = new float[25];
for (int k1 = -2; k1 <= 2; ++k1)
{
for (int l1 = -2; l1 <= 2; ++l1)
{
float f = 10.0F / MathHelper.sqrt_float(k1 * k1 + l1 * l1 + 0.2F);
parabolicField[k1 + 2 + (l1 + 2) * 5] = f;
}
}
}
double d0 = 684.412D;
double d1 = 684.412D;
noise5 = noiseGen5.generateNoiseOctaves(noise5, par2, par4, par5, par7, 1.121D, 1.121D, 0.5D);
noise6 = noiseGen6.generateNoiseOctaves(noise6, par2, par4, par5, par7, 200.0D, 200.0D, 0.5D);
noise3 = noiseGen3.generateNoiseOctaves(noise3, par2, par3, par4, par5, par6, par7, d0 / 80.0D, d1 / 160.0D, d0 / 80.0D);
noise1 = noiseGen1.generateNoiseOctaves(noise1, par2, par3, par4, par5, par6, par7, d0, d1, d0);
noise2 = noiseGen2.generateNoiseOctaves(noise2, par2, par3, par4, par5, par6, par7, d0, d1, d0);
boolean flag = false;
boolean flag1 = false;
int i2 = 0;
int j2 = 0;
for (int k2 = 0; k2 < par5; ++k2)
{
for (int l2 = 0; l2 < par7; ++l2)
{
float f1 = 0.0F;
float f2 = 0.0F;
float f3 = 0.0F;
byte b0 = 2;
BiomeGenBase biomegenbase = biomesForGeneration[k2 + 2 + (l2 + 2) * (par5 + 5)];
for (int i3 = -b0; i3 <= b0; ++i3)
{
for (int j3 = -b0; j3 <= b0; ++j3)
{
BiomeGenBase biomegenbase1 = biomesForGeneration[k2 + i3 + 2 + (l2 + j3 + 2) * (par5 + 5)];
float f4 = parabolicField[i3 + 2 + (j3 + 2) * 5] / (biomegenbase1.minHeight + 2.0F);
if (biomegenbase1.minHeight > biomegenbase.minHeight)
{
f4 /= 2.0F;
}
f1 += biomegenbase1.maxHeight * f4;
f2 += biomegenbase1.minHeight * f4;
f3 += f4;
}
}
f1 /= f3;
f2 /= f3;
f1 = f1 * 0.9F + 0.1F;
f2 = (f2 * 4.0F - 1.0F) / 8.0F;
double d2 = noise6[j2] / 8000.0D;
if (d2 < 0.0D)
{
d2 = -d2 * 0.3D;
}
d2 = d2 * 3.0D - 2.0D;
if (d2 < 0.0D)
{
d2 /= 2.0D;
if (d2 < -1.0D)
{
d2 = -1.0D;
}
d2 /= 1.4D;
d2 /= 2.0D;
}
else
{
if (d2 > 1.0D)
{
d2 = 1.0D;
}
d2 /= 8.0D;
}
++j2;
for (int k3 = 0; k3 < par6; ++k3)
{
double d3 = f2;
double d4 = f1;
d3 += d2 * 0.2D;
d3 = d3 * par6 / 16.0D;
double d5 = par6 / 2.0D + d3 * 4.0D;
double d6 = 0.0D;
double d7 = (k3 - d5) * 12.0D * 128.0D / 128.0D / d4;
if (d7 < 0.0D)
{
d7 *= 4.0D;
}
double d8 = noise1[i2] / 512.0D;
double d9 = noise2[i2] / 512.0D;
double d10 = (noise3[i2] / 10.0D + 1.0D) / 2.0D;
if (d10 < 0.0D)
{
d6 = d8;
}
else if (d10 > 1.0D)
{
d6 = d9;
}
else
{
d6 = d8 + (d9 - d8) * d10;
}
d6 -= d7;
if (k3 > par6 - 4)
{
double d11 = (k3 - (par6 - 4)) / 3.0F;
d6 = d6 * (1.0D - d11) + -10.0D * d11;
}
par1ArrayOfDouble[i2] = d6;
++i2;
}
}
}
return par1ArrayOfDouble;
}
| private double[] initializeNoiseField(double[] par1ArrayOfDouble, int par2, int par3, int par4, int par5, int par6, int par7)
{
ChunkProviderEvent.InitNoiseField event = new ChunkProviderEvent.InitNoiseField(this, par1ArrayOfDouble, par2, par3, par4, par5, par6, par7);
MinecraftForge.EVENT_BUS.post(event);
if (event.getResult() == Result.DENY) return event.noisefield;
if (par1ArrayOfDouble == null)
{
par1ArrayOfDouble = new double[par5 * par6 * par7];
}
if (parabolicField == null)
{
parabolicField = new float[25];
for (int k1 = -2; k1 <= 2; ++k1)
{
for (int l1 = -2; l1 <= 2; ++l1)
{
float f = 10.0F / MathHelper.sqrt_float(k1 * k1 + l1 * l1 + 0.2F);
parabolicField[k1 + 2 + (l1 + 2) * 5] = f;
}
}
}
double d0 = 684.412D;
double d1 = 684.412D;
noise5 = noiseGen5.generateNoiseOctaves(noise5, par2, par4, par5, par7, 1.121D, 1.121D, 0.5D);
noise6 = noiseGen6.generateNoiseOctaves(noise6, par2, par4, par5, par7, 200.0D, 200.0D, 0.5D);
noise3 = noiseGen3.generateNoiseOctaves(noise3, par2, par3, par4, par5, par6, par7, d0 / 80.0D, d1 / 160.0D, d0 / 80.0D);
noise1 = noiseGen1.generateNoiseOctaves(noise1, par2, par3, par4, par5, par6, par7, d0, d1, d0);
noise2 = noiseGen2.generateNoiseOctaves(noise2, par2, par3, par4, par5, par6, par7, d0, d1, d0);
boolean flag = false;
boolean flag1 = false;
int i2 = 0;
int j2 = 0;
for (int k2 = 0; k2 < par5; ++k2)
{
for (int l2 = 0; l2 < par7; ++l2)
{
float f1 = 0.0F;
float f2 = 0.0F;
float f3 = 0.0F;
byte b0 = 2;
BiomeGenBase biomegenbase = biomesForGeneration[k2 + 2 + (l2 + 2) * (par5 + 5)];
for (int i3 = -b0; i3 <= b0; ++i3)
{
for (int j3 = -b0; j3 <= b0; ++j3)
{
BiomeGenBase biomegenbase1 = biomesForGeneration[k2 + i3 + 2 + (l2 + j3 + 2) * (par5 + 5)];
float f4 = parabolicField[i3 + 2 + (j3 + 2) * 5] / (biomegenbase1.minHeight + 2.0F);
if (biomegenbase1.minHeight > biomegenbase.minHeight)
{
f4 /= 2.0F;
}
f1 += biomegenbase1.maxHeight * f4;
f2 += (biomegenbase1.minHeight - 2.0) * f4;
f3 += f4;
}
}
f1 /= f3;
f2 /= f3;
f1 = f1 * 0.9F + 0.1F;
f2 = (f2 * 4.0F - 1.0F) / 8.0F;
double d2 = noise6[j2] / 8000.0D;
if (d2 < 0.0D)
{
d2 = -d2 * 0.3D;
}
d2 = d2 * 3.0D - 2.0D;
if (d2 < 0.0D)
{
d2 /= 2.0D;
if (d2 < -1.0D)
{
d2 = -1.0D;
}
d2 /= 1.4D;
d2 /= 2.0D;
}
else
{
if (d2 > 1.0D)
{
d2 = 1.0D;
}
d2 /= 8.0D;
}
++j2;
for (int k3 = 0; k3 < par6; ++k3)
{
double d3 = f2;
double d4 = f1;
d3 += d2 * 0.2D;
d3 = d3 * par6 / 16.0D;
double d5 = par6 / 2.0D + d3 * 4.0D;
double d6 = 0.0D;
double d7 = (k3 - d5) * 12.0D * 128.0D / 128.0D / d4;
if (d7 < 0.0D)
{
d7 *= 4.0D;
}
double d8 = noise1[i2] / 512.0D;
double d9 = noise2[i2] / 512.0D;
double d10 = (noise3[i2] / 10.0D + 1.0D) / 2.0D;
if (d10 < 0.0D)
{
d6 = d8;
}
else if (d10 > 1.0D)
{
d6 = d9;
}
else
{
d6 = d8 + (d9 - d8) * d10;
}
d6 -= d7;
if (k3 > par6 - 4)
{
double d11 = (k3 - (par6 - 4)) / 3.0F;
d6 = d6 * (1.0D - d11) + -10.0D * d11;
}
par1ArrayOfDouble[i2] = d6;
++i2;
}
}
}
return par1ArrayOfDouble;
}
|
diff --git a/src/com/sdc/util/DeclarationWorker.java b/src/com/sdc/util/DeclarationWorker.java
index d643724..0362a98 100644
--- a/src/com/sdc/util/DeclarationWorker.java
+++ b/src/com/sdc/util/DeclarationWorker.java
@@ -1,527 +1,528 @@
package com.sdc.util;
import com.sdc.abstractLanguage.AbstractMethod;
import org.objectweb.asm.Opcodes;
import java.util.*;
public class DeclarationWorker {
public enum SupportedLanguage {
JAVA, JAVASCRIPT, KOTLIN
}
public static String getAccess(final int access, final SupportedLanguage language)
{
switch (language) {
case JAVA:
case JAVASCRIPT:
return getJavaAccess(access);
case KOTLIN:
return getKotlinAccess(access);
}
return "";
}
public static String getJavaAccess(final int access) {
StringBuilder sb = new StringBuilder("");
if ((access & Opcodes.ACC_PUBLIC) != 0) {
sb.append("public ");
}
if ((access & Opcodes.ACC_PRIVATE) != 0) {
sb.append("private ");
}
if ((access & Opcodes.ACC_PROTECTED) != 0) {
sb.append("protected ");
}
if ((access & Opcodes.ACC_FINAL) != 0) {
sb.append("final ");
}
if ((access & Opcodes.ACC_STATIC) != 0) {
sb.append("static ");
}
if ((access & Opcodes.ACC_SYNCHRONIZED) != 0) {
sb.append("synchronized ");
}
if ((access & Opcodes.ACC_VOLATILE) != 0) {
sb.append("volatile ");
}
if ((access & Opcodes.ACC_TRANSIENT) != 0) {
sb.append("transient ");
}
if ((access & Opcodes.ACC_ABSTRACT) != 0) {
sb.append("abstract ");
}
if ((access & Opcodes.ACC_STRICT) != 0) {
sb.append("strictfp ");
}
if ((access & Opcodes.ACC_SYNTHETIC) != 0) {
sb.append("synthetic ");
}
if ((access & Opcodes.ACC_ENUM) != 0) {
sb.append("enum ");
}
if ((access & Opcodes.ACC_BRIDGE) != 0) {
sb.append("bridge ");
}
return sb.toString();
}
public static String getKotlinAccess(final int access) {
StringBuilder sb = new StringBuilder("");
if ((access & Opcodes.ACC_PUBLIC) != 0) {
sb.append("public ");
}
if ((access & Opcodes.ACC_PRIVATE) != 0) {
sb.append("private ");
}
if ((access & Opcodes.ACC_PROTECTED) != 0) {
sb.append("protected ");
}
if ((access & Opcodes.ACC_FINAL) == 0) {
sb.append("open ");
}
if ((access & Opcodes.ACC_ABSTRACT) != 0) {
sb.append("abstract ");
}
if ((access & Opcodes.ACC_BRIDGE) != 0) {
sb.append("bridge ");
}
return sb.toString();
}
public static String getDescriptor(final String descriptor, final int pos, List<String> imports
, final SupportedLanguage language)
{
String result = "";
switch (language) {
case JAVA:
case JAVASCRIPT:
result = getJavaDescriptor(descriptor, pos, imports);
break;
case KOTLIN:
result = getKotlinDescriptor(descriptor, pos, imports);
break;
}
result = replaceInnerClassName(result).trim();
switch (language) {
case JAVA:
case JAVASCRIPT:
result = result + " ";
}
return result;
}
public static String getJavaDescriptor(final String descriptor, final int pos, List<String> imports) {
switch (descriptor.charAt(pos)) {
case 'V':
return "void";
case 'B':
return "byte";
case 'J':
return "long";
case 'Z':
return "boolean";
case 'I':
return "int";
case 'S':
return "short";
case 'C':
return "char";
case 'F':
return "float";
case 'D':
return "double";
case 'L':
if (descriptor.indexOf("<", pos) == -1 || descriptor.indexOf("<", pos) > descriptor.indexOf(";", pos)) {
return getSimpleClassName(descriptor, pos, imports);
} else {
return getClassNameWithGenerics(descriptor, pos, imports, SupportedLanguage.JAVA);
}
case 'T':
return descriptor.substring(pos + 1, descriptor.indexOf(";", pos));
case '+':
return "? extends " + getJavaDescriptor(descriptor, pos + 1, imports);
case '-':
return "? super " + getJavaDescriptor(descriptor, pos + 1, imports);
case '*':
return "?";
case '[':
return getJavaDescriptor(descriptor, pos + 1, imports).trim() + "[]";
default:
return "Object";
}
}
public static String getKotlinDescriptor(final String descriptor, final int pos, List<String> imports) {
switch (descriptor.charAt(pos)) {
case 'V':
return "";
case 'B':
return "Byte";
case 'J':
return "Long";
case 'Z':
return "Boolean";
case 'I':
return "Int";
case 'S':
return "Short";
case 'C':
return "Char";
case 'F':
return "Float";
case 'D':
return "Double";
case 'L':
if (descriptor.indexOf("<", pos) == -1 || descriptor.indexOf("<", pos) > descriptor.indexOf(";", pos)) {
final String actualClassName = getSimpleClassName(descriptor, pos, imports);
if (isPrimitiveClass(actualClassName)) {
return convertJavaPrimitiveClassToKotlin(actualClassName) + "?";
} else {
return actualClassName;
}
} else {
return convertJetFunctionRawType(getClassNameWithGenerics(descriptor, pos, imports, SupportedLanguage.KOTLIN));
}
case 'T':
return descriptor.substring(pos + 1, descriptor.indexOf(";", pos));
case '+':
return "out " + getKotlinDescriptor(descriptor, pos + 1, imports);
case '-':
return "in " + getKotlinDescriptor(descriptor, pos + 1, imports);
case '*':
return "? ";
case '@':
return getKotlinDescriptor(descriptor, pos + 1, imports);
case '[':
return "Array<" + getKotlinDescriptor(descriptor, pos + 1, imports) + ">";
default:
return "Any";
}
}
public static String getDescriptorByInt(final int desc, final SupportedLanguage language) {
switch (language) {
case JAVA:
case JAVASCRIPT:
return getJavaDescriptorByInt(desc);
case KOTLIN:
return getKotlinDescriptorByInt(desc);
default:
return "";
}
}
public static String getJavaDescriptorByInt(final int desc) {
switch (desc) {
case 1:
return "int ";
case 2:
return "float ";
case 3:
return "double ";
case 4:
return "long ";
default:
return "";
}
}
public static String getKotlinDescriptorByInt(final int i) {
switch (i) {
case 1:
return "Int ";
case 2:
return "Float ";
case 3:
return "Double ";
case 4:
return "Long ";
default:
return "";
}
}
public static int getParametersCount(final String descriptor) {
int result = 0;
int pos = 1;
while (pos < descriptor.indexOf(")")) {
pos = getNextTypePosition(descriptor, pos);
result++;
}
return result;
}
public static void addInformationAboutParameters(final String descriptor, final AbstractMethod abstractMethod
, final int startIndex, final SupportedLanguage language)
{
int count = startIndex - 1;
int pos = 0;
while (pos < descriptor.length()) {
final int backupPos = pos;
final int backupCount = count;
final String type = getDescriptor(descriptor, backupPos, abstractMethod.getImports(), language);
boolean isPrimitiveClass = false;
switch (descriptor.charAt(pos)) {
case 'B':
case 'Z':
case 'I':
case 'S':
case 'C':
case 'F':
case 'T':
case '[':
case '+':
case '-':
case '*':
count++;
break;
case 'J':
case 'D':
count += 2;
break;
case 'L':
count++;
isPrimitiveClass = isPrimitiveClass(type);
break;
}
pos = getNextTypePosition(descriptor, pos);
final int index = (count - backupCount) == 1 ? count : count - 1;
abstractMethod.addLocalVariableName(index, "x" + index);
if (language == SupportedLanguage.KOTLIN) {
abstractMethod.addLocalVariableType(index, isPrimitiveClass ? convertJavaPrimitiveClassToKotlin(type) + "?" : type);
} else {
abstractMethod.addLocalVariableType(index, type);
}
}
abstractMethod.setLastLocalVariableIndex(count);
}
public static String getClassName(final String fullClassName) {
final String[] classPackageParts = fullClassName.contains("/") ? fullClassName.split("/") : new String[] { fullClassName };
final String actualClassName = classPackageParts[classPackageParts.length - 1];
final String[] classParts = actualClassName.contains("$") ? actualClassName.split("\\$") : new String[] { actualClassName };
return replaceInnerClassName(classParts[classParts.length - 1]);
}
public static String replaceInnerClassName(final String className) {
final String result = convertInnerClassesToAcceptableName(className.trim());
return className.contains(" ") ? result + " " : result;
}
public static String getDecompiledFullClassName(final String fullClassName) {
return fullClassName.replace("/", ".");
}
public static void parseGenericDeclaration(final String signature, List<String> genericTypesList,
List<String> genericIdentifiersList, List<String> genericTypesImports, final SupportedLanguage language)
{
if (signature != null && signature.indexOf('<') == 0) {
int endPos = 1;
int startPos = 1;
boolean isGenericName = true;
while (signature.charAt(endPos) != '>') {
switch (signature.charAt(endPos)) {
case ':':
if (startPos != endPos) {
genericIdentifiersList.add(signature.substring(startPos, endPos));
}
endPos++;
startPos = endPos;
isGenericName = false;
break;
default:
if (!isGenericName) {
genericTypesList.add(getDescriptor(signature, endPos, genericTypesImports, language));
endPos = getNextTypePosition(signature, endPos);
startPos = endPos;
isGenericName = true;
} else {
endPos++;
}
}
}
return;
}
}
public static boolean isPrimitiveClass(final String type) {
Set<String> primitiveTypes = new HashSet<String>(Arrays.asList("Byte", "Long", "Boolean", "Integer", "Int", "Short", "Character", "Float", "Double", "Object"));
return primitiveTypes.contains(type);
}
public static String convertInnerClassesToAcceptableName(final String initialClassName) {
final String[] classParts = initialClassName.contains(".") ? initialClassName.split("\\.") : new String[] { initialClassName };
StringBuilder result = new StringBuilder("");
for (final String classPart : classParts) {
int pos = 0;
while (pos < classPart.length() && Character.isDigit(classPart.charAt(pos))) {
pos++;
}
if (pos > 0) {
final String anonymousClassIdentifier = pos == classPart.length() ? "AnonymousClass" : "";
result = result.append(".").append(classPart.substring(pos)).append(anonymousClassIdentifier).append("__").append(classPart.substring(0, pos));
} else {
result = result.append(".").append(classPart);
}
}
return result.deleteCharAt(0).toString();
}
private static String convertJavaPrimitiveClassToKotlin(final String javaClass) {
if (javaClass.equals("Integer")) {
return "Int";
} else if (javaClass.equals("Character")) {
return "Char";
} else if (javaClass.equals("Object")) {
return "Any";
}
return javaClass;
}
private static int getNextTypePosition(final String descriptor, final int startPos) {
switch (descriptor.charAt(startPos)) {
case 'B':
case 'J':
case 'Z':
case 'I':
case 'S':
case 'C':
case 'F':
case 'D':
return startPos + 1;
case 'L':
final int semicolonIndex = descriptor.indexOf(";", startPos);
final int bracketIndex = descriptor.indexOf("<", startPos);
if (bracketIndex == -1 || bracketIndex > semicolonIndex) {
return semicolonIndex + 1;
} else {
return skipGenericTypePart(descriptor, semicolonIndex) + 1;
}
case 'T':
return descriptor.indexOf(";", startPos) + 1;
case '[':
case '+':
case '-':
case '*':
default:
return getNextTypePosition(descriptor, startPos + 1);
}
}
private static int skipGenericTypePart(final String descriptor, final int startPos) {
Stack stack = new Stack();
stack.push(0);
int pos = startPos + 1;
while (!stack.isEmpty()) {
switch (descriptor.charAt(pos)) {
case '<':
stack.push(0);
break;
case '>':
stack.pop();
break;
}
pos++;
}
return pos;
}
private static String convertJetFunctionRawType(final String type) {
final int prefixLength = "Function".length();
if (type.startsWith("Function") && Character.isDigit(type.charAt(prefixLength))) {
final int parametersCount = Integer.valueOf(type.substring(prefixLength, type.indexOf("<")));
StringBuilder result = new StringBuilder("(");
int beginPartPos = type.indexOf("<") + 1;
int endPartPos = beginPartPos;
List<String> parts = new ArrayList<String>();
Stack stack = new Stack();
while (endPartPos < type.length()) {
switch (type.charAt(endPartPos)) {
case '<':
case '(':
stack.push(0);
break;
case ')':
stack.pop();
break;
case '>':
if (type.charAt(endPartPos - 1) == '-') {
break;
} else if (endPartPos != type.length() - 1) {
stack.pop();
endPartPos++;
continue;
}
case ',':
if (stack.isEmpty()) {
parts.add(type.substring(beginPartPos, endPartPos));
endPartPos += 2;
beginPartPos = endPartPos;
continue;
}
break;
}
endPartPos++;
}
if (parametersCount >= 1) {
for (int i = 0; i < parametersCount - 1; i++) {
result = result.append(parts.get(i)).append(", ");
}
result = result.append(parts.get(parametersCount - 1));
}
result = result.append(") -> ").append(parts.get(parametersCount));
+// return result.toString().replaceAll("([\\( ])(in|out) ", "$1");
return result.toString();
} else {
return type;
}
}
private static String getSimpleClassName(final String descriptor, final int pos, List<String> imports) {
final String className = descriptor.substring(pos + 1, descriptor.indexOf(";", pos));
imports.add(getDecompiledFullClassName(className));
return getClassName(className);
}
private static String getClassNameWithGenerics(final String descriptor, final int pos, List<String> imports, final SupportedLanguage language) {
final String className = descriptor.substring(pos + 1, descriptor.indexOf("<", pos));
imports.add(getDecompiledFullClassName(className));
StringBuilder result = new StringBuilder(getClassName(className));
result = result.append("<");
final int lastClassNamePos = skipGenericTypePart(descriptor, descriptor.indexOf("<", pos));
int curPos = pos + className.length() + 2;
while (curPos < lastClassNamePos - 1) {
final String genericType = getDescriptor(descriptor, curPos, imports, language).trim();
result = result.append(genericType);
curPos = getNextTypePosition(descriptor, curPos);
if (curPos < lastClassNamePos - 1) {
result = result.append(", ");
}
}
result = result.append(">");
return result.toString();
}
}
| true | true | private static String convertJetFunctionRawType(final String type) {
final int prefixLength = "Function".length();
if (type.startsWith("Function") && Character.isDigit(type.charAt(prefixLength))) {
final int parametersCount = Integer.valueOf(type.substring(prefixLength, type.indexOf("<")));
StringBuilder result = new StringBuilder("(");
int beginPartPos = type.indexOf("<") + 1;
int endPartPos = beginPartPos;
List<String> parts = new ArrayList<String>();
Stack stack = new Stack();
while (endPartPos < type.length()) {
switch (type.charAt(endPartPos)) {
case '<':
case '(':
stack.push(0);
break;
case ')':
stack.pop();
break;
case '>':
if (type.charAt(endPartPos - 1) == '-') {
break;
} else if (endPartPos != type.length() - 1) {
stack.pop();
endPartPos++;
continue;
}
case ',':
if (stack.isEmpty()) {
parts.add(type.substring(beginPartPos, endPartPos));
endPartPos += 2;
beginPartPos = endPartPos;
continue;
}
break;
}
endPartPos++;
}
if (parametersCount >= 1) {
for (int i = 0; i < parametersCount - 1; i++) {
result = result.append(parts.get(i)).append(", ");
}
result = result.append(parts.get(parametersCount - 1));
}
result = result.append(") -> ").append(parts.get(parametersCount));
return result.toString();
} else {
return type;
}
}
| private static String convertJetFunctionRawType(final String type) {
final int prefixLength = "Function".length();
if (type.startsWith("Function") && Character.isDigit(type.charAt(prefixLength))) {
final int parametersCount = Integer.valueOf(type.substring(prefixLength, type.indexOf("<")));
StringBuilder result = new StringBuilder("(");
int beginPartPos = type.indexOf("<") + 1;
int endPartPos = beginPartPos;
List<String> parts = new ArrayList<String>();
Stack stack = new Stack();
while (endPartPos < type.length()) {
switch (type.charAt(endPartPos)) {
case '<':
case '(':
stack.push(0);
break;
case ')':
stack.pop();
break;
case '>':
if (type.charAt(endPartPos - 1) == '-') {
break;
} else if (endPartPos != type.length() - 1) {
stack.pop();
endPartPos++;
continue;
}
case ',':
if (stack.isEmpty()) {
parts.add(type.substring(beginPartPos, endPartPos));
endPartPos += 2;
beginPartPos = endPartPos;
continue;
}
break;
}
endPartPos++;
}
if (parametersCount >= 1) {
for (int i = 0; i < parametersCount - 1; i++) {
result = result.append(parts.get(i)).append(", ");
}
result = result.append(parts.get(parametersCount - 1));
}
result = result.append(") -> ").append(parts.get(parametersCount));
// return result.toString().replaceAll("([\\( ])(in|out) ", "$1");
return result.toString();
} else {
return type;
}
}
|
diff --git a/src/main/java/org/spoutcraft/launcher/Logging/SystemConsoleListener.java b/src/main/java/org/spoutcraft/launcher/Logging/SystemConsoleListener.java
index 081738f..14e15e7 100644
--- a/src/main/java/org/spoutcraft/launcher/Logging/SystemConsoleListener.java
+++ b/src/main/java/org/spoutcraft/launcher/Logging/SystemConsoleListener.java
@@ -1,62 +1,63 @@
/*
* This file is part of Spoutcraft Launcher (http://wiki.getspout.org/).
*
* Spoutcraft Launcher is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Spoutcraft Launcher is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.spoutcraft.launcher.Logging;
import java.io.File;
import java.io.PrintStream;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;
import org.spoutcraft.launcher.PlatformUtils;
public class SystemConsoleListener {
public void initialize() throws Exception {
LogManager logManager = LogManager.getLogManager();
logManager.reset();
- new File(PlatformUtils.getWorkingDirectory() + "Logs").mkdirs();
+ File logDir = new File(PlatformUtils.getWorkingDirectory() + File.separator + "Logs");
+ logDir.mkdirs();
- Handler fileHandler = new FileHandler(PlatformUtils.getWorkingDirectory() + "Logs" + File.separator + "log", 10000, 5, true);
+ Handler fileHandler = new FileHandler(new File(logDir, "spoutcraft_%g.log").getPath(), 100000, 5, true);
fileHandler.setFormatter(new ClientLoggerFormatter());
Logger.getLogger("").addHandler(fileHandler);
PrintStream stdout = System.out;
/*PrintStream stderr = System.err;*/
Handler ConsoleHandle = new StreamHandler(stdout, new ClientLoggerFormatter());
Logger.getLogger("").addHandler(ConsoleHandle);
/*Handler ErrHandle = new StreamHandler(stderr, new ClientLoggerFormatter());
Logger.getLogger("").addHandler(ErrHandle); */
Logger logger;
SystemListenerStream los;
logger = Logger.getLogger("stdout");
los = new SystemListenerStream(logger, SystemListenerLevel.STDOUT);
System.setOut(new PrintStream(los, true));
/*logger = Logger.getLogger("stderr");
los= new SystemListenerStream(logger, SystemListenerLevel.STDERR);
System.setErr(new PrintStream(los, true));*/
}
}
| false | true | public void initialize() throws Exception {
LogManager logManager = LogManager.getLogManager();
logManager.reset();
new File(PlatformUtils.getWorkingDirectory() + "Logs").mkdirs();
Handler fileHandler = new FileHandler(PlatformUtils.getWorkingDirectory() + "Logs" + File.separator + "log", 10000, 5, true);
fileHandler.setFormatter(new ClientLoggerFormatter());
Logger.getLogger("").addHandler(fileHandler);
PrintStream stdout = System.out;
/*PrintStream stderr = System.err;*/
Handler ConsoleHandle = new StreamHandler(stdout, new ClientLoggerFormatter());
Logger.getLogger("").addHandler(ConsoleHandle);
/*Handler ErrHandle = new StreamHandler(stderr, new ClientLoggerFormatter());
Logger.getLogger("").addHandler(ErrHandle); */
Logger logger;
SystemListenerStream los;
logger = Logger.getLogger("stdout");
los = new SystemListenerStream(logger, SystemListenerLevel.STDOUT);
System.setOut(new PrintStream(los, true));
/*logger = Logger.getLogger("stderr");
los= new SystemListenerStream(logger, SystemListenerLevel.STDERR);
System.setErr(new PrintStream(los, true));*/
}
| public void initialize() throws Exception {
LogManager logManager = LogManager.getLogManager();
logManager.reset();
File logDir = new File(PlatformUtils.getWorkingDirectory() + File.separator + "Logs");
logDir.mkdirs();
Handler fileHandler = new FileHandler(new File(logDir, "spoutcraft_%g.log").getPath(), 100000, 5, true);
fileHandler.setFormatter(new ClientLoggerFormatter());
Logger.getLogger("").addHandler(fileHandler);
PrintStream stdout = System.out;
/*PrintStream stderr = System.err;*/
Handler ConsoleHandle = new StreamHandler(stdout, new ClientLoggerFormatter());
Logger.getLogger("").addHandler(ConsoleHandle);
/*Handler ErrHandle = new StreamHandler(stderr, new ClientLoggerFormatter());
Logger.getLogger("").addHandler(ErrHandle); */
Logger logger;
SystemListenerStream los;
logger = Logger.getLogger("stdout");
los = new SystemListenerStream(logger, SystemListenerLevel.STDOUT);
System.setOut(new PrintStream(los, true));
/*logger = Logger.getLogger("stderr");
los= new SystemListenerStream(logger, SystemListenerLevel.STDERR);
System.setErr(new PrintStream(los, true));*/
}
|
diff --git a/src/org/waveprotocol/wave/client/scroll/ScrollBuilder.java b/src/org/waveprotocol/wave/client/scroll/ScrollBuilder.java
index b99607ea..e18353d1 100644
--- a/src/org/waveprotocol/wave/client/scroll/ScrollBuilder.java
+++ b/src/org/waveprotocol/wave/client/scroll/ScrollBuilder.java
@@ -1,40 +1,40 @@
/**
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.waveprotocol.wave.client.scroll;
import org.waveprotocol.wave.client.wavepanel.impl.WavePanelImpl;
import org.waveprotocol.wave.client.wavepanel.view.View;
/**
* Installs the scrolling feature.
*
* @author [email protected] (David Hearnden)
*/
public final class ScrollBuilder {
private ScrollBuilder() {
}
/**
* Installs the scrolling feature.
*/
- public static SmartScroller<? super View> install(WavePanelImpl panel) {
+ public static SmartScroller<View> install(WavePanelImpl panel) {
ProxyScrollPanel scroller = ProxyScrollPanel.create(panel);
ScrollHandler.install(panel, scroller);
return SmartScroller.create(scroller);
}
}
| true | true | public static SmartScroller<? super View> install(WavePanelImpl panel) {
ProxyScrollPanel scroller = ProxyScrollPanel.create(panel);
ScrollHandler.install(panel, scroller);
return SmartScroller.create(scroller);
}
| public static SmartScroller<View> install(WavePanelImpl panel) {
ProxyScrollPanel scroller = ProxyScrollPanel.create(panel);
ScrollHandler.install(panel, scroller);
return SmartScroller.create(scroller);
}
|
diff --git a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java
index 6848b6b5..64499434 100644
--- a/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java
+++ b/ngrinder-controller/src/main/java/org/ngrinder/agent/controller/AgentManagerController.java
@@ -1,293 +1,293 @@
/*
* 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.ngrinder.agent.controller;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import org.apache.commons.lang.StringUtils;
import org.ngrinder.agent.service.AgentManagerService;
import org.ngrinder.agent.service.AgentPackageService;
import org.ngrinder.common.controller.BaseController;
import org.ngrinder.common.controller.RestAPI;
import org.ngrinder.common.util.HttpContainerContext;
import org.ngrinder.model.AgentInfo;
import org.ngrinder.region.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.File;
import java.util.List;
import java.util.Map;
import static org.ngrinder.common.util.CollectionUtils.newArrayList;
import static org.ngrinder.common.util.CollectionUtils.newHashMap;
/**
* Agent management controller.
*
* @author JunHo Yoon
* @since 3.1
*/
@Controller
@RequestMapping("/agent")
@PreAuthorize("hasAnyRole('A', 'S')")
public class AgentManagerController extends BaseController {
@Autowired
private AgentManagerService agentManagerService;
@Autowired
private HttpContainerContext httpContainerContext;
@Autowired
private RegionService regionService;
@Autowired
private AgentPackageService agentPackageService;
/**
* Get the agents.
*
* @param region the region to search. If null, it returns all the attached
* agents.
* @param request servlet request
* @param model model
* @return agent/list
*/
@RequestMapping({"", "/", "/list"})
public String getAll(@RequestParam(value = "region", required = false) final String region, ModelMap model) {
List<AgentInfo> agents = agentManagerService.getAllVisibleAgentInfoFromDB();
model.addAttribute("agents", Collections2.filter(agents, new Predicate<AgentInfo>() {
@Override
public boolean apply(AgentInfo agentInfo) {
if (StringUtils.equals(region, "all") || StringUtils.isEmpty(region)) {
return true;
}
final String eachAgentRegion = agentInfo.getRegion();
return eachAgentRegion.startsWith(region + "_owned") || region.equals(eachAgentRegion);
}
}));
model.addAttribute("region", region);
model.addAttribute("regions", regionService.getAll().keySet());
final String contextPath = httpContainerContext.getCurrentContextUrlFromUserRequest();
File agentPackage = null;
if (isClustered()) {
if (StringUtils.isNotBlank(region)) {
final String ip = regionService.getOne(region).getIp();
agentPackage = agentPackageService.createAgentPackage(ip, region, null);
}
} else {
agentPackage = agentPackageService.createAgentPackage("", "", null);
}
if (agentPackage != null) {
- model.addAttribute("downloadLink", contextPath + "/agent/download/" + agentPackage.getName());
+ model.addAttribute("downloadLink", "/agent/download/" + agentPackage.getName());
}
return "agent/list";
}
/**
* Approve or disapprove an agent, so that it can be assigned.
*
* @param id agent id to be processed
* @param approve approve or not
* @param region current region
* @param model model
* @return agent/agentList
*/
@RequestMapping(value = "/{id}/approve", method = RequestMethod.POST)
public String approve(@PathVariable("id") Long id,
@RequestParam(value = "approve", defaultValue = "true", required = false) boolean approve,
@RequestParam(value = "region", required = false) final String region, ModelMap model) {
agentManagerService.approve(id, approve);
model.addAttribute("region", region);
model.addAttribute("regions", regionService.getAll().keySet());
return "agent/list";
}
/**
* Get the agent detail info for the given agent id.
*
* @param id agent id
* @param model model
* @return agent/agentDetail
*/
@RequestMapping("/{id}")
public String getOne(@PathVariable Long id, ModelMap model) {
model.addAttribute("agent", agentManagerService.getOne(id));
return "agent/detail";
}
/**
* Get the current performance of the given agent.
*
* @param id agent id
* @param ip agent ip
* @param name agent name
* @return json message
*/
@PreAuthorize("hasAnyRole('A')")
@RequestMapping("/api/{id}/state")
public HttpEntity<String> getState(@PathVariable Long id, @RequestParam String ip, @RequestParam String name) {
agentManagerService.requestShareAgentSystemDataModel(id);
return toJsonHttpEntity(agentManagerService.getAgentSystemDataModel(ip, name));
}
/**
* Get the current all agents state.
*
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = {"/api/states/", "/api/states"}, method = RequestMethod.GET)
public HttpEntity<String> getStates() {
List<AgentInfo> agents = agentManagerService.getAllVisibleAgentInfoFromDB();
return toJsonHttpEntity(getAgentStatus(agents));
}
/**
* Get all agents from database.
*
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = {"/api/", "/api"}, method = RequestMethod.GET)
public HttpEntity<String> getAll() {
return toJsonHttpEntity(agentManagerService.getAllVisibleAgentInfoFromDB());
}
/**
* Get the agent for the given agent id.
*
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", method = RequestMethod.GET)
public HttpEntity<String> getOne(@PathVariable("id") Long id) {
return toJsonHttpEntity(agentManagerService.getOne(id));
}
/**
* Approve an agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=approve", method = RequestMethod.PUT)
public HttpEntity<String> approve(@PathVariable("id") Long id) {
agentManagerService.approve(id, true);
return successJsonHttpEntity();
}
/**
* Disapprove an agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=disapprove", method = RequestMethod.PUT)
public HttpEntity<String> disapprove(@PathVariable("id") Long id) {
agentManagerService.approve(id, false);
return successJsonHttpEntity();
}
/**
* Stop the given agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=stop", method = RequestMethod.PUT)
public HttpEntity<String> stop(@PathVariable("id") Long id) {
agentManagerService.stopAgent(id);
return successJsonHttpEntity();
}
/**
* Stop the given agent.
*
* @param ids comma separated agent id list
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api", params = "action=stop", method = RequestMethod.PUT)
public HttpEntity<String> stop(@RequestParam("ids") String ids) {
String[] split = StringUtils.split(ids, ",");
for (String each : split) {
stop(Long.parseLong(each));
}
return successJsonHttpEntity();
}
/**
* Update the given agent.
*
* @param id agent id
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api/{id}", params = "action=update", method = RequestMethod.PUT)
public HttpEntity<String> update(@PathVariable("id") Long id) {
agentManagerService.update(id);
return successJsonHttpEntity();
}
/**
* Send update message to agent side
*
* @param ids comma separated agent id list
* @return json message
*/
@RestAPI
@PreAuthorize("hasAnyRole('A')")
@RequestMapping(value = "/api", params = "action=update", method = RequestMethod.PUT)
public HttpEntity<String> update(@RequestParam("ids") String ids) {
String[] split = StringUtils.split(ids, ",");
for (String each : split) {
update(Long.parseLong(each));
}
return successJsonHttpEntity();
}
private List<Map<String, Object>> getAgentStatus(List<AgentInfo> agents) {
List<Map<String, Object>> statuses = newArrayList(agents.size());
for (AgentInfo each : agents) {
Map<String, Object> result = newHashMap();
result.put("id", each.getId());
result.put("port", each.getPort());
result.put("icon", each.getState().getCategory().getIconName());
result.put("state", each.getState());
statuses.add(result);
}
return statuses;
}
}
| true | true | public String getAll(@RequestParam(value = "region", required = false) final String region, ModelMap model) {
List<AgentInfo> agents = agentManagerService.getAllVisibleAgentInfoFromDB();
model.addAttribute("agents", Collections2.filter(agents, new Predicate<AgentInfo>() {
@Override
public boolean apply(AgentInfo agentInfo) {
if (StringUtils.equals(region, "all") || StringUtils.isEmpty(region)) {
return true;
}
final String eachAgentRegion = agentInfo.getRegion();
return eachAgentRegion.startsWith(region + "_owned") || region.equals(eachAgentRegion);
}
}));
model.addAttribute("region", region);
model.addAttribute("regions", regionService.getAll().keySet());
final String contextPath = httpContainerContext.getCurrentContextUrlFromUserRequest();
File agentPackage = null;
if (isClustered()) {
if (StringUtils.isNotBlank(region)) {
final String ip = regionService.getOne(region).getIp();
agentPackage = agentPackageService.createAgentPackage(ip, region, null);
}
} else {
agentPackage = agentPackageService.createAgentPackage("", "", null);
}
if (agentPackage != null) {
model.addAttribute("downloadLink", contextPath + "/agent/download/" + agentPackage.getName());
}
return "agent/list";
}
| public String getAll(@RequestParam(value = "region", required = false) final String region, ModelMap model) {
List<AgentInfo> agents = agentManagerService.getAllVisibleAgentInfoFromDB();
model.addAttribute("agents", Collections2.filter(agents, new Predicate<AgentInfo>() {
@Override
public boolean apply(AgentInfo agentInfo) {
if (StringUtils.equals(region, "all") || StringUtils.isEmpty(region)) {
return true;
}
final String eachAgentRegion = agentInfo.getRegion();
return eachAgentRegion.startsWith(region + "_owned") || region.equals(eachAgentRegion);
}
}));
model.addAttribute("region", region);
model.addAttribute("regions", regionService.getAll().keySet());
final String contextPath = httpContainerContext.getCurrentContextUrlFromUserRequest();
File agentPackage = null;
if (isClustered()) {
if (StringUtils.isNotBlank(region)) {
final String ip = regionService.getOne(region).getIp();
agentPackage = agentPackageService.createAgentPackage(ip, region, null);
}
} else {
agentPackage = agentPackageService.createAgentPackage("", "", null);
}
if (agentPackage != null) {
model.addAttribute("downloadLink", "/agent/download/" + agentPackage.getName());
}
return "agent/list";
}
|
diff --git a/src/de/fhb/polyencoder/Util.java b/src/de/fhb/polyencoder/Util.java
index 82e850c..d1a147e 100644
--- a/src/de/fhb/polyencoder/Util.java
+++ b/src/de/fhb/polyencoder/Util.java
@@ -1,93 +1,94 @@
package de.fhb.polyencoder;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map.Entry;
/**
* Collection of useful functions.
*
* @author Mark Rambow (markrambow[at]gmail[dot]com)
* @author Peter Pensold
* @version 0.5
*
*/
public class Util {
/**
* Calculates the following phrase with a and b:<br/>
* {@code Math.sqrt(Math.pow(a,2) + Math.pow(b,2))}
*
* @param a
* @param b
* @return the result of this phrase
*/
public static double sqrtOfSquared(double a, double b) {
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
}
public static double createCenter(double min, double max) {
return min + (max - min)/2;
}
public static String readFile(String fileName) {
String loadingFailedOutput = "";
FileReader fr;
StringBuilder sb = new StringBuilder();
String line;
try {
fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
+ sb.deleteCharAt(sb.length()-1);
fr.close();
} catch (FileNotFoundException e) {
sb = new StringBuilder(loadingFailedOutput);
} catch (IOException e) {
sb = new StringBuilder(loadingFailedOutput);
}
return sb.toString();
}
/**
* Replaces all possible appearances of marker inside a text. The marker is a
* regular expression. The marker will be surrounded with braces. E. g. if you
* use the marker {@code name} the method searches for {{@code name} inside
* the text.
*
* @param text
* the string to search for marker
* @param marker
* the marker for the place where the new text from parameter replace
* should be
* @param replace
* text that replaces the marker
* @return the replaced content of the text
*/
public static String replaceMarker(String text, String marker, String replace) {
return text.replaceAll("\\{" + marker + "\\}",replace);
}
public static String replaceMarker(String text, HashMap<String, String> map) {
for (Entry<String, String> entry : map.entrySet()) {
text = replaceMarker(text, entry.getKey(), entry.getValue());
}
return text;
}
}
| true | true | public static String readFile(String fileName) {
String loadingFailedOutput = "";
FileReader fr;
StringBuilder sb = new StringBuilder();
String line;
try {
fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
fr.close();
} catch (FileNotFoundException e) {
sb = new StringBuilder(loadingFailedOutput);
} catch (IOException e) {
sb = new StringBuilder(loadingFailedOutput);
}
return sb.toString();
}
| public static String readFile(String fileName) {
String loadingFailedOutput = "";
FileReader fr;
StringBuilder sb = new StringBuilder();
String line;
try {
fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
sb.deleteCharAt(sb.length()-1);
fr.close();
} catch (FileNotFoundException e) {
sb = new StringBuilder(loadingFailedOutput);
} catch (IOException e) {
sb = new StringBuilder(loadingFailedOutput);
}
return sb.toString();
}
|
diff --git a/src/main/java/com/forgenz/mobmanager/bounty/config/BountyWorldConfig.java b/src/main/java/com/forgenz/mobmanager/bounty/config/BountyWorldConfig.java
index 8c9ee12..3a5210c 100644
--- a/src/main/java/com/forgenz/mobmanager/bounty/config/BountyWorldConfig.java
+++ b/src/main/java/com/forgenz/mobmanager/bounty/config/BountyWorldConfig.java
@@ -1,120 +1,120 @@
/*
* Copyright 2013 Michael McKnight. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
package com.forgenz.mobmanager.bounty.config;
import java.util.HashMap;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.LivingEntity;
import com.forgenz.mobmanager.MMComponent;
import com.forgenz.mobmanager.abilities.abilities.AbilitySet;
import com.forgenz.mobmanager.common.config.AbstractConfig;
import com.forgenz.mobmanager.common.util.ExtendedEntityType;
public class BountyWorldConfig extends AbstractConfig
{
public final boolean useWorldSettings;
public final boolean allowPetKills;
public final boolean showMobName, showAbilitySetName;
private final HashMap<ExtendedEntityType, BountyMobConfig> mobRewards = new HashMap<ExtendedEntityType, BountyMobConfig>();
public BountyWorldConfig(FileConfiguration cfg, String folder)
{
ConfigurationSection sect;
/* ################ UseWorldSettings ################ */
if (folder.length() != 0)
{
useWorldSettings = cfg.getBoolean("UseWorldSettings", false);
- set(cfg, "UseWorldsettings", useWorldSettings);
+ set(cfg, "UseWorldSettings", useWorldSettings);
}
else
{
useWorldSettings = true;
}
/* ################ AllowPetKills ################ */
allowPetKills = cfg.getBoolean("AllowPetKills", true);
set(cfg, "AllowPetKills", allowPetKills);
/* ################ ShowMobName ################ */
showMobName = cfg.getBoolean("ShowMobName", true);
set(cfg, "ShowMobName", showMobName);
/* ################ ShowAbilitySetName ################ */
showAbilitySetName = cfg.getBoolean("ShowAbilitySetName", true);
set(cfg, "ShowAbilitySetName", showAbilitySetName);
/* ################ Rewards ################ */
sect = getConfigurationSection(cfg, "Rewards");
for (ExtendedEntityType entitytype : ExtendedEntityType.values())
{
String path = entitytype.toString();
ConfigurationSection mobSect = sect.getConfigurationSection(path);
if (mobSect == null)
mobSect = sect.createSection(path);
BountyMobConfig mobCfg = new BountyMobConfig(mobSect);
if (mobCfg.getMinReward() != 0.0 || mobCfg.getDifference() != 0.0)
{
mobRewards.put(entitytype, mobCfg);
}
}
}
public double getReward(ExtendedEntityType entityType)
{
BountyMobConfig mobReward = mobRewards.get(entityType);
return mobReward != null ? mobReward.getReward() : 0.0;
}
public String getMobName(LivingEntity entity)
{
if (showMobName)
{
String name = entity.getCustomName();
if (name != null)
return name;
}
if (showAbilitySetName && MMComponent.getAbilities().isEnabled())
{
String name = AbilitySet.getMeta(entity);
if (name != null)
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
return null;
}
}
| true | true | public BountyWorldConfig(FileConfiguration cfg, String folder)
{
ConfigurationSection sect;
/* ################ UseWorldSettings ################ */
if (folder.length() != 0)
{
useWorldSettings = cfg.getBoolean("UseWorldSettings", false);
set(cfg, "UseWorldsettings", useWorldSettings);
}
else
{
useWorldSettings = true;
}
/* ################ AllowPetKills ################ */
allowPetKills = cfg.getBoolean("AllowPetKills", true);
set(cfg, "AllowPetKills", allowPetKills);
/* ################ ShowMobName ################ */
showMobName = cfg.getBoolean("ShowMobName", true);
set(cfg, "ShowMobName", showMobName);
/* ################ ShowAbilitySetName ################ */
showAbilitySetName = cfg.getBoolean("ShowAbilitySetName", true);
set(cfg, "ShowAbilitySetName", showAbilitySetName);
/* ################ Rewards ################ */
sect = getConfigurationSection(cfg, "Rewards");
for (ExtendedEntityType entitytype : ExtendedEntityType.values())
{
String path = entitytype.toString();
ConfigurationSection mobSect = sect.getConfigurationSection(path);
if (mobSect == null)
mobSect = sect.createSection(path);
BountyMobConfig mobCfg = new BountyMobConfig(mobSect);
if (mobCfg.getMinReward() != 0.0 || mobCfg.getDifference() != 0.0)
{
mobRewards.put(entitytype, mobCfg);
}
}
}
| public BountyWorldConfig(FileConfiguration cfg, String folder)
{
ConfigurationSection sect;
/* ################ UseWorldSettings ################ */
if (folder.length() != 0)
{
useWorldSettings = cfg.getBoolean("UseWorldSettings", false);
set(cfg, "UseWorldSettings", useWorldSettings);
}
else
{
useWorldSettings = true;
}
/* ################ AllowPetKills ################ */
allowPetKills = cfg.getBoolean("AllowPetKills", true);
set(cfg, "AllowPetKills", allowPetKills);
/* ################ ShowMobName ################ */
showMobName = cfg.getBoolean("ShowMobName", true);
set(cfg, "ShowMobName", showMobName);
/* ################ ShowAbilitySetName ################ */
showAbilitySetName = cfg.getBoolean("ShowAbilitySetName", true);
set(cfg, "ShowAbilitySetName", showAbilitySetName);
/* ################ Rewards ################ */
sect = getConfigurationSection(cfg, "Rewards");
for (ExtendedEntityType entitytype : ExtendedEntityType.values())
{
String path = entitytype.toString();
ConfigurationSection mobSect = sect.getConfigurationSection(path);
if (mobSect == null)
mobSect = sect.createSection(path);
BountyMobConfig mobCfg = new BountyMobConfig(mobSect);
if (mobCfg.getMinReward() != 0.0 || mobCfg.getDifference() != 0.0)
{
mobRewards.put(entitytype, mobCfg);
}
}
}
|
diff --git a/MonacaFramework/src/mobi/monaca/framework/GCMIntentService.java b/MonacaFramework/src/mobi/monaca/framework/GCMIntentService.java
index fbbfa9e..1c938b1 100644
--- a/MonacaFramework/src/mobi/monaca/framework/GCMIntentService.java
+++ b/MonacaFramework/src/mobi/monaca/framework/GCMIntentService.java
@@ -1,60 +1,61 @@
package mobi.monaca.framework;
import mobi.monaca.framework.psedo.R;
import mobi.monaca.framework.util.MyLog;
import mobi.monaca.utils.gcm.GCMPushDataset;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = GCMIntentService.class.getSimpleName();
@Override
protected void onError(Context arg0, String arg1) {
MyLog.d(TAG, "onError :" + arg1);
}
@Override
protected void onMessage(Context arg0, Intent arg1) {
MyLog.d(TAG, "onMessage");
Bundle b = arg1.getExtras();
if (b == null) {
return;
}
String message = b.getString("message");
String pushProjectId = b.getString("push_project_id");
String extraJsonString = b.getString("extra_json");
GCMPushDataset data = new GCMPushDataset(pushProjectId, message, extraJsonString);
String title = b.getString("title") != null ? b.getString("title") : getString(R.string.app_name) + " Received Push";
Intent intent = new Intent(this, MonacaNotificationActivity.class);
intent.putExtra(GCMPushDataset.KEY, data);
+ intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
int id = (int)System.currentTimeMillis();
PendingIntent pending = PendingIntent.getActivity(this, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new Notification();
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.icon = R.drawable.icon;
notification.tickerText = title;
notification.setLatestEventInfo(this, title, message, pending);
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(id, notification);
}
@Override
protected void onRegistered(Context arg0, String arg1) {
MyLog.d(TAG, "onRegisterd :" + arg1);
}
@Override
protected void onUnregistered(Context arg0, String arg1) {
MyLog.d(TAG, "onUnregistered :" + arg1);
}
}
| true | true | protected void onMessage(Context arg0, Intent arg1) {
MyLog.d(TAG, "onMessage");
Bundle b = arg1.getExtras();
if (b == null) {
return;
}
String message = b.getString("message");
String pushProjectId = b.getString("push_project_id");
String extraJsonString = b.getString("extra_json");
GCMPushDataset data = new GCMPushDataset(pushProjectId, message, extraJsonString);
String title = b.getString("title") != null ? b.getString("title") : getString(R.string.app_name) + " Received Push";
Intent intent = new Intent(this, MonacaNotificationActivity.class);
intent.putExtra(GCMPushDataset.KEY, data);
int id = (int)System.currentTimeMillis();
PendingIntent pending = PendingIntent.getActivity(this, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new Notification();
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.icon = R.drawable.icon;
notification.tickerText = title;
notification.setLatestEventInfo(this, title, message, pending);
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(id, notification);
}
| protected void onMessage(Context arg0, Intent arg1) {
MyLog.d(TAG, "onMessage");
Bundle b = arg1.getExtras();
if (b == null) {
return;
}
String message = b.getString("message");
String pushProjectId = b.getString("push_project_id");
String extraJsonString = b.getString("extra_json");
GCMPushDataset data = new GCMPushDataset(pushProjectId, message, extraJsonString);
String title = b.getString("title") != null ? b.getString("title") : getString(R.string.app_name) + " Received Push";
Intent intent = new Intent(this, MonacaNotificationActivity.class);
intent.putExtra(GCMPushDataset.KEY, data);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
int id = (int)System.currentTimeMillis();
PendingIntent pending = PendingIntent.getActivity(this, id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new Notification();
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.icon = R.drawable.icon;
notification.tickerText = title;
notification.setLatestEventInfo(this, title, message, pending);
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(id, notification);
}
|
diff --git a/src/main/battlecode/engine/RobotRunnable.java b/src/main/battlecode/engine/RobotRunnable.java
index 7f8ed482..9fb40307 100644
--- a/src/main/battlecode/engine/RobotRunnable.java
+++ b/src/main/battlecode/engine/RobotRunnable.java
@@ -1,84 +1,86 @@
package battlecode.engine;
import java.lang.Runnable;
import java.lang.reflect.*;
import battlecode.engine.instrumenter.RobotDeathException;
import battlecode.engine.instrumenter.RobotMonitor;
import battlecode.engine.scheduler.Scheduler;
/*
RobotRunnable is a wrapper for a player's main class. It is basically a Runnable, whose run method both instantiates the player's
main class and runs the player's run method.
TODO:
- better commenting
- better error reporting
*/
class RobotRunnable implements Runnable {
private final Class<?> myPlayerClass;
private final GenericController myRobotController;
public RobotRunnable(Class playerClass, GenericController rc) {
myPlayerClass = playerClass;
myRobotController = rc;
}
// instantiates the class passed to the RobotRunnable constructor, and runs its run method
public void run() {
Constructor ctor;
Object o;
Runnable r;
try {
try {
+ Scheduler.endTurn();
ctor = myPlayerClass.getConstructor(Class.forName("battlecode.common.RobotController"));
} catch (Throwable t) {
+ if ((t instanceof RobotDeathException) || (t.getCause() instanceof RobotDeathException))
+ return;
ErrorReporter.report(t, "Check that the player class '" + myPlayerClass.getSimpleName() + "' has a constructor with one argument, of type RobotController.\n");
return;
}
try {
- Scheduler.endTurn();
o = ctor.newInstance(myRobotController);
} catch (Throwable t) {
if ((t instanceof RobotDeathException) || (t.getCause() instanceof RobotDeathException))
return;
ErrorReporter.report(t, "Check that the player does not throw an exception in its constructor.\n");
return;
}
try {
r = (Runnable) o;
} catch (Exception e) {
ErrorReporter.report("The player class '" + myPlayerClass.getSimpleName() + " does not implement Runnable.", "Check that the player class implements java.lang.Runnable.\n");
return;
}
try {
r.run();
} catch (RobotDeathException rde) {
return;
} catch (Throwable t) {
if (t.getCause() instanceof RobotDeathException)
return;
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because of:");
t.printStackTrace();
return;
}
if(!RobotMonitor.thrownRobotDeathException())
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because its run method returned");
} finally {
myRobotController.getRobot().suicide();
}
}
}
| false | true | public void run() {
Constructor ctor;
Object o;
Runnable r;
try {
try {
ctor = myPlayerClass.getConstructor(Class.forName("battlecode.common.RobotController"));
} catch (Throwable t) {
ErrorReporter.report(t, "Check that the player class '" + myPlayerClass.getSimpleName() + "' has a constructor with one argument, of type RobotController.\n");
return;
}
try {
Scheduler.endTurn();
o = ctor.newInstance(myRobotController);
} catch (Throwable t) {
if ((t instanceof RobotDeathException) || (t.getCause() instanceof RobotDeathException))
return;
ErrorReporter.report(t, "Check that the player does not throw an exception in its constructor.\n");
return;
}
try {
r = (Runnable) o;
} catch (Exception e) {
ErrorReporter.report("The player class '" + myPlayerClass.getSimpleName() + " does not implement Runnable.", "Check that the player class implements java.lang.Runnable.\n");
return;
}
try {
r.run();
} catch (RobotDeathException rde) {
return;
} catch (Throwable t) {
if (t.getCause() instanceof RobotDeathException)
return;
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because of:");
t.printStackTrace();
return;
}
if(!RobotMonitor.thrownRobotDeathException())
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because its run method returned");
} finally {
myRobotController.getRobot().suicide();
}
}
| public void run() {
Constructor ctor;
Object o;
Runnable r;
try {
try {
Scheduler.endTurn();
ctor = myPlayerClass.getConstructor(Class.forName("battlecode.common.RobotController"));
} catch (Throwable t) {
if ((t instanceof RobotDeathException) || (t.getCause() instanceof RobotDeathException))
return;
ErrorReporter.report(t, "Check that the player class '" + myPlayerClass.getSimpleName() + "' has a constructor with one argument, of type RobotController.\n");
return;
}
try {
o = ctor.newInstance(myRobotController);
} catch (Throwable t) {
if ((t instanceof RobotDeathException) || (t.getCause() instanceof RobotDeathException))
return;
ErrorReporter.report(t, "Check that the player does not throw an exception in its constructor.\n");
return;
}
try {
r = (Runnable) o;
} catch (Exception e) {
ErrorReporter.report("The player class '" + myPlayerClass.getSimpleName() + " does not implement Runnable.", "Check that the player class implements java.lang.Runnable.\n");
return;
}
try {
r.run();
} catch (RobotDeathException rde) {
return;
} catch (Throwable t) {
if (t.getCause() instanceof RobotDeathException)
return;
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because of:");
t.printStackTrace();
return;
}
if(!RobotMonitor.thrownRobotDeathException())
System.out.println("[Engine] Robot " + myRobotController.getRobot() + " died because its run method returned");
} finally {
myRobotController.getRobot().suicide();
}
}
|
diff --git a/src/com/github/Indiv0/BookDupe/ItemCraftListener.java b/src/com/github/Indiv0/BookDupe/ItemCraftListener.java
index c27c6dd..1dad890 100644
--- a/src/com/github/Indiv0/BookDupe/ItemCraftListener.java
+++ b/src/com/github/Indiv0/BookDupe/ItemCraftListener.java
@@ -1,159 +1,159 @@
package com.github.Indiv0.BookDupe;
import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.inventory.CraftingInventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import net.minecraft.server.*;
public class ItemCraftListener implements Listener {
// Create a method to handle/interact with crafting events.
@EventHandler
public void onItemCraft(CraftItemEvent event) {
// Get the crafting inventory (3x3 matrix) used to craft the item.
CraftingInventory craftingInventory = event.getInventory();
// Get the index of the first (and only) Material.WRITTEN_BOOK used in
// the recipe.
int writtenBookIndex = craftingInventory.first(Material.WRITTEN_BOOK);
// Makes sure the recipe contains a WRITTEN_BOOK.
if (writtenBookIndex == -1) return;
if (!event.getWhoClicked().hasPermission("bookdupe.use")) {
event.setCancelled(true);
return;
}
// ItemStack represention of the book to be cloned.
ItemStack initialBook = craftingInventory.getItem(writtenBookIndex);
// The base Minecraft class representation of the book to be cloned.
net.minecraft.server.ItemStack stack = ((CraftItemStack) initialBook).getHandle();
// Store all of the tags contained within the book.
NBTTagCompound tag = stack.getTag();
// If the player does not have permission to copy any book
// and the book was not written by the player, do not allow
// the player to copy the book.
if (!event.getWhoClicked().hasPermission("bookdupe.any")
- && !(tag.getString("author") == event.getWhoClicked().getName())) {
+ && !tag.getString("author").equals(event.getWhoClicked().getName())) {
event.setCancelled(true);
return;
}
// Get the player's inventory.
PlayerInventory playerInventory = event.getWhoClicked().getInventory();
// Create a new ItemStack by cloning the previous one.
CraftItemStack craftResult = (CraftItemStack) initialBook.clone();
// Gets the index of the first INK_SACK in the recipe.
int inkSackIndex = craftingInventory.first(Material.INK_SACK);
// Gets the index of the first FEATHER in the recipe.
int featherIndex = craftingInventory.first(Material.FEATHER);
// Gets the index of the first BOOK in the recipe.
int bookIndex = craftingInventory.first(Material.BOOK);
// Makes sure the recipe doesn't contain an INK_SACK, FEATHER, and BOOK.
if (inkSackIndex == -1 || featherIndex == -1 || bookIndex == -1) {
HashMap<Integer, ? extends ItemStack> map = craftingInventory
.all(Material.BOOK_AND_QUILL);
int amount = map.size();
// Check only one BOOK_AND_QUILL is in the crafting matrix.
if (amount != 2)
return;
// Adds the original book to the player's inventory.
playerInventory.addItem(craftResult.clone());
// Sets the result of the craft to the copied books.
event.setCurrentItem(craftResult);
}
// Handle a non BOOK_AND_QUILL based recipe.
else {
// If the player regularly clicked (singular craft).
if (!event.isShiftClick())
// Adds the original book to the player's inventory.
playerInventory.addItem(craftResult.clone());
// If the player didn't shift-click.
else {
// Gets the amount of INK_SACK in the crafting matrix.
int inkSackAmount = craftingInventory.getItem(inkSackIndex).getAmount();
// Gets the amount of FEATHER in the crafting matrix.
int featherAmount = craftingInventory.getItem(featherIndex).getAmount();
// Gets the amount of BOOK in the crafting matrix.
int bookAmount = craftingInventory.getItem(bookIndex).getAmount();
int lowestAmount = 0;
// Get the ingredient of which there is the least and loop until
// that ingredient no longer exists.
if (inkSackAmount < featherAmount && inkSackAmount < bookAmount)
lowestAmount = inkSackAmount;
// Otherwise check if the crafting inventory contains less
// FEATHER than any other ingredient.
if (featherAmount < inkSackAmount && featherAmount < bookAmount)
lowestAmount = featherAmount;
// Otherwise the crafting inventory contains less BOOK than any
// other ingredient.
else
lowestAmount = bookAmount;
// Loops through crafting matrix reducing item amounts
// one-by-one.
int itemsLeft = 0;
itemsLeft = craftingInventory.getItem(inkSackIndex).getAmount() - lowestAmount;
if (itemsLeft != 0)
craftingInventory.getItem(inkSackIndex).setAmount(itemsLeft);
else
craftingInventory.clear(inkSackIndex);
itemsLeft = craftingInventory.getItem(featherIndex).getAmount() - lowestAmount;
if (itemsLeft != 0)
craftingInventory.getItem(featherIndex).setAmount(itemsLeft);
else
craftingInventory.clear(featherIndex);
itemsLeft = craftingInventory.getItem(bookIndex).getAmount() - lowestAmount;
if (itemsLeft != 0)
craftingInventory.getItem(bookIndex).setAmount(itemsLeft);
else
craftingInventory.clear(bookIndex);
// Creates a HashMap to store items which do not fit into the
// player's inventory.
HashMap<Integer, ItemStack> leftOver = new HashMap<Integer, ItemStack>();
// Adds the new books to the player's inventory.
for (int i = 0; i < lowestAmount; i++) {
leftOver.putAll((playerInventory.addItem(craftResult.clone())));
if (!leftOver.isEmpty()) {
Location loc = event.getWhoClicked().getLocation();
ItemStack item = craftResult.clone();
event.getWhoClicked().getWorld().dropItem(loc, item);
}
}
}
// Sets the result of the craft to the copied books.
event.setCurrentItem(craftResult);
}
}
}
| true | true | public void onItemCraft(CraftItemEvent event) {
// Get the crafting inventory (3x3 matrix) used to craft the item.
CraftingInventory craftingInventory = event.getInventory();
// Get the index of the first (and only) Material.WRITTEN_BOOK used in
// the recipe.
int writtenBookIndex = craftingInventory.first(Material.WRITTEN_BOOK);
// Makes sure the recipe contains a WRITTEN_BOOK.
if (writtenBookIndex == -1) return;
if (!event.getWhoClicked().hasPermission("bookdupe.use")) {
event.setCancelled(true);
return;
}
// ItemStack represention of the book to be cloned.
ItemStack initialBook = craftingInventory.getItem(writtenBookIndex);
// The base Minecraft class representation of the book to be cloned.
net.minecraft.server.ItemStack stack = ((CraftItemStack) initialBook).getHandle();
// Store all of the tags contained within the book.
NBTTagCompound tag = stack.getTag();
// If the player does not have permission to copy any book
// and the book was not written by the player, do not allow
// the player to copy the book.
if (!event.getWhoClicked().hasPermission("bookdupe.any")
&& !(tag.getString("author") == event.getWhoClicked().getName())) {
event.setCancelled(true);
return;
}
// Get the player's inventory.
PlayerInventory playerInventory = event.getWhoClicked().getInventory();
// Create a new ItemStack by cloning the previous one.
CraftItemStack craftResult = (CraftItemStack) initialBook.clone();
// Gets the index of the first INK_SACK in the recipe.
int inkSackIndex = craftingInventory.first(Material.INK_SACK);
// Gets the index of the first FEATHER in the recipe.
int featherIndex = craftingInventory.first(Material.FEATHER);
// Gets the index of the first BOOK in the recipe.
int bookIndex = craftingInventory.first(Material.BOOK);
// Makes sure the recipe doesn't contain an INK_SACK, FEATHER, and BOOK.
if (inkSackIndex == -1 || featherIndex == -1 || bookIndex == -1) {
HashMap<Integer, ? extends ItemStack> map = craftingInventory
.all(Material.BOOK_AND_QUILL);
int amount = map.size();
// Check only one BOOK_AND_QUILL is in the crafting matrix.
if (amount != 2)
return;
// Adds the original book to the player's inventory.
playerInventory.addItem(craftResult.clone());
// Sets the result of the craft to the copied books.
event.setCurrentItem(craftResult);
}
// Handle a non BOOK_AND_QUILL based recipe.
else {
// If the player regularly clicked (singular craft).
if (!event.isShiftClick())
// Adds the original book to the player's inventory.
playerInventory.addItem(craftResult.clone());
// If the player didn't shift-click.
else {
// Gets the amount of INK_SACK in the crafting matrix.
int inkSackAmount = craftingInventory.getItem(inkSackIndex).getAmount();
// Gets the amount of FEATHER in the crafting matrix.
int featherAmount = craftingInventory.getItem(featherIndex).getAmount();
// Gets the amount of BOOK in the crafting matrix.
int bookAmount = craftingInventory.getItem(bookIndex).getAmount();
int lowestAmount = 0;
// Get the ingredient of which there is the least and loop until
// that ingredient no longer exists.
if (inkSackAmount < featherAmount && inkSackAmount < bookAmount)
lowestAmount = inkSackAmount;
// Otherwise check if the crafting inventory contains less
// FEATHER than any other ingredient.
if (featherAmount < inkSackAmount && featherAmount < bookAmount)
lowestAmount = featherAmount;
// Otherwise the crafting inventory contains less BOOK than any
// other ingredient.
else
lowestAmount = bookAmount;
// Loops through crafting matrix reducing item amounts
// one-by-one.
int itemsLeft = 0;
itemsLeft = craftingInventory.getItem(inkSackIndex).getAmount() - lowestAmount;
if (itemsLeft != 0)
craftingInventory.getItem(inkSackIndex).setAmount(itemsLeft);
else
craftingInventory.clear(inkSackIndex);
itemsLeft = craftingInventory.getItem(featherIndex).getAmount() - lowestAmount;
if (itemsLeft != 0)
craftingInventory.getItem(featherIndex).setAmount(itemsLeft);
else
craftingInventory.clear(featherIndex);
itemsLeft = craftingInventory.getItem(bookIndex).getAmount() - lowestAmount;
if (itemsLeft != 0)
craftingInventory.getItem(bookIndex).setAmount(itemsLeft);
else
craftingInventory.clear(bookIndex);
// Creates a HashMap to store items which do not fit into the
// player's inventory.
HashMap<Integer, ItemStack> leftOver = new HashMap<Integer, ItemStack>();
// Adds the new books to the player's inventory.
for (int i = 0; i < lowestAmount; i++) {
leftOver.putAll((playerInventory.addItem(craftResult.clone())));
if (!leftOver.isEmpty()) {
Location loc = event.getWhoClicked().getLocation();
ItemStack item = craftResult.clone();
event.getWhoClicked().getWorld().dropItem(loc, item);
}
}
}
// Sets the result of the craft to the copied books.
event.setCurrentItem(craftResult);
}
}
| public void onItemCraft(CraftItemEvent event) {
// Get the crafting inventory (3x3 matrix) used to craft the item.
CraftingInventory craftingInventory = event.getInventory();
// Get the index of the first (and only) Material.WRITTEN_BOOK used in
// the recipe.
int writtenBookIndex = craftingInventory.first(Material.WRITTEN_BOOK);
// Makes sure the recipe contains a WRITTEN_BOOK.
if (writtenBookIndex == -1) return;
if (!event.getWhoClicked().hasPermission("bookdupe.use")) {
event.setCancelled(true);
return;
}
// ItemStack represention of the book to be cloned.
ItemStack initialBook = craftingInventory.getItem(writtenBookIndex);
// The base Minecraft class representation of the book to be cloned.
net.minecraft.server.ItemStack stack = ((CraftItemStack) initialBook).getHandle();
// Store all of the tags contained within the book.
NBTTagCompound tag = stack.getTag();
// If the player does not have permission to copy any book
// and the book was not written by the player, do not allow
// the player to copy the book.
if (!event.getWhoClicked().hasPermission("bookdupe.any")
&& !tag.getString("author").equals(event.getWhoClicked().getName())) {
event.setCancelled(true);
return;
}
// Get the player's inventory.
PlayerInventory playerInventory = event.getWhoClicked().getInventory();
// Create a new ItemStack by cloning the previous one.
CraftItemStack craftResult = (CraftItemStack) initialBook.clone();
// Gets the index of the first INK_SACK in the recipe.
int inkSackIndex = craftingInventory.first(Material.INK_SACK);
// Gets the index of the first FEATHER in the recipe.
int featherIndex = craftingInventory.first(Material.FEATHER);
// Gets the index of the first BOOK in the recipe.
int bookIndex = craftingInventory.first(Material.BOOK);
// Makes sure the recipe doesn't contain an INK_SACK, FEATHER, and BOOK.
if (inkSackIndex == -1 || featherIndex == -1 || bookIndex == -1) {
HashMap<Integer, ? extends ItemStack> map = craftingInventory
.all(Material.BOOK_AND_QUILL);
int amount = map.size();
// Check only one BOOK_AND_QUILL is in the crafting matrix.
if (amount != 2)
return;
// Adds the original book to the player's inventory.
playerInventory.addItem(craftResult.clone());
// Sets the result of the craft to the copied books.
event.setCurrentItem(craftResult);
}
// Handle a non BOOK_AND_QUILL based recipe.
else {
// If the player regularly clicked (singular craft).
if (!event.isShiftClick())
// Adds the original book to the player's inventory.
playerInventory.addItem(craftResult.clone());
// If the player didn't shift-click.
else {
// Gets the amount of INK_SACK in the crafting matrix.
int inkSackAmount = craftingInventory.getItem(inkSackIndex).getAmount();
// Gets the amount of FEATHER in the crafting matrix.
int featherAmount = craftingInventory.getItem(featherIndex).getAmount();
// Gets the amount of BOOK in the crafting matrix.
int bookAmount = craftingInventory.getItem(bookIndex).getAmount();
int lowestAmount = 0;
// Get the ingredient of which there is the least and loop until
// that ingredient no longer exists.
if (inkSackAmount < featherAmount && inkSackAmount < bookAmount)
lowestAmount = inkSackAmount;
// Otherwise check if the crafting inventory contains less
// FEATHER than any other ingredient.
if (featherAmount < inkSackAmount && featherAmount < bookAmount)
lowestAmount = featherAmount;
// Otherwise the crafting inventory contains less BOOK than any
// other ingredient.
else
lowestAmount = bookAmount;
// Loops through crafting matrix reducing item amounts
// one-by-one.
int itemsLeft = 0;
itemsLeft = craftingInventory.getItem(inkSackIndex).getAmount() - lowestAmount;
if (itemsLeft != 0)
craftingInventory.getItem(inkSackIndex).setAmount(itemsLeft);
else
craftingInventory.clear(inkSackIndex);
itemsLeft = craftingInventory.getItem(featherIndex).getAmount() - lowestAmount;
if (itemsLeft != 0)
craftingInventory.getItem(featherIndex).setAmount(itemsLeft);
else
craftingInventory.clear(featherIndex);
itemsLeft = craftingInventory.getItem(bookIndex).getAmount() - lowestAmount;
if (itemsLeft != 0)
craftingInventory.getItem(bookIndex).setAmount(itemsLeft);
else
craftingInventory.clear(bookIndex);
// Creates a HashMap to store items which do not fit into the
// player's inventory.
HashMap<Integer, ItemStack> leftOver = new HashMap<Integer, ItemStack>();
// Adds the new books to the player's inventory.
for (int i = 0; i < lowestAmount; i++) {
leftOver.putAll((playerInventory.addItem(craftResult.clone())));
if (!leftOver.isEmpty()) {
Location loc = event.getWhoClicked().getLocation();
ItemStack item = craftResult.clone();
event.getWhoClicked().getWorld().dropItem(loc, item);
}
}
}
// Sets the result of the craft to the copied books.
event.setCurrentItem(craftResult);
}
}
|
diff --git a/src/Account_IO.java b/src/Account_IO.java
index 101bbbe..dad7865 100644
--- a/src/Account_IO.java
+++ b/src/Account_IO.java
@@ -1,88 +1,90 @@
import java.util.*;
import java.io.*;
/**
*
* @author Mudrekh Goderya, James Sanderlin
*
* The Account_IO class handles input and output of the current state of the program to accounts.txt
*
* @
*
*/
public class Account_IO
{
public Account_IO()
{
File accountFile = new File("accounts.txt");
try
{
Scanner in = new Scanner(accountFile);
//Parse the accounts file
while(in.hasNext())
{
String name = in.nextLine();
//System.out.println(name);
int accountId = Integer.parseInt(in.nextLine());
//System.out.println(accountId);
double balance = Double.parseDouble(in.nextLine());
//System.out.println(balance);
boolean flag = (in.nextInt() == 0) ? false : true;
//System.out.println(flag);
boolean isCommercial = (in.nextInt() == 0) ? false : true;
in.nextLine();
String dateString = in.nextLine();
/*TODO Convert dateString into Date (or Calendar?) object */
Date deadline = new Date();
String address = "";
//Read address until you see "PAYMENTS:"
String line = in.nextLine();
while(!line.equals("PAYMENTS:"))
{
address += line + "\n";
line = in.nextLine();
}
//Read Payments until you see a blank line.
line = in.nextLine();
while(!line.equals(""))
{
/*TODO Read in and create the payment objects */
//System.out.println("Line " + line);
line = in.nextLine();
}
if(isCommercial)
{
CommercialAccount a = new CommercialAccount(name, accountId, balance, flag, deadline, address);
System.out.println("COMMERCIAL ACCOUNT INFO:");
- System.out.println(a.clientName);
+ System.out.println(a.clientFirstName);
+ System.out.println(a.clientLastName);
System.out.println(a.accountID);
System.out.println(a.balance);
System.out.println(a.flag);
System.out.println(a.deadline);
System.out.println("ADDRESS: " + a.billingAddress);
System.out.println("END COMMERCIAL INFO");
}
else
{
ResidentialAccount a = new ResidentialAccount(name, accountId, balance, flag, deadline, address);
System.out.println("RESIDENTIAL ACCOUNT INFO:");
- System.out.println(a.clientName);
+ System.out.println(a.clientFirstName);
+ System.out.println(a.clientLastName);
System.out.println(a.accountID);
System.out.println(a.balance);
System.out.println(a.flag);
System.out.println(a.deadline);
System.out.println("ADDRESS: " + a.billingAddress);
System.out.println("END RESIDENTIAL INFO");
}
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
}
}
| false | true | public Account_IO()
{
File accountFile = new File("accounts.txt");
try
{
Scanner in = new Scanner(accountFile);
//Parse the accounts file
while(in.hasNext())
{
String name = in.nextLine();
//System.out.println(name);
int accountId = Integer.parseInt(in.nextLine());
//System.out.println(accountId);
double balance = Double.parseDouble(in.nextLine());
//System.out.println(balance);
boolean flag = (in.nextInt() == 0) ? false : true;
//System.out.println(flag);
boolean isCommercial = (in.nextInt() == 0) ? false : true;
in.nextLine();
String dateString = in.nextLine();
/*TODO Convert dateString into Date (or Calendar?) object */
Date deadline = new Date();
String address = "";
//Read address until you see "PAYMENTS:"
String line = in.nextLine();
while(!line.equals("PAYMENTS:"))
{
address += line + "\n";
line = in.nextLine();
}
//Read Payments until you see a blank line.
line = in.nextLine();
while(!line.equals(""))
{
/*TODO Read in and create the payment objects */
//System.out.println("Line " + line);
line = in.nextLine();
}
if(isCommercial)
{
CommercialAccount a = new CommercialAccount(name, accountId, balance, flag, deadline, address);
System.out.println("COMMERCIAL ACCOUNT INFO:");
System.out.println(a.clientName);
System.out.println(a.accountID);
System.out.println(a.balance);
System.out.println(a.flag);
System.out.println(a.deadline);
System.out.println("ADDRESS: " + a.billingAddress);
System.out.println("END COMMERCIAL INFO");
}
else
{
ResidentialAccount a = new ResidentialAccount(name, accountId, balance, flag, deadline, address);
System.out.println("RESIDENTIAL ACCOUNT INFO:");
System.out.println(a.clientName);
System.out.println(a.accountID);
System.out.println(a.balance);
System.out.println(a.flag);
System.out.println(a.deadline);
System.out.println("ADDRESS: " + a.billingAddress);
System.out.println("END RESIDENTIAL INFO");
}
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
}
| public Account_IO()
{
File accountFile = new File("accounts.txt");
try
{
Scanner in = new Scanner(accountFile);
//Parse the accounts file
while(in.hasNext())
{
String name = in.nextLine();
//System.out.println(name);
int accountId = Integer.parseInt(in.nextLine());
//System.out.println(accountId);
double balance = Double.parseDouble(in.nextLine());
//System.out.println(balance);
boolean flag = (in.nextInt() == 0) ? false : true;
//System.out.println(flag);
boolean isCommercial = (in.nextInt() == 0) ? false : true;
in.nextLine();
String dateString = in.nextLine();
/*TODO Convert dateString into Date (or Calendar?) object */
Date deadline = new Date();
String address = "";
//Read address until you see "PAYMENTS:"
String line = in.nextLine();
while(!line.equals("PAYMENTS:"))
{
address += line + "\n";
line = in.nextLine();
}
//Read Payments until you see a blank line.
line = in.nextLine();
while(!line.equals(""))
{
/*TODO Read in and create the payment objects */
//System.out.println("Line " + line);
line = in.nextLine();
}
if(isCommercial)
{
CommercialAccount a = new CommercialAccount(name, accountId, balance, flag, deadline, address);
System.out.println("COMMERCIAL ACCOUNT INFO:");
System.out.println(a.clientFirstName);
System.out.println(a.clientLastName);
System.out.println(a.accountID);
System.out.println(a.balance);
System.out.println(a.flag);
System.out.println(a.deadline);
System.out.println("ADDRESS: " + a.billingAddress);
System.out.println("END COMMERCIAL INFO");
}
else
{
ResidentialAccount a = new ResidentialAccount(name, accountId, balance, flag, deadline, address);
System.out.println("RESIDENTIAL ACCOUNT INFO:");
System.out.println(a.clientFirstName);
System.out.println(a.clientLastName);
System.out.println(a.accountID);
System.out.println(a.balance);
System.out.println(a.flag);
System.out.println(a.deadline);
System.out.println("ADDRESS: " + a.billingAddress);
System.out.println("END RESIDENTIAL INFO");
}
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
}
|
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/ui/ConnectTraktFinishedFragment.java b/SeriesGuide/src/com/battlelancer/seriesguide/ui/ConnectTraktFinishedFragment.java
index 2fef70121..45b3ff0b4 100644
--- a/SeriesGuide/src/com/battlelancer/seriesguide/ui/ConnectTraktFinishedFragment.java
+++ b/SeriesGuide/src/com/battlelancer/seriesguide/ui/ConnectTraktFinishedFragment.java
@@ -1,58 +1,58 @@
package com.battlelancer.seriesguide.ui;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
import com.uwetrottmann.seriesguide.R;
/**
* Tells about successful connection, allows to continue adding shows from users
* trakt library or upload existing shows from SeriesGuide.
*/
public class ConnectTraktFinishedFragment extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.connect_trakt_finished_fragment, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// library button
- getView().findViewById(R.id.buttonUploadShows).setOnClickListener(new OnClickListener() {
+ getView().findViewById(R.id.buttonShowLibrary).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO open library tab
Intent i = new Intent(getActivity(), AddActivity.class);
startActivity(i);
getActivity().finish();
}
});
// upload button
getView().findViewById(R.id.buttonUploadShows).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), TraktSyncActivity.class);
startActivity(i);
getActivity().finish();
}
});
// close button
getView().findViewById(R.id.buttonClose).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
}
}
| true | true | public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// library button
getView().findViewById(R.id.buttonUploadShows).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO open library tab
Intent i = new Intent(getActivity(), AddActivity.class);
startActivity(i);
getActivity().finish();
}
});
// upload button
getView().findViewById(R.id.buttonUploadShows).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), TraktSyncActivity.class);
startActivity(i);
getActivity().finish();
}
});
// close button
getView().findViewById(R.id.buttonClose).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
}
| public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// library button
getView().findViewById(R.id.buttonShowLibrary).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO open library tab
Intent i = new Intent(getActivity(), AddActivity.class);
startActivity(i);
getActivity().finish();
}
});
// upload button
getView().findViewById(R.id.buttonUploadShows).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), TraktSyncActivity.class);
startActivity(i);
getActivity().finish();
}
});
// close button
getView().findViewById(R.id.buttonClose).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
}
|
diff --git a/grails/src/persistence/org/codehaus/groovy/grails/metaclass/DataBindingDynamicConstructor.java b/grails/src/persistence/org/codehaus/groovy/grails/metaclass/DataBindingDynamicConstructor.java
index ab53fe5a3..cb4162b25 100644
--- a/grails/src/persistence/org/codehaus/groovy/grails/metaclass/DataBindingDynamicConstructor.java
+++ b/grails/src/persistence/org/codehaus/groovy/grails/metaclass/DataBindingDynamicConstructor.java
@@ -1,103 +1,103 @@
/*
* Copyright 2004-2005 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.codehaus.groovy.grails.metaclass;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.metaclass.DynamicConstructor;
import org.codehaus.groovy.grails.exceptions.GrailsDomainException;
import org.codehaus.groovy.grails.web.binding.GrailsDataBinder;
import org.codehaus.groovy.grails.web.metaclass.GrailsParameterMap;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.validation.DataBinder;
import org.springframework.web.bind.ServletRequestDataBinder;
/**
* A dynamic property that uses a Map of OGNL expressions to sets properties on the target object
*
* @author Graeme Rocher
* @since 0.3
*
* Created 23/07/06
*/
public class DataBindingDynamicConstructor implements DynamicConstructor {
private static final Log LOG = LogFactory.getLog( DataBindingDynamicConstructor.class );
public boolean isArgumentsMatch(Object[] args) {
if(args.length != 1 ) return false;
if(args[0] == null) return false;
if(HttpServletRequest.class.isAssignableFrom(args[0].getClass())) return true;
if(Map.class.isAssignableFrom(args[0].getClass())) return true;
return false;
}
public Object invoke(Class clazz, Object[] args) {
Object map = args[0];
Object instance;
try {
instance = clazz.newInstance();
} catch (InstantiationException e1) {
throw new GrailsDomainException("Error instantiated class [" + clazz + "]: " + e1.getMessage(),e1);
} catch (IllegalAccessException e1) {
throw new GrailsDomainException("Illegal access instantiated class [" + clazz + "]: " + e1.getMessage(),e1);
}
if(map instanceof GrailsParameterMap) {
GrailsParameterMap parameterMap = (GrailsParameterMap)map;
HttpServletRequest request = parameterMap.getRequest();
- ServletRequestDataBinder dataBinder = GrailsDataBinder.createBinder(map, instance.getClass().getName(),request);
+ ServletRequestDataBinder dataBinder = GrailsDataBinder.createBinder(instance, instance.getClass().getName(),request);
dataBinder.bind(request);
return instance;
}
else if (map instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest)map;
- ServletRequestDataBinder dataBinder = GrailsDataBinder.createBinder(map, instance.getClass().getName(),request);
+ ServletRequestDataBinder dataBinder = GrailsDataBinder.createBinder(instance, instance.getClass().getName(),request);
dataBinder.bind(request);
return instance;
}
else if(map instanceof Map) {
DataBinder dataBinder = new DataBinder(instance);
Map m = convertPotentialGStrings((Map)map);
PropertyValues pv = new MutablePropertyValues(m);
dataBinder.bind(pv);
}
return instance;
}
private Map convertPotentialGStrings(Map args) {
Map newArgs = new java.util.HashMap();
for(java.util.Iterator i = args.keySet().iterator(); i.hasNext();) {
Object key = i.next();
Object value = args.get(key);
if(key instanceof groovy.lang.GString) {
key = ((groovy.lang.GString)key).toString();
}
if(value instanceof groovy.lang.GString) {
value = ((groovy.lang.GString)value).toString();
}
newArgs.put(key,value);
}
return newArgs;
}
}
| false | true | public Object invoke(Class clazz, Object[] args) {
Object map = args[0];
Object instance;
try {
instance = clazz.newInstance();
} catch (InstantiationException e1) {
throw new GrailsDomainException("Error instantiated class [" + clazz + "]: " + e1.getMessage(),e1);
} catch (IllegalAccessException e1) {
throw new GrailsDomainException("Illegal access instantiated class [" + clazz + "]: " + e1.getMessage(),e1);
}
if(map instanceof GrailsParameterMap) {
GrailsParameterMap parameterMap = (GrailsParameterMap)map;
HttpServletRequest request = parameterMap.getRequest();
ServletRequestDataBinder dataBinder = GrailsDataBinder.createBinder(map, instance.getClass().getName(),request);
dataBinder.bind(request);
return instance;
}
else if (map instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest)map;
ServletRequestDataBinder dataBinder = GrailsDataBinder.createBinder(map, instance.getClass().getName(),request);
dataBinder.bind(request);
return instance;
}
else if(map instanceof Map) {
DataBinder dataBinder = new DataBinder(instance);
Map m = convertPotentialGStrings((Map)map);
PropertyValues pv = new MutablePropertyValues(m);
dataBinder.bind(pv);
}
return instance;
}
| public Object invoke(Class clazz, Object[] args) {
Object map = args[0];
Object instance;
try {
instance = clazz.newInstance();
} catch (InstantiationException e1) {
throw new GrailsDomainException("Error instantiated class [" + clazz + "]: " + e1.getMessage(),e1);
} catch (IllegalAccessException e1) {
throw new GrailsDomainException("Illegal access instantiated class [" + clazz + "]: " + e1.getMessage(),e1);
}
if(map instanceof GrailsParameterMap) {
GrailsParameterMap parameterMap = (GrailsParameterMap)map;
HttpServletRequest request = parameterMap.getRequest();
ServletRequestDataBinder dataBinder = GrailsDataBinder.createBinder(instance, instance.getClass().getName(),request);
dataBinder.bind(request);
return instance;
}
else if (map instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest)map;
ServletRequestDataBinder dataBinder = GrailsDataBinder.createBinder(instance, instance.getClass().getName(),request);
dataBinder.bind(request);
return instance;
}
else if(map instanceof Map) {
DataBinder dataBinder = new DataBinder(instance);
Map m = convertPotentialGStrings((Map)map);
PropertyValues pv = new MutablePropertyValues(m);
dataBinder.bind(pv);
}
return instance;
}
|
diff --git a/wings2/src/java/org/wings/plaf/css/ProgressBarCG.java b/wings2/src/java/org/wings/plaf/css/ProgressBarCG.java
index 45cf4ac9..6e80f0ab 100644
--- a/wings2/src/java/org/wings/plaf/css/ProgressBarCG.java
+++ b/wings2/src/java/org/wings/plaf/css/ProgressBarCG.java
@@ -1,134 +1,144 @@
// DO NOT EDIT! Your changes will be lost: generated from '/home/hengels/jdevel/wings/src/org/wings/plaf/css1/ProgressBar.plaf'
/*
* $Id$
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://www.j-wings.org).
*
* wingS 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.
*
* Please see COPYING for the complete licence.
*/
package org.wings.plaf.css;
import org.wings.*;
import org.wings.io.Device;
import org.wings.plaf.CGManager;
import java.io.IOException;
public class ProgressBarCG
extends AbstractComponentCG
implements SConstants, org.wings.plaf.ProgressBarCG {
//--- byte array converted template snippets.
public void installCG(final SComponent comp) {
final SProgressBar component = (SProgressBar) comp;
final CGManager manager = component.getSession().getCGManager();
Object value;
Object previous;
value = manager.getObject("SProgressBar.borderColor", java.awt.Color.class);
if (value != null) {
component.setBorderColor((java.awt.Color) value);
}
value = manager.getObject("SProgressBar.filledColor", java.awt.Color.class);
if (value != null) {
component.setFilledColor((java.awt.Color) value);
}
value = manager.getObject("SProgressBar.foreground", java.awt.Color.class);
if (value != null) {
component.setForeground((java.awt.Color) value);
}
value = manager.getObject("SProgressBar.preferredSize", SDimension.class);
if (value != null) {
component.setPreferredSize((SDimension) value);
}
value = manager.getObject("SProgressBar.unfilledColor", java.awt.Color.class);
if (value != null) {
component.setUnfilledColor((java.awt.Color) value);
}
}
public void uninstallCG(final SComponent comp) {
}
//--- code from common area in template.
private static final SIcon BLIND_ICON = new SResourceIcon("org/wings/icons/blind.gif");
//--- end code from common area in template.
public void writeContent(final Device device,
final SComponent _c)
throws IOException {
final SProgressBar component = (SProgressBar) _c;
//--- code from write-template.
String style = component.getStyle();
SDimension size = component.getPreferredSize();
int width = size != null ? size.getIntWidth() : 200;
int height = size != null ? size.getIntHeight() : 5;
if (component.isStringPainted()) {
device.print("<table><tr><td>");
}
if (component.isBorderPainted()) {
device.print("<table cellpadding=\"1\"><tr><td");
Utils.optAttribute(device, "bgcolor", component.getBorderColor());
device.print(">");
}
device.print("<table>");
device.print("<tr>");
device.print("<td");
- Utils.optAttribute(device, "bgcolor", component.getFilledColor());
+ //Utils.optAttribute(device, "bgcolor", component.getFilledColor());
+ if (component.getFilledColor() != null) {
+ device.print(" style=\"background-color: ");
+ Utils.write(device, component.getFilledColor());
+ device.print(";\"");
+ }
device.print(">");
device.print("<img");
Utils.optAttribute(device, "src", BLIND_ICON.getURL());
device.print(" width=\"");
device.print(String.valueOf(width * component.getPercentComplete()));
device.print("\"");
device.print(" height=\"");
device.print(String.valueOf(height));
device.print("\"></td>");
device.print("<td");
- Utils.optAttribute(device, "bgcolor", component.getUnfilledColor());
+ //Utils.optAttribute(device, "bgcolor", component.getUnfilledColor());
+ if (component.getUnfilledColor() != null) {
+ device.print(" style=\"background-color: ");
+ Utils.write(device, component.getUnfilledColor());
+ device.print(";\"");
+ }
device.print(">");
device.print("<img");
Utils.optAttribute(device, "src", BLIND_ICON.getURL());
device.print(" width=\"");
device.print(String.valueOf(width * (1 - component.getPercentComplete())));
device.print("\"");
device.print(" height=\"");
device.print(String.valueOf(height));
device.print("\">");
device.print("</td>");
device.print("</tr>");
device.print("</table>");
if (component.isBorderPainted()) {
device.print("</td></tr></table>");
}
if (component.isStringPainted()) {
device.print("</td></tr><tr><td align=\"center\">");
if (style != null) {
device.print("<span class=\"");
Utils.write(device, style);
device.print("\">");
}
Utils.write(device, component.getString());
if (style != null) {
device.print("</span>");
}
device.print("</td></tr></table>");
}
//--- end code from write-template.
}
}
| false | true | public void writeContent(final Device device,
final SComponent _c)
throws IOException {
final SProgressBar component = (SProgressBar) _c;
//--- code from write-template.
String style = component.getStyle();
SDimension size = component.getPreferredSize();
int width = size != null ? size.getIntWidth() : 200;
int height = size != null ? size.getIntHeight() : 5;
if (component.isStringPainted()) {
device.print("<table><tr><td>");
}
if (component.isBorderPainted()) {
device.print("<table cellpadding=\"1\"><tr><td");
Utils.optAttribute(device, "bgcolor", component.getBorderColor());
device.print(">");
}
device.print("<table>");
device.print("<tr>");
device.print("<td");
Utils.optAttribute(device, "bgcolor", component.getFilledColor());
device.print(">");
device.print("<img");
Utils.optAttribute(device, "src", BLIND_ICON.getURL());
device.print(" width=\"");
device.print(String.valueOf(width * component.getPercentComplete()));
device.print("\"");
device.print(" height=\"");
device.print(String.valueOf(height));
device.print("\"></td>");
device.print("<td");
Utils.optAttribute(device, "bgcolor", component.getUnfilledColor());
device.print(">");
device.print("<img");
Utils.optAttribute(device, "src", BLIND_ICON.getURL());
device.print(" width=\"");
device.print(String.valueOf(width * (1 - component.getPercentComplete())));
device.print("\"");
device.print(" height=\"");
device.print(String.valueOf(height));
device.print("\">");
device.print("</td>");
device.print("</tr>");
device.print("</table>");
if (component.isBorderPainted()) {
device.print("</td></tr></table>");
}
if (component.isStringPainted()) {
device.print("</td></tr><tr><td align=\"center\">");
if (style != null) {
device.print("<span class=\"");
Utils.write(device, style);
device.print("\">");
}
Utils.write(device, component.getString());
if (style != null) {
device.print("</span>");
}
device.print("</td></tr></table>");
}
//--- end code from write-template.
}
| public void writeContent(final Device device,
final SComponent _c)
throws IOException {
final SProgressBar component = (SProgressBar) _c;
//--- code from write-template.
String style = component.getStyle();
SDimension size = component.getPreferredSize();
int width = size != null ? size.getIntWidth() : 200;
int height = size != null ? size.getIntHeight() : 5;
if (component.isStringPainted()) {
device.print("<table><tr><td>");
}
if (component.isBorderPainted()) {
device.print("<table cellpadding=\"1\"><tr><td");
Utils.optAttribute(device, "bgcolor", component.getBorderColor());
device.print(">");
}
device.print("<table>");
device.print("<tr>");
device.print("<td");
//Utils.optAttribute(device, "bgcolor", component.getFilledColor());
if (component.getFilledColor() != null) {
device.print(" style=\"background-color: ");
Utils.write(device, component.getFilledColor());
device.print(";\"");
}
device.print(">");
device.print("<img");
Utils.optAttribute(device, "src", BLIND_ICON.getURL());
device.print(" width=\"");
device.print(String.valueOf(width * component.getPercentComplete()));
device.print("\"");
device.print(" height=\"");
device.print(String.valueOf(height));
device.print("\"></td>");
device.print("<td");
//Utils.optAttribute(device, "bgcolor", component.getUnfilledColor());
if (component.getUnfilledColor() != null) {
device.print(" style=\"background-color: ");
Utils.write(device, component.getUnfilledColor());
device.print(";\"");
}
device.print(">");
device.print("<img");
Utils.optAttribute(device, "src", BLIND_ICON.getURL());
device.print(" width=\"");
device.print(String.valueOf(width * (1 - component.getPercentComplete())));
device.print("\"");
device.print(" height=\"");
device.print(String.valueOf(height));
device.print("\">");
device.print("</td>");
device.print("</tr>");
device.print("</table>");
if (component.isBorderPainted()) {
device.print("</td></tr></table>");
}
if (component.isStringPainted()) {
device.print("</td></tr><tr><td align=\"center\">");
if (style != null) {
device.print("<span class=\"");
Utils.write(device, style);
device.print("\">");
}
Utils.write(device, component.getString());
if (style != null) {
device.print("</span>");
}
device.print("</td></tr></table>");
}
//--- end code from write-template.
}
|
diff --git a/blocks/sublima-app/src/main/java/com/computas/sublima/app/index/FreetextTriples.java b/blocks/sublima-app/src/main/java/com/computas/sublima/app/index/FreetextTriples.java
index 6957c920..d251eb0a 100644
--- a/blocks/sublima-app/src/main/java/com/computas/sublima/app/index/FreetextTriples.java
+++ b/blocks/sublima-app/src/main/java/com/computas/sublima/app/index/FreetextTriples.java
@@ -1,163 +1,163 @@
package com.computas.sublima.app.index;
import com.computas.sublima.app.service.URLActions;
import com.computas.sublima.query.impl.DefaultSparqlDispatcher;
import com.computas.sublima.query.service.MappingService;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.util.HashSet;
/**
* This class generates triples to be inserted for all resources that represent a media type.
* The triple, sub:literals, is a concatenation of all configured literals that will make up
* the content of which we do freetext search against in Mediasone.
* <p/>
* The class uses a configured SPARQL/SPARUL end point to perform all getting and inserting of data.
*
* @author: mha
* Date: 03.des.2008
*/
public class FreetextTriples {
private DefaultSparqlDispatcher sparqlQuery = new DefaultSparqlDispatcher();
private GenerateUtils gu = new GenerateUtils();
private MappingService ms = new MappingService();
public FreetextTriples() {
}
/**
* This method takes the resource URI as input and returns a String representation of the sub:literals triple
* to be inserted in the graph.
*
* @param uri String representation of the URI for the resource to generate sub:literals for
* @param searchableProperties A string array with the properties to index
* @param prefixes A string array with the prefixes for the properties to index
* @param graphs graphname
* @return String with sub:literals N3-triple
*/
public String generateFreetextTripleForURI(String uri, String[] searchableProperties, String[] prefixes, String[] graphs, boolean indexExternalContent) {
if (!uri.startsWith("<") && !uri.endsWith(">")) {
uri = "<" + uri + ">";
}
String concatenatedSearchableText = getConcatenatedTextFromURI(uri, searchableProperties, prefixes, graphs);
if (indexExternalContent) {
String externalContent = getResourceExternalLiteralsAsString(uri);
return uri + " <http://xmlns.computas.com/sublima#literals> \"" + concatenatedSearchableText + "\" .\n" + uri + " <http://xmlns.computas.com/sublima#externalliterals> \"" + concatenatedSearchableText + " " + externalContent + "\" .\n";
} else {
return concatenatedSearchableText.isEmpty() ? null : uri + " <http://xmlns.computas.com/sublima#literals> \"" + concatenatedSearchableText + "\" .";
}
}
/**
* This method queries the end point and returns a concatenated String with the searchable text
*
* @param uri String representation of the URI for the resource to generate sub:literals for
* @param fieldsToIndex String array representation of the fields of the resource to query
* @param prefixes Prefixes
* @param graphs graphname
* @return String with contatenated text
*/
public String getConcatenatedTextFromURI(String uri, String[] fieldsToIndex, String[] prefixes, String[] graphs) {
if (!uri.startsWith("<") && !uri.endsWith(">")) {
uri = "<" + uri + ">";
}
String query = gu.createSelectQueryToGetFields(uri, fieldsToIndex, prefixes, graphs);
String xml = (String) sparqlQuery.query(query);
StringBuilder results = new StringBuilder();
HashSet<String> set = new HashSet<String>();
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
- XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//td");
+ XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//literal");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
// I use set here to avoid getting the same results over and over. Seems like the query gives me a result that is repeated per n(Agent)
// todo Check the SPARQL with Kjetil or David to check if we can get rid of the repeating results
for (int i = 0; i < nodes.getLength(); i++) {
if (!nodes.item(i).getTextContent().trim().isEmpty()) {
set.add(nodes.item(i).getTextContent().trim());
}
}
for (String text : set) {
results.append(ms.charactermapping(text)).append(". ");
}
} catch (Exception e) {
System.out.println("Could not get concatenated text of URI from XML result");
e.printStackTrace();
}
return escapeString(results.toString());
}
/**
* Method to get the external content as an triple for a specific resource including the internal literals
*
* @param uri
* @return a String ie. "<http://theresource.net> sub:externalliterals """ This is the resource . net external content including internal content""""
*/
public String getResourceExternalLiteralsAsString(String uri) {
StringBuilder externalContent = new StringBuilder();
URLActions urlAction = new URLActions(uri);
String code = urlAction.getCode();
if ("302".equals(code) ||
"303".equals(code) ||
"304".equals(code) ||
"305".equals(code) ||
"307".equals(code) ||
code.startsWith("2")) {
try {
externalContent.append(urlAction.strippedContent(null).replace("\\", "\\\\"));
} catch (Exception e) {
System.out.println(e);
}
}
return escapeString(externalContent.toString());
}
private String escapeString(String s) {
StringBuilder sb = new StringBuilder();
int i;
char c;
for (i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (c >= 32 && c <= 127) { //<http://www.w3.org/2001/sw/RDFCore/ntriples/#character>
if (c == 92 || c == 34 || c == 10 || c == 13 || c == 9) { //<http://www.w3.org/2001/sw/RDFCore/ntriples/#sec-string1>
sb.append('\\');
sb.append(c);
} else {
sb.append(c);
}
} else {
String hexstr = Integer.toHexString(c).toUpperCase();
int pad = 4 - hexstr.length();
sb.append("\\u");
for (; pad > 0; pad--)
sb.append('0');
sb.append(hexstr);
}
}
return sb.toString();
}
}
| true | true | public String getConcatenatedTextFromURI(String uri, String[] fieldsToIndex, String[] prefixes, String[] graphs) {
if (!uri.startsWith("<") && !uri.endsWith(">")) {
uri = "<" + uri + ">";
}
String query = gu.createSelectQueryToGetFields(uri, fieldsToIndex, prefixes, graphs);
String xml = (String) sparqlQuery.query(query);
StringBuilder results = new StringBuilder();
HashSet<String> set = new HashSet<String>();
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//td");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
// I use set here to avoid getting the same results over and over. Seems like the query gives me a result that is repeated per n(Agent)
// todo Check the SPARQL with Kjetil or David to check if we can get rid of the repeating results
for (int i = 0; i < nodes.getLength(); i++) {
if (!nodes.item(i).getTextContent().trim().isEmpty()) {
set.add(nodes.item(i).getTextContent().trim());
}
}
for (String text : set) {
results.append(ms.charactermapping(text)).append(". ");
}
} catch (Exception e) {
System.out.println("Could not get concatenated text of URI from XML result");
e.printStackTrace();
}
return escapeString(results.toString());
}
| public String getConcatenatedTextFromURI(String uri, String[] fieldsToIndex, String[] prefixes, String[] graphs) {
if (!uri.startsWith("<") && !uri.endsWith(">")) {
uri = "<" + uri + ">";
}
String query = gu.createSelectQueryToGetFields(uri, fieldsToIndex, prefixes, graphs);
String xml = (String) sparqlQuery.query(query);
StringBuilder results = new StringBuilder();
HashSet<String> set = new HashSet<String>();
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//literal");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
// I use set here to avoid getting the same results over and over. Seems like the query gives me a result that is repeated per n(Agent)
// todo Check the SPARQL with Kjetil or David to check if we can get rid of the repeating results
for (int i = 0; i < nodes.getLength(); i++) {
if (!nodes.item(i).getTextContent().trim().isEmpty()) {
set.add(nodes.item(i).getTextContent().trim());
}
}
for (String text : set) {
results.append(ms.charactermapping(text)).append(". ");
}
} catch (Exception e) {
System.out.println("Could not get concatenated text of URI from XML result");
e.printStackTrace();
}
return escapeString(results.toString());
}
|
diff --git a/src/de/enough/glaze/style/definition/converter/background/LayerBackgroundConverter.java b/src/de/enough/glaze/style/definition/converter/background/LayerBackgroundConverter.java
index 29cceb6..e853711 100644
--- a/src/de/enough/glaze/style/definition/converter/background/LayerBackgroundConverter.java
+++ b/src/de/enough/glaze/style/definition/converter/background/LayerBackgroundConverter.java
@@ -1,142 +1,143 @@
package de.enough.glaze.style.definition.converter.background;
import de.enough.glaze.style.Dimension;
import de.enough.glaze.style.StyleSheet;
import de.enough.glaze.style.background.GzBackground;
import de.enough.glaze.style.background.GzBackgroundFactory;
import de.enough.glaze.style.definition.Definition;
import de.enough.glaze.style.definition.StyleSheetDefinition;
import de.enough.glaze.style.definition.converter.BackgroundConverter;
import de.enough.glaze.style.definition.converter.Converter;
import de.enough.glaze.style.parser.exception.CssSyntaxError;
import de.enough.glaze.style.parser.property.DimensionPropertyParser;
import de.enough.glaze.style.parser.property.Property;
import de.enough.glaze.style.parser.property.ValuePropertyParser;
public class LayerBackgroundConverter implements Converter {
/**
* the instance
*/
private static LayerBackgroundConverter INSTANCE;
/**
* Returns the instance
*
* @return the instance
*/
public static LayerBackgroundConverter getInstance() {
if (INSTANCE == null) {
INSTANCE = new LayerBackgroundConverter();
}
return INSTANCE;
}
/*
* (non-Javadoc)
*
* @see de.enough.glaze.style.definition.converter.Converter#getIds()
*/
public String[] getIds() {
return new String[] { "background-backgrounds", "background-margins" };
}
/*
* (non-Javadoc)
*
* @see
* de.enough.glaze.style.definition.converter.Converter#convert(de.enough
* .glaze.style.definition.Definition)
*/
public Object convert(Definition definition) throws CssSyntaxError {
if (!definition.hasProperties(this)) {
return null;
}
Property backgroundTypeProp = definition.getProperty("background-type");
Property backgroundsProp = definition
.getProperty("background-backgrounds");
Property backgroundMarginsProp = definition
.getProperty("background-margins");
GzBackground[] backgrounds = null;
Dimension[] margins = null;
if (backgroundsProp != null) {
Object result = ValuePropertyParser.getInstance().parse(
backgroundsProp);
if (result instanceof String) {
String backgroundId = (String) result;
GzBackground background = getBackground(backgroundId);
if (background != null) {
backgrounds = new GzBackground[] { background };
} else {
throw new CssSyntaxError("unable to resolve background",
- backgroundId);
+ backgroundId, backgroundsProp.getLine());
}
} else if (result instanceof String[]) {
String[] backgroundIds = (String[]) result;
backgrounds = new GzBackground[backgroundIds.length];
for (int index = 0; index < backgroundIds.length; index++) {
String backgroundId = backgroundIds[index];
GzBackground background = getBackground(backgroundId);
if (background != null) {
backgrounds[index] = background;
} else {
throw new CssSyntaxError(
- "unable to resolve background", backgroundId);
+ "unable to resolve background", backgroundId,
+ backgroundsProp.getLine());
}
}
}
}
if (backgroundMarginsProp != null) {
Object result = DimensionPropertyParser.getInstance().parse(
backgroundMarginsProp);
if (result instanceof Dimension) {
Dimension dimension = (Dimension) result;
if (backgrounds.length == 1) {
margins = new Dimension[] { dimension };
} else {
throw new CssSyntaxError(
"the number of margins must match the number of backgrounds",
backgroundMarginsProp);
}
} else if (result instanceof Dimension[]) {
Dimension[] dimensions = (Dimension[]) result;
if (backgrounds.length == dimensions.length) {
margins = dimensions;
} else {
throw new CssSyntaxError(
"the number of margins must match the number of backgrounds",
backgroundMarginsProp);
}
}
}
if (backgrounds != null && margins != null) {
return GzBackgroundFactory.createLayerBackground(backgrounds,
margins);
} else {
throw new CssSyntaxError(
"unable to create layer background, properties are missing",
backgroundTypeProp);
}
}
public GzBackground getBackground(String id) throws CssSyntaxError {
GzBackground background = StyleSheet.getInstance().getBackground(id);
if (background == null) {
StyleSheetDefinition styleSheetDefinition = StyleSheet
.getInstance().getDefinition();
Definition backgroundDefinition = styleSheetDefinition
.getBackgroundDefinition(id);
background = (GzBackground) BackgroundConverter.getInstance()
.convert(backgroundDefinition);
}
return background;
}
}
| false | true | public Object convert(Definition definition) throws CssSyntaxError {
if (!definition.hasProperties(this)) {
return null;
}
Property backgroundTypeProp = definition.getProperty("background-type");
Property backgroundsProp = definition
.getProperty("background-backgrounds");
Property backgroundMarginsProp = definition
.getProperty("background-margins");
GzBackground[] backgrounds = null;
Dimension[] margins = null;
if (backgroundsProp != null) {
Object result = ValuePropertyParser.getInstance().parse(
backgroundsProp);
if (result instanceof String) {
String backgroundId = (String) result;
GzBackground background = getBackground(backgroundId);
if (background != null) {
backgrounds = new GzBackground[] { background };
} else {
throw new CssSyntaxError("unable to resolve background",
backgroundId);
}
} else if (result instanceof String[]) {
String[] backgroundIds = (String[]) result;
backgrounds = new GzBackground[backgroundIds.length];
for (int index = 0; index < backgroundIds.length; index++) {
String backgroundId = backgroundIds[index];
GzBackground background = getBackground(backgroundId);
if (background != null) {
backgrounds[index] = background;
} else {
throw new CssSyntaxError(
"unable to resolve background", backgroundId);
}
}
}
}
if (backgroundMarginsProp != null) {
Object result = DimensionPropertyParser.getInstance().parse(
backgroundMarginsProp);
if (result instanceof Dimension) {
Dimension dimension = (Dimension) result;
if (backgrounds.length == 1) {
margins = new Dimension[] { dimension };
} else {
throw new CssSyntaxError(
"the number of margins must match the number of backgrounds",
backgroundMarginsProp);
}
} else if (result instanceof Dimension[]) {
Dimension[] dimensions = (Dimension[]) result;
if (backgrounds.length == dimensions.length) {
margins = dimensions;
} else {
throw new CssSyntaxError(
"the number of margins must match the number of backgrounds",
backgroundMarginsProp);
}
}
}
if (backgrounds != null && margins != null) {
return GzBackgroundFactory.createLayerBackground(backgrounds,
margins);
} else {
throw new CssSyntaxError(
"unable to create layer background, properties are missing",
backgroundTypeProp);
}
}
| public Object convert(Definition definition) throws CssSyntaxError {
if (!definition.hasProperties(this)) {
return null;
}
Property backgroundTypeProp = definition.getProperty("background-type");
Property backgroundsProp = definition
.getProperty("background-backgrounds");
Property backgroundMarginsProp = definition
.getProperty("background-margins");
GzBackground[] backgrounds = null;
Dimension[] margins = null;
if (backgroundsProp != null) {
Object result = ValuePropertyParser.getInstance().parse(
backgroundsProp);
if (result instanceof String) {
String backgroundId = (String) result;
GzBackground background = getBackground(backgroundId);
if (background != null) {
backgrounds = new GzBackground[] { background };
} else {
throw new CssSyntaxError("unable to resolve background",
backgroundId, backgroundsProp.getLine());
}
} else if (result instanceof String[]) {
String[] backgroundIds = (String[]) result;
backgrounds = new GzBackground[backgroundIds.length];
for (int index = 0; index < backgroundIds.length; index++) {
String backgroundId = backgroundIds[index];
GzBackground background = getBackground(backgroundId);
if (background != null) {
backgrounds[index] = background;
} else {
throw new CssSyntaxError(
"unable to resolve background", backgroundId,
backgroundsProp.getLine());
}
}
}
}
if (backgroundMarginsProp != null) {
Object result = DimensionPropertyParser.getInstance().parse(
backgroundMarginsProp);
if (result instanceof Dimension) {
Dimension dimension = (Dimension) result;
if (backgrounds.length == 1) {
margins = new Dimension[] { dimension };
} else {
throw new CssSyntaxError(
"the number of margins must match the number of backgrounds",
backgroundMarginsProp);
}
} else if (result instanceof Dimension[]) {
Dimension[] dimensions = (Dimension[]) result;
if (backgrounds.length == dimensions.length) {
margins = dimensions;
} else {
throw new CssSyntaxError(
"the number of margins must match the number of backgrounds",
backgroundMarginsProp);
}
}
}
if (backgrounds != null && margins != null) {
return GzBackgroundFactory.createLayerBackground(backgrounds,
margins);
} else {
throw new CssSyntaxError(
"unable to create layer background, properties are missing",
backgroundTypeProp);
}
}
|
diff --git a/smali/src/test/java/LexerTest.java b/smali/src/test/java/LexerTest.java
index ed28280..5afc2e2 100644
--- a/smali/src/test/java/LexerTest.java
+++ b/smali/src/test/java/LexerTest.java
@@ -1,212 +1,212 @@
/*
* [The "BSD licence"]
* Copyright (c) 2010 Ben Gruver
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CommonToken;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.jf.dexlib.Util.Utf8Utils;
import org.jf.smali.*;
import static org.jf.smali.expectedTokensTestGrammarParser.ExpectedToken;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
import java.util.HashMap;
import java.util.List;
public class LexerTest {
private static final HashMap<String, Integer> tokenTypesByName;
static {
tokenTypesByName = new HashMap<String, Integer>();
for (int i=0; i<smaliParser.tokenNames.length; i++) {
tokenTypesByName.put(smaliParser.tokenNames[i], i);
}
}
@Test
public void DirectiveTest() {
runTest("DirectiveTest");
}
@Test
public void ByteLiteralTest() {
runTest("ByteLiteralTest");
}
@Test
public void ShortLiteralTest() {
runTest("ShortLiteralTest");
}
@Test
public void IntegerLiteralTest() {
runTest("IntegerLiteralTest");
}
@Test
public void LongLiteralTest() {
runTest("LongLiteralTest");
}
@Test
public void FloatLiteralTest() {
runTest("FloatLiteralTest");
}
@Test
public void CharLiteralTest() {
runTest("CharLiteralTest");
}
@Test
public void StringLiteralTest() {
runTest("StringLiteralTest");
}
@Test
public void MiscTest() {
runTest("MiscTest");
}
@Test
public void CommentTest() {
runTest("CommentTest", false);
}
@Test
public void InstructionTest() {
runTest("InstructionTest", true);
}
@Test
public void TypeAndIdentifierTest() {
runTest("TypeAndIdentifierTest");
}
@Test
public void SymbolTest() {
runTest("SymbolTest", false);
}
@Test
public void RealSmaliFileTest() {
runTest("RealSmaliFileTest", true);
}
public void runTest(String test) {
runTest(test, true);
}
public void runTest(String test, boolean discardHiddenTokens) {
String smaliFile = String.format("LexerTest%s%s.smali", File.separatorChar, test);
String tokensFile = String.format("LexerTest%s%s.tokens", File.separatorChar, test);
expectedTokensTestGrammarLexer expectedTokensLexer = null;
try {
expectedTokensLexer = new expectedTokensTestGrammarLexer(new ANTLRInputStream(
LexerTest.class.getClassLoader().getResourceAsStream(tokensFile)));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
CommonTokenStream expectedTokensStream = new CommonTokenStream(expectedTokensLexer);
expectedTokensTestGrammarParser expectedTokensParser =
new expectedTokensTestGrammarParser(expectedTokensStream);
try {
expectedTokensParser.top();
} catch (RecognitionException ex) {
throw new RuntimeException(ex);
}
List<ExpectedToken> expectedTokens = expectedTokensParser.getExpectedTokens();
InputStream smaliStream = LexerTest.class.getClassLoader().getResourceAsStream(smaliFile);
if (smaliStream == null) {
Assert.fail("Could not load " + smaliFile);
}
smaliFlexLexer lexer = new smaliFlexLexer(smaliStream);
lexer.setSourceFile(new File(test + ".smali"));
lexer.setSuppressErrors(true);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
List tokens = tokenStream.getTokens();
int expectedTokenIndex = 0;
CommonToken token;
for (int i=0; i<tokens.size(); i++) {
token = (CommonToken)tokens.get(i);
if (discardHiddenTokens && token.getChannel() == smaliLexer.HIDDEN) {
continue;
}
if (expectedTokenIndex >= expectedTokens.size()) {
Assert.fail("Too many tokens");
}
if (token.getType() == smaliParser.INVALID_TOKEN) {
Assert.assertTrue("Encountered an INVALID_TOKEN not on the error channel",
token.getChannel() == smaliLexer.ERROR_CHANNEL);
}
ExpectedToken expectedToken = expectedTokens.get(expectedTokenIndex++);
if (!tokenTypesByName.containsKey(expectedToken.tokenName)) {
Assert.fail("Unknown token: " + expectedToken.tokenName);
}
int expectedTokenType = tokenTypesByName.get(expectedToken.tokenName);
if (token.getType() != expectedTokenType) {
- Assert.fail(String.format("Invalid token at index %d. Expecting %s, got %s",
- expectedTokenIndex-1, expectedToken.tokenName, getTokenName(token.getType())));
+ Assert.fail(String.format("Invalid token at index %d. Expecting %s, got %s(%s)",
+ expectedTokenIndex-1, expectedToken.tokenName, getTokenName(token.getType()), token.getText()));
}
if (expectedToken.tokenText != null) {
if (!expectedToken.tokenText.equals(token.getText())) {
Assert.fail(
String.format("Invalid token text at index %d. Expecting text \"%s\", got \"%s\"",
expectedTokenIndex - 1, expectedToken.tokenText, token.getText()));
}
}
}
if (expectedTokenIndex < expectedTokens.size()) {
Assert.fail(String.format("Not enough tokens. Expecting %d tokens, but got %d", expectedTokens.size(),
expectedTokenIndex));
}
}
private static String getTokenName(int tokenType) {
return smaliParser.tokenNames[tokenType];
}
}
| true | true | public void runTest(String test, boolean discardHiddenTokens) {
String smaliFile = String.format("LexerTest%s%s.smali", File.separatorChar, test);
String tokensFile = String.format("LexerTest%s%s.tokens", File.separatorChar, test);
expectedTokensTestGrammarLexer expectedTokensLexer = null;
try {
expectedTokensLexer = new expectedTokensTestGrammarLexer(new ANTLRInputStream(
LexerTest.class.getClassLoader().getResourceAsStream(tokensFile)));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
CommonTokenStream expectedTokensStream = new CommonTokenStream(expectedTokensLexer);
expectedTokensTestGrammarParser expectedTokensParser =
new expectedTokensTestGrammarParser(expectedTokensStream);
try {
expectedTokensParser.top();
} catch (RecognitionException ex) {
throw new RuntimeException(ex);
}
List<ExpectedToken> expectedTokens = expectedTokensParser.getExpectedTokens();
InputStream smaliStream = LexerTest.class.getClassLoader().getResourceAsStream(smaliFile);
if (smaliStream == null) {
Assert.fail("Could not load " + smaliFile);
}
smaliFlexLexer lexer = new smaliFlexLexer(smaliStream);
lexer.setSourceFile(new File(test + ".smali"));
lexer.setSuppressErrors(true);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
List tokens = tokenStream.getTokens();
int expectedTokenIndex = 0;
CommonToken token;
for (int i=0; i<tokens.size(); i++) {
token = (CommonToken)tokens.get(i);
if (discardHiddenTokens && token.getChannel() == smaliLexer.HIDDEN) {
continue;
}
if (expectedTokenIndex >= expectedTokens.size()) {
Assert.fail("Too many tokens");
}
if (token.getType() == smaliParser.INVALID_TOKEN) {
Assert.assertTrue("Encountered an INVALID_TOKEN not on the error channel",
token.getChannel() == smaliLexer.ERROR_CHANNEL);
}
ExpectedToken expectedToken = expectedTokens.get(expectedTokenIndex++);
if (!tokenTypesByName.containsKey(expectedToken.tokenName)) {
Assert.fail("Unknown token: " + expectedToken.tokenName);
}
int expectedTokenType = tokenTypesByName.get(expectedToken.tokenName);
if (token.getType() != expectedTokenType) {
Assert.fail(String.format("Invalid token at index %d. Expecting %s, got %s",
expectedTokenIndex-1, expectedToken.tokenName, getTokenName(token.getType())));
}
if (expectedToken.tokenText != null) {
if (!expectedToken.tokenText.equals(token.getText())) {
Assert.fail(
String.format("Invalid token text at index %d. Expecting text \"%s\", got \"%s\"",
expectedTokenIndex - 1, expectedToken.tokenText, token.getText()));
}
}
}
if (expectedTokenIndex < expectedTokens.size()) {
Assert.fail(String.format("Not enough tokens. Expecting %d tokens, but got %d", expectedTokens.size(),
expectedTokenIndex));
}
}
| public void runTest(String test, boolean discardHiddenTokens) {
String smaliFile = String.format("LexerTest%s%s.smali", File.separatorChar, test);
String tokensFile = String.format("LexerTest%s%s.tokens", File.separatorChar, test);
expectedTokensTestGrammarLexer expectedTokensLexer = null;
try {
expectedTokensLexer = new expectedTokensTestGrammarLexer(new ANTLRInputStream(
LexerTest.class.getClassLoader().getResourceAsStream(tokensFile)));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
CommonTokenStream expectedTokensStream = new CommonTokenStream(expectedTokensLexer);
expectedTokensTestGrammarParser expectedTokensParser =
new expectedTokensTestGrammarParser(expectedTokensStream);
try {
expectedTokensParser.top();
} catch (RecognitionException ex) {
throw new RuntimeException(ex);
}
List<ExpectedToken> expectedTokens = expectedTokensParser.getExpectedTokens();
InputStream smaliStream = LexerTest.class.getClassLoader().getResourceAsStream(smaliFile);
if (smaliStream == null) {
Assert.fail("Could not load " + smaliFile);
}
smaliFlexLexer lexer = new smaliFlexLexer(smaliStream);
lexer.setSourceFile(new File(test + ".smali"));
lexer.setSuppressErrors(true);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
List tokens = tokenStream.getTokens();
int expectedTokenIndex = 0;
CommonToken token;
for (int i=0; i<tokens.size(); i++) {
token = (CommonToken)tokens.get(i);
if (discardHiddenTokens && token.getChannel() == smaliLexer.HIDDEN) {
continue;
}
if (expectedTokenIndex >= expectedTokens.size()) {
Assert.fail("Too many tokens");
}
if (token.getType() == smaliParser.INVALID_TOKEN) {
Assert.assertTrue("Encountered an INVALID_TOKEN not on the error channel",
token.getChannel() == smaliLexer.ERROR_CHANNEL);
}
ExpectedToken expectedToken = expectedTokens.get(expectedTokenIndex++);
if (!tokenTypesByName.containsKey(expectedToken.tokenName)) {
Assert.fail("Unknown token: " + expectedToken.tokenName);
}
int expectedTokenType = tokenTypesByName.get(expectedToken.tokenName);
if (token.getType() != expectedTokenType) {
Assert.fail(String.format("Invalid token at index %d. Expecting %s, got %s(%s)",
expectedTokenIndex-1, expectedToken.tokenName, getTokenName(token.getType()), token.getText()));
}
if (expectedToken.tokenText != null) {
if (!expectedToken.tokenText.equals(token.getText())) {
Assert.fail(
String.format("Invalid token text at index %d. Expecting text \"%s\", got \"%s\"",
expectedTokenIndex - 1, expectedToken.tokenText, token.getText()));
}
}
}
if (expectedTokenIndex < expectedTokens.size()) {
Assert.fail(String.format("Not enough tokens. Expecting %d tokens, but got %d", expectedTokens.size(),
expectedTokenIndex));
}
}
|
diff --git a/class23_homework/A-Denis-Kalfov-10/src/org/elsys/homework_23/Main.java b/class23_homework/A-Denis-Kalfov-10/src/org/elsys/homework_23/Main.java
index 1d92a80..7eccb98 100644
--- a/class23_homework/A-Denis-Kalfov-10/src/org/elsys/homework_23/Main.java
+++ b/class23_homework/A-Denis-Kalfov-10/src/org/elsys/homework_23/Main.java
@@ -1,97 +1,97 @@
package org.elsys.homework_23;
import java.io.IOException;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
int seat_num=0;
int[] one_TwoTogether;
one_TwoTogether = new int[300];
int index=1;
int all=0;
int info=0;
int alone=0;
int seatNum_alone_cp=0;
int placeOnlyFor_1=0;
int placeOnlyFor_1SeatNum=0;
for (;all<=162;){
- System.in.read();
seat_num+=1;
ArrayList<Integer> l = new ArrayList<Integer>();
Passengers newPassenger = new Passengers();
int countOfPassengers=0;
if (newPassenger.passengers==2){
countOfPassengers+=2;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==3){
countOfPassengers+=3;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==1){
countOfPassengers++;
l.add(newPassenger.passengers);
}
if (countOfPassengers==3) {
System.out.println("seat N: "+(seat_num)+" "+(seat_num+1)+" "+(seat_num+2));
seat_num=seat_num+2;
}else if (countOfPassengers==2){
System.out.println("seat N: "+seat_num+" "+ (seat_num+1));
info++;
if (info>0){
index+=1;
one_TwoTogether[index]=seat_num+2;
}
seat_num=seat_num+2;
}else if (countOfPassengers==1){
if (alone==1){
System.out.println("seat N: "+(seatNum_alone_cp+1));
alone=0;
placeOnlyFor_1++;
placeOnlyFor_1SeatNum=seatNum_alone_cp+2;
seat_num-=1;
} else if (info==0 && placeOnlyFor_1!=1){
System.out.println("seat N: "+seat_num);
seatNum_alone_cp=seat_num;
alone++;
seat_num+=2;
} else if (info>0){
System.out.println("seat N: "+one_TwoTogether[index]);
index--;
info--;
seat_num-=1;
} else if (placeOnlyFor_1==1){
System.out.println("seat N: "+placeOnlyFor_1SeatNum);
placeOnlyFor_1--;
seat_num-=1;
}
}
System.out.println(l+"\n");
+ System.in.read();
if (seat_num>=162){
break;
}
}
System.out.println("Free seats: "+((alone*2)+info+placeOnlyFor_1));
} }
| false | true | public static void main(String[] args) throws IOException {
int seat_num=0;
int[] one_TwoTogether;
one_TwoTogether = new int[300];
int index=1;
int all=0;
int info=0;
int alone=0;
int seatNum_alone_cp=0;
int placeOnlyFor_1=0;
int placeOnlyFor_1SeatNum=0;
for (;all<=162;){
System.in.read();
seat_num+=1;
ArrayList<Integer> l = new ArrayList<Integer>();
Passengers newPassenger = new Passengers();
int countOfPassengers=0;
if (newPassenger.passengers==2){
countOfPassengers+=2;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==3){
countOfPassengers+=3;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==1){
countOfPassengers++;
l.add(newPassenger.passengers);
}
if (countOfPassengers==3) {
System.out.println("seat N: "+(seat_num)+" "+(seat_num+1)+" "+(seat_num+2));
seat_num=seat_num+2;
}else if (countOfPassengers==2){
System.out.println("seat N: "+seat_num+" "+ (seat_num+1));
info++;
if (info>0){
index+=1;
one_TwoTogether[index]=seat_num+2;
}
seat_num=seat_num+2;
}else if (countOfPassengers==1){
if (alone==1){
System.out.println("seat N: "+(seatNum_alone_cp+1));
alone=0;
placeOnlyFor_1++;
placeOnlyFor_1SeatNum=seatNum_alone_cp+2;
seat_num-=1;
} else if (info==0 && placeOnlyFor_1!=1){
System.out.println("seat N: "+seat_num);
seatNum_alone_cp=seat_num;
alone++;
seat_num+=2;
} else if (info>0){
System.out.println("seat N: "+one_TwoTogether[index]);
index--;
info--;
seat_num-=1;
} else if (placeOnlyFor_1==1){
System.out.println("seat N: "+placeOnlyFor_1SeatNum);
placeOnlyFor_1--;
seat_num-=1;
}
}
System.out.println(l+"\n");
if (seat_num>=162){
break;
}
}
System.out.println("Free seats: "+((alone*2)+info+placeOnlyFor_1));
} }
| public static void main(String[] args) throws IOException {
int seat_num=0;
int[] one_TwoTogether;
one_TwoTogether = new int[300];
int index=1;
int all=0;
int info=0;
int alone=0;
int seatNum_alone_cp=0;
int placeOnlyFor_1=0;
int placeOnlyFor_1SeatNum=0;
for (;all<=162;){
seat_num+=1;
ArrayList<Integer> l = new ArrayList<Integer>();
Passengers newPassenger = new Passengers();
int countOfPassengers=0;
if (newPassenger.passengers==2){
countOfPassengers+=2;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==3){
countOfPassengers+=3;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==1){
countOfPassengers++;
l.add(newPassenger.passengers);
}
if (countOfPassengers==3) {
System.out.println("seat N: "+(seat_num)+" "+(seat_num+1)+" "+(seat_num+2));
seat_num=seat_num+2;
}else if (countOfPassengers==2){
System.out.println("seat N: "+seat_num+" "+ (seat_num+1));
info++;
if (info>0){
index+=1;
one_TwoTogether[index]=seat_num+2;
}
seat_num=seat_num+2;
}else if (countOfPassengers==1){
if (alone==1){
System.out.println("seat N: "+(seatNum_alone_cp+1));
alone=0;
placeOnlyFor_1++;
placeOnlyFor_1SeatNum=seatNum_alone_cp+2;
seat_num-=1;
} else if (info==0 && placeOnlyFor_1!=1){
System.out.println("seat N: "+seat_num);
seatNum_alone_cp=seat_num;
alone++;
seat_num+=2;
} else if (info>0){
System.out.println("seat N: "+one_TwoTogether[index]);
index--;
info--;
seat_num-=1;
} else if (placeOnlyFor_1==1){
System.out.println("seat N: "+placeOnlyFor_1SeatNum);
placeOnlyFor_1--;
seat_num-=1;
}
}
System.out.println(l+"\n");
System.in.read();
if (seat_num>=162){
break;
}
}
System.out.println("Free seats: "+((alone*2)+info+placeOnlyFor_1));
} }
|
diff --git a/src/com/android/mms/ui/ConversationHeaderView.java b/src/com/android/mms/ui/ConversationHeaderView.java
index 4bd0c75..054637c 100644
--- a/src/com/android/mms/ui/ConversationHeaderView.java
+++ b/src/com/android/mms/ui/ConversationHeaderView.java
@@ -1,248 +1,248 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.ui;
import java.util.List;
import com.android.mms.R;
import com.android.mms.data.Contact;
import com.android.mms.data.ContactList;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.provider.ContactsContract.Intents;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.TextAppearanceSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.QuickContactBadge;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* This class manages the view for given conversation.
*/
public class ConversationHeaderView extends RelativeLayout implements Contact.UpdateListener {
private static final String TAG = "ConversationHeaderView";
private static final boolean DEBUG = false;
private TextView mSubjectView;
private TextView mFromView;
private TextView mDateView;
private View mAttachmentView;
private View mErrorIndicator;
private ImageView mPresenceView;
private QuickContactBadge mAvatarView;
static private Drawable sDefaultContactImage;
// For posting UI update Runnables from other threads:
private Handler mHandler = new Handler();
private ConversationHeader mConversationHeader;
private static final StyleSpan STYLE_BOLD = new StyleSpan(Typeface.BOLD);
public ConversationHeaderView(Context context) {
super(context);
}
public ConversationHeaderView(Context context, AttributeSet attrs) {
super(context, attrs);
if (sDefaultContactImage == null) {
sDefaultContactImage = context.getResources().getDrawable(R.drawable.ic_contact_picture);
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mFromView = (TextView) findViewById(R.id.from);
mSubjectView = (TextView) findViewById(R.id.subject);
mDateView = (TextView) findViewById(R.id.date);
mAttachmentView = findViewById(R.id.attachment);
mErrorIndicator = findViewById(R.id.error);
mPresenceView = (ImageView) findViewById(R.id.presence);
mAvatarView = (QuickContactBadge) findViewById(R.id.avatar);
}
public void setPresenceIcon(int iconId) {
if (iconId == 0) {
mPresenceView.setVisibility(View.GONE);
} else {
mPresenceView.setImageResource(iconId);
mPresenceView.setVisibility(View.VISIBLE);
}
}
public ConversationHeader getConversationHeader() {
return mConversationHeader;
}
private void setConversationHeader(ConversationHeader header) {
mConversationHeader = header;
}
/**
* Only used for header binding.
*/
public void bind(String title, String explain) {
mFromView.setText(title);
mSubjectView.setText(explain);
}
private CharSequence formatMessage(ConversationHeader ch) {
final int size = android.R.style.TextAppearance_Small;
final int color = android.R.styleable.Theme_textColorSecondary;
String from = ch.getFrom();
SpannableStringBuilder buf = new SpannableStringBuilder(from);
if (ch.getMessageCount() > 1) {
buf.append(" (" + ch.getMessageCount() + ") ");
}
int before = buf.length();
if (ch.hasDraft()) {
buf.append(" ");
buf.append(mContext.getResources().getString(R.string.has_draft));
buf.setSpan(new TextAppearanceSpan(mContext, size, color), before,
buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
buf.setSpan(new ForegroundColorSpan(
mContext.getResources().getColor(R.drawable.text_color_red)),
before, buf.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
// Unread messages are shown in bold
if (!ch.isRead()) {
buf.setSpan(STYLE_BOLD, 0, buf.length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
return buf;
}
private void updateAvatarView() {
ConversationHeader ch = mConversationHeader;
Drawable avatarDrawable;
if (ch.getContacts().size() == 1) {
Contact contact = ch.getContacts().get(0);
avatarDrawable = contact.getAvatar(sDefaultContactImage);
if (contact.existsInDatabase()) {
mAvatarView.assignContactUri(contact.getUri());
} else {
mAvatarView.assignContactFromPhone(contact.getNumber(), true);
}
} else {
// TODO get a multiple recipients asset (or do something else)
avatarDrawable = sDefaultContactImage;
mAvatarView.assignContactUri(null);
}
mAvatarView.setImageDrawable(avatarDrawable);
mAvatarView.setVisibility(View.VISIBLE);
}
private void updateFromView() {
ConversationHeader ch = mConversationHeader;
ch.updateRecipients();
mFromView.setText(formatMessage(ch));
setPresenceIcon(ch.getContacts().getPresenceResId());
updateAvatarView();
}
public void onUpdate(Contact updated) {
mHandler.post(new Runnable() {
public void run() {
updateFromView();
}
});
}
public final void bind(Context context, final ConversationHeader ch) {
//if (DEBUG) Log.v(TAG, "bind()");
setConversationHeader(ch);
- int bgcolor = ch.isRead()?
- mContext.getResources().getColor(R.color.read_bgcolor) :
- mContext.getResources().getColor(R.color.unread_bgcolor);
+ Drawable background = ch.isRead()?
+ mContext.getResources().getDrawable(R.drawable.conversation_item_background_read) :
+ mContext.getResources().getDrawable(R.drawable.conversation_item_background_unread);
- setBackgroundColor(bgcolor);
+ setBackgroundDrawable(background);
LayoutParams attachmentLayout = (LayoutParams)mAttachmentView.getLayoutParams();
boolean hasError = ch.hasError();
// When there's an error icon, the attachment icon is left of the error icon.
// When there is not an error icon, the attachment icon is left of the date text.
// As far as I know, there's no way to specify that relationship in xml.
if (hasError) {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.error);
} else {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.date);
}
boolean hasAttachment = ch.hasAttachment();
mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE);
// Date
mDateView.setText(ch.getDate());
// From.
mFromView.setText(formatMessage(ch));
// Register for updates in changes of any of the contacts in this conversation.
ContactList contacts = ch.getContacts();
if (DEBUG) Log.v(TAG, "bind: contacts.addListeners " + this);
contacts.addListeners(this);
setPresenceIcon(contacts.getPresenceResId());
// Subject
mSubjectView.setText(ch.getSubject());
LayoutParams subjectLayout = (LayoutParams)mSubjectView.getLayoutParams();
// We have to make the subject left of whatever optional items are shown on the right.
subjectLayout.addRule(RelativeLayout.LEFT_OF, hasAttachment ? R.id.attachment :
(hasError ? R.id.error : R.id.date));
// Transmission error indicator.
mErrorIndicator.setVisibility(hasError ? VISIBLE : GONE);
updateAvatarView();
}
public final void unbind() {
if (DEBUG) Log.v(TAG, "unbind: contacts.removeListeners " + this);
// Unregister contact update callbacks.
mConversationHeader.getContacts().removeListeners(this);
}
}
| false | true | public final void bind(Context context, final ConversationHeader ch) {
//if (DEBUG) Log.v(TAG, "bind()");
setConversationHeader(ch);
int bgcolor = ch.isRead()?
mContext.getResources().getColor(R.color.read_bgcolor) :
mContext.getResources().getColor(R.color.unread_bgcolor);
setBackgroundColor(bgcolor);
LayoutParams attachmentLayout = (LayoutParams)mAttachmentView.getLayoutParams();
boolean hasError = ch.hasError();
// When there's an error icon, the attachment icon is left of the error icon.
// When there is not an error icon, the attachment icon is left of the date text.
// As far as I know, there's no way to specify that relationship in xml.
if (hasError) {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.error);
} else {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.date);
}
boolean hasAttachment = ch.hasAttachment();
mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE);
// Date
mDateView.setText(ch.getDate());
// From.
mFromView.setText(formatMessage(ch));
// Register for updates in changes of any of the contacts in this conversation.
ContactList contacts = ch.getContacts();
if (DEBUG) Log.v(TAG, "bind: contacts.addListeners " + this);
contacts.addListeners(this);
setPresenceIcon(contacts.getPresenceResId());
// Subject
mSubjectView.setText(ch.getSubject());
LayoutParams subjectLayout = (LayoutParams)mSubjectView.getLayoutParams();
// We have to make the subject left of whatever optional items are shown on the right.
subjectLayout.addRule(RelativeLayout.LEFT_OF, hasAttachment ? R.id.attachment :
(hasError ? R.id.error : R.id.date));
// Transmission error indicator.
mErrorIndicator.setVisibility(hasError ? VISIBLE : GONE);
updateAvatarView();
}
| public final void bind(Context context, final ConversationHeader ch) {
//if (DEBUG) Log.v(TAG, "bind()");
setConversationHeader(ch);
Drawable background = ch.isRead()?
mContext.getResources().getDrawable(R.drawable.conversation_item_background_read) :
mContext.getResources().getDrawable(R.drawable.conversation_item_background_unread);
setBackgroundDrawable(background);
LayoutParams attachmentLayout = (LayoutParams)mAttachmentView.getLayoutParams();
boolean hasError = ch.hasError();
// When there's an error icon, the attachment icon is left of the error icon.
// When there is not an error icon, the attachment icon is left of the date text.
// As far as I know, there's no way to specify that relationship in xml.
if (hasError) {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.error);
} else {
attachmentLayout.addRule(RelativeLayout.LEFT_OF, R.id.date);
}
boolean hasAttachment = ch.hasAttachment();
mAttachmentView.setVisibility(hasAttachment ? VISIBLE : GONE);
// Date
mDateView.setText(ch.getDate());
// From.
mFromView.setText(formatMessage(ch));
// Register for updates in changes of any of the contacts in this conversation.
ContactList contacts = ch.getContacts();
if (DEBUG) Log.v(TAG, "bind: contacts.addListeners " + this);
contacts.addListeners(this);
setPresenceIcon(contacts.getPresenceResId());
// Subject
mSubjectView.setText(ch.getSubject());
LayoutParams subjectLayout = (LayoutParams)mSubjectView.getLayoutParams();
// We have to make the subject left of whatever optional items are shown on the right.
subjectLayout.addRule(RelativeLayout.LEFT_OF, hasAttachment ? R.id.attachment :
(hasError ? R.id.error : R.id.date));
// Transmission error indicator.
mErrorIndicator.setVisibility(hasError ? VISIBLE : GONE);
updateAvatarView();
}
|
diff --git a/org.iucn.sis.client/src/org/iucn/sis/client/tabs/WorkingSetPage.java b/org.iucn.sis.client/src/org/iucn/sis/client/tabs/WorkingSetPage.java
index cc9c277f..03d209e9 100644
--- a/org.iucn.sis.client/src/org/iucn/sis/client/tabs/WorkingSetPage.java
+++ b/org.iucn.sis.client/src/org/iucn/sis/client/tabs/WorkingSetPage.java
@@ -1,352 +1,352 @@
package org.iucn.sis.client.tabs;
import org.iucn.sis.client.api.caches.AuthorizationCache;
import org.iucn.sis.client.api.caches.RegionCache;
import org.iucn.sis.client.api.caches.TaxonomyCache;
import org.iucn.sis.client.api.caches.WorkingSetCache;
import org.iucn.sis.client.api.container.StateManager;
import org.iucn.sis.client.api.ui.models.workingset.WSStore;
import org.iucn.sis.client.api.utils.FormattedDate;
import org.iucn.sis.client.container.SimpleSISClient;
import org.iucn.sis.client.panels.ClientUIContainer;
import org.iucn.sis.client.panels.filters.AssessmentFilterPanel;
import org.iucn.sis.client.panels.utils.RefreshLayoutContainer;
import org.iucn.sis.client.panels.workingsets.DeleteWorkingSetPanel;
import org.iucn.sis.client.panels.workingsets.WorkingSetAddAssessmentsPanel;
import org.iucn.sis.client.panels.workingsets.WorkingSetEditBasicPanel;
import org.iucn.sis.client.panels.workingsets.WorkingSetExporter;
import org.iucn.sis.client.panels.workingsets.WorkingSetOptionsPanel;
import org.iucn.sis.client.panels.workingsets.WorkingSetPermissionPanel;
import org.iucn.sis.client.panels.workingsets.WorkingSetReportPanel;
import org.iucn.sis.client.panels.workingsets.WorkingSetSummaryPanel;
import org.iucn.sis.shared.api.acl.base.AuthorizableObject;
import org.iucn.sis.shared.api.acl.feature.AuthorizableDraftAssessment;
import org.iucn.sis.shared.api.models.WorkingSet;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.solertium.lwxml.shared.GenericCallback;
import com.solertium.util.extjs.client.WindowUtils;
import com.solertium.util.gwt.ui.DrawsLazily;
import com.solertium.util.gwt.ui.StyledHTML;
public class WorkingSetPage extends FeaturedItemContainer<Integer> {
public static String URL_HOME = "home";
public static String URL_EDIT = "edit";
public static String URL_TAXA = "taxa";
public static String URL_ASSESSMENTS = "assessments";
private final WorkingSetSummaryPanel homePage = new WorkingSetSummaryPanel();
private final WorkingSetEditBasicPanel editor = new WorkingSetEditBasicPanel(this);
private final WorkingSetAddAssessmentsPanel assessments = new WorkingSetAddAssessmentsPanel(this);
private final WorkingSetOptionsPanel taxa = new WorkingSetOptionsPanel();
@Override
protected void drawBody(DoneDrawingCallback callback) {
String url = getUrl();
if (URL_EDIT.equals(url))
setBodyContainer(editor);
else if (URL_TAXA.equals(url))
setBodyContainer(taxa);
else if (URL_ASSESSMENTS.equals(url))
setBodyContainer(assessments);
else
setBodyContainer(homePage);
callback.isDrawn();
}
public void refreshFeature() {
drawFeatureArea();
ClientUIContainer.headerContainer.centerPanel.refreshWorkingSetView();
}
@Override
public LayoutContainer updateFeature() {
final WorkingSet item = WorkingSetCache.impl.getWorkingSet(getSelectedItem());
final LayoutContainer container = new LayoutContainer();
container.add(new StyledHTML("<center>" + item.getName() + "</center>", "page_workingSet_featured_header"));
container.add(createSpacer(40));
final Grid stats = new Grid(3, 2);
stats.setCellSpacing(3);
stats.setWidget(0, 0, new StyledHTML("Created:", "page_workingSet_featured_prompt"));
stats.setWidget(0, 1, new StyledHTML(FormattedDate.impl.getDate(item.getCreatedDate()), "page_workingSet_featured_content"));
stats.setWidget(1, 0, new StyledHTML("Mode:", "page_workingSet_featured_prompt"));
stats.setWidget(1, 1, new StyledHTML("Public", "page_workingSet_featured_content"));
stats.setWidget(2, 0, new StyledHTML("Scope:", "page_workingSet_featured_prompt"));
stats.setWidget(2, 1, new StyledHTML(AssessmentFilterPanel.getString(item.getFilter()), "page_workingSet_featured_content"));
for (int i = 0; i < stats.getRowCount(); i++)
stats.getCellFormatter().setVerticalAlignment(i, 0, HasVerticalAlignment.ALIGN_TOP);
container.add(stats);
return container;
}
@Override
protected void updateSelection(Integer selection) {
//WorkingSetCache.impl.setCurrentWorkingSet(selection, true);
StateManager.impl.setWorkingSet(WorkingSetCache.impl.getWorkingSet(selection));
}
protected void setBodyContainer(LayoutContainer container) {
bodyContainer.removeAll();
if (container instanceof RefreshLayoutContainer)
((RefreshLayoutContainer)container).refresh();
bodyContainer.add(container);
}
@Override
protected void drawOptions(DrawsLazily.DoneDrawingCallback callback) {
- final WorkingSet item = WorkingSetCache.impl.getWorkingSet(getSelectedItem());
+ //final WorkingSet item = WorkingSetCache.impl.getWorkingSet(getSelectedItem());
if (optionsContainer.getItemCount() == 0) {
final TableLayout layout = new TableLayout(1);
layout.setCellHorizontalAlign(HorizontalAlignment.CENTER);
layout.setCellVerticalAlign(VerticalAlignment.MIDDLE);
layout.setCellSpacing(20);
final LayoutContainer buttonArea = new LayoutContainer(layout);
buttonArea.setScrollMode(Scroll.AUTOY);
buttonArea.add(createButton("Edit Basic Information", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(editor);
}
}));
buttonArea.add(createButton("Taxa Manager", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(taxa);
}
}));
buttonArea.add(createButton("Create Draft Assessment", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(assessments);
}
}));
buttonArea.add(createButton("Permisison Manager", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.GRANT,
WorkingSetCache.impl.getCurrentWorkingSet())) {
final WorkingSetPermissionPanel panel = new WorkingSetPermissionPanel();
panel.draw(new DrawsLazily.DoneDrawingCallback() {
public void isDrawn() {
setBodyContainer(panel);
}
});
} else
WindowUtils.errorAlert("Insufficient Permissions", "You do not have permission to manage " +
"the permissions for this Working Set.");
}
}));
buttonArea.add(createButton("Report Generator", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(new WorkingSetReportPanel());
}
}));
buttonArea.add(createButton("Export to Offline", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
//setBodyContainer(new WorkingSetExporter(WorkingSetPage.this));
WindowUtils.confirmAlert("Export Working Set", "A dialog box will appear and ask"
+ " you where you like to save the zipped working set. The zipped file "
+ "will contain the entire working set including the basic information, the "
+ "taxa information, and the draft assessments associated with each taxa if they"
+ " exist. Proceed?", new WindowUtils.SimpleMessageBoxListener() {
public void onYes() {
- export(item);
+ export(WorkingSetCache.impl.getWorkingSet(getSelectedItem()));
}
});
}
}));
buttonArea.add(createButton("Export to Access", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
final ContentPanel panel = new ContentPanel();
panel.setHeading("Export to Access");
panel.getHeader().addTool(new Button("Cancel", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setManagerTab();
}
}));
panel.setUrl("/export/access/" + WorkingSetCache.impl.getCurrentWorkingSet().getId());
setBodyContainer(panel);
}
}));
buttonArea.add(createButton("Unsubscribe", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
WindowUtils.confirmAlert("Unsubscribe?", "Are you sure you want to unsubscribe " +
"from this working set? You will be able to subscribe again if your " +
"permissions are unchanged.",
new WindowUtils.SimpleMessageBoxListener() {
public void onYes() {
- WorkingSetCache.impl.unsubscribeToWorkingSet(item, new GenericCallback<String>() {
+ WorkingSetCache.impl.unsubscribeToWorkingSet(WorkingSetCache.impl.getWorkingSet(getSelectedItem()), new GenericCallback<String>() {
public void onSuccess(String result) {
- WindowUtils.infoAlert("You have successfully unsubscribed from the working set " + item.getWorkingSetName() + ".");
+ WindowUtils.infoAlert("You have successfully unsubscribed from the working set " + WorkingSetCache.impl.getWorkingSet(getSelectedItem()).getWorkingSetName() + ".");
WSStore.getStore().update();
StateManager.impl.reset();
}
public void onFailure(Throwable caught) {
WindowUtils.errorAlert("Failed to unsubscribe from this working set. Please try again later.");
}
});
}
});
}
}));
- if (canDelete(item)) {
+ if (canDelete(WorkingSetCache.impl.getWorkingSet(getSelectedItem()))) {
buttonArea.add(createButton("Delete", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
WindowUtils.confirmAlert("Delete working set?", "Are you sure you " +
"want to completely delete this working set? <b>You can not " +
"undo this operation.</b>", new WindowUtils.SimpleMessageBoxListener() {
public void onYes() {
- DeleteWorkingSetPanel.ensurePermissionsCleared(item.getId(), new GenericCallback<String>() {
+ DeleteWorkingSetPanel.ensurePermissionsCleared(WorkingSetCache.impl.getWorkingSet(getSelectedItem()).getId(), new GenericCallback<String>() {
public void onFailure(Throwable caught) {
if (caught != null) {
WindowUtils.errorAlert("Error communicating with the server. Please try again later.");
}
else {
WindowUtils.errorAlert("Permission Error", "There are still users that are granted permissions via this Working Set. " +
"Before you can delete, please visit the Permission Manager and remove all of these users.");
}
}
public void onSuccess(String result) {
- WorkingSetCache.impl.deleteWorkingSet(item, new GenericCallback<String>() {
+ WorkingSetCache.impl.deleteWorkingSet(WorkingSetCache.impl.getWorkingSet(getSelectedItem()), new GenericCallback<String>() {
public void onFailure(Throwable caught) {
WindowUtils.errorAlert("Failed to delete this working set. Please try again later.");
}
@Override
public void onSuccess(String result) {
- WindowUtils.infoAlert("You have successfully deleted the working set " + item.getWorkingSetName() + ".");
+ WindowUtils.infoAlert("You have successfully deleted the working set " + WorkingSetCache.impl.getWorkingSet(getSelectedItem()).getWorkingSetName() + ".");
WSStore.getStore().update();
StateManager.impl.reset();
}
});
}
});
}
});
}
}));
}
optionsContainer.removeAll();
optionsContainer.add(buttonArea);
}
callback.isDrawn();
}
private boolean canDelete(WorkingSet workingSet) {
return AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.DELETE, workingSet);
}
private Button createButton(String text, SelectionListener<ButtonEvent> listener) {
return createButton(text, null, listener);
}
private Button createButton(String text, String icon, SelectionListener<ButtonEvent> listener) {
Button button = new Button(text);
button.setIconStyle(icon);
button.setWidth(150);
button.addSelectionListener(listener);
return button;
}
public void setEditWorkingSetTab() {
setBodyContainer(editor);
}
public void setManagerTab() {
setBodyContainer(homePage);
}
public void setAssessmentTab() {
setBodyContainer(assessments);
}
public void setEditTaxaTab() {
setBodyContainer(taxa);
}
private void export(final WorkingSet ws) {
if (SimpleSISClient.iAmOnline) {
WindowUtils.confirmAlert("Lock Assessments", "Would you like to lock the online version " +
"of the draft assessments of the regions " + RegionCache.impl.getRegionNamesAsReadable(ws.getFilter()) +
" for this working set? You can only commit changes to online versions via an " +
"import if you have obtained the locks.", new WindowUtils.MessageBoxListener() {
public void onYes() {
attemptLocking(ws);
}
public void onNo() {
fireExport(ws, false);
}
}, "Yes", "No");
} else {
attemptLocking(ws);
}
}
/**
* TODO: do all this mess on the server.
* @param ws
*/
private void attemptLocking(final WorkingSet ws) {
String permissionProblem = null;
for (Integer curSpecies : ws.getSpeciesIDs()) {
AuthorizableDraftAssessment d = new AuthorizableDraftAssessment(
TaxonomyCache.impl.getTaxon(curSpecies), ws.getFilter().getRegionIDsCSV());
if(!AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.WRITE, d))
permissionProblem = d.getTaxon().getFullName();
}
if (permissionProblem == null) {
fireExport(ws, true);
} else {
WindowUtils.confirmAlert("Insufficient Permissions", "You cannot lock " +
"the assessments for this working set as you do not have sufficient " +
"permissions to edit the draft assessments for at least " +
"the taxon " + permissionProblem + ". Would you like to export the " +
"working set without locking anyway?", new WindowUtils.SimpleMessageBoxListener() {
public void onYes() {
fireExport(ws, false);
}
});
}
}
public void fireExport(final WorkingSet workingSet, boolean lock) {
WindowUtils.infoAlert("Export Started", "Your working sets are being exported. A popup "
+ "will notify you when the export has finished and when the files are "
+ "available for download.");
WorkingSetCache.impl.exportWorkingSet(workingSet.getId(), lock, new GenericCallback<String>() {
public void onFailure(Throwable caught) {
WindowUtils.errorAlert("Export failed, please try again later.");
}
public void onSuccess(String arg0) {
WorkingSetExporter.saveExportedZip(arg0, workingSet);
}
});
}
}
| false | true | protected void drawOptions(DrawsLazily.DoneDrawingCallback callback) {
final WorkingSet item = WorkingSetCache.impl.getWorkingSet(getSelectedItem());
if (optionsContainer.getItemCount() == 0) {
final TableLayout layout = new TableLayout(1);
layout.setCellHorizontalAlign(HorizontalAlignment.CENTER);
layout.setCellVerticalAlign(VerticalAlignment.MIDDLE);
layout.setCellSpacing(20);
final LayoutContainer buttonArea = new LayoutContainer(layout);
buttonArea.setScrollMode(Scroll.AUTOY);
buttonArea.add(createButton("Edit Basic Information", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(editor);
}
}));
buttonArea.add(createButton("Taxa Manager", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(taxa);
}
}));
buttonArea.add(createButton("Create Draft Assessment", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(assessments);
}
}));
buttonArea.add(createButton("Permisison Manager", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.GRANT,
WorkingSetCache.impl.getCurrentWorkingSet())) {
final WorkingSetPermissionPanel panel = new WorkingSetPermissionPanel();
panel.draw(new DrawsLazily.DoneDrawingCallback() {
public void isDrawn() {
setBodyContainer(panel);
}
});
} else
WindowUtils.errorAlert("Insufficient Permissions", "You do not have permission to manage " +
"the permissions for this Working Set.");
}
}));
buttonArea.add(createButton("Report Generator", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(new WorkingSetReportPanel());
}
}));
buttonArea.add(createButton("Export to Offline", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
//setBodyContainer(new WorkingSetExporter(WorkingSetPage.this));
WindowUtils.confirmAlert("Export Working Set", "A dialog box will appear and ask"
+ " you where you like to save the zipped working set. The zipped file "
+ "will contain the entire working set including the basic information, the "
+ "taxa information, and the draft assessments associated with each taxa if they"
+ " exist. Proceed?", new WindowUtils.SimpleMessageBoxListener() {
public void onYes() {
export(item);
}
});
}
}));
buttonArea.add(createButton("Export to Access", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
final ContentPanel panel = new ContentPanel();
panel.setHeading("Export to Access");
panel.getHeader().addTool(new Button("Cancel", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setManagerTab();
}
}));
panel.setUrl("/export/access/" + WorkingSetCache.impl.getCurrentWorkingSet().getId());
setBodyContainer(panel);
}
}));
buttonArea.add(createButton("Unsubscribe", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
WindowUtils.confirmAlert("Unsubscribe?", "Are you sure you want to unsubscribe " +
"from this working set? You will be able to subscribe again if your " +
"permissions are unchanged.",
new WindowUtils.SimpleMessageBoxListener() {
public void onYes() {
WorkingSetCache.impl.unsubscribeToWorkingSet(item, new GenericCallback<String>() {
public void onSuccess(String result) {
WindowUtils.infoAlert("You have successfully unsubscribed from the working set " + item.getWorkingSetName() + ".");
WSStore.getStore().update();
StateManager.impl.reset();
}
public void onFailure(Throwable caught) {
WindowUtils.errorAlert("Failed to unsubscribe from this working set. Please try again later.");
}
});
}
});
}
}));
if (canDelete(item)) {
buttonArea.add(createButton("Delete", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
WindowUtils.confirmAlert("Delete working set?", "Are you sure you " +
"want to completely delete this working set? <b>You can not " +
"undo this operation.</b>", new WindowUtils.SimpleMessageBoxListener() {
public void onYes() {
DeleteWorkingSetPanel.ensurePermissionsCleared(item.getId(), new GenericCallback<String>() {
public void onFailure(Throwable caught) {
if (caught != null) {
WindowUtils.errorAlert("Error communicating with the server. Please try again later.");
}
else {
WindowUtils.errorAlert("Permission Error", "There are still users that are granted permissions via this Working Set. " +
"Before you can delete, please visit the Permission Manager and remove all of these users.");
}
}
public void onSuccess(String result) {
WorkingSetCache.impl.deleteWorkingSet(item, new GenericCallback<String>() {
public void onFailure(Throwable caught) {
WindowUtils.errorAlert("Failed to delete this working set. Please try again later.");
}
@Override
public void onSuccess(String result) {
WindowUtils.infoAlert("You have successfully deleted the working set " + item.getWorkingSetName() + ".");
WSStore.getStore().update();
StateManager.impl.reset();
}
});
}
});
}
});
}
}));
}
optionsContainer.removeAll();
optionsContainer.add(buttonArea);
}
callback.isDrawn();
}
| protected void drawOptions(DrawsLazily.DoneDrawingCallback callback) {
//final WorkingSet item = WorkingSetCache.impl.getWorkingSet(getSelectedItem());
if (optionsContainer.getItemCount() == 0) {
final TableLayout layout = new TableLayout(1);
layout.setCellHorizontalAlign(HorizontalAlignment.CENTER);
layout.setCellVerticalAlign(VerticalAlignment.MIDDLE);
layout.setCellSpacing(20);
final LayoutContainer buttonArea = new LayoutContainer(layout);
buttonArea.setScrollMode(Scroll.AUTOY);
buttonArea.add(createButton("Edit Basic Information", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(editor);
}
}));
buttonArea.add(createButton("Taxa Manager", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(taxa);
}
}));
buttonArea.add(createButton("Create Draft Assessment", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(assessments);
}
}));
buttonArea.add(createButton("Permisison Manager", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
if (AuthorizationCache.impl.hasRight(SimpleSISClient.currentUser, AuthorizableObject.GRANT,
WorkingSetCache.impl.getCurrentWorkingSet())) {
final WorkingSetPermissionPanel panel = new WorkingSetPermissionPanel();
panel.draw(new DrawsLazily.DoneDrawingCallback() {
public void isDrawn() {
setBodyContainer(panel);
}
});
} else
WindowUtils.errorAlert("Insufficient Permissions", "You do not have permission to manage " +
"the permissions for this Working Set.");
}
}));
buttonArea.add(createButton("Report Generator", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setBodyContainer(new WorkingSetReportPanel());
}
}));
buttonArea.add(createButton("Export to Offline", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
//setBodyContainer(new WorkingSetExporter(WorkingSetPage.this));
WindowUtils.confirmAlert("Export Working Set", "A dialog box will appear and ask"
+ " you where you like to save the zipped working set. The zipped file "
+ "will contain the entire working set including the basic information, the "
+ "taxa information, and the draft assessments associated with each taxa if they"
+ " exist. Proceed?", new WindowUtils.SimpleMessageBoxListener() {
public void onYes() {
export(WorkingSetCache.impl.getWorkingSet(getSelectedItem()));
}
});
}
}));
buttonArea.add(createButton("Export to Access", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
final ContentPanel panel = new ContentPanel();
panel.setHeading("Export to Access");
panel.getHeader().addTool(new Button("Cancel", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
setManagerTab();
}
}));
panel.setUrl("/export/access/" + WorkingSetCache.impl.getCurrentWorkingSet().getId());
setBodyContainer(panel);
}
}));
buttonArea.add(createButton("Unsubscribe", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
WindowUtils.confirmAlert("Unsubscribe?", "Are you sure you want to unsubscribe " +
"from this working set? You will be able to subscribe again if your " +
"permissions are unchanged.",
new WindowUtils.SimpleMessageBoxListener() {
public void onYes() {
WorkingSetCache.impl.unsubscribeToWorkingSet(WorkingSetCache.impl.getWorkingSet(getSelectedItem()), new GenericCallback<String>() {
public void onSuccess(String result) {
WindowUtils.infoAlert("You have successfully unsubscribed from the working set " + WorkingSetCache.impl.getWorkingSet(getSelectedItem()).getWorkingSetName() + ".");
WSStore.getStore().update();
StateManager.impl.reset();
}
public void onFailure(Throwable caught) {
WindowUtils.errorAlert("Failed to unsubscribe from this working set. Please try again later.");
}
});
}
});
}
}));
if (canDelete(WorkingSetCache.impl.getWorkingSet(getSelectedItem()))) {
buttonArea.add(createButton("Delete", new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
WindowUtils.confirmAlert("Delete working set?", "Are you sure you " +
"want to completely delete this working set? <b>You can not " +
"undo this operation.</b>", new WindowUtils.SimpleMessageBoxListener() {
public void onYes() {
DeleteWorkingSetPanel.ensurePermissionsCleared(WorkingSetCache.impl.getWorkingSet(getSelectedItem()).getId(), new GenericCallback<String>() {
public void onFailure(Throwable caught) {
if (caught != null) {
WindowUtils.errorAlert("Error communicating with the server. Please try again later.");
}
else {
WindowUtils.errorAlert("Permission Error", "There are still users that are granted permissions via this Working Set. " +
"Before you can delete, please visit the Permission Manager and remove all of these users.");
}
}
public void onSuccess(String result) {
WorkingSetCache.impl.deleteWorkingSet(WorkingSetCache.impl.getWorkingSet(getSelectedItem()), new GenericCallback<String>() {
public void onFailure(Throwable caught) {
WindowUtils.errorAlert("Failed to delete this working set. Please try again later.");
}
@Override
public void onSuccess(String result) {
WindowUtils.infoAlert("You have successfully deleted the working set " + WorkingSetCache.impl.getWorkingSet(getSelectedItem()).getWorkingSetName() + ".");
WSStore.getStore().update();
StateManager.impl.reset();
}
});
}
});
}
});
}
}));
}
optionsContainer.removeAll();
optionsContainer.add(buttonArea);
}
callback.isDrawn();
}
|
diff --git a/core/api/src/main/java/org/qi4j/api/query/QueryExpressions.java b/core/api/src/main/java/org/qi4j/api/query/QueryExpressions.java
index b5203e78a..c9769ac19 100644
--- a/core/api/src/main/java/org/qi4j/api/query/QueryExpressions.java
+++ b/core/api/src/main/java/org/qi4j/api/query/QueryExpressions.java
@@ -1,833 +1,833 @@
/*
* Copyright 2007 Rickard Öberg.
* Copyright 2007 Niclas Hedhman.
* Copyright 2008 Alin Dreghiciu.
* Copyright 2012 Paul Merlin.
*
* 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
* ied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.qi4j.api.query;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import org.qi4j.api.association.Association;
import org.qi4j.api.association.GenericAssociationInfo;
import org.qi4j.api.association.ManyAssociation;
import org.qi4j.api.composite.Composite;
import org.qi4j.api.entity.Identity;
import org.qi4j.api.injection.scope.State;
import org.qi4j.api.property.GenericPropertyInfo;
import org.qi4j.api.property.Property;
import org.qi4j.api.query.grammar.AndSpecification;
import org.qi4j.api.query.grammar.AssociationFunction;
import org.qi4j.api.query.grammar.AssociationNotNullSpecification;
import org.qi4j.api.query.grammar.AssociationNullSpecification;
import org.qi4j.api.query.grammar.ContainsAllSpecification;
import org.qi4j.api.query.grammar.ContainsSpecification;
import org.qi4j.api.query.grammar.EqSpecification;
import org.qi4j.api.query.grammar.GeSpecification;
import org.qi4j.api.query.grammar.GtSpecification;
import org.qi4j.api.query.grammar.LeSpecification;
import org.qi4j.api.query.grammar.LtSpecification;
import org.qi4j.api.query.grammar.ManyAssociationContainsSpecification;
import org.qi4j.api.query.grammar.ManyAssociationFunction;
import org.qi4j.api.query.grammar.MatchesSpecification;
import org.qi4j.api.query.grammar.NeSpecification;
import org.qi4j.api.query.grammar.NotSpecification;
import org.qi4j.api.query.grammar.OrSpecification;
import org.qi4j.api.query.grammar.OrderBy;
import org.qi4j.api.query.grammar.PropertyFunction;
import org.qi4j.api.query.grammar.PropertyNotNullSpecification;
import org.qi4j.api.query.grammar.PropertyNullSpecification;
import org.qi4j.api.query.grammar.PropertyReference;
import org.qi4j.api.query.grammar.Variable;
import org.qi4j.api.util.NullArgumentException;
import org.qi4j.functional.Specification;
import static org.qi4j.functional.Iterables.prepend;
/**
* Static factory methods for query expressions and operators.
*/
public final class QueryExpressions
{
// This is used for eq(Association,Composite)
private static final Method IDENTITY_METHOD;
static
{
try
{
IDENTITY_METHOD = Identity.class.getMethod( "identity" );
}
catch( NoSuchMethodException e )
{
throw new InternalError( "Qi4j Core API codebase is corrupted. Contact Qi4j team: QueryExpressions" );
}
}
// Templates and variables -----------------------------------------------|
/**
* Create a Query Template using the given type.
*
* @param <T> the type of the template
* @param clazz a class declaring the type of the template
*
* @return a new Query Template
*/
public static <T> T templateFor( Class<T> clazz )
{
NullArgumentException.validateNotNull( "Template class", clazz );
if( clazz.isInterface() )
{
return clazz.cast( Proxy.newProxyInstance( clazz.getClassLoader(),
new Class<?>[] { clazz },
new TemplateHandler<T>( null, null, null ) ) );
}
else
{
try
{
T mixin = clazz.newInstance();
for( Field field : clazz.getFields() )
{
if( field.getAnnotation( State.class ) != null )
{
if( field.getType().equals( Property.class ) )
{
field.set( mixin,
Proxy.newProxyInstance( field.getType().getClassLoader(),
new Class<?>[]{ field.getType() },
new PropertyReferenceHandler<>( new PropertyFunction<T>( null, null, null, field ) ) ) );
}
else if( field.getType().equals( Association.class ) )
{
field.set( mixin,
Proxy.newProxyInstance( field.getType().getClassLoader(),
new Class<?>[]{ field.getType() },
new AssociationReferenceHandler<>( new AssociationFunction<T>( null, null, field ) ) ) );
}
- else if( field.getType().equals( Property.class ) )
+ else if( field.getType().equals( ManyAssociation.class ) )
{
field.set( mixin,
Proxy.newProxyInstance( field.getType().getClassLoader(),
new Class<?>[]{ field.getType() },
new ManyAssociationReferenceHandler<>( new ManyAssociationFunction<T>( null, null, field ) ) ) );
}
}
}
return mixin;
}
catch( IllegalAccessException | IllegalArgumentException | InstantiationException | SecurityException e )
{
throw new IllegalArgumentException( "Cannot use class as template", e );
}
}
}
/**
* Create a Query Template using the given mixin class and association.
*
* @param <T> the type of the template
* @param mixinType a class declaring the type of the template
* @param association an association
*
* @return a new Query Template
*/
public static <T> T templateFor( final Class<T> mixinType, Association<?> association )
{
NullArgumentException.validateNotNull( "Mixin class", mixinType );
NullArgumentException.validateNotNull( "Association", association );
return mixinType.cast( Proxy.newProxyInstance( mixinType.getClassLoader(),
new Class<?>[]{ mixinType },
new TemplateHandler<T>( null, association( association ), null ) ) );
}
public static <T> T oneOf( final ManyAssociation<T> association )
{
NullArgumentException.validateNotNull( "Association", association );
return association.get( 0 );
}
/**
* Create a new Query Variable.
*
* @param name a name for the Variable
*
* @return a new Query Variable.
*/
public static Variable variable( String name )
{
NullArgumentException.validateNotNull( "Variable name", name );
return new Variable( name );
}
/**
* Create a new Query Template PropertyFunction.
*
* @param <T> type of the Property
* @param property a Property
*
* @return a new Query Template PropertyFunction
*/
@SuppressWarnings( "unchecked" )
public static <T> PropertyFunction<T> property( Property<T> property )
{
return ( ( PropertyReferenceHandler<T> ) Proxy.getInvocationHandler( property ) ).property();
}
/**
* Create a new Query Property instance.
*
* @param <T> type of the Property
* @param mixinClass mixin of the Property
* @param fieldName name of the Property field
*
* @return a new Query Property instance for the given mixin and property name.
*/
@SuppressWarnings( "unchecked" )
public static <T> Property<T> property( Class<?> mixinClass, String fieldName )
{
try
{
Field field = mixinClass.getField( fieldName );
if( !Property.class.isAssignableFrom( field.getType() ) )
{
throw new IllegalArgumentException( "Field must be of type Property<?>" );
}
return ( Property<T> ) Proxy.newProxyInstance(
mixinClass.getClassLoader(),
new Class<?>[]{ field.getType() },
new PropertyReferenceHandler<>( new PropertyFunction<T>( null, null, null, field ) ) );
}
catch( NoSuchFieldException e )
{
throw new IllegalArgumentException( "No such field '" + fieldName + "' in mixin " + mixinClass.getName() );
}
}
/**
* Create a new Query Template AssociationFunction.
*
* @param <T> type of the Association
* @param association an Association
*
* @return a new Query Template AssociationFunction
*/
@SuppressWarnings( "unchecked" )
public static <T> AssociationFunction<T> association( Association<T> association )
{
return ( ( AssociationReferenceHandler<T> ) Proxy.getInvocationHandler( association ) ).association();
}
/**
* Create a new Query Template ManyAssociationFunction.
*
* @param <T> type of the ManyAssociation
* @param association a ManyAssociation
*
* @return a new Query Template ManyAssociationFunction
*/
@SuppressWarnings( "unchecked" )
public static <T> ManyAssociationFunction<T> manyAssociation( ManyAssociation<T> association )
{
return ( ( ManyAssociationReferenceHandler<T> ) Proxy.getInvocationHandler( association ) ).manyAssociation();
}
// And/Or/Not ------------------------------------------------------------|
/**
* Create a new AND specification.
*
* @param left first operand
* @param right second operand
* @param optionalRight optional operands
*
* @return a new AND specification
*/
@SafeVarargs
public static AndSpecification and( Specification<Composite> left,
Specification<Composite> right,
Specification<Composite>... optionalRight
)
{
return new AndSpecification( prepend( left, prepend( right, Arrays.asList( optionalRight ) ) ) );
}
/**
* Create a new OR specification.
*
* @param left first operand
* @param right second operand
* @param optionalRight optional operands
*
* @return a new OR specification
*/
@SafeVarargs
public static OrSpecification or( Specification<Composite> left,
Specification<Composite> right,
Specification<Composite>... optionalRight
)
{
return new OrSpecification( prepend( left, prepend( right, Arrays.asList( optionalRight ) ) ) );
}
/**
* Create a new NOT specification.
*
* @param operand specification to be negated
*
* @return a new NOT specification
*/
public static NotSpecification not( Specification<Composite> operand )
{
return new NotSpecification( operand );
}
// Comparisons -----------------------------------------------------------|
/**
* Create a new EQUALS specification for a Property.
*
* @param property a Property
* @param value its value
*
* @return a new EQUALS specification for a Property.
*/
public static <T> EqSpecification<T> eq( Property<T> property, T value )
{
return new EqSpecification<>( property( property ), value );
}
/**
* Create a new EQUALS specification for a Property using a named Variable.
*
* @param property a Property
* @param variable a Query Variable
*
* @return a new EQUALS specification for a Property using a named Variable.
*/
@SuppressWarnings( {"raw", "unchecked"} )
public static <T> EqSpecification<T> eq( Property<T> property, Variable variable )
{
return new EqSpecification( property( property ), variable );
}
/**
* Create a new EQUALS specification for an Association.
*
* @param association an Association
* @param value its value
*
* @return a new EQUALS specification for an Association.
*/
public static <T> EqSpecification<String> eq( Association<T> association, T value )
{
return new EqSpecification<>( new PropertyFunction<String>( null,
association( association ),
null,
IDENTITY_METHOD ),
value.toString() );
}
/**
* Create a new GREATER OR EQUALS specification for a Property.
*
* @param property a Property
* @param value its value
*
* @return a new GREATER OR EQUALS specification for a Property.
*/
public static <T> GeSpecification<T> ge( Property<T> property, T value )
{
return new GeSpecification<>( property( property ), value );
}
/**
* Create a new GREATER OR EQUALS specification for a Property using a named Variable.
*
* @param property a Property
* @param variable a Query Variable
*
* @return a new GREATER OR EQUALS specification for a Property using a named Variable.
*/
@SuppressWarnings( {"raw", "unchecked"} )
public static <T> GeSpecification<T> ge( Property<T> property, Variable variable )
{
return new GeSpecification( property( property ), variable );
}
/**
* Create a new GREATER THAN specification for a Property.
*
* @param property a Property
* @param value its value
*
* @return a new GREATER THAN specification for a Property.
*/
public static <T> GtSpecification<T> gt( Property<T> property, T value )
{
return new GtSpecification<>( property( property ), value );
}
/**
* Create a new GREATER THAN specification for a Property using a named Variable.
*
* @param property a Property
* @param variable a Query Variable
*
* @return a new GREATER THAN specification for a Property using a named Variable.
*/
@SuppressWarnings( {"raw", "unchecked"} )
public static <T> GtSpecification<T> gt( Property<T> property, Variable variable )
{
return new GtSpecification( property( property ), variable );
}
/**
* Create a new LESS OR EQUALS specification for a Property.
*
* @param property a Property
* @param value its value
*
* @return a new LESS OR EQUALS specification for a Property.
*/
public static <T> LeSpecification<T> le( Property<T> property, T value )
{
return new LeSpecification<>( property( property ), value );
}
/**
* Create a new LESS OR EQUALS specification for a Property using a named Variable.
*
* @param property a Property
* @param variable a Query Variable
*
* @return a new LESS OR EQUALS specification for a Property using a named Variable.
*/
@SuppressWarnings( {"raw", "unchecked"} )
public static <T> LeSpecification<T> le( Property<T> property, Variable variable )
{
return new LeSpecification( property( property ), variable );
}
/**
* Create a new LESSER THAN specification for a Property.
*
* @param property a Property
* @param value its value
*
* @return a new LESSER THAN specification for a Property.
*/
public static <T> LtSpecification<T> lt( Property<T> property, T value )
{
return new LtSpecification<>( property( property ), value );
}
/**
* Create a new LESSER THAN specification for a Property using a named Variable.
*
* @param property a Property
* @param variable a Query Variable
*
* @return a new LESSER THAN specification for a Property using a named Variable.
*/
@SuppressWarnings( {"raw", "unchecked"} )
public static <T> LtSpecification<T> lt( Property<T> property, Variable variable )
{
return new LtSpecification( property( property ), variable );
}
/**
* Create a new NOT EQUALS specification for a Property.
*
* @param property a Property
* @param value its value
*
* @return a new NOT EQUALS specification for a Property.
*/
public static <T> NeSpecification<T> ne( Property<T> property, T value )
{
return new NeSpecification<>( property( property ), value );
}
/**
* Create a new NOT EQUALS specification for a Property using a named Variable.
*
* @param property a Property
* @param variable a Query Variable
*
* @return a new NOT EQUALS specification for a Property using a named Variable.
*/
@SuppressWarnings( {"raw", "unchecked"} )
public static <T> NeSpecification<T> ne( Property<T> property, Variable variable )
{
return new NeSpecification( property( property ), variable );
}
/**
* Create a new REGULAR EXPRESSION specification for a Property.
*
* @param property a Property
* @param regexp its value
*
* @return a new REGULAR EXPRESSION specification for a Property.
*/
public static MatchesSpecification matches( Property<String> property, String regexp )
{
return new MatchesSpecification( property( property ), regexp );
}
/**
* Create a new REGULAR EXPRESSION specification for a Property using a named Variable.
*
* @param property a Property
* @param variable a Query Variable
*
* @return a new REGULAR EXPRESSION specification for a Property using a named Variable.
*/
public static MatchesSpecification matches( Property<String> property, Variable variable )
{
return new MatchesSpecification( property( property ), variable );
}
// Null checks -----------------------------------------------------------|
/**
* Create a new NOT NULL specification for a Property.
*
* @param property a Property
*
* @return a new NOT NULL specification for a Property.
*/
public static <T> PropertyNotNullSpecification<T> isNotNull( Property<T> property )
{
return new PropertyNotNullSpecification<>( property( property ) );
}
/**
* Create a new NULL specification for a Property.
*
* @param property a Property
*
* @return a new NULL specification for a Property.
*/
public static <T> PropertyNullSpecification<T> isNull( Property<T> property )
{
return new PropertyNullSpecification<>( property( property ) );
}
/**
* Create a new NOT NULL specification for an Association.
*
* @param association an Association
*
* @return a new NOT NULL specification for an Association.
*/
public static <T> AssociationNotNullSpecification<T> isNotNull( Association<T> association )
{
return new AssociationNotNullSpecification<>( association( association ) );
}
/**
* Create a new NULL specification for an Association.
*
* @param association an Association
*
* @return a new NULL specification for an Association.
*/
public static <T> AssociationNullSpecification<T> isNull( Association<T> association )
{
return new AssociationNullSpecification<>( association( association ) );
}
// Collections -----------------------------------------------------------|
/**
* Create a new CONTAINS ALL specification for a Collection Property.
*
* @param collectionProperty a Collection Property
* @param values its values
*
* @return a new CONTAINS ALL specification for a Collection Property.
*/
public static <T> ContainsAllSpecification<T> containsAll( Property<? extends Collection<T>> collectionProperty,
Iterable<T> values )
{
NullArgumentException.validateNotNull( "Values", values );
return new ContainsAllSpecification<>( property( collectionProperty ), values );
}
/**
* Create a new CONTAINS ALL specification for a Collection Property using named Variables.
*
* @param collectionProperty a Collection Property
* @param variables named Variables
*
* @return a new CONTAINS ALL specification for a Collection Property using named Variables.
*/
@SuppressWarnings( {"raw", "unchecked"} )
public static <T> ContainsAllSpecification<T> containsAllVariables(
Property<? extends Collection<T>> collectionProperty,
Iterable<Variable> variables )
{
NullArgumentException.validateNotNull( "Variables", variables );
return new ContainsAllSpecification( property( collectionProperty ), variables );
}
/**
* Create a new CONTAINS specification for a Collection Property.
*
* @param collectionProperty a Collection Property
* @param value the value
*
* @return a new CONTAINS specification for a Collection Property.
*/
public static <T> ContainsSpecification<T> contains( Property<? extends Collection<T>> collectionProperty,
T value )
{
NullArgumentException.validateNotNull( "Value", value );
return new ContainsSpecification<>( property( collectionProperty ), value );
}
/**
* Create a new CONTAINS specification for a Collection Property using named Variables.
*
* @param collectionProperty a Collection Property
* @param variable named Variable
*
* @return a new CONTAINS specification for a Collection Property using named Variables.
*/
@SuppressWarnings( {"raw", "unchecked"} )
public static <T> ContainsSpecification<T> contains( Property<? extends Collection<T>> collectionProperty,
Variable variable )
{
NullArgumentException.validateNotNull( "Variable", variable );
return new ContainsSpecification( property( collectionProperty ), variable );
}
/**
* Create a new CONTAINS specification for a ManyAssociation.
*
* @param manyAssoc a ManyAssociation
* @param value the value
*
* @return a new CONTAINS specification for a ManyAssociation.
*/
public static <T> ManyAssociationContainsSpecification<T> contains( ManyAssociation<T> manyAssoc,
T value )
{
return new ManyAssociationContainsSpecification<>( manyAssociation( manyAssoc ), value );
}
// Ordering --------------------------------------------------------------|
/**
* Create a new Query ascending order segment for a Property.
*
* @param <T> type of the Property
* @param property a Property
*
* @return a new Query ascending order segment for a Property.
*/
public static <T> OrderBy orderBy( final Property<T> property )
{
return orderBy( property, OrderBy.Order.ASCENDING );
}
/**
* Create a new Query ordering segment for a Property.
*
* @param <T> type of the Property
* @param property a Property
* @param order ascending or descending
*
* @return a new Query ordering segment for a Property.
*/
public static <T> OrderBy orderBy( final Property<T> property, final OrderBy.Order order )
{
return new OrderBy( property( property ), order );
}
// Query Templates InvocationHandlers ------------------------------------|
private static class TemplateHandler<T>
implements InvocationHandler
{
private final PropertyFunction<?> compositeProperty;
private final AssociationFunction<?> compositeAssociation;
private final ManyAssociationFunction<?> compositeManyAssociation;
private TemplateHandler( PropertyFunction<?> CompositeProperty,
AssociationFunction<?> CompositeAssociation,
ManyAssociationFunction<?> CompositeManyAssociation
)
{
this.compositeProperty = CompositeProperty;
this.compositeAssociation = CompositeAssociation;
this.compositeManyAssociation = CompositeManyAssociation;
}
@Override
public Object invoke( Object o, Method method, Object[] objects )
throws Throwable
{
if( Property.class.isAssignableFrom( method.getReturnType() ) )
{
return Proxy.newProxyInstance(
method.getReturnType().getClassLoader(),
new Class<?>[]{ method.getReturnType() },
new PropertyReferenceHandler<>( new PropertyFunction<T>( compositeProperty,
compositeAssociation,
compositeManyAssociation,
method ) ) );
}
else if( Association.class.isAssignableFrom( method.getReturnType() ) )
{
return Proxy.newProxyInstance(
method.getReturnType().getClassLoader(),
new Class<?>[]{ method.getReturnType() },
new AssociationReferenceHandler<>( new AssociationFunction<T>( compositeAssociation,
compositeManyAssociation,
method ) ) );
}
else if( ManyAssociation.class.isAssignableFrom( method.getReturnType() ) )
{
return Proxy.newProxyInstance(
method.getReturnType().getClassLoader(),
new Class<?>[]{ method.getReturnType() },
new ManyAssociationReferenceHandler<>( new ManyAssociationFunction<T>( compositeAssociation,
compositeManyAssociation,
method ) ) );
}
return null;
}
}
private static class PropertyReferenceHandler<T>
implements InvocationHandler
{
private final PropertyFunction<T> property;
private PropertyReferenceHandler( PropertyFunction<T> property )
{
this.property = property;
}
private PropertyFunction<T> property()
{
return property;
}
@Override
public Object invoke( Object o, final Method method, Object[] objects )
throws Throwable
{
if( method.equals( Property.class.getMethod( "get" ) ) )
{
Type propertyType = GenericPropertyInfo.propertyTypeOf( property.accessor() );
if( propertyType.getClass().equals( Class.class ) )
{
return Proxy.newProxyInstance( method.getDeclaringClass().getClassLoader(),
new Class<?>[]{ (Class<?>) propertyType, PropertyReference.class },
new TemplateHandler<T>( property, null, null ) );
}
}
return null;
}
}
private static class AssociationReferenceHandler<T>
implements InvocationHandler
{
private final AssociationFunction<T> association;
private AssociationReferenceHandler( AssociationFunction<T> association )
{
this.association = association;
}
private AssociationFunction<T> association()
{
return association;
}
@Override
public Object invoke( Object o, final Method method, Object[] objects )
throws Throwable
{
if( method.equals( Association.class.getMethod( "get" ) ) )
{
Type associationType = GenericAssociationInfo.associationTypeOf( association.accessor() );
if( associationType.getClass().equals( Class.class ) )
{
return Proxy.newProxyInstance( method.getDeclaringClass().getClassLoader(),
new Class<?>[]{ (Class) associationType, PropertyReference.class },
new TemplateHandler<T>( null, association, null ) );
}
}
return null;
}
}
private static class ManyAssociationReferenceHandler<T>
implements InvocationHandler
{
private final ManyAssociationFunction<T> manyAssociation;
private ManyAssociationReferenceHandler( ManyAssociationFunction<T> manyAssociation )
{
this.manyAssociation = manyAssociation;
}
public ManyAssociationFunction<T> manyAssociation()
{
return manyAssociation;
}
@Override
public Object invoke( Object o, final Method method, Object[] objects )
throws Throwable
{
if( method.equals( ManyAssociation.class.getMethod( "get", Integer.TYPE ) ) )
{
Type manyAssociationType = GenericAssociationInfo.associationTypeOf( manyAssociation.accessor() );
if( manyAssociationType.getClass().equals( Class.class ) )
{
return Proxy.newProxyInstance( method.getDeclaringClass().getClassLoader(),
new Class<?>[]{ (Class) manyAssociationType, PropertyReference.class },
new TemplateHandler<T>( null, null, manyAssociation ) );
}
}
return null;
}
}
private QueryExpressions()
{
}
}
| true | true | public static <T> T templateFor( Class<T> clazz )
{
NullArgumentException.validateNotNull( "Template class", clazz );
if( clazz.isInterface() )
{
return clazz.cast( Proxy.newProxyInstance( clazz.getClassLoader(),
new Class<?>[] { clazz },
new TemplateHandler<T>( null, null, null ) ) );
}
else
{
try
{
T mixin = clazz.newInstance();
for( Field field : clazz.getFields() )
{
if( field.getAnnotation( State.class ) != null )
{
if( field.getType().equals( Property.class ) )
{
field.set( mixin,
Proxy.newProxyInstance( field.getType().getClassLoader(),
new Class<?>[]{ field.getType() },
new PropertyReferenceHandler<>( new PropertyFunction<T>( null, null, null, field ) ) ) );
}
else if( field.getType().equals( Association.class ) )
{
field.set( mixin,
Proxy.newProxyInstance( field.getType().getClassLoader(),
new Class<?>[]{ field.getType() },
new AssociationReferenceHandler<>( new AssociationFunction<T>( null, null, field ) ) ) );
}
else if( field.getType().equals( Property.class ) )
{
field.set( mixin,
Proxy.newProxyInstance( field.getType().getClassLoader(),
new Class<?>[]{ field.getType() },
new ManyAssociationReferenceHandler<>( new ManyAssociationFunction<T>( null, null, field ) ) ) );
}
}
}
return mixin;
}
catch( IllegalAccessException | IllegalArgumentException | InstantiationException | SecurityException e )
{
throw new IllegalArgumentException( "Cannot use class as template", e );
}
}
}
| public static <T> T templateFor( Class<T> clazz )
{
NullArgumentException.validateNotNull( "Template class", clazz );
if( clazz.isInterface() )
{
return clazz.cast( Proxy.newProxyInstance( clazz.getClassLoader(),
new Class<?>[] { clazz },
new TemplateHandler<T>( null, null, null ) ) );
}
else
{
try
{
T mixin = clazz.newInstance();
for( Field field : clazz.getFields() )
{
if( field.getAnnotation( State.class ) != null )
{
if( field.getType().equals( Property.class ) )
{
field.set( mixin,
Proxy.newProxyInstance( field.getType().getClassLoader(),
new Class<?>[]{ field.getType() },
new PropertyReferenceHandler<>( new PropertyFunction<T>( null, null, null, field ) ) ) );
}
else if( field.getType().equals( Association.class ) )
{
field.set( mixin,
Proxy.newProxyInstance( field.getType().getClassLoader(),
new Class<?>[]{ field.getType() },
new AssociationReferenceHandler<>( new AssociationFunction<T>( null, null, field ) ) ) );
}
else if( field.getType().equals( ManyAssociation.class ) )
{
field.set( mixin,
Proxy.newProxyInstance( field.getType().getClassLoader(),
new Class<?>[]{ field.getType() },
new ManyAssociationReferenceHandler<>( new ManyAssociationFunction<T>( null, null, field ) ) ) );
}
}
}
return mixin;
}
catch( IllegalAccessException | IllegalArgumentException | InstantiationException | SecurityException e )
{
throw new IllegalArgumentException( "Cannot use class as template", e );
}
}
}
|
diff --git a/org.eclipse.iee.sample.formula/src/org/eclipse/iee/sample/formula/pad/hover/HoverShell.java b/org.eclipse.iee.sample.formula/src/org/eclipse/iee/sample/formula/pad/hover/HoverShell.java
index 3ccbe60..e89e0cd 100644
--- a/org.eclipse.iee.sample.formula/src/org/eclipse/iee/sample/formula/pad/hover/HoverShell.java
+++ b/org.eclipse.iee.sample.formula/src/org/eclipse/iee/sample/formula/pad/hover/HoverShell.java
@@ -1,48 +1,48 @@
package org.eclipse.iee.sample.formula.pad.hover;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class HoverShell {
public Shell fShell;
public Label fLabel;
public HoverShell(Composite parent, Image image) {
- fShell = new Shell(SWT.TOOL | SWT.NO_FOCUS);
+ fShell = new Shell(SWT.TOOL | SWT.NO_FOCUS | SWT.ON_TOP);
fShell.setVisible(false);
Point pt = parent.toDisplay(10, 30);
fShell.setLocation(pt.x, pt.y);
fShell.setSize(0, 0);
fShell.setLayout(new FillLayout());
fLabel = new Label(fShell, SWT.NONE);
setImage(image);
pack();
}
public void dispose() {
fShell.dispose();
fLabel.dispose();
}
public void setImage(Image image) {
fLabel.setImage(image);
}
public void pack() {
fShell.pack();
fShell.setVisible(true);
}
public void setVisible(boolean visibility) {
fShell.setVisible(visibility);
}
}
| true | true | public HoverShell(Composite parent, Image image) {
fShell = new Shell(SWT.TOOL | SWT.NO_FOCUS);
fShell.setVisible(false);
Point pt = parent.toDisplay(10, 30);
fShell.setLocation(pt.x, pt.y);
fShell.setSize(0, 0);
fShell.setLayout(new FillLayout());
fLabel = new Label(fShell, SWT.NONE);
setImage(image);
pack();
}
| public HoverShell(Composite parent, Image image) {
fShell = new Shell(SWT.TOOL | SWT.NO_FOCUS | SWT.ON_TOP);
fShell.setVisible(false);
Point pt = parent.toDisplay(10, 30);
fShell.setLocation(pt.x, pt.y);
fShell.setSize(0, 0);
fShell.setLayout(new FillLayout());
fLabel = new Label(fShell, SWT.NONE);
setImage(image);
pack();
}
|
diff --git a/testrunner/src/com/baidu/cafe/local/FPSTracer.java b/testrunner/src/com/baidu/cafe/local/FPSTracer.java
index 185a588..b1daa2d 100644
--- a/testrunner/src/com/baidu/cafe/local/FPSTracer.java
+++ b/testrunner/src/com/baidu/cafe/local/FPSTracer.java
@@ -1,114 +1,118 @@
package com.baidu.cafe.local;
import java.util.ArrayList;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
/**
* @author [email protected], [email protected]
* @date 2012-9-17
* @version
* @todo
*/
public class FPSTracer {
private final static int interval = 1000;
private static long mFpsStartTime = -1;
private static long mFpsPrevTime = -1;
private static int mFpsNumFrames = 0;
private static float mTotalFps = 0;
private static int mFpsCount = 0;
public static void trace(final LocalLib local) {
final boolean threadDisable = true;
new Thread(new Runnable() {
@Override
public void run() {
int time = 0;
ArrayList<View> decorViews = new ArrayList<View>();
while (threadDisable) {
time++;
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// eat it
}
- View decorView = local.getWindowDecorViews()[0];
+ View[] windowDecorViews = local.getWindowDecorViews();
+ if (0 == windowDecorViews.length) {
+ continue;
+ }
+ View decorView = windowDecorViews[0];
if (!decorViews.contains(decorView)) {
print("add listener at " + decorView);
ViewTreeObserver observer = decorView.getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
countFPS();
return true;
}
});
decorViews.add(decorView);
}
// print fps average 1s
float averageFPS = 0 == mFpsCount ? 0 : mTotalFps / mFpsCount;
print(time + "s: " + averageFPS);
modifyFPS(-1);
modifyFPSCount(0);
}
}
}).start();
}
private static void countFPS() {
long nowTime = System.currentTimeMillis();
if (mFpsStartTime < 0) {
mFpsStartTime = mFpsPrevTime = nowTime;
mFpsNumFrames = 0;
} else {
long frameTime = nowTime - mFpsPrevTime;
// print("Frame time:\t" + frameTime);
mFpsPrevTime = nowTime;
int interval = 1000;
if (frameTime < interval) {
float fps = (float) 1000 / frameTime;
// print("FPS:\t" + fps);
modifyFPS(fps);
modifyFPSCount(-1);
} else {
// discard frameTime > interval
}
}
}
/**
* @param fps
* -1 means reset mFps to 0; otherwise means add fps to mFps
*/
synchronized private static void modifyFPS(float fps) {
if (-1 == fps) {
mTotalFps = 0;
} else {
mTotalFps += fps;
}
}
/**
* @param count
* -1 means mFpsCount increase; otherwise means set mFpsCount to
* count
*/
synchronized private static void modifyFPSCount(int count) {
if (-1 == count) {
mFpsCount++;
} else {
mFpsCount = count;
}
}
private static void print(String msg) {
Log.i("FPS", msg);
}
}
| true | true | public static void trace(final LocalLib local) {
final boolean threadDisable = true;
new Thread(new Runnable() {
@Override
public void run() {
int time = 0;
ArrayList<View> decorViews = new ArrayList<View>();
while (threadDisable) {
time++;
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// eat it
}
View decorView = local.getWindowDecorViews()[0];
if (!decorViews.contains(decorView)) {
print("add listener at " + decorView);
ViewTreeObserver observer = decorView.getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
countFPS();
return true;
}
});
decorViews.add(decorView);
}
// print fps average 1s
float averageFPS = 0 == mFpsCount ? 0 : mTotalFps / mFpsCount;
print(time + "s: " + averageFPS);
modifyFPS(-1);
modifyFPSCount(0);
}
}
}).start();
}
| public static void trace(final LocalLib local) {
final boolean threadDisable = true;
new Thread(new Runnable() {
@Override
public void run() {
int time = 0;
ArrayList<View> decorViews = new ArrayList<View>();
while (threadDisable) {
time++;
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// eat it
}
View[] windowDecorViews = local.getWindowDecorViews();
if (0 == windowDecorViews.length) {
continue;
}
View decorView = windowDecorViews[0];
if (!decorViews.contains(decorView)) {
print("add listener at " + decorView);
ViewTreeObserver observer = decorView.getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
countFPS();
return true;
}
});
decorViews.add(decorView);
}
// print fps average 1s
float averageFPS = 0 == mFpsCount ? 0 : mTotalFps / mFpsCount;
print(time + "s: " + averageFPS);
modifyFPS(-1);
modifyFPSCount(0);
}
}
}).start();
}
|
diff --git a/juddi-client/src/main/java/org/apache/juddi/v3/client/UDDIServiceWSDL.java b/juddi-client/src/main/java/org/apache/juddi/v3/client/UDDIServiceWSDL.java
index 9bd102812..b416fd4a2 100644
--- a/juddi-client/src/main/java/org/apache/juddi/v3/client/UDDIServiceWSDL.java
+++ b/juddi-client/src/main/java/org/apache/juddi/v3/client/UDDIServiceWSDL.java
@@ -1,151 +1,152 @@
package org.apache.juddi.v3.client;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class UDDIServiceWSDL {
/** The WSDLEnpoint Types as defined in the UDDI v3 specification. */
public static enum WSDLEndPointType {SECURITY, INQUIRY, PUBLISH, SUBSCRIPTION, SUBSCRIPTION_LISTENER, CUSTODY_TRANSFER,
REPLICATION, VALUESETVALIDATION, VALUESETCACHING};
/** The default file name of the uddi_v3_service.wsdl file. The file will be located and read of the classpath. */
private String uddiV3ServiceWSDL = "uddi_v3_service.wsdl";
/** The default soap:address location values of the WSDLEndPointTypes as defined in the UDDI v3 Client Specification. */
private final static Map<WSDLEndPointType, String> specEndPoints = new HashMap<WSDLEndPointType, String>();
/** the wsdl imports */
private final static String[] imports = {
"uddi_api_v3_binding.wsdl",
"uddi_api_v3_portType.wsdl",
"uddi_custody_v3_binding.wsdl",
"uddi_custody_v3_portType.wsdl",
"uddi_repl_v3_binding.wsdl",
"uddi_repl_v3_portType.wsdl",
"uddi_sub_v3_binding.wsdl",
"uddi_sub_v3_portType.wsdl",
"uddi_subr_v3_binding.wsdl",
"uddi_subr_v3_portType.wsdl",
"uddi_v3.xsd",
"uddi_v3_service.wsdl",
"uddi_v3custody.xsd",
"uddi_v3policy.xsd",
"uddi_v3policy_instanceParms.xsd",
"uddi_v3replication.xsd",
"uddi_v3subscription.xsd",
"uddi_v3subscriptionListener.xsd",
"uddi_v3valueset.xsd",
"uddi_v3valuesetcaching.xsd",
"uddi_vs_v3_binding.wsdl",
"uddi_vs_v3_portType.wsdl",
"uddi_vscache_v3_binding.wsdl",
"uddi_vscache_v3_portType.wsdl"
};
static {
specEndPoints.put(WSDLEndPointType.SECURITY , "http://localhost/uddi/security/");
specEndPoints.put(WSDLEndPointType.INQUIRY , "http://localhost/uddi/inquire/");
specEndPoints.put(WSDLEndPointType.PUBLISH , "http://localhost/uddi/publish/");
specEndPoints.put(WSDLEndPointType.SUBSCRIPTION , "http://localhost/uddi/subscription/");
specEndPoints.put(WSDLEndPointType.SUBSCRIPTION_LISTENER, "http://localhost/uddi/subscriptionlistener/");
specEndPoints.put(WSDLEndPointType.CUSTODY_TRANSFER , "http://localhost/uddi/custody/");
specEndPoints.put(WSDLEndPointType.REPLICATION , "http://localhost/uddi/replication/");
specEndPoints.put(WSDLEndPointType.VALUESETVALIDATION , "http://localhost/uddi/valuesetvalidation/");
specEndPoints.put(WSDLEndPointType.VALUESETCACHING , "http://localhost/uddi/valuesetcaching/");
}
/**
* Returns the path to a temporary uddi_v3_service.wsdl file, where the soap:address location
* of the given endPointType has been updated with the value specified in the soapAddressLocation.
*
* @param endpointType
* @param soapAddressLocation
* @return WSDL File Path
* @throws IOException
*/
public URL getWSDLFilePath(WSDLEndPointType endpointType, String soapAddressLocation) throws IOException
{
String wsdlString = getServiceWSDLContent();
String specEndPoint = specEndPoints.get(endpointType);
wsdlString = wsdlString.replace(specEndPoint, soapAddressLocation);
String destDir = System.getProperty("java.io.tmpdir");
File tmpDir = new File(destDir);
if (!tmpDir.exists()) {
System.out.println("tmp dir does not exist:" + destDir);
+ tmpDir.mkdirs();
}
File tmpWSDLFile = new File(destDir + File.separator + "uddi_v3_service.wsdl");
if (tmpWSDLFile.exists()) {
tmpWSDLFile.delete();
}
tmpWSDLFile.createNewFile();
Writer out = new OutputStreamWriter(new FileOutputStream(tmpWSDLFile));
try {
out.write(wsdlString);
} finally {
out.close();
}
copyImportFiles();
URL url = new URL("file:" + tmpWSDLFile.getAbsolutePath());
return url;
}
/**
*
* @return
* @throws IOException
*/
protected String getServiceWSDLContent() throws IOException
{
URL serviceWSDLURL = ClassUtil.getResource(getUddiV3ServiceWSDL(), this.getClass());
if (serviceWSDLURL==null) throw new IOException("Could not locate resource " + getUddiV3ServiceWSDL());
return read(serviceWSDLURL);
}
private void copyImportFiles() throws IOException
{
URL serviceWSDLURL = ClassUtil.getResource(getUddiV3ServiceWSDL(),this.getClass());
if (serviceWSDLURL==null) throw new IOException("Could not locate resource " + getUddiV3ServiceWSDL());
int endIndex = 0;
if (getUddiV3ServiceWSDL().contains(File.separator)) {
endIndex = getUddiV3ServiceWSDL().lastIndexOf(File.separator);
}
String srcDir = getUddiV3ServiceWSDL().substring(0,endIndex);
String destDir = System.getProperty("java.io.tmpdir");
for (String importFileName : imports) {
URL url = ClassUtil.getResource(srcDir + importFileName, this.getClass());
String content = read(url);
File importFile = new File(destDir + File.separator + importFileName);
Writer out = new OutputStreamWriter(new FileOutputStream(importFile));
try {
out.write(content);
} finally {
out.close();
}
}
}
private String read(URL url) throws IOException {
InputStream resourceStream = url.openStream();
StringBuilder wsdl = new StringBuilder();
byte[] b = new byte[4096];
for (int n; (n = resourceStream.read(b)) != -1;) {
wsdl.append(new String(b, 0, n));
}
return wsdl.toString();
}
public String getUddiV3ServiceWSDL() {
return uddiV3ServiceWSDL;
}
public void setUddiV3ServiceWSDL(String uddiV3ServiceWSDL) {
this.uddiV3ServiceWSDL = uddiV3ServiceWSDL;
}
}
| true | true | public URL getWSDLFilePath(WSDLEndPointType endpointType, String soapAddressLocation) throws IOException
{
String wsdlString = getServiceWSDLContent();
String specEndPoint = specEndPoints.get(endpointType);
wsdlString = wsdlString.replace(specEndPoint, soapAddressLocation);
String destDir = System.getProperty("java.io.tmpdir");
File tmpDir = new File(destDir);
if (!tmpDir.exists()) {
System.out.println("tmp dir does not exist:" + destDir);
}
File tmpWSDLFile = new File(destDir + File.separator + "uddi_v3_service.wsdl");
if (tmpWSDLFile.exists()) {
tmpWSDLFile.delete();
}
tmpWSDLFile.createNewFile();
Writer out = new OutputStreamWriter(new FileOutputStream(tmpWSDLFile));
try {
out.write(wsdlString);
} finally {
out.close();
}
copyImportFiles();
URL url = new URL("file:" + tmpWSDLFile.getAbsolutePath());
return url;
}
| public URL getWSDLFilePath(WSDLEndPointType endpointType, String soapAddressLocation) throws IOException
{
String wsdlString = getServiceWSDLContent();
String specEndPoint = specEndPoints.get(endpointType);
wsdlString = wsdlString.replace(specEndPoint, soapAddressLocation);
String destDir = System.getProperty("java.io.tmpdir");
File tmpDir = new File(destDir);
if (!tmpDir.exists()) {
System.out.println("tmp dir does not exist:" + destDir);
tmpDir.mkdirs();
}
File tmpWSDLFile = new File(destDir + File.separator + "uddi_v3_service.wsdl");
if (tmpWSDLFile.exists()) {
tmpWSDLFile.delete();
}
tmpWSDLFile.createNewFile();
Writer out = new OutputStreamWriter(new FileOutputStream(tmpWSDLFile));
try {
out.write(wsdlString);
} finally {
out.close();
}
copyImportFiles();
URL url = new URL("file:" + tmpWSDLFile.getAbsolutePath());
return url;
}
|
diff --git a/test-modules/test-core/src/main/java/org/openlmis/UiUtils/DBWrapper.java b/test-modules/test-core/src/main/java/org/openlmis/UiUtils/DBWrapper.java
index e91ecb9a03..4b05dc7908 100644
--- a/test-modules/test-core/src/main/java/org/openlmis/UiUtils/DBWrapper.java
+++ b/test-modules/test-core/src/main/java/org/openlmis/UiUtils/DBWrapper.java
@@ -1,1576 +1,1578 @@
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.UiUtils;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.lang.String.format;
import static java.lang.System.getProperty;
public class DBWrapper {
public static final int DEFAULT_MAX_MONTH_OF_STOCK = 3;
public static final String DEFAULT_DB_URL = "jdbc:postgresql://localhost:5432/open_lmis";
public static final String DEFAULT_DB_USERNAME = "postgres";
public static final String DEFAULT_DB_PASSWORD = "p@ssw0rd";
Connection connection;
public DBWrapper() throws IOException, SQLException {
String dbUser = getProperty("dbUser", DEFAULT_DB_USERNAME);
String dbPassword = getProperty("dbPassword", DEFAULT_DB_PASSWORD);
String dbUrl = getProperty("dbUrl", DEFAULT_DB_URL);
loadDriver();
connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
}
public void closeConnection() throws SQLException {
if (connection != null) connection.close();
}
private void loadDriver() {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.exit(1);
}
}
private void update(String sql) throws SQLException {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
}
}
private void update(String sql, Object... params) throws SQLException {
update(format(sql, params));
}
private ResultSet query(String sql) throws SQLException {
return connection.createStatement().executeQuery(sql);
}
private List<Map<String, String>> select(String sql, Object... params) throws SQLException {
ResultSet rs = query(sql, params);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List<Map<String, String>> list = new ArrayList<>();
while (rs.next()) {
Map<String, String> row = new HashMap<>();
for (int i = 1; i <= columns; ++i) {
row.put(md.getColumnName(i), rs.getString(i));
}
list.add(row);
}
return list;
}
private ResultSet query(String sql, Object... params) throws SQLException {
return query(format(sql, params));
}
public void insertUser(String userId, String userName, String password, String facilityCode, String email)
throws SQLException, IOException {
update("delete from users where userName like('%s')", userName);
update("INSERT INTO users(id, userName, password, facilityId, firstName, lastName, email, active, verified) " +
"VALUES ('%s', '%s', '%s', (SELECT id FROM facilities WHERE code = '%s'), 'Fatima', 'Doe', '%s','true','true')",
userId, userName, password, facilityCode, email);
}
public void insertPeriodAndAssociateItWithSchedule(String period, String schedule) throws SQLException, IOException {
insertProcessingPeriod(period, period, "2013-09-29", "2020-09-30", 66, schedule);
}
public void deleteProcessingPeriods() throws SQLException, IOException {
update("delete from processing_periods");
}
public List<String> getProductDetailsForProgram(String programCode) throws SQLException {
List<String> prodDetails = new ArrayList<>();
ResultSet rs = query("select programs.code as programCode, programs.name as programName, " +
"products.code as productCode, products.primaryName as productName, products.description as desc, " +
"products.dosesPerDispensingUnit as unit, PG.name as pgName " +
"from products, programs, program_products PP, product_categories PG " +
"where programs.id = PP.programId and PP.productId=products.id and " +
"PG.id = products.categoryId and programs.code='" + programCode + "' " +
"and products.active='true' and PP.active='true'");
while (rs.next()) {
String programName = rs.getString(2);
String productCode = rs.getString(3);
String productName = rs.getString(4);
String desc = rs.getString(5);
String unit = rs.getString(6);
String pcName = rs.getString(7);
prodDetails.add(programName + "," + productCode + "," + productName + "," + desc + "," + unit + "," + pcName);
}
return prodDetails;
}
public List<String> getProductDetailsForProgramAndFacilityType(String programCode, String facilityCode) throws SQLException {
List<String> prodDetails = new ArrayList<>();
ResultSet rs = query("select prog.code as programCode, prog.name as programName, prod.code as productCode, " +
"prod.primaryName as productName, prod.description as desc, prod.dosesPerDispensingUnit as unit, " +
"pg.name as pgName from products prod, programs prog, program_products pp, product_categories pg, " +
"facility_approved_products fap, facility_types ft where prog.id=pp.programId and pp.productId=prod.id and " +
"pg.id = prod.categoryId and fap. programProductId = pp.id and ft.id=fap.facilityTypeId and prog.code='" +
programCode + "' and ft.code='" + facilityCode + "' " + "and prod.active='true' and pp.active='true'");
while (rs.next()) {
String programName = rs.getString(2);
String productCode = rs.getString(3);
String productName = rs.getString(4);
String desc = rs.getString(5);
String unit = rs.getString(6);
String pgName = rs.getString(7);
prodDetails.add(programName + "," + productCode + "," + productName + "," + desc + "," + unit + "," + pgName);
}
return prodDetails;
}
public void updateActiveStatusOfProduct(String productCode, String active) throws SQLException {
update("update products set active='%s' where code='%s'", active, productCode);
}
public int getRecordCountInTable(String tableName) throws SQLException {
ResultSet rs = query("select count(*) from %s", tableName);
if (rs.next()) {
return rs.getInt("count");
}
return -1;
}
public void updateActiveStatusOfProgramProduct(String productCode, String programCode, String active) throws SQLException {
update("update program_products set active='%s' WHERE" +
" programId = (select id from programs where code='%s') AND" +
" productId = (select id from products where code='%s')", active, programCode, productCode);
}
public List<String> getFacilityCodeNameForDeliveryZoneAndProgram(String deliveryZoneName, String program, boolean active) throws SQLException {
List<String> codeName = new ArrayList<>();
ResultSet rs = query("select f.code, f.name from facilities f, programs p, programs_supported ps, delivery_zone_members dzm, delivery_zones dz where " +
"dzm.DeliveryZoneId=dz.id and " +
"f.active='" + active + "' and " +
"p.id= ps.programId and " +
"p.code='" + program + "' and " +
"dz.id = dzm.DeliveryZoneId and " +
"dz.name='" + deliveryZoneName + "' and " +
"dzm.facilityId = f.id and " +
"ps.facilityId = f.id;");
while (rs.next()) {
String code = rs.getString("code");
String name = rs.getString("name");
codeName.add(code + " - " + name);
}
return codeName;
}
public void updateVirtualPropertyOfFacility(String facilityCode, String flag) throws SQLException, IOException {
update("UPDATE facilities SET virtualFacility='%s' WHERE code='%s'", flag, facilityCode);
}
public void deleteDeliveryZoneMembers(String facilityCode) throws SQLException, IOException {
update("delete from delivery_zone_members where facilityId in (select id from facilities where code ='%s')", facilityCode);
}
public String getVirtualPropertyOfFacility(String facilityCode) throws SQLException, IOException {
String flag = "";
ResultSet rs = query("select virtualFacility from facilities where code = '%s'", facilityCode);
if (rs.next()) {
flag = rs.getString("virtualFacility");
}
return flag;
}
public String getActivePropertyOfFacility(String facilityCode) throws SQLException, IOException {
String flag = "";
ResultSet rs = query("select active from facilities where code='%s'", facilityCode);
if (rs.next()) {
flag = rs.getString("active");
}
return flag;
}
public void updateUser(String password, String email) throws SQLException, IOException {
update("DELETE FROM user_password_reset_tokens");
update("update users set password = '%s', active = TRUE, verified = TRUE where email = '%s'", password, email);
}
public void updateRestrictLogin(String userName, boolean status) throws SQLException, IOException {
update("update users set restrictLogin = '%s' where userName = '%s'", status, userName);
}
public String getRestrictLogin(String userName) throws SQLException, IOException {
String status = null;
ResultSet rs = query("select restrictLogin from users where userName='%s'", userName);
if (rs.next()) {
status = rs.getString("restrictLogin");
}
return status;
}
public void insertRequisitions(int numberOfRequisitions, String program, boolean withSupplyLine) throws SQLException, IOException {
int numberOfRequisitionsAlreadyPresent = 0;
boolean flag = true;
ResultSet rs = query("select count(*) from requisitions");
if (rs.next()) {
numberOfRequisitionsAlreadyPresent = Integer.parseInt(rs.getString(1));
}
for (int i = numberOfRequisitionsAlreadyPresent + 1; i <= numberOfRequisitions + numberOfRequisitionsAlreadyPresent; i++) {
insertProcessingPeriod("PeriodName" + i, "PeriodDesc" + i, "2012-12-01", "2015-12-01", 1, "M");
update("insert into requisitions (facilityId, programId, periodId, status, emergency, " +
"fullSupplyItemsSubmittedCost, nonFullSupplyItemsSubmittedCost, supervisoryNodeId) " +
"values ((Select id from facilities where code='F10'),(Select id from programs where code='" + program + "')," +
"(Select id from processing_periods where name='PeriodName" + i + "'), 'APPROVED', 'false', 50.0000, 0.0000, " +
"(select id from supervisory_nodes where code='N1'))");
update("INSERT INTO requisition_line_items " +
"(rnrId, productCode,product,productDisplayOrder,productCategory,productCategoryDisplayOrder, beginningBalance, quantityReceived, quantityDispensed, stockInHand, " +
"dispensingUnit, maxMonthsOfStock, dosesPerMonth, dosesPerDispensingUnit, packSize,fullSupply,totalLossesAndAdjustments,newPatientCount,stockOutDays,price,roundToZero,packRoundingThreshold) VALUES" +
"((SELECT max(id) FROM requisitions), 'P10','antibiotic Capsule 300/200/600 mg',1,'Antibiotics',1, '0', '11' , '1', '10' ,'Strip','3', '30', '10', '10','t',0,0,0,12.5000,'f',1);");
}
if (withSupplyLine) {
ResultSet rs1 = query("select * from supply_lines where supervisoryNodeId = " +
"(select id from supervisory_nodes where code = 'N1') and programId = " +
"(select id from programs where code='" + program + "') and supplyingFacilityId = " +
"(select id from facilities where code = 'F10')");
if (rs1.next()) {
flag = false;
}
}
if (withSupplyLine) {
if (flag) {
insertSupplyLines("N1", program, "F10", true);
}
}
}
public void insertFulfilmentRoleAssignment(String userName, String roleName, String facilityCode) throws SQLException {
update("insert into fulfillment_role_assignments(userId, roleId, facilityId) values " +
"((select id from users where username='" + userName + "')," +
"(select id from roles where name='" + roleName + "'),(select id from facilities where code='" + facilityCode + "'))");
}
public String getDeliveryZoneNameAssignedToUser(String user) throws SQLException, IOException {
String deliveryZoneName = "";
ResultSet rs = query("select name from delivery_zones where id in(select deliveryZoneId from role_assignments where " +
"userId=(select id from users where username='" + user + "'))");
if (rs.next()) {
deliveryZoneName = rs.getString("name");
}
return deliveryZoneName;
}
public String getRoleNameAssignedToUser(String user) throws SQLException, IOException {
String userName = "";
ResultSet rs = query("select name from roles where id in(select roleId from role_assignments where " +
"userId=(select id from users where username='" + user + "'))");
if (rs.next()) {
userName = rs.getString("name");
}
return userName;
}
public void insertFacilities(String facility1, String facility2) throws IOException, SQLException {
update("INSERT INTO facilities\n" +
"(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility) values\n" +
"('" + facility1 + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',5,2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/1887','TRUE','fc','TRUE', 'FALSE'),\n" +
"('" + facility2 + "','Central Hospital','IT department','G7646',9876234981,'fax','A','B',5,2,333,22.3,1.2,3.3,3,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'FALSE');\n");
update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES" +
" ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 1, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 2, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 5, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 1, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 5, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 2, '11/11/12', true, 1)");
}
public void insertVirtualFacility(String facilityCode, String parentFacilityCode) throws IOException, SQLException {
update("INSERT INTO facilities\n" +
"(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility,parentFacilityId) values\n" +
"('" + facilityCode + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',5,2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'TRUE',(SELECT id FROM facilities WHERE code = '" + parentFacilityCode + "'))");
update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES" +
" ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 1, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 2, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 5, '11/11/12', true, 1)");
update("insert into requisition_group_members (requisitionGroupId, facilityId, createdDate, modifiedDate) values " +
"((select requisitionGroupId from requisition_group_members where facilityId=(SELECT id FROM facilities WHERE code = '" + parentFacilityCode + "'))," +
"(SELECT id FROM facilities WHERE code = '" + facilityCode + "'),NOW(),NOW())");
}
public void deletePeriod(String periodName) throws IOException, SQLException {
update("delete from processing_periods where name='" + periodName + "';");
}
public void insertFacilitiesWithDifferentGeoZones(String facility1, String facility2, String geoZone1, String geoZone2) throws IOException, SQLException {
update("INSERT INTO facilities\n" +
"(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility) values\n" +
"('" + facility1 + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',(select id from geographic_zones where code='" + geoZone1 + "'),2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/1887','TRUE','fc','TRUE', 'FALSE'),\n" +
"('" + facility2 + "','Central Hospital','IT department','G7646',9876234981,'fax','A','B',(select id from geographic_zones where code='" + geoZone2 + "'),2,333,22.3,1.2,3.3,3,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'FALSE');\n");
update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES\n" +
"((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 1, '11/11/12', true, 1),\n" +
"((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 2, '11/11/12', true, 1),\n" +
"((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 5, '11/11/12', true, 1),\n" +
"((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 1, '11/11/12', true, 1),\n" +
"((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 5, '11/11/12', true, 1),\n" +
"((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 2, '11/11/12', true, 1);");
}
public void insertGeographicZone(String code, String name, String parentName) throws IOException, SQLException {
update("insert into geographic_zones (code, name, levelId, parentId) " +
"values ('%s','%s',(select max(levelId) from geographic_zones)," +
"(select id from geographic_zones where code='%s'))", code, name, parentName);
}
public void allocateFacilityToUser(String userId, String facilityCode) throws IOException, SQLException {
update("update users set facilityId = (Select id from facilities where code = '%s') where id = '%s'", facilityCode, userId);
}
public void updateSourceOfAProgramTemplate(String program, String label, String source) throws IOException, SQLException {
update("update program_rnr_columns set source = '%s'" +
" where programId = (select id from programs where code = '%s') and label = '%s'", source, program, label);
}
public void deleteData() throws SQLException, IOException {
update("delete from budget_line_items");
update("delete from budget_file_info");
update("delete from role_rights where roleId not in(1)");
update("delete from role_assignments where userId not in (1)");
update("delete from fulfillment_role_assignments");
update("delete from roles where name not in ('Admin')");
update("delete from facility_approved_products");
update("delete from program_product_price_history");
update("delete from pod_line_items");
update("delete from pod");
update("delete from orders");
update("DELETE FROM requisition_status_changes");
update("delete from user_password_reset_tokens");
update("delete from comments");
update("delete from facility_visits");
update("delete from epi_use_line_items");
update("delete from epi_use");
+ update("delete from epi_inventory");
+ update("delete from epi_inventory_line_items");
update("delete from refrigerator_problems");
update("delete from refrigerator_readings");
update("delete from distribution_refrigerators");
update("delete from distributions");
update("delete from users where userName not like('Admin%')");
update("DELETE FROM requisition_line_item_losses_adjustments");
update("DELETE FROM requisition_line_items");
update("DELETE FROM regimen_line_items");
update("DELETE FROM requisitions");
update("delete from program_product_isa");
update("delete from facility_approved_products");
update("delete from facility_program_products");
update("delete from program_products");
update("delete from products");
update("delete from product_categories");
update("delete from product_groups");
update("delete from supply_lines");
update("delete from programs_supported");
update("delete from requisition_group_members");
update("delete from program_rnr_columns");
update("delete from requisition_group_program_schedules");
update("delete from requisition_groups");
update("delete from requisition_group_members");
update("delete from delivery_zone_program_schedules");
update("delete from delivery_zone_warehouses");
update("delete from delivery_zone_members");
update("delete from role_assignments where deliveryZoneId in (select id from delivery_zones where code in('DZ1','DZ2'))");
update("delete from delivery_zones");
update("delete from supervisory_nodes");
update("delete from refrigerators");
update("delete from facility_ftp_details");
update("delete from facilities");
update("delete from geographic_zones where code not in ('Root','Arusha','Dodoma', 'Ngorongoro')");
update("delete from processing_periods");
update("delete from processing_schedules");
update("delete from atomfeed.event_records");
update("delete from regimens");
update("delete from program_regimen_columns");
}
public void insertRole(String role, String description) throws SQLException, IOException {
ResultSet rs = query("Select id from roles where name='%s'", role);
if (!rs.next()) {
update("INSERT INTO roles(name, description) VALUES('%s', '%s')", role, description);
}
}
public void insertSupervisoryNode(String facilityCode, String supervisoryNodeCode, String supervisoryNodeName, String supervisoryNodeParentCode) throws SQLException, IOException {
update("delete from supervisory_nodes");
update("INSERT INTO supervisory_nodes (parentId, facilityId, name, code) " +
"VALUES (%s, (SELECT id FROM facilities WHERE code = '%s'), '%s', '%s')",
supervisoryNodeParentCode, facilityCode, supervisoryNodeName, supervisoryNodeCode);
}
public void insertSupervisoryNodeSecond(String facilityCode,
String supervisoryNodeCode,
String supervisoryNodeName,
String supervisoryNodeParentCode) throws SQLException, IOException {
update("INSERT INTO supervisory_nodes" +
" (parentId, facilityId, name, code) VALUES" +
" ((select id from supervisory_nodes where code ='%s'), (SELECT id FROM facilities WHERE code = '%s'), '%s', '%s')"
, supervisoryNodeParentCode, facilityCode, supervisoryNodeName, supervisoryNodeCode);
}
public void insertRequisitionGroups(String code1, String code2, String supervisoryNodeCode1, String supervisoryNodeCode2) throws SQLException, IOException {
ResultSet rs = query("Select id from requisition_groups;");
if (rs.next()) {
update("delete from requisition_groups;");
}
update("INSERT INTO requisition_groups ( code ,name,description,supervisoryNodeId )values\n" +
"('" + code2 + "','Requistion Group 2','Supports EM(Q1M)',(select id from supervisory_nodes where code ='" + supervisoryNodeCode2 + "')),\n" +
"('" + code1 + "','Requistion Group 1','Supports EM(Q2M)',(select id from supervisory_nodes where code ='" + supervisoryNodeCode1 + "'))");
}
public void insertRequisitionGroupMembers(String RG1facility, String RG2facility) throws SQLException, IOException {
ResultSet rs = query("Select requisitionGroupId from requisition_group_members;");
if (rs.next()) {
update("delete from requisition_group_members;");
}
update("INSERT INTO requisition_group_members ( requisitionGroupId ,facilityId )values\n" +
"((select id from requisition_groups where code ='RG1'),(select id from facilities where code ='" + RG1facility + "')),\n" +
"((select id from requisition_groups where code ='RG2'),(select id from facilities where code ='" + RG2facility + "'));");
}
public void insertRequisitionGroupProgramSchedule() throws SQLException, IOException {
ResultSet rs = query("Select requisitionGroupId from requisition_group_members;");
if (rs.next()) {
update("delete from requisition_group_program_schedules;");
}
update("insert into requisition_group_program_schedules ( requisitionGroupId , programId , scheduleId , directDelivery ) values\n" +
"((select id from requisition_groups where code='RG1'),(select id from programs where code='ESS_MEDS'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" +
"((select id from requisition_groups where code='RG1'),(select id from programs where code='MALARIA'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" +
"((select id from requisition_groups where code='RG1'),(select id from programs where code='HIV'),(select id from processing_schedules where code='M'),TRUE),\n" +
"((select id from requisition_groups where code='RG2'),(select id from programs where code='ESS_MEDS'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" +
"((select id from requisition_groups where code='RG2'),(select id from programs where code='MALARIA'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" +
"((select id from requisition_groups where code='RG2'),(select id from programs where code='HIV'),(select id from processing_schedules where code='M'),TRUE);\n");
}
//TODO
public void insertRoleAssignment(String userID, String roleName) throws SQLException, IOException {
update("delete from role_assignments where userId='" + userID + "';");
update(" INSERT INTO role_assignments\n" +
" (userId, roleId, programId, supervisoryNodeId) VALUES \n" +
" ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, null),\n" +
" ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, (SELECT id from supervisory_nodes WHERE code = 'N1'));");
}
//TODO
public void insertRoleAssignmentForSupervisoryNodeForProgramId1(String userID, String roleName, String supervisoryNode) throws SQLException, IOException {
update("delete from role_assignments where userId='" + userID + "';");
update(" INSERT INTO role_assignments\n" +
" (userId, roleId, programId, supervisoryNodeId) VALUES \n" +
" ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, null),\n" +
" ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, (SELECT id from supervisory_nodes WHERE code = '" + supervisoryNode + "'));");
}
public void updateRoleGroupMember(String facilityCode) throws SQLException, IOException {
update("update requisition_group_members set facilityId = " +
"(select id from facilities where code ='" + facilityCode + "') where " +
"requisitionGroupId=(select id from requisition_groups where code='RG2');");
update("update requisition_group_members set facilityId = " +
"(select id from facilities where code ='F11') where requisitionGroupId = " +
"(select id from requisition_groups where code='RG1');");
}
public void alterUserID(String userName, String userId) throws SQLException, IOException {
update("delete from user_password_reset_tokens;");
update("delete from users where id='" + userId + "' ;");
update(" update users set id='" + userId + "' where username='" + userName + "'");
}
public void insertProducts(String product1, String product2) throws SQLException, IOException {
update("delete from facility_approved_products;");
update("delete from program_products;");
update("delete from products;");
update("delete from product_categories;");
update("INSERT INTO product_categories (code, name, displayOrder) values ('C1', 'Antibiotics', 1);");
update("INSERT INTO products\n" +
"(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" +
"('" + product1 + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1')),\n" +
"('" + product2 + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1'));\n");
}
public void deleteCategoryFromProducts() throws SQLException, IOException {
update("UPDATE products SET categoryId = null");
}
public void deleteDescriptionFromProducts() throws SQLException, IOException {
update("UPDATE products SET description = null");
}
public void insertProductWithCategory(String product, String productName, String category) throws SQLException, IOException {
update("INSERT INTO product_categories (code, name, displayOrder) values ('" + category + "', '" + productName + "', 1);");
update("INSERT INTO products\n" +
"(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" +
"('" + product + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', '" + productName + "', '" + productName + "', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1'));\n");
}
public void insertProductGroup(String group) throws SQLException, IOException {
update("INSERT INTO product_groups (code, name) values ('" + group + "', '" + group + "-Name');");
}
public void insertProductWithGroup(String product, String productName, String group, boolean status) throws SQLException, IOException {
update("INSERT INTO products\n" +
"(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, productGroupId) values\n" +
"('" + product + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', '" + productName + "', '" + productName + "', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', " + status + ",TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_groups where code='" + group + "'));\n");
}
public void updateProgramToAPushType(String program, boolean flag) throws SQLException {
update("update programs set push='" + flag + "' where code='" + program + "';");
}
public void insertProgramProducts(String product1, String product2, String program) throws SQLException, IOException {
ResultSet rs = query("Select id from program_products;");
if (rs.next()) {
update("delete from facility_approved_products;");
update("delete from program_products;");
}
update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" +
"((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product1 + "'), 30, 12.5, true),\n" +
"((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product2 + "'), 30, 12.5, true);");
}
public void insertProgramProduct(String product, String program, String doses, String active) throws SQLException, IOException {
update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" +
"((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product + "'), '" + doses + "', 12.5, '" + active + "');");
}
public void insertProgramProductsWithCategory(String product, String program) throws SQLException, IOException {
update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" +
"((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product + "'), 30, 12.5, true);");
}
public void insertProgramProductISA(String program, String product, String whoRatio, String dosesPerYear, String wastageFactor, String bufferPercentage, String minimumValue, String maximumValue, String adjustmentValue) throws SQLException, IOException {
update("INSERT INTO program_product_isa(programProductId, whoRatio, dosesPerYear, wastageFactor, bufferPercentage, minimumValue, maximumValue, adjustmentValue) VALUES\n" +
"((SELECT ID from program_products where programId = " +
"(SELECT ID from programs where code='" + program + "') and productId = " +
"(SELECT id from products WHERE code = '" + product + "')),"
+ whoRatio + "," + dosesPerYear + "," + wastageFactor + "," + bufferPercentage + "," + minimumValue + ","
+ maximumValue + "," + adjustmentValue + ");");
}
public void deleteFacilityApprovedProducts() throws SQLException {
update("DELETE FROM facility_approved_products");
}
public void insertFacilityApprovedProduct(String productCode, String programCode, String facilityTypeCode) throws Exception {
String facilityTypeIdQuery = format("(SELECT id FROM facility_types WHERE code = '%s')", facilityTypeCode);
String productIdQuery = format("(SELECT id FROM products WHERE code = '%s')", productCode);
String programIdQuery = format("(SELECT ID from programs where code = '%s' )", programCode);
String programProductIdQuery = format("(SELECT id FROM program_products WHERE programId = %s AND productId = %s)",
programIdQuery, productIdQuery);
update(format("INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES (%s,%s,%d)",
facilityTypeIdQuery, programProductIdQuery, DEFAULT_MAX_MONTH_OF_STOCK));
}
public String fetchNonFullSupplyData(String productCode, String facilityTypeID, String programID) throws SQLException, IOException {
ResultSet rs = query("Select p.code, p.displayOrder, p.primaryName, pf.code as ProductForm," +
"p.strength as Strength, du.code as DosageUnit from facility_approved_products fap, " +
"program_products pp, products p, product_forms pf , dosage_units du where fap. facilityTypeId='" + facilityTypeID + "' " +
"and p. fullSupply = false and p.active=true and pp.programId='" + programID + "' and p. code='" + productCode + "' " +
"and pp.productId=p.id and fap. programProductId=pp.id and pp.active=true and pf.id=p.formId " +
"and du.id = p.dosageUnitId order by p. displayOrder asc;");
String nonFullSupplyValues = null;
if (rs.next()) {
nonFullSupplyValues = rs.getString("primaryName") + " " + rs.getString("productForm") + " " + rs.getString("strength") + " " + rs.getString("dosageUnit");
}
return nonFullSupplyValues;
}
public void insertSchedule(String scheduleCode, String scheduleName, String scheduleDesc) throws SQLException, IOException {
update("INSERT INTO processing_schedules(code, name, description) values('" + scheduleCode + "', '" + scheduleName + "', '" + scheduleDesc + "');");
}
public void insertProcessingPeriod(String periodName, String periodDesc, String periodStartDate, String periodEndDate, Integer numberOfMonths, String scheduleCode) throws SQLException, IOException {
update("INSERT INTO processing_periods\n" +
"(name, description, startDate, endDate, numberOfMonths, scheduleId, modifiedBy) VALUES\n" +
"('" + periodName + "', '" + periodDesc + "', '" + periodStartDate + " 00:00:00', '" + periodEndDate + " 23:59:59', " + numberOfMonths + ", (SELECT id FROM processing_schedules WHERE code = '" + scheduleCode + "'), (SELECT id FROM users LIMIT 1));");
}
public void configureTemplate(String program) throws SQLException, IOException {
update("INSERT INTO program_rnr_columns\n" +
"(masterColumnId, programId, visible, source, formulaValidationRequired, position, label) VALUES\n" +
"(1, (select id from programs where code = '" + program + "'), true, 'U', false,1, 'Skip'),\n" +
"(2, (select id from programs where code = '" + program + "'), true, 'R', false,2, 'Product Code'),\n" +
"(3, (select id from programs where code = '" + program + "'), true, 'R', false,3, 'Product'),\n" +
"(4, (select id from programs where code = '" + program + "'), true, 'R', false,4, 'Unit/Unit of Issue'),\n" +
"(5, (select id from programs where code = '" + program + "'), true, 'U', false,5, 'Beginning Balance'),\n" +
"(6, (select id from programs where code = '" + program + "'), true, 'U', false,6, 'Total Received Quantity'),\n" +
"(7, (select id from programs where code = '" + program + "'), true, 'C', false,7, 'Total'),\n" +
"(8, (select id from programs where code = '" + program + "'), true, 'U', false,8, 'Total Consumed Quantity'),\n" +
"(9, (select id from programs where code = '" + program + "'), true, 'U', false,9, 'Total Losses / Adjustments'),\n" +
"(10, (select id from programs where code = '" + program + "'), true, 'C', true,10, 'Stock on Hand'),\n" +
"(11, (select id from programs where code = '" + program + "'), true, 'U', false,11, 'New Patients'),\n" +
"(12, (select id from programs where code = '" + program + "'), true, 'U', false,12, 'Total StockOut days'),\n" +
"(13, (select id from programs where code = '" + program + "'), true, 'C', false,13, 'Adjusted Total Consumption'),\n" +
"(14, (select id from programs where code = '" + program + "'), true, 'C', false,14, 'Average Monthly Consumption(AMC)'),\n" +
"(15, (select id from programs where code = '" + program + "'), true, 'C', false,15, 'Maximum Stock Quantity'),\n" +
"(16, (select id from programs where code = '" + program + "'), true, 'C', false,16, 'Calculated Order Quantity'),\n" +
"(17, (select id from programs where code = '" + program + "'), true, 'U', false,17, 'Requested quantity'),\n" +
"(18, (select id from programs where code = '" + program + "'), true, 'U', false,18, 'Requested quantity explanation'),\n" +
"(19, (select id from programs where code = '" + program + "'), true, 'U', false,19, 'Approved Quantity'),\n" +
"(20, (select id from programs where code = '" + program + "'), true, 'C', false,20, 'Packs to Ship'),\n" +
"(21, (select id from programs where code = '" + program + "'), true, 'R', false,21, 'Price per pack'),\n" +
"(22, (select id from programs where code = '" + program + "'), true, 'C', false,22, 'Total cost'),\n" +
"(23, (select id from programs where code = '" + program + "'), true, 'U', false,23, 'Expiration Date'),\n" +
"(24, (select id from programs where code = '" + program + "'), true, 'U', false,24, 'Remarks');");
}
public void configureTemplateForCommTrack(String program) throws SQLException, IOException {
update("INSERT INTO program_rnr_columns\n" +
"(masterColumnId, programId, visible, source, position, label) VALUES\n" +
"(2, (select id from programs where code = '" + program + "'), true, 'R', 1, 'Product Code'),\n" +
"(3, (select id from programs where code = '" + program + "'), true, 'R', 2, 'Product'),\n" +
"(4, (select id from programs where code = '" + program + "'), true, 'R', 3, 'Unit/Unit of Issue'),\n" +
"(5, (select id from programs where code = '" + program + "'), true, 'U', 4, 'Beginning Balance'),\n" +
"(6, (select id from programs where code = '" + program + "'), true, 'U', 5, 'Total Received Quantity'),\n" +
"(7, (select id from programs where code = '" + program + "'), true, 'C', 6, 'Total'),\n" +
"(8, (select id from programs where code = '" + program + "'), true, 'C', 7, 'Total Consumed Quantity'),\n" +
"(9, (select id from programs where code = '" + program + "'), true, 'U', 8, 'Total Losses / Adjustments'),\n" +
"(10, (select id from programs where code = '" + program + "'), true, 'U', 9, 'Stock on Hand'),\n" +
"(11, (select id from programs where code = '" + program + "'), true, 'U', 10, 'New Patients'),\n" +
"(12, (select id from programs where code = '" + program + "'), true, 'U', 11, 'Total StockOut days'),\n" +
"(13, (select id from programs where code = '" + program + "'), true, 'C', 12, 'Adjusted Total Consumption'),\n" +
"(14, (select id from programs where code = '" + program + "'), true, 'C', 13, 'Average Monthly Consumption(AMC)'),\n" +
"(15, (select id from programs where code = '" + program + "'), true, 'C', 14, 'Maximum Stock Quantity'),\n" +
"(16, (select id from programs where code = '" + program + "'), true, 'C', 15, 'Calculated Order Quantity'),\n" +
"(17, (select id from programs where code = '" + program + "'), true, 'U', 16, 'Requested quantity'),\n" +
"(18, (select id from programs where code = '" + program + "'), true, 'U', 17, 'Requested quantity explanation'),\n" +
"(19, (select id from programs where code = '" + program + "'), true, 'U', 18, 'Approved Quantity'),\n" +
"(20, (select id from programs where code = '" + program + "'), true, 'C', 19, 'Packs to Ship'),\n" +
"(21, (select id from programs where code = '" + program + "'), true, 'R', 20, 'Price per pack'),\n" +
"(22, (select id from programs where code = '" + program + "'), true, 'C', 21, 'Total cost'),\n" +
"(23, (select id from programs where code = '" + program + "'), true, 'U', 22, 'Expiration Date'),\n" +
"(24, (select id from programs where code = '" + program + "'), true, 'U', 23, 'Remarks');");
}
public String getFacilityName(String code) throws IOException, SQLException {
String name = null;
ResultSet rs = query("select name from facilities where code = '" + code + "';");
if (rs.next()) {
name = rs.getString("name");
}
return name;
}
public String getFacilityPopulation(String code) throws IOException, SQLException {
String population = null;
ResultSet rs = query("select catchmentPopulation from facilities where code = '" + code + "';");
if (rs.next()) {
population = rs.getString("catchmentPopulation");
}
return population;
}
public Integer getOverriddenIsa(String facilityCode, String program, String product) throws IOException, SQLException {
Integer overriddenIsa = 0;
ResultSet rs = query("select overriddenIsa from facility_program_products " +
"where facilityId = '" + getFacilityID(facilityCode) + "' and programProductId = " +
"(select id from program_products where programId='" + getProgramID(program) + "' and productId='" + getProductID(product) + "');");
if (rs.next()) {
overriddenIsa = rs.getInt("overriddenIsa")/getPackSize("P11");
}
return overriddenIsa;
}
public void InsertOverriddenIsa(String facilityCode, String program, String product, int overriddenIsa) throws IOException, SQLException {
update("INSERT INTO facility_program_products (facilityId, programProductId,overriddenIsa) VALUES (" + getFacilityID(facilityCode) + "," +
"(select id from program_products where programId='" + getProgramID(program) + "' and productId='" + getProductID(product) + "')," + overriddenIsa + ");");
}
public void updateOverriddenIsa(String facilityCode, String program, String product, String overriddenIsa) throws IOException, SQLException {
update("Update facility_program_products set overriddenIsa=" + overriddenIsa + " where facilityId='"
+ getFacilityID(facilityCode) + "' and programProductId = (select id from program_products where programId='"
+ getProgramID(program) + "' and productId='" + getProductID(product) + "');");
}
public String[] getProgramProductISA(String program, String product) throws IOException, SQLException {
String isaParams[] = new String[7];
ResultSet rs = query("select * from program_product_Isa where " +
" programProductId = (select id from program_products where programId='" + getProgramID(program) + "' and productId='" + getProductID(product) + "');");
if (rs.next()) {
isaParams[0] = rs.getString("whoRatio");
isaParams[1] = rs.getString("dosesPerYear");
isaParams[2] = rs.getString("wastageFactor");
isaParams[3] = rs.getString("bufferPercentage");
isaParams[4] = rs.getString("adjustmentValue");
isaParams[5] = rs.getString("minimumValue");
isaParams[6] = rs.getString("maximumValue");
}
return isaParams;
}
public Long getFacilityID(String facilityCode) throws IOException, SQLException {
Long id = null;
ResultSet rs = query("select id from facilities where code='" + facilityCode + "';");
if (rs.next()) {
id = rs.getLong("id");
}
return id;
}
public String getFacilityFieldBYCode(String field, String code) throws IOException, SQLException {
String facilityField = null;
ResultSet rs = query("SELECT %s FROM facilities WHERE code = '%s'", field, code);
if (rs.next()) {
facilityField = rs.getString(1);
}
return facilityField;
}
public void updateFacilityFieldBYCode(String field, String value, String code) throws IOException, SQLException {
update("update facilities set " + field + "='" + value + "' where code='" + code + "';");
}
public void insertSupplyLines(String supervisoryNode, String programCode, String facilityCode, boolean exportOrders) throws IOException, SQLException {
update("insert into supply_lines (description, supervisoryNodeId, programId, supplyingFacilityId,exportOrders) values\n" +
"('supplying node for " + programCode + "', (select id from supervisory_nodes where code = '" + supervisoryNode + "'), (select id from programs where code='" + programCode + "'),(select id from facilities where code = '" + facilityCode + "')," + exportOrders + ");\n");
}
public void updateSupplyLines(String previousFacilityCode, String newFacilityCode) throws IOException, SQLException {
update("update supply_lines SET supplyingFacilityId=(select id from facilities where code = '" + newFacilityCode + "') " +
"where supplyingFacilityId=(select id from facilities where code = '" + previousFacilityCode + "');");
}
public void insertValuesInRequisition(boolean emergencyRequisitionRequired) throws IOException, SQLException {
update("update requisition_line_items set beginningBalance=1, quantityReceived=1, quantityDispensed = 1, " +
"newPatientCount = 1, stockOutDays = 1, quantityRequested = 10, reasonForRequestedQuantity = 'bad climate', " +
"normalizedConsumption = 10, packsToShip = 1");
update("update requisitions set fullSupplyItemsSubmittedCost = 12.5000, nonFullSupplyItemsSubmittedCost = 0.0000");
if (emergencyRequisitionRequired) {
update("update requisitions set emergency='true'");
}
}
public void insertValuesInRegimenLineItems(String patientsOnTreatment,
String patientsToInitiateTreatment,
String patientsStoppedTreatment,
String remarks) throws IOException, SQLException {
update("update regimen_line_items set patientsOnTreatment='" + patientsOnTreatment
+ "', patientsToInitiateTreatment='" + patientsToInitiateTreatment + "', patientsStoppedTreatment='"
+ patientsStoppedTreatment + "',remarks='" + remarks + "';");
}
public void insertApprovedQuantity(Integer quantity) throws IOException, SQLException {
update("update requisition_line_items set quantityApproved=" + quantity);
}
public void updateRequisitionStatus(String status, String username, String program) throws IOException, SQLException {
update("update requisitions set status='" + status + "';");
ResultSet rs = query("select id from requisitions where programId = (select id from programs where code='" + program + "');");
while (rs.next()) {
update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', " +
"(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));");
}
update("update requisitions set supervisoryNodeId = (select id from supervisory_nodes where code='N1');");
update("update requisitions set createdBy= (select id from users where username = '" + username + "') , modifiedBy= (select id from users where username = '" + username + "');");
}
public void updateRequisitionStatusByRnrId(String status, String username, int rnrId) throws IOException, SQLException {
update("update requisitions set status='" + status + "' where id=" + rnrId + ";");
update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rnrId + ", '" + status + "', " +
"(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));");
update("update requisitions set supervisoryNodeId = (select id from supervisory_nodes where code='N1');");
update("update requisitions set createdBy= (select id from users where username = '" + username + "') , modifiedBy= (select id from users where username = '" + username + "');");
}
public String getSupplyFacilityName(String supervisoryNode, String programCode) throws IOException, SQLException {
String facilityName = null;
ResultSet rs = query("select name from facilities where id=" +
"(select supplyingFacilityId from supply_lines where supervisoryNodeId=" +
"(select id from supervisory_nodes where code='" + supervisoryNode + "') and programId = " +
"(select id from programs where code='" + programCode + "'));");
if (rs.next()) {
facilityName = rs.getString("name");
}
return facilityName;
}
public String getUserID(String userName) throws IOException, SQLException {
String userId = null;
ResultSet rs = query("select id from users where username='" + userName + "'");
if (rs.next()) {
userId = rs.getString("id");
}
return userId;
}
public int getMaxRnrID() throws IOException, SQLException {
int rnrId = 0;
ResultSet rs = query("select max(id) from requisitions");
if (rs.next()) {
rnrId = Integer.parseInt(rs.getString("max"));
}
return rnrId;
}
public void setupMultipleProducts(String program, String facilityType, int numberOfProductsOfEachType, boolean defaultDisplayOrder) throws SQLException, IOException {
update("delete from facility_approved_products;");
update("delete from program_products;");
update("delete from products;");
update("delete from product_categories;");
String iniProductCodeNonFullSupply = "NF";
String iniProductCodeFullSupply = "F";
update("INSERT INTO product_categories (code, name, displayOrder) values ('C1', 'Antibiotics', 1);");
ResultSet rs = query("Select id from product_categories where code='C1';");
int categoryId = 0;
if (rs.next()) {
categoryId = rs.getInt("id");
}
String insertSql;
insertSql = "INSERT INTO products (code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n";
for (int i = 0; i < numberOfProductsOfEachType; i++) {
if (defaultDisplayOrder) {
insertSql = insertSql + "('" + iniProductCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, " + categoryId + "),\n";
insertSql = insertSql + "('" + iniProductCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 1, " + categoryId + "),\n";
} else {
insertSql = insertSql + "('" + iniProductCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, " + i + ", " + categoryId + "),\n";
insertSql = insertSql + "('" + iniProductCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, " + i + ", " + categoryId + "),\n";
}
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";\n";
update(insertSql);
insertSql = "INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n";
for (int i = 0; i < numberOfProductsOfEachType; i++) {
insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + iniProductCodeFullSupply + i + "'), 30, 12.5, true),\n";
insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + iniProductCodeNonFullSupply + i + "'), 30, 12.5, true),\n";
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";";
update(insertSql);
insertSql = "INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES\n";
for (int i = 0; i < numberOfProductsOfEachType; i++) {
insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + iniProductCodeFullSupply + i + "')), 3),\n";
insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + iniProductCodeNonFullSupply + i + "')), 3),\n";
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";";
update(insertSql);
}
public void setupMultipleCategoryProducts(String program, String facilityType, int numberOfCategories, boolean defaultDisplayOrder) throws SQLException, IOException {
update("delete from facility_approved_products;");
update("delete from program_products;");
update("delete from products;");
update("delete from product_categories;");
String iniProductCodeNonFullSupply = "NF";
String iniProductCodeFullSupply = "F";
String insertSql = "INSERT INTO product_categories (code, name, displayOrder) values\n";
for (int i = 0; i < numberOfCategories; i++) {
if (defaultDisplayOrder) {
insertSql = insertSql + "('C" + i + "', 'Antibiotics" + i + "',1),\n";
} else {
insertSql = insertSql + "('C" + i + "', 'Antibiotics" + i + "'," + i + "),\n";
}
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";";
update(insertSql);
insertSql = "INSERT INTO products (code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n";
for (int i = 0; i < 11; i++) {
insertSql = insertSql + "('" + iniProductCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (select id from product_categories where code='C" + i + "')),\n";
insertSql = insertSql + "('" + iniProductCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 1, (select id from product_categories where code='C" + i + "')),\n";
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";\n";
update(insertSql);
insertSql = "INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n";
for (int i = 0; i < 11; i++) {
insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + iniProductCodeFullSupply + i + "'), 30, 12.5, true),\n";
insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + iniProductCodeNonFullSupply + i + "'), 30, 12.5, true),\n";
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";";
update(insertSql);
insertSql = "INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES\n";
for (int i = 0; i < 11; i++) {
insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + iniProductCodeFullSupply + i + "')), 3),\n";
insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + iniProductCodeNonFullSupply + i + "')), 3),\n";
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";";
update(insertSql);
}
public void assignRight(String roleName, String roleRight) throws SQLException, IOException {
update("INSERT INTO role_rights\n" +
" (roleId, rightName) VALUES\n" +
" ((select id from roles where name='" + roleName + "'), '" + roleRight + "');");
}
public void updatePacksToShip(String packsToShip) throws SQLException {
update("update requisition_line_items set packsToShip='" + packsToShip + "';");
}
public Long getProgramID(String program) throws IOException, SQLException {
Long programID = null;
ResultSet rs = query("SELECT ID from programs where code='" + program + "'");
if (rs.next()) {
programID = rs.getLong("id");
}
return programID;
}
public Long getProductID(String product) throws IOException, SQLException {
Long productID = null;
ResultSet rs = query("SELECT ID from products where code='" + product + "'");
if (rs.next()) {
productID = rs.getLong("id");
}
return productID;
}
public String getRequisitionStatus(Long requisitionId) throws IOException, SQLException {
String requisitionStatus = null;
ResultSet rs = query("SELECT status from requisitions where id=" + requisitionId);
if (rs.next()) {
requisitionStatus = rs.getString("status");
}
return requisitionStatus;
}
public String getOrderStatus(Long orderId) throws IOException, SQLException {
String orderStatus = null;
ResultSet rs = query("SELECT status from orders where id=" + orderId);
if (rs.next()) {
orderStatus = rs.getString("status");
}
return orderStatus;
}
public String getOrderId() throws IOException, SQLException {
String orderId = null;
ResultSet rs = query("SELECT id from orders");
if (rs.next()) {
orderId = rs.getString("id");
}
return orderId;
}
public void insertPastPeriodRequisitionAndLineItems(String facilityCode, String program, String periodName, String product) throws IOException, SQLException {
update("DELETE FROM requisition_line_item_losses_adjustments;");
update("DELETE FROM requisition_line_items;");
update("DELETE FROM requisitions;");
update("INSERT INTO requisitions " +
"(facilityId, programId, periodId, status) VALUES " +
"((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), (SELECT ID from programs where code='" + program + "'), (select id from processing_periods where name='" + periodName + "'), 'RELEASED');");
update("INSERT INTO requisition_line_items " +
"(rnrId, productCode, beginningBalance, quantityReceived, quantityDispensed, stockInHand, normalizedConsumption, " +
"dispensingUnit, maxMonthsOfStock, dosesPerMonth, dosesPerDispensingUnit, packSize,fullSupply) VALUES" +
"((SELECT id FROM requisitions), '" + product + "', '0', '11' , '1', '10', '1' ,'Strip','0', '0', '0', '10','t');");
}
public String getRowsCountFromDB(String tableName) throws IOException, SQLException {
String rowCount = null;
ResultSet rs = query("SELECT count(*) as count from " + tableName + "");
if (rs.next()) {
rowCount = rs.getString("count");
}
return rowCount;
}
public void insertRoleAssignmentForDistribution(String userName, String roleName, String deliveryZoneCode) throws SQLException, IOException {
update("INSERT INTO role_assignments\n" +
" (userId, roleId, deliveryZoneId) VALUES\n" +
" ((SELECT id FROM USERS WHERE username='" + userName + "'), (SELECT id FROM roles WHERE name = '" + roleName + "'),\n" +
" (SELECT id FROM delivery_zones WHERE code='" + deliveryZoneCode + "'));");
}
public void deleteDeliveryZoneToFacilityMapping(String deliveryZoneName) throws SQLException, IOException {
update("delete from delivery_zone_members where deliveryZoneId in (select id from delivery_zones where name='" + deliveryZoneName + "');");
}
public void deleteProgramToFacilityMapping(String programCode) throws SQLException, IOException {
update("delete from programs_supported where programId in (select id from programs where code='" + programCode + "');");
}
public void updateActiveStatusOfFacility(String facilityCode, String active) throws SQLException, IOException {
update("update facilities set active='" + active + "' where code='" + facilityCode + "';");
}
public void updatePopulationOfFacility(String facility, String population) throws SQLException, IOException {
update("update facilities set catchmentPopulation=" + population + " where code='" + facility + "';");
}
public void insertDeliveryZone(String code, String name) throws SQLException {
update("INSERT INTO delivery_zones ( code ,name)values\n" +
"('" + code + "','" + name + "');");
}
public void insertWarehouseIntoSupplyLinesTable(String facilityCodeFirst,
String programFirst, String supervisoryNode, boolean exportOrders) throws SQLException {
update("INSERT INTO supply_lines (supplyingFacilityId, programId, supervisoryNodeId, description, exportOrders, createdBy, modifiedBy) values " +
"(" + "(select id from facilities where code = '" + facilityCodeFirst + "')," + "(select id from programs where name ='" + programFirst + "')," + "(select id from supervisory_nodes where code='" + supervisoryNode + "'),'warehouse', " + exportOrders + ", '1', '1');");
}
public void insertDeliveryZoneMembers(String code, String facility) throws SQLException {
update("INSERT INTO delivery_zone_members ( deliveryZoneId ,facilityId )values\n" +
"((select id from delivery_zones where code ='" + code + "'),(select id from facilities where code ='" + facility + "'));");
}
public void insertDeliveryZoneProgramSchedule(String code, String program, String scheduleCode) throws SQLException {
update("INSERT INTO delivery_zone_program_schedules\n" +
"(deliveryZoneId, programId, scheduleId ) values(\n" +
"(select id from delivery_zones where code='" + code + "'),\n" +
"(select id from programs where code='" + program + "'),\n" +
"(select id from processing_schedules where code='" + scheduleCode + "')\n" +
");");
}
public void insertProcessingPeriodForDistribution(int numberOfPeriodsRequired, String schedule) throws IOException, SQLException {
for (int counter = 1; counter <= numberOfPeriodsRequired; counter++) {
String startDate = "2013-01-0" + counter;
String endDate = "2013-01-0" + counter;
insertProcessingPeriod("Period" + counter, "PeriodDecs" + counter, startDate, endDate, 1, schedule);
}
}
public void updateActiveStatusOfProgram(String programCode, boolean status) throws SQLException {
update("update programs SET active=" + status + " where code='" + programCode + "';");
}
public void insertRegimenTemplateColumnsForProgram(String programName) throws SQLException {
update("INSERT INTO program_regimen_columns(name, programId, label, visible, dataType) values\n" +
"('code',(SELECT id FROM programs WHERE name='" + programName + "'), 'header.code',true,'regimen.reporting.dataType.text'),\n" +
"('name',(SELECT id FROM programs WHERE name='" + programName + "'),'header.name',true,'regimen.reporting.dataType.text'),\n" +
"('patientsOnTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients on treatment',true,'regimen.reporting.dataType.numeric'),\n" +
"('patientsToInitiateTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients to be initiated treatment',true,'regimen.reporting.dataType.numeric'),\n" +
"('patientsStoppedTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients stopped treatment',true,'regimen.reporting.dataType.numeric'),\n" +
"('remarks',(SELECT id FROM programs WHERE name='" + programName + "'),'Remarks',true,'regimen.reporting.dataType.text');");
}
public void insertRegimenTemplateConfiguredForProgram(String programName, String categoryCode, String code, String name, boolean active) throws SQLException {
update("update programs set regimenTemplateConfigured='true' where name='" + programName + "';");
update("INSERT INTO regimens\n" +
" (programId, categoryId, code, name, active,displayOrder) VALUES\n" +
" ((SELECT id FROM programs WHERE name='" + programName + "'), (SELECT id FROM regimen_categories WHERE code = '" + categoryCode + "'),\n" +
" '" + code + "','" + name + "','" + active + "',1);");
}
public void setRegimenTemplateConfiguredForAllPrograms(boolean flag) throws SQLException {
update("update programs set regimenTemplateConfigured='" + flag + "';");
}
public String getAllActivePrograms() throws SQLException {
String programsString = "";
ResultSet rs = query("select * from programs where active=true;");
while (rs.next()) {
programsString = programsString + rs.getString("name");
}
return programsString;
}
public void updateProgramRegimenColumns(String programName, String regimenColumnName, boolean visible) throws SQLException {
update("update program_regimen_columns set visible=" + visible + " where name ='" + regimenColumnName +
"'and programId=(SELECT id FROM programs WHERE name='" + programName + "');");
}
public void setupOrderFileConfiguration(String filePrefix, String headerInFile) throws IOException, SQLException {
update("DELETE FROM order_configuration;");
update("INSERT INTO order_configuration \n" +
" (filePrefix, headerInFile) VALUES\n" +
" ('" + filePrefix + "', '" + headerInFile + "');");
}
public void setupShipmentFileConfiguration(String headerInFile) throws IOException, SQLException {
update("DELETE FROM shipment_configuration;");
update("INSERT INTO shipment_configuration(headerInFile) VALUES('" + headerInFile + "')");
}
public void setupOrderFileOpenLMISColumns(String dataFieldLabel, String includeInOrderFile, String columnLabel,
int position, String Format) throws IOException, SQLException {
update("UPDATE order_file_columns SET " +
"includeInOrderFile='" + includeInOrderFile + "', columnLabel='" + columnLabel + "', position=" + position
+ ", format='" + Format + "' where dataFieldLabel='" + dataFieldLabel + "'");
}
public void deleteOrderFileNonOpenLMISColumns() throws SQLException {
update("DELETE FROM order_file_columns where openLMISField = FALSE");
}
public void setupOrderFileNonOpenLMISColumns(String dataFieldLabel, String includeInOrderFile,
String columnLabel, int position) throws IOException, SQLException {
update("INSERT INTO order_file_columns (dataFieldLabel, includeInOrderFile, columnLabel, position, openLMISField) " +
"VALUES ('" + dataFieldLabel + "','" + includeInOrderFile + "','" + columnLabel + "'," + position + ", FALSE)");
}
public String getCreatedDate(String tableName, String dateFormat) throws SQLException {
String createdDate = null;
ResultSet rs = query("SELECT to_char(createdDate, '" + dateFormat + "' ) from " + tableName);
if (rs.next()) {
createdDate = rs.getString(1);
}
return createdDate;
}
public void updateProductToHaveGroup(String product, String productGroup) throws SQLException {
update("UPDATE products set productGroupId = (SELECT id from product_groups where code = '" + productGroup + "') where code = '" + product + "'");
}
public void deleteReport(String reportName) throws SQLException {
update("DELETE FROM report_templates where name = '" + reportName + "'");
}
public void insertOrders(String status, String username, String program) throws IOException, SQLException {
ResultSet rs = query("select id from requisitions where programId=(select id from programs where code='" + program + "');");
while (rs.next()) {
update("update requisitions set status='RELEASED' where id =" + rs.getString("id"));
update("insert into orders(Id, status,supplyLineId, createdBy, modifiedBy) values(" + rs.getString("id")
+ ", '" + status + "', (select id from supply_lines where supplyingFacilityId = " +
"(select facilityId from fulfillment_role_assignments where userId = " +
"(select id from users where username = '" + username + "')) limit 1) ," +
"(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));");
}
}
public void setupUserForFulfillmentRole(String username, String roleName, String facilityCode) throws IOException, SQLException {
update("insert into fulfillment_role_assignments(userId, roleId,facilityId) values((select id from users where userName = '" + username +
"'),(select id from roles where name = '" + roleName + "')," +
"(select id from facilities where code = '" + facilityCode + "'));");
}
public HashMap getFacilityVisitDetails() throws SQLException {
HashMap m1 = new HashMap();
ResultSet rs = query("select observations,confirmedByName,confirmedByTitle,verifiedByName,verifiedByTitle from facility_visits;");
while (rs.next()) {
m1.put("observations", rs.getString("observations"));
m1.put("confirmedByName", rs.getString("confirmedByName"));
m1.put("confirmedByTitle", rs.getString("confirmedByTitle"));
m1.put("verifiedByName", rs.getString("verifiedByName"));
m1.put("verifiedByTitle", rs.getString("verifiedByTitle"));
}
return m1;
}
public String getWarehouse1Name(String facilityCode) throws SQLException {
String warehouseName = "";
ResultSet rs = query("select name from facilities where code='" + facilityCode + "';");
if (rs.next())
warehouseName = rs.getString(1);
return warehouseName;
}
public void disableFacility(String warehouseName) throws SQLException {
update("UPDATE facilities SET enabled='false' WHERE name='" + warehouseName + "';");
}
public void enableFacility(String warehouseName) throws SQLException {
update("UPDATE facilities SET enabled='true' WHERE name='" + warehouseName + "';");
}
public int getPODLineItemQuantityReceived(long orderId, String productCode) throws Exception {
try (ResultSet rs1 = query("SELECT id FROM pod WHERE OrderId = %d", orderId)) {
if (rs1.next()) {
int podId = rs1.getInt("id");
ResultSet rs2 = query("SELECT quantityReceived FROM pod_line_items WHERE podId = %d and productCode='%s'", podId, productCode);
if (rs2.next()) {
return rs2.getInt("quantityReceived");
}
}
}
return -1;
}
public void setExportOrdersFlagInSupplyLinesTable(boolean flag, String facilityCode) throws SQLException {
update("UPDATE supply_lines SET exportOrders='" + flag + "' WHERE supplyingFacilityId=(select id from facilities where code='" + facilityCode + "');");
}
public void enterValidDetailsInFacilityFtpDetailsTable(String facilityCode) throws SQLException {
update("INSERT INTO facility_ftp_details(facilityId, serverHost, serverPort, username, password, localFolderPath) VALUES" +
"((SELECT id FROM facilities WHERE code = '%s' ), '192.168.34.1', 21, 'openlmis', 'openlmis', '/ftp');", facilityCode);
}
public int getRequisitionGroupId(String facilityCode) throws SQLException {
int rgId = 0;
ResultSet rs = query("SELECT requisitionGroupId FROM requisition_group_members where facilityId=(SELECT id FROM facilities WHERE code ='" + facilityCode + "');");
if (rs.next()) {
rgId = rs.getInt(1);
}
return rgId;
}
public List<Integer> getAllProgramsOfFacility(String facilityCode) throws SQLException {
List<Integer> l1 = new ArrayList<>();
ResultSet rs = query("SELECT programId FROM programs_supported WHERE facilityId = (SELECT id FROM facilities WHERE code ='%s')", facilityCode);
while (rs.next()) {
l1.add(rs.getInt(1));
}
return l1;
}
public String getProgramFieldForProgramIdAndFacilityCode(int programId, String facilityCode, String field) throws SQLException {
String res = null;
ResultSet rs = query("SELECT %s FROM programs_supported WHERE programId = %d AND facilityId = (SELECT id FROM facilities WHERE code = '%s')",
field, programId, facilityCode);
if (rs.next()) {
res = rs.getString(1);
}
return res;
}
public Date getProgramStartDateForProgramIdAndFacilityCode(int programId, String facilityCode) throws SQLException {
Date date = null;
ResultSet rs = query("SELECT startDate FROM programs_supported WHERE programId = %d AND facilityId = (SELECT id FROM facilities WHERE code ='%s')",
programId, facilityCode);
if (rs.next()) {
date = rs.getDate(1);
}
return date;
}
public void changeVirtualFacilityTypeId(String facilityCode, int facilityTypeId) throws SQLException {
update("UPDATE facilities SET typeid=" + facilityTypeId + "WHERE code='" + facilityCode + "';");
}
public String getGeographicZoneId(String geographicZone) throws SQLException {
String res = null;
ResultSet rs = query("select id from geographic_zones WHERE code ='" + geographicZone + "';");
if (rs.next()) {
res = rs.getString(1);
}
return res;
}
public String getFacilityTypeId(String facilityType) throws SQLException {
String res = null;
ResultSet rs = query("select id from facility_types WHERE code ='" + facilityType + "';");
if (rs.next()) {
res = rs.getString(1);
}
return res;
}
public void deleteCurrentPeriod() throws SQLException {
update("delete from processing_periods where endDate>=NOW()");
}
public void updateProgramsSupportedByField(String field, String newValue, String facilityCode) throws SQLException {
update("Update programs_supported set " + field + "='" + newValue + "' where facilityId=(Select id from facilities where code ='"
+ facilityCode + "');");
}
public void deleteSupervisoryRoleFromRoleAssignment() throws SQLException {
update("delete from role_assignments where supervisoryNodeId is not null;");
}
public void deleteRnrTemplate() throws SQLException {
update("delete from program_rnr_columns");
}
public void deleteProductAvailableAtFacility(String productCode, String programCode, String facilityCode) throws SQLException {
update("delete from facility_approved_products where facilityTypeId=(select typeId from facilities where code='" + facilityCode + "') " +
"and programproductid=(select id from program_products where programId=(select id from programs where code='" + programCode + "')" +
"and productid=(select id from products where code='" + productCode + "'));");
}
public void UpdateProductFullSupplyStatus(String productCode, boolean fullSupply) throws SQLException {
update("UPDATE products SET fullSupply=" + fullSupply + " WHERE code='" + productCode + "';");
}
public float getRequisitionFullSupplyItemsSubmittedCost(int requisitionId) throws SQLException {
float fullSupplyItemsSubmittedCost = 0f;
ResultSet rs = query("SELECT fullSupplyItemsSubmittedCost FROM requisitions WHERE id =" + requisitionId + ";");
if (rs.next()) {
fullSupplyItemsSubmittedCost = rs.getFloat(1);
}
return fullSupplyItemsSubmittedCost;
}
public void updateConfigureTemplateValidationFlag(String programCode, String flag) throws SQLException {
update("UPDATE program_rnr_columns set formulaValidationRequired ='" + flag + "' WHERE programId=" +
"(SELECT id from programs where code='" + programCode + "');");
}
public void updateConfigureTemplate(String programCode, String fieldName, String fieldValue, String visibilityFlag, String rnrColumnName) throws SQLException {
update("UPDATE program_rnr_columns SET visible ='" + visibilityFlag + "', " + fieldName + "='" + fieldValue + "' WHERE programId=" +
"(SELECT id from programs where code='" + programCode + "')" +
"AND masterColumnId =(SELECT id from master_rnr_columns WHERE name = '" + rnrColumnName + "') ;");
}
public void deleteConfigureTemplate(String program) throws SQLException {
update("DELETE FROM program_rnr_columns where programId=(select id from programs where code = '" + program + "');");
}
public String getApproverName(long requisitionId) throws IOException, SQLException {
String name = null;
ResultSet rs = query("SELECT name FROM requisition_status_changes WHERE rnrId =" + requisitionId + " and status='APPROVED';");
if (rs.next()) {
name = rs.getString("name");
}
return name;
}
public String getRequisitionLineItemFieldValue(Long requisitionId, String field, String productCode) throws SQLException {
String value = null;
ResultSet rs = query("SELECT %s FROM requisition_line_items WHERE rnrId = %d AND productCode = '%s'",
field, requisitionId, productCode);
if (rs.next()) {
value = rs.getString(field);
}
return value;
}
public void updateProductFullSupplyFlag(boolean isFullSupply, String productCode) throws SQLException {
update("UPDATE products SET fullSupply = %b WHERE code = '%s'", isFullSupply, productCode);
}
public void insertRoleAssignmentForSupervisoryNode(String userID, String roleName, String supervisoryNode, String programCode) throws SQLException {
update(" INSERT INTO role_assignments\n" +
" (userId, roleId, programId, supervisoryNodeId) VALUES \n" +
" ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "')," +
" (SELECT id from programs WHERE code='" + programCode + "'), " +
"(SELECT id from supervisory_nodes WHERE code = '" + supervisoryNode + "'));");
}
public void insertRequisitionGroupProgramScheduleForProgram(String requisitionGroupCode, String programCode, String scheduleCode) throws SQLException {
update("delete from requisition_group_program_schedules where programId=(select id from programs where code='" + programCode + "');");
update("insert into requisition_group_program_schedules ( requisitionGroupId , programId , scheduleId , directDelivery ) values\n" +
"((select id from requisition_groups where code='" + requisitionGroupCode + "'),(select id from programs where code='" + programCode + "')," +
"(select id from processing_schedules where code='" + scheduleCode + "'),TRUE);");
}
public void updateCreatedDateInRequisitionStatusChanges(String newDate, Long rnrId) throws SQLException {
update("update requisition_status_changes SET createdDate= '" + newDate + "' WHERE rnrId=" + rnrId + ";");
}
public void updateCreatedDateInPODLineItems(String newDate, Long rnrId) throws SQLException {
update("update pod SET createdDate= '" + newDate + "' WHERE orderId=" + rnrId + ";");
}
public void updatePeriodIdInRequisitions(Long rnrId) throws SQLException {
Integer reqId = 0;
ResultSet rs = query("select " + "periodId" + " from requisitions where id= " + rnrId + ";");
if (rs.next()) {
reqId = Integer.parseInt(rs.getString(1));
}
reqId = reqId - 1;
update("update requisitions SET periodId= '" + reqId + "' WHERE id=" + rnrId + ";");
}
public void updateProductsByField(String field, String fieldValue, String productCode) throws SQLException {
update("update products set " + field + "=" + fieldValue + " where code='" + productCode + "';");
}
public void updateCreatedDateAfterRequisitionIsInitiated(String createdDate) throws SQLException {
update("update requisitions set createdDate ='" + createdDate + "';");
update("update requisition_line_items set createdDate ='" + createdDate + "';");
update("update requisition_status_changes set createdDate='" + createdDate + "';");
}
public void updateSupervisoryNodeForRequisitionGroup(String requisitionGroup, String supervisoryNodeCode) throws SQLException {
update("update requisition_groups set supervisoryNodeId=(select id from supervisory_nodes where code='" + supervisoryNodeCode +
"') where code='" + requisitionGroup + "';");
}
public void updateOrderStatus(String status, String username, String program) throws IOException, SQLException {
update("update orders set status='RECEIVED'");
}
public void updateRequisitionToEmergency() throws IOException, SQLException {
update("update requisitions set Emergency=true");
}
public void deleteSupplyLine() throws IOException, SQLException {
update("delete from supply_lines where description='supplying node for MALARIA'");
}
public String getOrderFtpComment(Long orderId) throws IOException, SQLException {
String orderFtpcomment = null;
ResultSet rs = query("SELECT ftpComment from orders where id=" + orderId);
if (rs.next()) {
orderFtpcomment = rs.getString("ftpComment");
}
return orderFtpcomment;
}
public Map<String, String> getEpiUseDetails(String productGroupCode, String facilityCode) throws SQLException {
return select("SELECT * FROM epi_use_line_items WHERE productGroupName = " +
"(SELECT name FROM product_groups where code = '%s') AND epiUseId=(Select id from epi_use where facilityId=" +
"(Select id from facilities where code ='%s'));", productGroupCode, facilityCode).get(0);
}
public void updateBudgetFlag(String ProgramName, Boolean Flag) throws IOException, SQLException {
update("update programs set budgetingapplies ='" + Flag + "' where name ='" + ProgramName + "';");
}
public void insertBudgetData() throws IOException, SQLException {
update("INSERT INTO budget_file_info VALUES (1,'abc.csv','f',200,'12/12/13',200,'12/12/13');");
update("INSERT INTO budget_line_items VALUES (1,(select id from processing_periods where name='current Period'),1,'01/01/2013',200,'hjhj',200,'12/12/2013',200,'12/12/2013',(select id from facilities where code='F10'),1);");
}
public void updateBudgetLineItemsByField(String field, String newValue) throws SQLException {
update("UPDATE budget_line_items SET " + field + " ='" + newValue + "';");
}
public void addRefrigeratorToFacility(String brand, String model, String serialNumber, String facilityCode) throws SQLException {
update("INSERT INTO refrigerators(brand, model, serialNumber, facilityId, createdBy , modifiedBy) VALUES" +
"('" + brand + "','" + model + "','" + serialNumber + "',(SELECT id FROM facilities WHERE code = '" + facilityCode + "'),1,1);");
}
public ResultSet getRefrigeratorReadings(String refrigeratorSerialNumber) throws SQLException {
ResultSet resultSet = query("SELECT * FROM refrigerator_readings WHERE refrigeratorId = " +
"(SELECT id FROM refrigerators WHERE serialNumber = '%s');", refrigeratorSerialNumber);
resultSet.next();
return resultSet;
}
public ResultSet getRefrigeratorProblems(Long readingId) throws SQLException {
ResultSet resultSet = query("SELECT * FROM refrigerator_problems WHERE readingId = %d", readingId);
return resultSet;
}
public Integer getPackSize(String programCode) throws SQLException {
Integer packSize=0;
ResultSet rs = query("SELECT packsize FROM products WHERE code='"+programCode+"';");
if (rs.next()) {
packSize = rs.getInt("packSize");
}
return packSize;
}
}
| true | true | public void deleteData() throws SQLException, IOException {
update("delete from budget_line_items");
update("delete from budget_file_info");
update("delete from role_rights where roleId not in(1)");
update("delete from role_assignments where userId not in (1)");
update("delete from fulfillment_role_assignments");
update("delete from roles where name not in ('Admin')");
update("delete from facility_approved_products");
update("delete from program_product_price_history");
update("delete from pod_line_items");
update("delete from pod");
update("delete from orders");
update("DELETE FROM requisition_status_changes");
update("delete from user_password_reset_tokens");
update("delete from comments");
update("delete from facility_visits");
update("delete from epi_use_line_items");
update("delete from epi_use");
update("delete from refrigerator_problems");
update("delete from refrigerator_readings");
update("delete from distribution_refrigerators");
update("delete from distributions");
update("delete from users where userName not like('Admin%')");
update("DELETE FROM requisition_line_item_losses_adjustments");
update("DELETE FROM requisition_line_items");
update("DELETE FROM regimen_line_items");
update("DELETE FROM requisitions");
update("delete from program_product_isa");
update("delete from facility_approved_products");
update("delete from facility_program_products");
update("delete from program_products");
update("delete from products");
update("delete from product_categories");
update("delete from product_groups");
update("delete from supply_lines");
update("delete from programs_supported");
update("delete from requisition_group_members");
update("delete from program_rnr_columns");
update("delete from requisition_group_program_schedules");
update("delete from requisition_groups");
update("delete from requisition_group_members");
update("delete from delivery_zone_program_schedules");
update("delete from delivery_zone_warehouses");
update("delete from delivery_zone_members");
update("delete from role_assignments where deliveryZoneId in (select id from delivery_zones where code in('DZ1','DZ2'))");
update("delete from delivery_zones");
update("delete from supervisory_nodes");
update("delete from refrigerators");
update("delete from facility_ftp_details");
update("delete from facilities");
update("delete from geographic_zones where code not in ('Root','Arusha','Dodoma', 'Ngorongoro')");
update("delete from processing_periods");
update("delete from processing_schedules");
update("delete from atomfeed.event_records");
update("delete from regimens");
update("delete from program_regimen_columns");
}
| public void deleteData() throws SQLException, IOException {
update("delete from budget_line_items");
update("delete from budget_file_info");
update("delete from role_rights where roleId not in(1)");
update("delete from role_assignments where userId not in (1)");
update("delete from fulfillment_role_assignments");
update("delete from roles where name not in ('Admin')");
update("delete from facility_approved_products");
update("delete from program_product_price_history");
update("delete from pod_line_items");
update("delete from pod");
update("delete from orders");
update("DELETE FROM requisition_status_changes");
update("delete from user_password_reset_tokens");
update("delete from comments");
update("delete from facility_visits");
update("delete from epi_use_line_items");
update("delete from epi_use");
update("delete from epi_inventory");
update("delete from epi_inventory_line_items");
update("delete from refrigerator_problems");
update("delete from refrigerator_readings");
update("delete from distribution_refrigerators");
update("delete from distributions");
update("delete from users where userName not like('Admin%')");
update("DELETE FROM requisition_line_item_losses_adjustments");
update("DELETE FROM requisition_line_items");
update("DELETE FROM regimen_line_items");
update("DELETE FROM requisitions");
update("delete from program_product_isa");
update("delete from facility_approved_products");
update("delete from facility_program_products");
update("delete from program_products");
update("delete from products");
update("delete from product_categories");
update("delete from product_groups");
update("delete from supply_lines");
update("delete from programs_supported");
update("delete from requisition_group_members");
update("delete from program_rnr_columns");
update("delete from requisition_group_program_schedules");
update("delete from requisition_groups");
update("delete from requisition_group_members");
update("delete from delivery_zone_program_schedules");
update("delete from delivery_zone_warehouses");
update("delete from delivery_zone_members");
update("delete from role_assignments where deliveryZoneId in (select id from delivery_zones where code in('DZ1','DZ2'))");
update("delete from delivery_zones");
update("delete from supervisory_nodes");
update("delete from refrigerators");
update("delete from facility_ftp_details");
update("delete from facilities");
update("delete from geographic_zones where code not in ('Root','Arusha','Dodoma', 'Ngorongoro')");
update("delete from processing_periods");
update("delete from processing_schedules");
update("delete from atomfeed.event_records");
update("delete from regimens");
update("delete from program_regimen_columns");
}
|
diff --git a/src/main/ed/appserver/AppRequest.java b/src/main/ed/appserver/AppRequest.java
index 7d0694256..f5d85a31e 100644
--- a/src/main/ed/appserver/AppRequest.java
+++ b/src/main/ed/appserver/AppRequest.java
@@ -1,96 +1,96 @@
// AppRequest.java
package ed.appserver;
import java.io.*;
import java.util.*;
import ed.js.*;
import ed.js.engine.*;
import ed.net.httpserver.*;
public class AppRequest {
AppRequest( AppContext context , HttpRequest request , String uri ){
_context = context;
_request = request;
_scope = _context.scopeChild();
if ( uri == null )
uri = _request.getURI();
_uri = uri.equals( "/" ) ? "/index" : uri;
}
public AppContext getContext(){
return _context;
}
public Scope getScope(){
return _scope;
}
public String getURI(){
return _uri;
}
String getRoot(){
return _context.getRoot();
}
String getCustomer(){
return "";
}
boolean fork(){
return true;
}
boolean isStatic(){
- String uri = getURI();
+ String uri = getWantedURI();
if ( uri.endsWith( ".jxp" ) )
return false;
int period = uri.indexOf( "." );
if ( period < 0 )
return false;
String ext = uri.substring( period + 1 );
if ( MimeTypes.get( ext.toLowerCase() ) == null )
return false;
return true;
}
String getOverrideURI(){
Object o = _scope.get( "mapUrlToJxpFile" );
if ( o == null )
return null;
if ( ! ( o instanceof JSFunction ) )
return null;
Object res = ((JSFunction)o).call( _scope , new JSString( getURI() ) );
if ( res == null )
return null;
return res.toString();
}
String getWantedURI(){
String override = getOverrideURI();
if ( override != null )
return override;
return getURI();
}
File getFile(){
return _context.getFile( getWantedURI() );
}
final String _uri;
final HttpRequest _request;
final AppContext _context;
final Scope _scope;
}
| true | true | boolean isStatic(){
String uri = getURI();
if ( uri.endsWith( ".jxp" ) )
return false;
int period = uri.indexOf( "." );
if ( period < 0 )
return false;
String ext = uri.substring( period + 1 );
if ( MimeTypes.get( ext.toLowerCase() ) == null )
return false;
return true;
}
| boolean isStatic(){
String uri = getWantedURI();
if ( uri.endsWith( ".jxp" ) )
return false;
int period = uri.indexOf( "." );
if ( period < 0 )
return false;
String ext = uri.substring( period + 1 );
if ( MimeTypes.get( ext.toLowerCase() ) == null )
return false;
return true;
}
|
diff --git a/src/DerpyAI/DerpyBlank.java b/src/DerpyAI/DerpyBlank.java
index 1bc45b4..79271c5 100644
--- a/src/DerpyAI/DerpyBlank.java
+++ b/src/DerpyAI/DerpyBlank.java
@@ -1,14 +1,14 @@
package DerpyAI;
import java.awt.Point;
public class DerpyBlank extends DerpyPiece{
public DerpyBlank(Point p) {
- super(true,"WX");
+ super(true,"X");
currentLocation = p;
xMoveConstraint = 8;
yMoveConstraint = 8;
}
}
| true | true | public DerpyBlank(Point p) {
super(true,"WX");
currentLocation = p;
xMoveConstraint = 8;
yMoveConstraint = 8;
}
| public DerpyBlank(Point p) {
super(true,"X");
currentLocation = p;
xMoveConstraint = 8;
yMoveConstraint = 8;
}
|
diff --git a/src/test/unit/org/jboss/seam/test/unit/ContextTest.java b/src/test/unit/org/jboss/seam/test/unit/ContextTest.java
index 4bcb8f1b..b69bd330 100644
--- a/src/test/unit/org/jboss/seam/test/unit/ContextTest.java
+++ b/src/test/unit/org/jboss/seam/test/unit/ContextTest.java
@@ -1,287 +1,287 @@
//$Id$
package org.jboss.seam.test.unit;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.context.ExternalContext;
import javax.servlet.http.HttpServletRequest;
import org.jboss.seam.Component;
import org.jboss.seam.Namespace;
import org.jboss.seam.Seam;
import org.jboss.seam.contexts.ApplicationContext;
import org.jboss.seam.contexts.Context;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.contexts.EventContext;
import org.jboss.seam.contexts.FacesLifecycle;
import org.jboss.seam.contexts.ServerConversationContext;
import org.jboss.seam.contexts.ServletLifecycle;
import org.jboss.seam.contexts.SessionContext;
import org.jboss.seam.core.ConversationEntries;
import org.jboss.seam.core.Init;
import org.jboss.seam.core.Manager;
import org.jboss.seam.el.EL;
import org.jboss.seam.el.SeamELResolver;
import org.jboss.seam.mock.MockExternalContext;
import org.jboss.seam.mock.MockHttpServletRequest;
import org.jboss.seam.mock.MockHttpSession;
import org.jboss.seam.mock.MockServletContext;
import org.jboss.seam.servlet.ServletRequestMap;
import org.jboss.seam.servlet.ServletRequestSessionMap;
import org.jboss.seam.web.Parameters;
import org.jboss.seam.web.ServletContexts;
import org.jboss.seam.web.Session;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ContextTest {
private void installComponent(Context appContext, Class clazz) {
appContext.set(Seam.getComponentName(clazz) + ".component",
new Component(clazz));
}
@Test
public void testContextManagement() throws Exception {
ELContext elContext = EL.createELContext();
SeamELResolver seamVariableResolver = new SeamELResolver();
// org.jboss.seam.bpm.SeamVariableResolver jbpmVariableResolver = new
// org.jboss.seam.bpm.SeamVariableResolver();
MockServletContext servletContext = new MockServletContext();
ServletLifecycle.beginApplication(servletContext);
MockExternalContext externalContext = new MockExternalContext(
servletContext);
Context appContext = new ApplicationContext(externalContext
.getApplicationMap());
// appContext.set( Seam.getComponentName(Init.class), new Init() );
installComponent(appContext, ConversationEntries.class);
installComponent(appContext, Manager.class);
installComponent(appContext, Session.class);
installComponent(appContext, ServletContexts.class);
installComponent(appContext, Parameters.class);
appContext.set(Seam.getComponentName(Init.class), new Init());
installComponent(appContext, Bar.class);
installComponent(appContext, Foo.class);
appContext.set("otherFoo", new Foo());
assert !Contexts.isEventContextActive();
assert !Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert !Contexts.isApplicationContextActive();
FacesLifecycle.beginRequest(externalContext);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
Manager.instance().setCurrentConversationId("3");
FacesLifecycle.resumeConversation(externalContext);
Manager.instance().setLongRunningConversation(true);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
assert !Contexts.isPageContextActive();
assert Contexts.getEventContext() != null;
assert Contexts.getSessionContext() != null;
assert Contexts.getConversationContext() != null;
assert Contexts.getApplicationContext() != null;
assert Contexts.getEventContext() instanceof EventContext;
assert Contexts.getSessionContext() instanceof SessionContext;
assert Contexts.getConversationContext() instanceof ServerConversationContext;
assert Contexts.getApplicationContext() instanceof ApplicationContext;
Contexts.getSessionContext().set("zzz", "bar");
Contexts.getApplicationContext().set("zzz", "bar");
Contexts.getConversationContext().set("xxx", "yyy");
Object bar = seamVariableResolver.getValue(elContext, null, "bar");
assert bar != null;
assert bar instanceof Bar;
assert Contexts.getConversationContext().get("bar") == bar;
Object foo = Contexts.getSessionContext().get("foo");
assert foo != null;
assert foo instanceof Foo;
FacesLifecycle.endRequest(externalContext);
assert !Contexts.isEventContextActive();
assert !Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert !Contexts.isApplicationContextActive();
assert ((MockHttpSession) externalContext.getSession(false))
.getAttributes().size() == 4;
assert ((MockServletContext) externalContext.getContext())
- .getAttributes().size() == 11;
+ .getAttributes().size() == 12;
FacesLifecycle.beginRequest(externalContext);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
Manager.instance().setCurrentConversationId("3");
FacesLifecycle.resumeConversation(externalContext);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
assert Contexts.getEventContext() != null;
assert Contexts.getSessionContext() != null;
assert Contexts.getConversationContext() != null;
assert Contexts.getApplicationContext() != null;
assert Contexts.getEventContext() instanceof EventContext;
assert Contexts.getSessionContext() instanceof SessionContext;
assert Contexts.getConversationContext() instanceof ServerConversationContext;
assert Contexts.getApplicationContext() instanceof ApplicationContext;
assert Contexts.getSessionContext().get("zzz").equals("bar");
assert Contexts.getApplicationContext().get("zzz").equals("bar");
assert Contexts.getConversationContext().get("xxx").equals("yyy");
assert Contexts.getConversationContext().get("bar") == bar;
assert Contexts.getSessionContext().get("foo") == foo;
assert Contexts.getConversationContext().getNames().length == 2;
- assert Contexts.getApplicationContext().getNames().length == 11;
+ assert Contexts.getApplicationContext().getNames().length == 12;
assert Contexts.getSessionContext().getNames().length == 2;
assert seamVariableResolver.getValue(elContext, null, "zzz").equals(
"bar");
assert seamVariableResolver.getValue(elContext, null, "xxx").equals(
"yyy");
assert seamVariableResolver.getValue(elContext, null, "bar") == bar;
assert seamVariableResolver.getValue(elContext, null, "foo") == foo;
// JBSEAM-3077
assert EL.EL_RESOLVER.getValue(elContext, new Namespace("org.jboss.seam.core."), "conversationEntries") instanceof ConversationEntries;
try {
assert EL.EL_RESOLVER.getValue(elContext, new Namespace("org.jboss.seam."), "caughtException") == null;
} catch (Exception e) {
Assert.fail("An exception should not be thrown when a qualified name resolves to null", e);
}
/*
* assert jbpmVariableResolver.resolveVariable("zzz").equals("bar");
* assert jbpmVariableResolver.resolveVariable("xxx").equals("yyy");
* assert jbpmVariableResolver.resolveVariable("bar")==bar; assert
* jbpmVariableResolver.resolveVariable("foo")==foo;
*/
Manager.instance().setLongRunningConversation(false);
FacesLifecycle.endRequest(externalContext);
assert !Contexts.isEventContextActive();
assert !Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert !Contexts.isApplicationContextActive();
assert ((MockHttpSession) externalContext.getSession(false))
.getAttributes().size() == 3; // foo, zzz, org.jboss.seam.core.conversationEntries
assert ((MockServletContext) externalContext.getContext())
- .getAttributes().size() == 11;
+ .getAttributes().size() == 12;
ServletLifecycle.endSession(((HttpServletRequest) externalContext
.getRequest()).getSession());
ServletLifecycle.endApplication();
}
@Test
public void testContexts() {
MockServletContext servletContext = new MockServletContext();
ServletLifecycle.beginApplication(servletContext);
MockHttpSession session = new MockHttpSession(servletContext);
MockHttpServletRequest request = new MockHttpServletRequest(session);
final ExternalContext externalContext = new MockExternalContext(
servletContext, request);
final Map sessionAdaptor = new ServletRequestSessionMap(request);
Map requestAdaptor = new ServletRequestMap(request);
Context appContext = new ApplicationContext(externalContext
.getApplicationMap());
installComponent(appContext, ConversationEntries.class);
installComponent(appContext, Manager.class);
appContext.set(Seam.getComponentName(Init.class), new Init());
FacesLifecycle.beginRequest(externalContext);
Manager.instance().setLongRunningConversation(true);
testContext(new ApplicationContext(externalContext.getApplicationMap()));
testContext(new SessionContext(sessionAdaptor));
testContext(new EventContext(requestAdaptor));
testContext(new ServerConversationContext(sessionAdaptor, "1"));
testEquivalence(new ContextCreator() {
public Context createContext() {
return new ServerConversationContext(sessionAdaptor, "1");
}
});
testEquivalence(new ContextCreator() {
public Context createContext() {
return new SessionContext(sessionAdaptor);
}
});
testEquivalence(new ContextCreator() {
public Context createContext() {
return new ApplicationContext(externalContext.getApplicationMap());
}
});
testIsolation(new ServerConversationContext(sessionAdaptor, "1"),
new ServerConversationContext(sessionAdaptor, "2"));
// testIsolation( new WebSessionContext(externalContext), new
// WebSessionContext( new MockExternalContext()) );
ServletLifecycle.endApplication();
}
private interface ContextCreator {
Context createContext();
}
private void testEquivalence(ContextCreator creator) {
//Creates a new context for each action to better simulate these operations
//happening in different call contexts.
{ //Test Adding
Context ctx = creator.createContext();
ctx.set("foo", "bar");
ctx.flush();
}
{ //Is Added?
Context ctx = creator.createContext();
assert ctx.get("foo").equals("bar");
}
{ // Test Removing
Context ctx = creator.createContext();
ctx.remove("foo");
ctx.flush();
}
{ // Is Removed?
Context ctx = creator.createContext();
assert !ctx.isSet("foo");
}
}
private void testIsolation(Context ctx, Context cty) {
ctx.set("foo", "bar");
ctx.flush();
assert !cty.isSet("foo");
cty.set("foo", "bar");
ctx.remove("foo");
ctx.flush();
assert cty.get("foo").equals("bar");
}
private void testContext(Context ctx) {
assert !ctx.isSet("foo");
ctx.set("foo", "bar");
assert ctx.isSet("foo");
assert ctx.get("foo").equals("bar");
ctx.remove("foo");
assert !ctx.isSet("foo");
}
}
| false | true | public void testContextManagement() throws Exception {
ELContext elContext = EL.createELContext();
SeamELResolver seamVariableResolver = new SeamELResolver();
// org.jboss.seam.bpm.SeamVariableResolver jbpmVariableResolver = new
// org.jboss.seam.bpm.SeamVariableResolver();
MockServletContext servletContext = new MockServletContext();
ServletLifecycle.beginApplication(servletContext);
MockExternalContext externalContext = new MockExternalContext(
servletContext);
Context appContext = new ApplicationContext(externalContext
.getApplicationMap());
// appContext.set( Seam.getComponentName(Init.class), new Init() );
installComponent(appContext, ConversationEntries.class);
installComponent(appContext, Manager.class);
installComponent(appContext, Session.class);
installComponent(appContext, ServletContexts.class);
installComponent(appContext, Parameters.class);
appContext.set(Seam.getComponentName(Init.class), new Init());
installComponent(appContext, Bar.class);
installComponent(appContext, Foo.class);
appContext.set("otherFoo", new Foo());
assert !Contexts.isEventContextActive();
assert !Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert !Contexts.isApplicationContextActive();
FacesLifecycle.beginRequest(externalContext);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
Manager.instance().setCurrentConversationId("3");
FacesLifecycle.resumeConversation(externalContext);
Manager.instance().setLongRunningConversation(true);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
assert !Contexts.isPageContextActive();
assert Contexts.getEventContext() != null;
assert Contexts.getSessionContext() != null;
assert Contexts.getConversationContext() != null;
assert Contexts.getApplicationContext() != null;
assert Contexts.getEventContext() instanceof EventContext;
assert Contexts.getSessionContext() instanceof SessionContext;
assert Contexts.getConversationContext() instanceof ServerConversationContext;
assert Contexts.getApplicationContext() instanceof ApplicationContext;
Contexts.getSessionContext().set("zzz", "bar");
Contexts.getApplicationContext().set("zzz", "bar");
Contexts.getConversationContext().set("xxx", "yyy");
Object bar = seamVariableResolver.getValue(elContext, null, "bar");
assert bar != null;
assert bar instanceof Bar;
assert Contexts.getConversationContext().get("bar") == bar;
Object foo = Contexts.getSessionContext().get("foo");
assert foo != null;
assert foo instanceof Foo;
FacesLifecycle.endRequest(externalContext);
assert !Contexts.isEventContextActive();
assert !Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert !Contexts.isApplicationContextActive();
assert ((MockHttpSession) externalContext.getSession(false))
.getAttributes().size() == 4;
assert ((MockServletContext) externalContext.getContext())
.getAttributes().size() == 11;
FacesLifecycle.beginRequest(externalContext);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
Manager.instance().setCurrentConversationId("3");
FacesLifecycle.resumeConversation(externalContext);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
assert Contexts.getEventContext() != null;
assert Contexts.getSessionContext() != null;
assert Contexts.getConversationContext() != null;
assert Contexts.getApplicationContext() != null;
assert Contexts.getEventContext() instanceof EventContext;
assert Contexts.getSessionContext() instanceof SessionContext;
assert Contexts.getConversationContext() instanceof ServerConversationContext;
assert Contexts.getApplicationContext() instanceof ApplicationContext;
assert Contexts.getSessionContext().get("zzz").equals("bar");
assert Contexts.getApplicationContext().get("zzz").equals("bar");
assert Contexts.getConversationContext().get("xxx").equals("yyy");
assert Contexts.getConversationContext().get("bar") == bar;
assert Contexts.getSessionContext().get("foo") == foo;
assert Contexts.getConversationContext().getNames().length == 2;
assert Contexts.getApplicationContext().getNames().length == 11;
assert Contexts.getSessionContext().getNames().length == 2;
assert seamVariableResolver.getValue(elContext, null, "zzz").equals(
"bar");
assert seamVariableResolver.getValue(elContext, null, "xxx").equals(
"yyy");
assert seamVariableResolver.getValue(elContext, null, "bar") == bar;
assert seamVariableResolver.getValue(elContext, null, "foo") == foo;
// JBSEAM-3077
assert EL.EL_RESOLVER.getValue(elContext, new Namespace("org.jboss.seam.core."), "conversationEntries") instanceof ConversationEntries;
try {
assert EL.EL_RESOLVER.getValue(elContext, new Namespace("org.jboss.seam."), "caughtException") == null;
} catch (Exception e) {
Assert.fail("An exception should not be thrown when a qualified name resolves to null", e);
}
/*
* assert jbpmVariableResolver.resolveVariable("zzz").equals("bar");
* assert jbpmVariableResolver.resolveVariable("xxx").equals("yyy");
* assert jbpmVariableResolver.resolveVariable("bar")==bar; assert
* jbpmVariableResolver.resolveVariable("foo")==foo;
*/
Manager.instance().setLongRunningConversation(false);
FacesLifecycle.endRequest(externalContext);
assert !Contexts.isEventContextActive();
assert !Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert !Contexts.isApplicationContextActive();
assert ((MockHttpSession) externalContext.getSession(false))
.getAttributes().size() == 3; // foo, zzz, org.jboss.seam.core.conversationEntries
assert ((MockServletContext) externalContext.getContext())
.getAttributes().size() == 11;
ServletLifecycle.endSession(((HttpServletRequest) externalContext
.getRequest()).getSession());
ServletLifecycle.endApplication();
}
| public void testContextManagement() throws Exception {
ELContext elContext = EL.createELContext();
SeamELResolver seamVariableResolver = new SeamELResolver();
// org.jboss.seam.bpm.SeamVariableResolver jbpmVariableResolver = new
// org.jboss.seam.bpm.SeamVariableResolver();
MockServletContext servletContext = new MockServletContext();
ServletLifecycle.beginApplication(servletContext);
MockExternalContext externalContext = new MockExternalContext(
servletContext);
Context appContext = new ApplicationContext(externalContext
.getApplicationMap());
// appContext.set( Seam.getComponentName(Init.class), new Init() );
installComponent(appContext, ConversationEntries.class);
installComponent(appContext, Manager.class);
installComponent(appContext, Session.class);
installComponent(appContext, ServletContexts.class);
installComponent(appContext, Parameters.class);
appContext.set(Seam.getComponentName(Init.class), new Init());
installComponent(appContext, Bar.class);
installComponent(appContext, Foo.class);
appContext.set("otherFoo", new Foo());
assert !Contexts.isEventContextActive();
assert !Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert !Contexts.isApplicationContextActive();
FacesLifecycle.beginRequest(externalContext);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
Manager.instance().setCurrentConversationId("3");
FacesLifecycle.resumeConversation(externalContext);
Manager.instance().setLongRunningConversation(true);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
assert !Contexts.isPageContextActive();
assert Contexts.getEventContext() != null;
assert Contexts.getSessionContext() != null;
assert Contexts.getConversationContext() != null;
assert Contexts.getApplicationContext() != null;
assert Contexts.getEventContext() instanceof EventContext;
assert Contexts.getSessionContext() instanceof SessionContext;
assert Contexts.getConversationContext() instanceof ServerConversationContext;
assert Contexts.getApplicationContext() instanceof ApplicationContext;
Contexts.getSessionContext().set("zzz", "bar");
Contexts.getApplicationContext().set("zzz", "bar");
Contexts.getConversationContext().set("xxx", "yyy");
Object bar = seamVariableResolver.getValue(elContext, null, "bar");
assert bar != null;
assert bar instanceof Bar;
assert Contexts.getConversationContext().get("bar") == bar;
Object foo = Contexts.getSessionContext().get("foo");
assert foo != null;
assert foo instanceof Foo;
FacesLifecycle.endRequest(externalContext);
assert !Contexts.isEventContextActive();
assert !Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert !Contexts.isApplicationContextActive();
assert ((MockHttpSession) externalContext.getSession(false))
.getAttributes().size() == 4;
assert ((MockServletContext) externalContext.getContext())
.getAttributes().size() == 12;
FacesLifecycle.beginRequest(externalContext);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
Manager.instance().setCurrentConversationId("3");
FacesLifecycle.resumeConversation(externalContext);
assert Contexts.isEventContextActive();
assert Contexts.isSessionContextActive();
assert Contexts.isConversationContextActive();
assert Contexts.isApplicationContextActive();
assert Contexts.getEventContext() != null;
assert Contexts.getSessionContext() != null;
assert Contexts.getConversationContext() != null;
assert Contexts.getApplicationContext() != null;
assert Contexts.getEventContext() instanceof EventContext;
assert Contexts.getSessionContext() instanceof SessionContext;
assert Contexts.getConversationContext() instanceof ServerConversationContext;
assert Contexts.getApplicationContext() instanceof ApplicationContext;
assert Contexts.getSessionContext().get("zzz").equals("bar");
assert Contexts.getApplicationContext().get("zzz").equals("bar");
assert Contexts.getConversationContext().get("xxx").equals("yyy");
assert Contexts.getConversationContext().get("bar") == bar;
assert Contexts.getSessionContext().get("foo") == foo;
assert Contexts.getConversationContext().getNames().length == 2;
assert Contexts.getApplicationContext().getNames().length == 12;
assert Contexts.getSessionContext().getNames().length == 2;
assert seamVariableResolver.getValue(elContext, null, "zzz").equals(
"bar");
assert seamVariableResolver.getValue(elContext, null, "xxx").equals(
"yyy");
assert seamVariableResolver.getValue(elContext, null, "bar") == bar;
assert seamVariableResolver.getValue(elContext, null, "foo") == foo;
// JBSEAM-3077
assert EL.EL_RESOLVER.getValue(elContext, new Namespace("org.jboss.seam.core."), "conversationEntries") instanceof ConversationEntries;
try {
assert EL.EL_RESOLVER.getValue(elContext, new Namespace("org.jboss.seam."), "caughtException") == null;
} catch (Exception e) {
Assert.fail("An exception should not be thrown when a qualified name resolves to null", e);
}
/*
* assert jbpmVariableResolver.resolveVariable("zzz").equals("bar");
* assert jbpmVariableResolver.resolveVariable("xxx").equals("yyy");
* assert jbpmVariableResolver.resolveVariable("bar")==bar; assert
* jbpmVariableResolver.resolveVariable("foo")==foo;
*/
Manager.instance().setLongRunningConversation(false);
FacesLifecycle.endRequest(externalContext);
assert !Contexts.isEventContextActive();
assert !Contexts.isSessionContextActive();
assert !Contexts.isConversationContextActive();
assert !Contexts.isApplicationContextActive();
assert ((MockHttpSession) externalContext.getSession(false))
.getAttributes().size() == 3; // foo, zzz, org.jboss.seam.core.conversationEntries
assert ((MockServletContext) externalContext.getContext())
.getAttributes().size() == 12;
ServletLifecycle.endSession(((HttpServletRequest) externalContext
.getRequest()).getSession());
ServletLifecycle.endApplication();
}
|
diff --git a/src/main/java/de/tarent/maven/plugins/pkg/Utils.java b/src/main/java/de/tarent/maven/plugins/pkg/Utils.java
index 8eef398..60e1925 100644
--- a/src/main/java/de/tarent/maven/plugins/pkg/Utils.java
+++ b/src/main/java/de/tarent/maven/plugins/pkg/Utils.java
@@ -1,1172 +1,1177 @@
/*
* Maven Packaging Plugin,
* Maven plugin to package a Project (deb, ipk, izpack)
* Copyright (C) 2000-2008 tarent GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License,version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
* tarent GmbH., hereby disclaims all copyright
* interest in the program 'Maven Packaging Plugin'
* Signature of Elmar Geese, 11 March 2008
* Elmar Geese, CEO tarent GmbH.
*/
package de.tarent.maven.plugins.pkg;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.NotFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.model.License;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.artifact.InvalidDependencyVersionException;
import org.codehaus.plexus.archiver.ArchiveFile;
import org.codehaus.plexus.archiver.ArchiveFile.Entry;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
import de.tarent.maven.plugins.pkg.annotations.MergeMe;
import de.tarent.maven.plugins.pkg.merger.CollectionMerger;
import de.tarent.maven.plugins.pkg.merger.IMerge;
import de.tarent.maven.plugins.pkg.merger.ObjectMerger;
import de.tarent.maven.plugins.pkg.merger.PropertiesMerger;
import de.tarent.maven.plugins.pkg.packager.DebPackager;
import de.tarent.maven.plugins.pkg.packager.IpkPackager;
import de.tarent.maven.plugins.pkg.packager.IzPackPackager;
import de.tarent.maven.plugins.pkg.packager.Packager;
import de.tarent.maven.plugins.pkg.packager.RPMPackager;
/**
* A bunch of method with often used functionality. There is nothing special
* about them they just make other code more readable.
*
* @author Robert Schuster ([email protected])
*/
public final class Utils {
private static final String STARTER_CLASS = "_Starter.class";
/**
* Look up Archiver/UnArchiver implementations.
* @component role="org.codehaus.plexus.archiver.manager.ArchiverManager"
* @required
* @readonly
*/
protected static ArchiverManager archiverManager;
/**
* File filter that ignores files ending with "~", ".cvsignore" and CVS and
* SVN files.
*/
public static final IOFileFilter FILTER = FileFilterUtils.makeSVNAware(FileFilterUtils
.makeCVSAware(new NotFileFilter(new SuffixFileFilter(new String[] { "~", ".cvsignore" }))));
public static void createParentDirs(File f, String item) throws MojoExecutionException {
File p = f.getParentFile();
if (!p.exists() && !p.mkdirs()){
throw new MojoExecutionException("Cannot create parent dirs for the " + item + " .");
}
}
/**
* Creates a file and the file's parent directories.
*
* @param f
* @param item
* @throws MojoExecutionException
*/
public static void createFile(File f, String item) throws MojoExecutionException {
try {
createParentDirs(f, item);
f.createNewFile();
} catch (IOException ioe) {
throw new MojoExecutionException("IOException while creating " + item + " file.", ioe);
}
}
/**
* This wraps doing a "chmod +x" on a file + logging.
*
* @param l
* @param f
* @param item
* @throws MojoExecutionException
*/
public static void makeExecutable(Log l, String f) throws MojoExecutionException {
l.info("make executable " + f);
exec(new String[] { "chmod", "+x", f }, "Changing the " + f + " file attributes failed.", "Unable to make " + f
+ " file executable.");
}
/**
* This wraps doing a "chmod +x" on a file.
*
* @param f
* @param item
* @throws MojoExecutionException
*/
public static void makeExecutable(File f, String item) throws MojoExecutionException {
exec(new String[] { "chmod", "+x", f.getAbsolutePath() }, "Changing the " + item + " file attributes failed.",
"Unable to make " + item + " file executable.");
}
/**
* Checks whether a certain program is available.
*
* <p>
* It fails with a {@link MojoExecutionException} if the program is not
* available.
*
* @param programName
* @throws MojoExecutionException
*/
public static void checkProgramAvailability(String programName) throws MojoExecutionException {
exec(new String[] { "which", programName }, null, programName
+ " is not available on your system. Check your installation!", "Error executing " + programName
+ ". Aborting!",null);
}
/**
* Checks whether a certain program is available.
*
* <p>
* It fails with a {@link MojoExecutionException} if the program is not
* available.
*
* @param programName
* @throws MojoExecutionException
*/
public static String getProgramVersionOutput(String programName) throws MojoExecutionException {
return inputStreamToString(exec(new String[] { programName, "--version" }, null,
" dpkg-deb is not available on your system. Check your installation!", "Error executing dpkg-deb"
+ ". Aborting!",null)).trim();
}
- private static String inputStreamToString(InputStream in) {
+ private static String inputStreamToString(InputStream in) throws MojoExecutionException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try{
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
- bufferedReader.close();
}catch(IOException ex){
- new MojoExecutionException("Error reading input stream");
- }
+ throw new MojoExecutionException("Error reading input stream");
+ } finally {
+ try {
+ bufferedReader.close();
+ } catch (IOException e) {
+ throw new MojoExecutionException("Error closing reader");
+ }
+ }
return stringBuilder.toString();
}
/**
* A method which makes executing programs easier.
*
* @param args
* @param failureMsg
* @param ioExceptionMsg
* @throws MojoExecutionException
*/
public static void exec(String[] args, String failureMsg, String ioExceptionMsg) throws MojoExecutionException {
exec(args, null, failureMsg, ioExceptionMsg, null);
}
public static InputStream exec(String[] args, File workingDir, String failureMsg,
String ioExceptionMsg) throws MojoExecutionException {
return exec(args, workingDir, failureMsg, ioExceptionMsg, null);
}
public static InputStream exec(String[] args, String failureMsg,
String ioExceptionMsg, String userInput) throws MojoExecutionException {
return exec(args, null, failureMsg, ioExceptionMsg, userInput);
}
/**
* A method which makes executing programs easier.
*
* @param args
* @param failureMsg
* @param ioExceptionMsg
* @throws MojoExecutionException
*/
public static InputStream exec(String[] args, File workingDir, String failureMsg,
String ioExceptionMsg, String userInput)
throws MojoExecutionException {
/*
* debug code which prints out the execution command-line. Enable if
* neccessary. for(int i=0;i<args.length;i++) { System.err.print(args[i]
* + " "); } System.err.println();
*/
// Creates process with the defined language setting of LC_ALL=C
// That way the textual output of certain commands is predictable.
ProcessBuilder pb = new ProcessBuilder(args);
pb.directory(workingDir);
Map<String, String> env = pb.environment();
env.put("LC_ALL", "C");
Process p = null;
try {
p = pb.start();
if(userInput!=null){
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
writer.println(userInput);
writer.flush();
writer.close();
}
int exitValue = p.waitFor();
if (exitValue != 0) {
print(p);
throw new MojoExecutionException(String.format("(Subprocess exit value = %s) %s", exitValue, failureMsg));
}
} catch (IOException ioe) {
throw new MojoExecutionException(ioExceptionMsg + " :" + ioe.getMessage(), ioe);
} catch (InterruptedException ie) {
// Cannot happen.
throw new MojoExecutionException("InterruptedException", ie);
}
return p.getInputStream();
}
/**
* Stores the contents of an input stream in a file. This is used to copy a
* resource from the classpath.
*
* @param is
* @param file
* @param ioExceptionMsg
* @throws MojoExecutionException
*/
public static void storeInputStream(InputStream is, File file, String ioExceptionMsg) throws MojoExecutionException {
if (is == null){
throw new MojoExecutionException("InputStream must not be null.");
}
try {
FileOutputStream fos = new FileOutputStream(file);
IOUtils.copy(is, fos);
is.close();
fos.close();
} catch (IOException ioe) {
throw new MojoExecutionException(ioExceptionMsg, ioe);
}
}
/**
* This method can be used to debug the output of processes.
*
* @param p
*/
public static void print(Process p) {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
while (br.ready()) {
System.err.println("*** Process output ***");
System.err.println(br.readLine());
System.err.println("**********************");
}
} catch (IOException ioe) {
// foo
}
}
public static long copyProjectArtifact(Log l, File src, File dst) throws MojoExecutionException {
if (l!=null){
l.info("copying artifact: " + src.getAbsolutePath());
l.info("destination: " + dst.getAbsolutePath());
}
Utils.createFile(dst, "destination artifact");
try {
FileUtils.copyFile(src, dst);
return src.length();
} catch (IOException ioe) {
throw new MojoExecutionException("IOException while copying artifact file.", ioe);
}
}
/**
* Convert the artifactId into a Debian package name which contains gcj
* precompiled binaries.
*
* @param artifactId
* @return
*/
public static String gcjise(String artifactId, String section, boolean debianise) {
return debianise && section.equals("libs") ? "lib" + artifactId + "-gcj" : artifactId + "-gcj";
}
/**
* Concatenates two dependency lines. If both parts (prefix and suffix) are
* non-empty the lines will be joined with a comma in between.
* <p>
* If one of the parts is empty the other will be returned.
* </p>
*
* @param prefix
* @param suffix
* @return
*/
public static String joinDependencyLines(String prefix, String suffix) {
return (prefix.length() == 0) ? suffix : (suffix.length() == 0) ? prefix : prefix + ", " + suffix;
}
public static long copyFiles(Log l, File srcDir, File dstDir, List<? extends AuxFile> auxFiles, String type)
throws MojoExecutionException {
return copyFiles(l, srcDir, dstDir, auxFiles, type, false);
}
/**
* Copies the <code>AuxFile</code> instances contained within the set. It
* takes the <code>srcAuxFilesDir</code> and <code>auxFileDstDir</code>
* arguments into account to specify the parent source and destination
* directory of the files.
*
* By default files are copied into directories. If the <code>rename</code>
* property of the <code>AuxFile</code> instance is set however the file is
* copied and renamed to the last part of the path.
*
* The return value is the amount of copied bytes.
*
* @param l
* @param srcAuxFilesDir
* @param dstDir
* @param auxFiles
* @param makeExecutable
* @return
* @throws MojoExecutionException
*/
public static long copyFiles(Log l, File srcDir, File dstDir, List<? extends AuxFile> auxFiles, String type,
boolean makeExecutable) throws MojoExecutionException {
long size = 0;
Iterator<? extends AuxFile> ite = auxFiles.iterator();
while (ite.hasNext()) {
AuxFile af = (AuxFile) ite.next();
File from = new File(srcDir, af.from);
File to = new File(dstDir, af.to);
l.info("copying " + type + ": " + from.toString());
l.info("destination: " + to.toString());
if (!from.exists()){
throw new MojoExecutionException("File to copy does not exist: " + from.toString());
}
createParentDirs(to, type);
try {
if (from.isDirectory()) {
to = new File(to, from.getName());
FileUtils.copyDirectory(from, to, FILTER);
for (final Iterator<File> files = FileUtils.iterateFiles(from, FILTER, FILTER); files.hasNext(); ) {
final File nextFile = files.next();
size += nextFile.length();
}
} else if (af.isRename()) {
FileUtils.copyFile(from, to);
size += from.length();
if (makeExecutable){
makeExecutable(l, to.getAbsolutePath());
}
} else {
FileUtils.copyFileToDirectory(from, to);
size += from.length();
if (makeExecutable){
makeExecutable(l, to.getAbsolutePath() + File.separator + from.getName());
}
}
} catch (IOException ioe) {
throw new MojoExecutionException("IOException while copying " + type, ioe);
}
}
return size;
}
/**
* Converts the artifactId into a package name. Currently this only
* applies to libraries which get a "lib" prefix and a "-java" suffix.
*
* <p>An optional packageNameSuffix can be specified which is appended
* to the artifact id.</p>
*
* <p>When <code>debianise</code> is set the name will be lowercased.</p>
*
* @param artifactId
* @return
*/
public static String createPackageName(String artifactId, String packageNameSuffix, String section, boolean debianise) {
String baseName = (packageNameSuffix != null) ? (artifactId + "-" + packageNameSuffix) : artifactId;
if (debianise) {
// Debian naming does not allow any uppercase characters.
baseName = baseName.toLowerCase();
// Debian java libraries are called lib${FOO}-java
if (section.equals("libs")) {
baseName = "lib" + baseName + "-java";
}
}
return baseName;
}
/**
* Batch creates the package names for the given {@link TargetConfiguration} instances using the method {@link #createPackageName}.
*
* @param artifactId
* @param tcs
* @param debianise
* @return
*/
public static List<String> createPackageNames(String artifactId, List<TargetConfiguration> tcs, boolean debianise) {
ArrayList<String> pns = new ArrayList<String>(tcs.size());
for (TargetConfiguration tc : tcs) {
pns.add(createPackageName(artifactId, tc.getPackageNameSuffix(), tc.getSection(), debianise));
}
return pns;
}
/**
* Copies the starter classfile to the starter path, prepares the classpath
* properties file and stores it at that location, too.
*
* @param dstStarterRoot
* @param dependencies
* @param libraryPrefix
* @throws MojoExecutionException
*/
public static void setupStarter(Log l, String mainClass, File dstStarterRoot, Path classpath)
throws MojoExecutionException {
File destStarterClassFile = new File(dstStarterRoot, STARTER_CLASS);
Utils.createFile(destStarterClassFile, "starter class");
Utils.storeInputStream(Utils.class.getResourceAsStream("/" + STARTER_CLASS), destStarterClassFile,
"Unable to store starter class file in destination.");
File destClasspathFile = new File(dstStarterRoot, "_classpath");
Utils.createFile(destClasspathFile, "starter classpath");
PrintWriter writer = null;
try {
writer = new PrintWriter(destClasspathFile);
writer.println("# This file controls the application's classpath and is autogenerated.");
writer.println("# Slashes (/) in the filenames are replaced with the platform-specific");
writer.println("# separator char at runtime.");
writer.println("# The next line is the fully-classified name of the main class:");
writer.println(mainClass);
writer.println("# The following lines are the classpath entries:");
for (String e : classpath) {
writer.println(e);
}
l.info("created library entries");
} catch (IOException e) {
throw new MojoExecutionException("storing the classpath entries failed", e);
} finally {
if (writer != null){
writer.close();
}
}
}
/**
* Copies the Artifacts contained in the set to the folder denoted by
* <code>dst</code> and returns the amount of bytes copied.
*
* <p>
* If an artifact is a zip archive it is unzipped in this folder.
* </p>
*
* @param l
* @param artifacts
* @param dst
* @return
* @throws MojoExecutionException
*/
public static long copyArtifacts(Log l, Set<Artifact> artifacts, File dst) throws MojoExecutionException {
long byteAmount = 0;
if (artifacts.size() == 0) {
l.info("no artifact to copy.");
return byteAmount;
}
l.info("copying " + artifacts.size() + " dependency artifacts.");
l.info("destination: " + dst.toString());
try {
Iterator<Artifact> ite = artifacts.iterator();
while (ite.hasNext()) {
Artifact a = (Artifact) ite.next();
l.info("copying artifact: " + a);
File f = a.getFile();
if (f != null) {
l.debug("from file: " + f);
if (a.getType().equals("zip")) {
// Assume that this is a ZIP file with native libraries
// inside.
// TODO: Determine size of all entries and add this
// to the byteAmount.
unpack(a.getFile(), dst);
} else {
FileUtils.copyFileToDirectory(f, dst);
byteAmount += (long) f.length();
}
} else {
throw new MojoExecutionException("Unable to copy Artifact " + a
+ " because it is not locally available.");
}
}
} catch (IOException ioe) {
throw new MojoExecutionException("IOException while copying dependency artifacts.", ioe);
}
return byteAmount;
}
/**
* Unpacks the given file.
*
* @param file
* File to be unpacked.
* @param dst
* Location where to put the unpacked files.
*/
protected static void unpack(File file, File dst) throws MojoExecutionException {
try {
dst.mkdirs();
UnArchiver unArchiver = archiverManager.getUnArchiver(file);
unArchiver.setSourceFile(file);
unArchiver.setDestDirectory(dst);
unArchiver.extract();
} catch (NoSuchArchiverException e) {
throw new MojoExecutionException("Unknown archiver type", e);
} catch (ArchiverException e) {
throw new MojoExecutionException("Error unpacking file: " + file + " to: " + dst + "\r\n" + e.toString(), e);
}
}
/**
* Makes a valid and useful package version string from one that cannot be
* used or is unsuitable.
*
* <p>
* At the moment the method removes underscores only.
* </p>
*
* @param string
* The string which might contain underscores
* @return The given string without underscores
*/
public static String sanitizePackageVersion(String string) {
return string.replaceAll("_", "");
}
/**
* Gathers the project's artifacts and the artifacts of all its (transitive)
* dependencies filtered by the given filter instance.
*
* @param filter
* @return
* @throws ArtifactResolutionException
* @throws ArtifactNotFoundException
* @throws ProjectBuildingException
* @throws InvalidDependencyVersionException
*/
@SuppressWarnings("unchecked")
public static Set<Artifact> findArtifacts(ArtifactFilter filter,
ArtifactFactory factory,
ArtifactResolver resolver,
MavenProject project,
Artifact artifact,
ArtifactRepository local,
List<ArtifactRepository> remoteRepos,
ArtifactMetadataSource metadataSource)
throws ArtifactResolutionException,ArtifactNotFoundException,
ProjectBuildingException,InvalidDependencyVersionException {
ArtifactResolutionResult result = resolver.resolveTransitively(project.getDependencyArtifacts(),
artifact,
local,
remoteRepos,
metadataSource,
filter);
return (Set<Artifact>) result.getArtifacts();
}
/**
* Returns a TargetConfiguration object that matches the desired target String.
* @param target
* @param targetConfigurations
* @return
* @throws MojoExecutionException
*/
public static TargetConfiguration getTargetConfigurationFromString(String target,
List<TargetConfiguration> targetConfigurations) throws MojoExecutionException{
for (TargetConfiguration currentTargetConfiguration : targetConfigurations) {
if (currentTargetConfiguration.getTarget().equals(target)) {
return currentTargetConfiguration;
}
}
throw new MojoExecutionException("Target " + target + " not found. Check your spelling or configuration (is this target being defined in relation to another, but does not exist anymore?).");
}
/**
* Returns the default Distro to use for a certain TargetConfiguration.
* @param configuration
* @return
* @throws MojoExecutionException
*/
public static String getDefaultDistro(String targetString, List<TargetConfiguration> targetConfigurations, Log l) throws MojoExecutionException {
String distro = null;
TargetConfiguration target = Utils.getTargetConfigurationFromString(targetString, targetConfigurations);
if (target.getDefaultDistro() != null) {
distro = target.getDefaultDistro();
l.info("Default distribution is set to \"" + distro + "\".");
} else
switch (target.getDistros().size()) {
case 0:
throw new MojoExecutionException(
"No distros defined for configuration " + targetString);
case 1:
distro = (String) target.getDistros().iterator().next();
l.info(String.format("Only one distro defined, using '%s' as default", distro));
break;
default:
String m = "No default configuration given for distro '"
+ targetString
+ "', and more than one distro is supported. Please provide one.";
l.error(m);
throw new MojoExecutionException(m);
}
return distro;
}
/**
* Returns a string with the license(s) of a MavenProject.
*
* @param project
* @return
* @throws MojoExecutionException
*/
@SuppressWarnings("unchecked")
public static String getConsolidatedLicenseString(MavenProject project) throws MojoExecutionException {
StringBuilder license = new StringBuilder();
Iterator<License> ite = null;
try {
ite = (Iterator<License>) project.getLicenses().iterator();
license.append(((License) ite.next()).getName());
} catch (Exception ex) {
throw new MojoExecutionException("Please provide at least one license in your POM.",ex);
}
while (ite.hasNext()) {
license.append(", ");
license.append(((License) ite.next()).getName());
}
return license.toString();
}
/**
* Simple function to grab information from an URL
* @param url
* @return
* @throws IOException
*/
public static String getTextFromUrl(String url) throws IOException{
InputStream stream = null;
try {
stream = new URL(url).openStream();
return IOUtils.toString(stream);
} finally {
IOUtils.closeQuietly(stream);
}
}
/**
* Converts a byte amount to the unit used by the Debian control file
* (usually KiB). That value can then be used in a ControlFileGenerator
* instance.
*
* @param byteAmount
* @return
*/
public static long getInstalledSize(long byteAmount) {
return byteAmount / 1024L;
}
/**
* A <code>TargetConfiguration</code> can depend on another and so multiple
* build processes might need to be run for a single <code>TargetConfiguration</code>.
*
* <p>The list of <code>TargetConfiguration</code> instance that need to be built is
* called a build chain. A build chain with <code>n</code> entries contains <code>n-1</code>
* instances that need to be built before. The last element in the build chain is the
* one that was initially requested and must be build last.</p>
*
* @param target
* @param distro
* @return
* @throws MojoExecutionException
*/
public static List<TargetConfiguration> createBuildChain(
String target,
String distro,
List<TargetConfiguration> targetConfigurations)
throws MojoExecutionException
{
LinkedList<TargetConfiguration> tcs = new LinkedList<TargetConfiguration>();
// Merges vertically, that means through the 'parent' property.
TargetConfiguration tc = Utils.getTargetConfigurationFromString(target, targetConfigurations);
//Utils.getMergedConfigurationImpl(target, distro, targetConfigurations, true);
// In getMergedConfiguraion we check if targets that are hierarchically related
// support the same distro. Here we will have to check again, as there may not
// be parent-child relationship between them.
if(tc.getDistros().contains(distro)){
tcs.addFirst(tc);
List<String> relations = tc.getRelations();
for (String relation : relations) {
tcs.addAll(0, createBuildChain(relation, distro, targetConfigurations));
}
return tcs;
}else{
throw new MojoExecutionException("target configuration '" + tc.getTarget() +
"' does not support distro: " + distro);
}
}
/**
* Returns a Packager Object for a certain packaging type (deb, rpm, etc.)
*
* <p>Conveniently throws a {@link MojoExecutionException} if there is no
* {@link Packager} instance for the given package type.</p>
*
* @param packaging
* @return
*/
public static Packager getPackagerForPackaging(String packaging)
throws MojoExecutionException {
Map<String, Class<? extends Packager>> extPackagerMap = new HashMap<String, Class<? extends Packager>>();
extPackagerMap.put("deb", DebPackager.class);
extPackagerMap.put("ipk", IpkPackager.class);
extPackagerMap.put("izpack", IzPackPackager.class);
extPackagerMap.put("rpm", RPMPackager.class);
Class<? extends Packager> klass = extPackagerMap.get(packaging);
try {
return klass.newInstance();
} catch (InstantiationException e) {
throw new MojoExecutionException("Unsupported packaging type: "+ packaging, e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unsupported packaging type: "+ packaging, e);
}
}
/**
* Conveniently converts a list of target configurations into a map where
* each instance can be accessed by its name (ie. the target property).
*
* <p>Super conveniently this method throws an exception if during the
* conversion it is found out that there is more than one entry with the
* same target.</p>
*
* @param tcs
*/
public static Map<String, TargetConfiguration> toMap(List<TargetConfiguration> tcs)
throws MojoExecutionException {
HashMap<String, TargetConfiguration> m = new HashMap<String, TargetConfiguration>();
for (TargetConfiguration tc : tcs) {
if (m.put(tc.getTarget(), tc) != null) {
throw new MojoExecutionException("Target with name '" + tc.getTarget() + " exists more than once. Fix the plugin configuration!");
}
}
return m;
}
/**
* Given a list of target names resolves them into their actual {@link TargetConfiguration}
* instances. The resolution is done using the given map.
*
* <p>Additionally this method throws an exception if an entry could not be found in the map
* as this means something is configured wrongly.</p>
*
* @param targetNames
* @param map
* @return
* @throws MojoExecutionException
*/
public static List<TargetConfiguration> resolveConfigurations(List<String> targetNames, Map<String, TargetConfiguration> map)
throws MojoExecutionException {
ArrayList<TargetConfiguration> tcs = new ArrayList<TargetConfiguration>(targetNames.size());
for (String s : targetNames) {
TargetConfiguration tc = map.get(s);
if (tc == null) {
throw new MojoExecutionException("Target configuration '" + tc + "' is requested as a related target configuration but does not exist. Fix the plugin configuration!");
}
tcs.add(tc);
}
return tcs;
}
/**
* Sets all unset properties, either to the values of the parent or to a
* (hard-coded) default value if the property is not set in the parent.
*
* <p>
* Using this method the packaging plugin can generate a merge of the
* default and a distro-specific configuration.
* </p>
*
* @param child
* @param parent
* @return
* @throws MojoExecutionException
*/
public static TargetConfiguration mergeConfigurations(TargetConfiguration child,
TargetConfiguration parent) throws MojoExecutionException{
if (child.isReady()){
throw new MojoExecutionException(String.format("target configuration '%s' is already merged.", child.getTarget()));
}
Field[] allFields = TargetConfiguration.class.getDeclaredFields();
for (Field field : allFields){
field.setAccessible(true);
if(field.getAnnotation(MergeMe.class) != null){
try {
Object defaultValue = new Object();
IMerge merger;
if(field.getAnnotation(MergeMe.class).defaultValueIsNull()){
defaultValue=null;
}
if(field.getType()==Properties.class){
if(defaultValue!=null){
defaultValue = new Properties();
}
merger = new PropertiesMerger();
}else if(field.getType()==List.class){
if(defaultValue!=null){
defaultValue = new ArrayList<Object>();
}
merger = new CollectionMerger();
}else if(field.getType()==Set.class){
if(defaultValue!=null){
defaultValue = new HashSet<Object>();
}
merger = new CollectionMerger();
}else if(field.getType()==String.class){
if(defaultValue!=null){
defaultValue =field.getAnnotation(MergeMe.class).defaultString();
}
merger = new ObjectMerger();
}else if(field.getType()==Boolean.class){
defaultValue = field.getAnnotation(MergeMe.class).defaultBoolean();
merger = new ObjectMerger();
}else{
merger = new ObjectMerger();
}
Object childValue = field.get(child);
Object parentValue = field.get(parent);
try {
field.set(child, merger.merge(childValue,
parentValue,
defaultValue));
} catch (InstantiationException e) {
throw new MojoExecutionException("Error merging configurations",e);
}
}catch (SecurityException e){
throw new MojoExecutionException(e.getMessage(),e);
}catch (IllegalArgumentException e){
throw new MojoExecutionException(e.getMessage(),e);
}catch (IllegalAccessException e){
throw new MojoExecutionException(e.getMessage(),e);
}
}
}
child.setReady(true);
return child;
}
/**
* Recursively merges all configurations with their parents and returns a
* list of the available targetConfigurations ready to be consumed by the
* plugin.
*
* @param targetConfigurations
* @return
* @throws MojoExecutionException
*/
public static void mergeAllConfigurations(List<TargetConfiguration> targetConfigurations)
throws MojoExecutionException {
// We will loop through all targets
for (TargetConfiguration tc : targetConfigurations) {
// If tc is ready it means that this list has already been merged
if (tc.isReady()) {
throw new MojoExecutionException("This targetConfiguration list has already been merged.");
} else {
// Check if we are at the top of the hierarchy
if (tc.parent == null) {
// If we are at the top we will just fixate the configuration
tc.fixate();
} else {
// If there is a parent we will merge recursivelly tc's hierarchy
mergeAncestorsRecursively(tc,targetConfigurations);
}
}
}
}
/**
* Recursively merge the ancestors for a certain configuration.
*
* @param tc
* @param parent
* @param targetConfigurations
* @return
* @throws MojoExecutionException
*/
private static void mergeAncestorsRecursively(TargetConfiguration tc, List<TargetConfiguration> targetConfigurations) throws MojoExecutionException {
TargetConfiguration parent = getTargetConfigurationFromString(tc.parent, targetConfigurations);
// If the top of the hierarchy has not been reached yet,
// all remaining ancestors will be merged.
// The ready flag of the parent will also be checked
// in order to avoid redundant work.
if (parent.parent != null && !parent.isReady()) {
mergeAncestorsRecursively(parent, targetConfigurations);
}
// Once done checking all ancestors
// the child will be merged with the parent
mergeConfigurations(tc, parent);
}
/**
* Extracts a file from an archive and stores it in a temporary location.
* The file will be deleted when the virtual machine exits.
*
* @param archive
* @param needle
* @return
* @throws MojoExecutionException
*/
@SuppressWarnings("unchecked")
public static File getFileFromArchive(ArchiveFile archive, String needle) throws MojoExecutionException{
final int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
Entry entry;
Enumeration<? extends Entry> e;
try {
e = archive.getEntries();
} catch (IOException ex) {
throw new MojoExecutionException("Error getting entries from archive",ex);
}
while (e.hasMoreElements()){
entry = e.nextElement();
// If the entry we are in matches the needle we will store its contents to a temp file
if (entry.getName().equals(needle)){
// The file will be saved in the temporary directory
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File extractedFile;
try {
extractedFile = File.createTempFile("mvn-pkg-plugin",
"temp",
tempDir);
} catch (IOException ex) {
throw new MojoExecutionException("Error creating temporary file found",ex);
}
try {
is = new BufferedInputStream
(archive.getInputStream(entry));
} catch (IOException ex) {
throw new MojoExecutionException("Error reading entry from archive",ex);
}
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos;
try {
fos = new FileOutputStream(extractedFile);
} catch (FileNotFoundException ex) {
throw new MojoExecutionException("Error reading entry from archive",ex);
}
dest = new
BufferedOutputStream(fos, BUFFER);
try {
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
} catch (IOException ex) {
throw new MojoExecutionException("Error writing to temporary file",ex);
}finally{
try {
dest.flush();
dest.close();
is.close();
} catch (IOException ex) {
throw new MojoExecutionException("Error closing streams.",ex);
}
}
extractedFile.deleteOnExit();
return extractedFile;
}
}
throw new MojoExecutionException("Desired file not found");
}
/**
* Tries to match a string representing a debian package name against the convention.
* <a href="http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Source">http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Source</a>
* @param string
* @return True if matches
*/
public static boolean checkDebianPackageNameConvention(String string){
Pattern pattern = Pattern.compile("[a-z0-9][a-z0-9+.-]*[a-z0-9+.]");
Matcher m = pattern.matcher(string);
if(m.matches()){
return true;
}else{
return false;
}
}
/**
* Tries to match a string representing a debian package version against the convention.<br/>
* <a href="http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version">http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version</a>
* @param string
* @return True if matches
*/
public static boolean checkDebianPackageVersionConvention(String string){
boolean compliant = true;
Pattern pattern = Pattern.compile("[0-9][A-Za-z0-9.+~:-]*");
Matcher m = pattern.matcher(string);
if(!m.matches()){
compliant = false;
}
// A version must never end with a hyphen
if(string.endsWith("-")){
compliant = false;
}
// A version should never contain a colon if it does not start with an epoch
Pattern epoch = Pattern.compile("^[0-9][0-9]*:.*");
m = epoch.matcher(string);
if(!m.matches() && string.contains(":")){
compliant= false;
}
return compliant;
}
}
| false | true | public static void makeExecutable(Log l, String f) throws MojoExecutionException {
l.info("make executable " + f);
exec(new String[] { "chmod", "+x", f }, "Changing the " + f + " file attributes failed.", "Unable to make " + f
+ " file executable.");
}
/**
* This wraps doing a "chmod +x" on a file.
*
* @param f
* @param item
* @throws MojoExecutionException
*/
public static void makeExecutable(File f, String item) throws MojoExecutionException {
exec(new String[] { "chmod", "+x", f.getAbsolutePath() }, "Changing the " + item + " file attributes failed.",
"Unable to make " + item + " file executable.");
}
/**
* Checks whether a certain program is available.
*
* <p>
* It fails with a {@link MojoExecutionException} if the program is not
* available.
*
* @param programName
* @throws MojoExecutionException
*/
public static void checkProgramAvailability(String programName) throws MojoExecutionException {
exec(new String[] { "which", programName }, null, programName
+ " is not available on your system. Check your installation!", "Error executing " + programName
+ ". Aborting!",null);
}
/**
* Checks whether a certain program is available.
*
* <p>
* It fails with a {@link MojoExecutionException} if the program is not
* available.
*
* @param programName
* @throws MojoExecutionException
*/
public static String getProgramVersionOutput(String programName) throws MojoExecutionException {
return inputStreamToString(exec(new String[] { programName, "--version" }, null,
" dpkg-deb is not available on your system. Check your installation!", "Error executing dpkg-deb"
+ ". Aborting!",null)).trim();
}
private static String inputStreamToString(InputStream in) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try{
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
bufferedReader.close();
}catch(IOException ex){
new MojoExecutionException("Error reading input stream");
}
return stringBuilder.toString();
}
/**
* A method which makes executing programs easier.
*
* @param args
* @param failureMsg
* @param ioExceptionMsg
* @throws MojoExecutionException
*/
public static void exec(String[] args, String failureMsg, String ioExceptionMsg) throws MojoExecutionException {
exec(args, null, failureMsg, ioExceptionMsg, null);
}
public static InputStream exec(String[] args, File workingDir, String failureMsg,
String ioExceptionMsg) throws MojoExecutionException {
return exec(args, workingDir, failureMsg, ioExceptionMsg, null);
}
public static InputStream exec(String[] args, String failureMsg,
String ioExceptionMsg, String userInput) throws MojoExecutionException {
return exec(args, null, failureMsg, ioExceptionMsg, userInput);
}
/**
* A method which makes executing programs easier.
*
* @param args
* @param failureMsg
* @param ioExceptionMsg
* @throws MojoExecutionException
*/
public static InputStream exec(String[] args, File workingDir, String failureMsg,
String ioExceptionMsg, String userInput)
throws MojoExecutionException {
/*
* debug code which prints out the execution command-line. Enable if
* neccessary. for(int i=0;i<args.length;i++) { System.err.print(args[i]
* + " "); } System.err.println();
*/
// Creates process with the defined language setting of LC_ALL=C
// That way the textual output of certain commands is predictable.
ProcessBuilder pb = new ProcessBuilder(args);
pb.directory(workingDir);
Map<String, String> env = pb.environment();
env.put("LC_ALL", "C");
Process p = null;
try {
p = pb.start();
if(userInput!=null){
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
writer.println(userInput);
writer.flush();
writer.close();
}
int exitValue = p.waitFor();
if (exitValue != 0) {
print(p);
throw new MojoExecutionException(String.format("(Subprocess exit value = %s) %s", exitValue, failureMsg));
}
} catch (IOException ioe) {
throw new MojoExecutionException(ioExceptionMsg + " :" + ioe.getMessage(), ioe);
} catch (InterruptedException ie) {
// Cannot happen.
throw new MojoExecutionException("InterruptedException", ie);
}
return p.getInputStream();
}
/**
* Stores the contents of an input stream in a file. This is used to copy a
* resource from the classpath.
*
* @param is
* @param file
* @param ioExceptionMsg
* @throws MojoExecutionException
*/
public static void storeInputStream(InputStream is, File file, String ioExceptionMsg) throws MojoExecutionException {
if (is == null){
throw new MojoExecutionException("InputStream must not be null.");
}
try {
FileOutputStream fos = new FileOutputStream(file);
IOUtils.copy(is, fos);
is.close();
fos.close();
} catch (IOException ioe) {
throw new MojoExecutionException(ioExceptionMsg, ioe);
}
}
/**
* This method can be used to debug the output of processes.
*
* @param p
*/
public static void print(Process p) {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
while (br.ready()) {
System.err.println("*** Process output ***");
System.err.println(br.readLine());
System.err.println("**********************");
}
} catch (IOException ioe) {
// foo
}
}
public static long copyProjectArtifact(Log l, File src, File dst) throws MojoExecutionException {
if (l!=null){
l.info("copying artifact: " + src.getAbsolutePath());
l.info("destination: " + dst.getAbsolutePath());
}
Utils.createFile(dst, "destination artifact");
try {
FileUtils.copyFile(src, dst);
return src.length();
} catch (IOException ioe) {
throw new MojoExecutionException("IOException while copying artifact file.", ioe);
}
}
/**
* Convert the artifactId into a Debian package name which contains gcj
* precompiled binaries.
*
* @param artifactId
* @return
*/
public static String gcjise(String artifactId, String section, boolean debianise) {
return debianise && section.equals("libs") ? "lib" + artifactId + "-gcj" : artifactId + "-gcj";
}
/**
* Concatenates two dependency lines. If both parts (prefix and suffix) are
* non-empty the lines will be joined with a comma in between.
* <p>
* If one of the parts is empty the other will be returned.
* </p>
*
* @param prefix
* @param suffix
* @return
*/
public static String joinDependencyLines(String prefix, String suffix) {
return (prefix.length() == 0) ? suffix : (suffix.length() == 0) ? prefix : prefix + ", " + suffix;
}
public static long copyFiles(Log l, File srcDir, File dstDir, List<? extends AuxFile> auxFiles, String type)
throws MojoExecutionException {
return copyFiles(l, srcDir, dstDir, auxFiles, type, false);
}
/**
* Copies the <code>AuxFile</code> instances contained within the set. It
* takes the <code>srcAuxFilesDir</code> and <code>auxFileDstDir</code>
* arguments into account to specify the parent source and destination
* directory of the files.
*
* By default files are copied into directories. If the <code>rename</code>
* property of the <code>AuxFile</code> instance is set however the file is
* copied and renamed to the last part of the path.
*
* The return value is the amount of copied bytes.
*
* @param l
* @param srcAuxFilesDir
* @param dstDir
* @param auxFiles
* @param makeExecutable
* @return
* @throws MojoExecutionException
*/
public static long copyFiles(Log l, File srcDir, File dstDir, List<? extends AuxFile> auxFiles, String type,
boolean makeExecutable) throws MojoExecutionException {
long size = 0;
Iterator<? extends AuxFile> ite = auxFiles.iterator();
while (ite.hasNext()) {
AuxFile af = (AuxFile) ite.next();
File from = new File(srcDir, af.from);
File to = new File(dstDir, af.to);
l.info("copying " + type + ": " + from.toString());
l.info("destination: " + to.toString());
if (!from.exists()){
throw new MojoExecutionException("File to copy does not exist: " + from.toString());
}
createParentDirs(to, type);
try {
if (from.isDirectory()) {
to = new File(to, from.getName());
FileUtils.copyDirectory(from, to, FILTER);
for (final Iterator<File> files = FileUtils.iterateFiles(from, FILTER, FILTER); files.hasNext(); ) {
final File nextFile = files.next();
size += nextFile.length();
}
} else if (af.isRename()) {
FileUtils.copyFile(from, to);
size += from.length();
if (makeExecutable){
makeExecutable(l, to.getAbsolutePath());
}
} else {
FileUtils.copyFileToDirectory(from, to);
size += from.length();
if (makeExecutable){
makeExecutable(l, to.getAbsolutePath() + File.separator + from.getName());
}
}
} catch (IOException ioe) {
throw new MojoExecutionException("IOException while copying " + type, ioe);
}
}
return size;
}
/**
* Converts the artifactId into a package name. Currently this only
* applies to libraries which get a "lib" prefix and a "-java" suffix.
*
* <p>An optional packageNameSuffix can be specified which is appended
* to the artifact id.</p>
*
* <p>When <code>debianise</code> is set the name will be lowercased.</p>
*
* @param artifactId
* @return
*/
public static String createPackageName(String artifactId, String packageNameSuffix, String section, boolean debianise) {
String baseName = (packageNameSuffix != null) ? (artifactId + "-" + packageNameSuffix) : artifactId;
if (debianise) {
// Debian naming does not allow any uppercase characters.
baseName = baseName.toLowerCase();
// Debian java libraries are called lib${FOO}-java
if (section.equals("libs")) {
baseName = "lib" + baseName + "-java";
}
}
return baseName;
}
/**
* Batch creates the package names for the given {@link TargetConfiguration} instances using the method {@link #createPackageName}.
*
* @param artifactId
* @param tcs
* @param debianise
* @return
*/
public static List<String> createPackageNames(String artifactId, List<TargetConfiguration> tcs, boolean debianise) {
ArrayList<String> pns = new ArrayList<String>(tcs.size());
for (TargetConfiguration tc : tcs) {
pns.add(createPackageName(artifactId, tc.getPackageNameSuffix(), tc.getSection(), debianise));
}
return pns;
}
/**
* Copies the starter classfile to the starter path, prepares the classpath
* properties file and stores it at that location, too.
*
* @param dstStarterRoot
* @param dependencies
* @param libraryPrefix
* @throws MojoExecutionException
*/
public static void setupStarter(Log l, String mainClass, File dstStarterRoot, Path classpath)
throws MojoExecutionException {
File destStarterClassFile = new File(dstStarterRoot, STARTER_CLASS);
Utils.createFile(destStarterClassFile, "starter class");
Utils.storeInputStream(Utils.class.getResourceAsStream("/" + STARTER_CLASS), destStarterClassFile,
"Unable to store starter class file in destination.");
File destClasspathFile = new File(dstStarterRoot, "_classpath");
Utils.createFile(destClasspathFile, "starter classpath");
PrintWriter writer = null;
try {
writer = new PrintWriter(destClasspathFile);
writer.println("# This file controls the application's classpath and is autogenerated.");
writer.println("# Slashes (/) in the filenames are replaced with the platform-specific");
writer.println("# separator char at runtime.");
writer.println("# The next line is the fully-classified name of the main class:");
writer.println(mainClass);
writer.println("# The following lines are the classpath entries:");
for (String e : classpath) {
writer.println(e);
}
l.info("created library entries");
} catch (IOException e) {
throw new MojoExecutionException("storing the classpath entries failed", e);
} finally {
if (writer != null){
writer.close();
}
}
}
/**
* Copies the Artifacts contained in the set to the folder denoted by
* <code>dst</code> and returns the amount of bytes copied.
*
* <p>
* If an artifact is a zip archive it is unzipped in this folder.
* </p>
*
* @param l
* @param artifacts
* @param dst
* @return
* @throws MojoExecutionException
*/
public static long copyArtifacts(Log l, Set<Artifact> artifacts, File dst) throws MojoExecutionException {
long byteAmount = 0;
if (artifacts.size() == 0) {
l.info("no artifact to copy.");
return byteAmount;
}
l.info("copying " + artifacts.size() + " dependency artifacts.");
l.info("destination: " + dst.toString());
try {
Iterator<Artifact> ite = artifacts.iterator();
while (ite.hasNext()) {
Artifact a = (Artifact) ite.next();
l.info("copying artifact: " + a);
File f = a.getFile();
if (f != null) {
l.debug("from file: " + f);
if (a.getType().equals("zip")) {
// Assume that this is a ZIP file with native libraries
// inside.
// TODO: Determine size of all entries and add this
// to the byteAmount.
unpack(a.getFile(), dst);
} else {
FileUtils.copyFileToDirectory(f, dst);
byteAmount += (long) f.length();
}
} else {
throw new MojoExecutionException("Unable to copy Artifact " + a
+ " because it is not locally available.");
}
}
} catch (IOException ioe) {
throw new MojoExecutionException("IOException while copying dependency artifacts.", ioe);
}
return byteAmount;
}
/**
* Unpacks the given file.
*
* @param file
* File to be unpacked.
* @param dst
* Location where to put the unpacked files.
*/
protected static void unpack(File file, File dst) throws MojoExecutionException {
try {
dst.mkdirs();
UnArchiver unArchiver = archiverManager.getUnArchiver(file);
unArchiver.setSourceFile(file);
unArchiver.setDestDirectory(dst);
unArchiver.extract();
} catch (NoSuchArchiverException e) {
throw new MojoExecutionException("Unknown archiver type", e);
} catch (ArchiverException e) {
throw new MojoExecutionException("Error unpacking file: " + file + " to: " + dst + "\r\n" + e.toString(), e);
}
}
/**
* Makes a valid and useful package version string from one that cannot be
* used or is unsuitable.
*
* <p>
* At the moment the method removes underscores only.
* </p>
*
* @param string
* The string which might contain underscores
* @return The given string without underscores
*/
public static String sanitizePackageVersion(String string) {
return string.replaceAll("_", "");
}
/**
* Gathers the project's artifacts and the artifacts of all its (transitive)
* dependencies filtered by the given filter instance.
*
* @param filter
* @return
* @throws ArtifactResolutionException
* @throws ArtifactNotFoundException
* @throws ProjectBuildingException
* @throws InvalidDependencyVersionException
*/
@SuppressWarnings("unchecked")
public static Set<Artifact> findArtifacts(ArtifactFilter filter,
ArtifactFactory factory,
ArtifactResolver resolver,
MavenProject project,
Artifact artifact,
ArtifactRepository local,
List<ArtifactRepository> remoteRepos,
ArtifactMetadataSource metadataSource)
throws ArtifactResolutionException,ArtifactNotFoundException,
ProjectBuildingException,InvalidDependencyVersionException {
ArtifactResolutionResult result = resolver.resolveTransitively(project.getDependencyArtifacts(),
artifact,
local,
remoteRepos,
metadataSource,
filter);
return (Set<Artifact>) result.getArtifacts();
}
/**
* Returns a TargetConfiguration object that matches the desired target String.
* @param target
* @param targetConfigurations
* @return
* @throws MojoExecutionException
*/
public static TargetConfiguration getTargetConfigurationFromString(String target,
List<TargetConfiguration> targetConfigurations) throws MojoExecutionException{
for (TargetConfiguration currentTargetConfiguration : targetConfigurations) {
if (currentTargetConfiguration.getTarget().equals(target)) {
return currentTargetConfiguration;
}
}
throw new MojoExecutionException("Target " + target + " not found. Check your spelling or configuration (is this target being defined in relation to another, but does not exist anymore?).");
}
/**
* Returns the default Distro to use for a certain TargetConfiguration.
* @param configuration
* @return
* @throws MojoExecutionException
*/
public static String getDefaultDistro(String targetString, List<TargetConfiguration> targetConfigurations, Log l) throws MojoExecutionException {
String distro = null;
TargetConfiguration target = Utils.getTargetConfigurationFromString(targetString, targetConfigurations);
if (target.getDefaultDistro() != null) {
distro = target.getDefaultDistro();
l.info("Default distribution is set to \"" + distro + "\".");
} else
switch (target.getDistros().size()) {
case 0:
throw new MojoExecutionException(
"No distros defined for configuration " + targetString);
case 1:
distro = (String) target.getDistros().iterator().next();
l.info(String.format("Only one distro defined, using '%s' as default", distro));
break;
default:
String m = "No default configuration given for distro '"
+ targetString
+ "', and more than one distro is supported. Please provide one.";
l.error(m);
throw new MojoExecutionException(m);
}
return distro;
}
/**
* Returns a string with the license(s) of a MavenProject.
*
* @param project
* @return
* @throws MojoExecutionException
*/
@SuppressWarnings("unchecked")
public static String getConsolidatedLicenseString(MavenProject project) throws MojoExecutionException {
StringBuilder license = new StringBuilder();
Iterator<License> ite = null;
try {
ite = (Iterator<License>) project.getLicenses().iterator();
license.append(((License) ite.next()).getName());
} catch (Exception ex) {
throw new MojoExecutionException("Please provide at least one license in your POM.",ex);
}
while (ite.hasNext()) {
license.append(", ");
license.append(((License) ite.next()).getName());
}
return license.toString();
}
/**
* Simple function to grab information from an URL
* @param url
* @return
* @throws IOException
*/
public static String getTextFromUrl(String url) throws IOException{
InputStream stream = null;
try {
stream = new URL(url).openStream();
return IOUtils.toString(stream);
} finally {
IOUtils.closeQuietly(stream);
}
}
/**
* Converts a byte amount to the unit used by the Debian control file
* (usually KiB). That value can then be used in a ControlFileGenerator
* instance.
*
* @param byteAmount
* @return
*/
public static long getInstalledSize(long byteAmount) {
return byteAmount / 1024L;
}
/**
* A <code>TargetConfiguration</code> can depend on another and so multiple
* build processes might need to be run for a single <code>TargetConfiguration</code>.
*
* <p>The list of <code>TargetConfiguration</code> instance that need to be built is
* called a build chain. A build chain with <code>n</code> entries contains <code>n-1</code>
* instances that need to be built before. The last element in the build chain is the
* one that was initially requested and must be build last.</p>
*
* @param target
* @param distro
* @return
* @throws MojoExecutionException
*/
public static List<TargetConfiguration> createBuildChain(
String target,
String distro,
List<TargetConfiguration> targetConfigurations)
throws MojoExecutionException
{
LinkedList<TargetConfiguration> tcs = new LinkedList<TargetConfiguration>();
// Merges vertically, that means through the 'parent' property.
TargetConfiguration tc = Utils.getTargetConfigurationFromString(target, targetConfigurations);
//Utils.getMergedConfigurationImpl(target, distro, targetConfigurations, true);
// In getMergedConfiguraion we check if targets that are hierarchically related
// support the same distro. Here we will have to check again, as there may not
// be parent-child relationship between them.
if(tc.getDistros().contains(distro)){
tcs.addFirst(tc);
List<String> relations = tc.getRelations();
for (String relation : relations) {
tcs.addAll(0, createBuildChain(relation, distro, targetConfigurations));
}
return tcs;
}else{
throw new MojoExecutionException("target configuration '" + tc.getTarget() +
"' does not support distro: " + distro);
}
}
/**
* Returns a Packager Object for a certain packaging type (deb, rpm, etc.)
*
* <p>Conveniently throws a {@link MojoExecutionException} if there is no
* {@link Packager} instance for the given package type.</p>
*
* @param packaging
* @return
*/
public static Packager getPackagerForPackaging(String packaging)
throws MojoExecutionException {
Map<String, Class<? extends Packager>> extPackagerMap = new HashMap<String, Class<? extends Packager>>();
extPackagerMap.put("deb", DebPackager.class);
extPackagerMap.put("ipk", IpkPackager.class);
extPackagerMap.put("izpack", IzPackPackager.class);
extPackagerMap.put("rpm", RPMPackager.class);
Class<? extends Packager> klass = extPackagerMap.get(packaging);
try {
return klass.newInstance();
} catch (InstantiationException e) {
throw new MojoExecutionException("Unsupported packaging type: "+ packaging, e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unsupported packaging type: "+ packaging, e);
}
}
/**
* Conveniently converts a list of target configurations into a map where
* each instance can be accessed by its name (ie. the target property).
*
* <p>Super conveniently this method throws an exception if during the
* conversion it is found out that there is more than one entry with the
* same target.</p>
*
* @param tcs
*/
public static Map<String, TargetConfiguration> toMap(List<TargetConfiguration> tcs)
throws MojoExecutionException {
HashMap<String, TargetConfiguration> m = new HashMap<String, TargetConfiguration>();
for (TargetConfiguration tc : tcs) {
if (m.put(tc.getTarget(), tc) != null) {
throw new MojoExecutionException("Target with name '" + tc.getTarget() + " exists more than once. Fix the plugin configuration!");
}
}
return m;
}
/**
* Given a list of target names resolves them into their actual {@link TargetConfiguration}
* instances. The resolution is done using the given map.
*
* <p>Additionally this method throws an exception if an entry could not be found in the map
* as this means something is configured wrongly.</p>
*
* @param targetNames
* @param map
* @return
* @throws MojoExecutionException
*/
public static List<TargetConfiguration> resolveConfigurations(List<String> targetNames, Map<String, TargetConfiguration> map)
throws MojoExecutionException {
ArrayList<TargetConfiguration> tcs = new ArrayList<TargetConfiguration>(targetNames.size());
for (String s : targetNames) {
TargetConfiguration tc = map.get(s);
if (tc == null) {
throw new MojoExecutionException("Target configuration '" + tc + "' is requested as a related target configuration but does not exist. Fix the plugin configuration!");
}
tcs.add(tc);
}
return tcs;
}
/**
* Sets all unset properties, either to the values of the parent or to a
* (hard-coded) default value if the property is not set in the parent.
*
* <p>
* Using this method the packaging plugin can generate a merge of the
* default and a distro-specific configuration.
* </p>
*
* @param child
* @param parent
* @return
* @throws MojoExecutionException
*/
public static TargetConfiguration mergeConfigurations(TargetConfiguration child,
TargetConfiguration parent) throws MojoExecutionException{
if (child.isReady()){
throw new MojoExecutionException(String.format("target configuration '%s' is already merged.", child.getTarget()));
}
Field[] allFields = TargetConfiguration.class.getDeclaredFields();
for (Field field : allFields){
field.setAccessible(true);
if(field.getAnnotation(MergeMe.class) != null){
try {
Object defaultValue = new Object();
IMerge merger;
if(field.getAnnotation(MergeMe.class).defaultValueIsNull()){
defaultValue=null;
}
if(field.getType()==Properties.class){
if(defaultValue!=null){
defaultValue = new Properties();
}
merger = new PropertiesMerger();
}else if(field.getType()==List.class){
if(defaultValue!=null){
defaultValue = new ArrayList<Object>();
}
merger = new CollectionMerger();
}else if(field.getType()==Set.class){
if(defaultValue!=null){
defaultValue = new HashSet<Object>();
}
merger = new CollectionMerger();
}else if(field.getType()==String.class){
if(defaultValue!=null){
defaultValue =field.getAnnotation(MergeMe.class).defaultString();
}
merger = new ObjectMerger();
}else if(field.getType()==Boolean.class){
defaultValue = field.getAnnotation(MergeMe.class).defaultBoolean();
merger = new ObjectMerger();
}else{
merger = new ObjectMerger();
}
Object childValue = field.get(child);
Object parentValue = field.get(parent);
try {
field.set(child, merger.merge(childValue,
parentValue,
defaultValue));
} catch (InstantiationException e) {
throw new MojoExecutionException("Error merging configurations",e);
}
}catch (SecurityException e){
throw new MojoExecutionException(e.getMessage(),e);
}catch (IllegalArgumentException e){
throw new MojoExecutionException(e.getMessage(),e);
}catch (IllegalAccessException e){
throw new MojoExecutionException(e.getMessage(),e);
}
}
}
child.setReady(true);
return child;
}
/**
* Recursively merges all configurations with their parents and returns a
* list of the available targetConfigurations ready to be consumed by the
* plugin.
*
* @param targetConfigurations
* @return
* @throws MojoExecutionException
*/
public static void mergeAllConfigurations(List<TargetConfiguration> targetConfigurations)
throws MojoExecutionException {
// We will loop through all targets
for (TargetConfiguration tc : targetConfigurations) {
// If tc is ready it means that this list has already been merged
if (tc.isReady()) {
throw new MojoExecutionException("This targetConfiguration list has already been merged.");
} else {
// Check if we are at the top of the hierarchy
if (tc.parent == null) {
// If we are at the top we will just fixate the configuration
tc.fixate();
} else {
// If there is a parent we will merge recursivelly tc's hierarchy
mergeAncestorsRecursively(tc,targetConfigurations);
}
}
}
}
/**
* Recursively merge the ancestors for a certain configuration.
*
* @param tc
* @param parent
* @param targetConfigurations
* @return
* @throws MojoExecutionException
*/
private static void mergeAncestorsRecursively(TargetConfiguration tc, List<TargetConfiguration> targetConfigurations) throws MojoExecutionException {
TargetConfiguration parent = getTargetConfigurationFromString(tc.parent, targetConfigurations);
// If the top of the hierarchy has not been reached yet,
// all remaining ancestors will be merged.
// The ready flag of the parent will also be checked
// in order to avoid redundant work.
if (parent.parent != null && !parent.isReady()) {
mergeAncestorsRecursively(parent, targetConfigurations);
}
// Once done checking all ancestors
// the child will be merged with the parent
mergeConfigurations(tc, parent);
}
/**
* Extracts a file from an archive and stores it in a temporary location.
* The file will be deleted when the virtual machine exits.
*
* @param archive
* @param needle
* @return
* @throws MojoExecutionException
*/
@SuppressWarnings("unchecked")
public static File getFileFromArchive(ArchiveFile archive, String needle) throws MojoExecutionException{
final int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
Entry entry;
Enumeration<? extends Entry> e;
try {
e = archive.getEntries();
} catch (IOException ex) {
throw new MojoExecutionException("Error getting entries from archive",ex);
}
while (e.hasMoreElements()){
entry = e.nextElement();
// If the entry we are in matches the needle we will store its contents to a temp file
if (entry.getName().equals(needle)){
// The file will be saved in the temporary directory
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File extractedFile;
try {
extractedFile = File.createTempFile("mvn-pkg-plugin",
"temp",
tempDir);
} catch (IOException ex) {
throw new MojoExecutionException("Error creating temporary file found",ex);
}
try {
is = new BufferedInputStream
(archive.getInputStream(entry));
} catch (IOException ex) {
throw new MojoExecutionException("Error reading entry from archive",ex);
}
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos;
try {
fos = new FileOutputStream(extractedFile);
} catch (FileNotFoundException ex) {
throw new MojoExecutionException("Error reading entry from archive",ex);
}
dest = new
BufferedOutputStream(fos, BUFFER);
try {
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
} catch (IOException ex) {
throw new MojoExecutionException("Error writing to temporary file",ex);
}finally{
try {
dest.flush();
dest.close();
is.close();
} catch (IOException ex) {
throw new MojoExecutionException("Error closing streams.",ex);
}
}
extractedFile.deleteOnExit();
return extractedFile;
}
}
throw new MojoExecutionException("Desired file not found");
}
/**
* Tries to match a string representing a debian package name against the convention.
* <a href="http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Source">http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Source</a>
* @param string
* @return True if matches
*/
public static boolean checkDebianPackageNameConvention(String string){
Pattern pattern = Pattern.compile("[a-z0-9][a-z0-9+.-]*[a-z0-9+.]");
Matcher m = pattern.matcher(string);
if(m.matches()){
return true;
}else{
return false;
}
}
/**
* Tries to match a string representing a debian package version against the convention.<br/>
* <a href="http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version">http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version</a>
* @param string
* @return True if matches
*/
public static boolean checkDebianPackageVersionConvention(String string){
boolean compliant = true;
Pattern pattern = Pattern.compile("[0-9][A-Za-z0-9.+~:-]*");
Matcher m = pattern.matcher(string);
if(!m.matches()){
compliant = false;
}
// A version must never end with a hyphen
if(string.endsWith("-")){
compliant = false;
}
// A version should never contain a colon if it does not start with an epoch
Pattern epoch = Pattern.compile("^[0-9][0-9]*:.*");
m = epoch.matcher(string);
if(!m.matches() && string.contains(":")){
compliant= false;
}
return compliant;
}
}
| public static void makeExecutable(Log l, String f) throws MojoExecutionException {
l.info("make executable " + f);
exec(new String[] { "chmod", "+x", f }, "Changing the " + f + " file attributes failed.", "Unable to make " + f
+ " file executable.");
}
/**
* This wraps doing a "chmod +x" on a file.
*
* @param f
* @param item
* @throws MojoExecutionException
*/
public static void makeExecutable(File f, String item) throws MojoExecutionException {
exec(new String[] { "chmod", "+x", f.getAbsolutePath() }, "Changing the " + item + " file attributes failed.",
"Unable to make " + item + " file executable.");
}
/**
* Checks whether a certain program is available.
*
* <p>
* It fails with a {@link MojoExecutionException} if the program is not
* available.
*
* @param programName
* @throws MojoExecutionException
*/
public static void checkProgramAvailability(String programName) throws MojoExecutionException {
exec(new String[] { "which", programName }, null, programName
+ " is not available on your system. Check your installation!", "Error executing " + programName
+ ". Aborting!",null);
}
/**
* Checks whether a certain program is available.
*
* <p>
* It fails with a {@link MojoExecutionException} if the program is not
* available.
*
* @param programName
* @throws MojoExecutionException
*/
public static String getProgramVersionOutput(String programName) throws MojoExecutionException {
return inputStreamToString(exec(new String[] { programName, "--version" }, null,
" dpkg-deb is not available on your system. Check your installation!", "Error executing dpkg-deb"
+ ". Aborting!",null)).trim();
}
private static String inputStreamToString(InputStream in) throws MojoExecutionException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try{
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
}catch(IOException ex){
throw new MojoExecutionException("Error reading input stream");
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
throw new MojoExecutionException("Error closing reader");
}
}
return stringBuilder.toString();
}
/**
* A method which makes executing programs easier.
*
* @param args
* @param failureMsg
* @param ioExceptionMsg
* @throws MojoExecutionException
*/
public static void exec(String[] args, String failureMsg, String ioExceptionMsg) throws MojoExecutionException {
exec(args, null, failureMsg, ioExceptionMsg, null);
}
public static InputStream exec(String[] args, File workingDir, String failureMsg,
String ioExceptionMsg) throws MojoExecutionException {
return exec(args, workingDir, failureMsg, ioExceptionMsg, null);
}
public static InputStream exec(String[] args, String failureMsg,
String ioExceptionMsg, String userInput) throws MojoExecutionException {
return exec(args, null, failureMsg, ioExceptionMsg, userInput);
}
/**
* A method which makes executing programs easier.
*
* @param args
* @param failureMsg
* @param ioExceptionMsg
* @throws MojoExecutionException
*/
public static InputStream exec(String[] args, File workingDir, String failureMsg,
String ioExceptionMsg, String userInput)
throws MojoExecutionException {
/*
* debug code which prints out the execution command-line. Enable if
* neccessary. for(int i=0;i<args.length;i++) { System.err.print(args[i]
* + " "); } System.err.println();
*/
// Creates process with the defined language setting of LC_ALL=C
// That way the textual output of certain commands is predictable.
ProcessBuilder pb = new ProcessBuilder(args);
pb.directory(workingDir);
Map<String, String> env = pb.environment();
env.put("LC_ALL", "C");
Process p = null;
try {
p = pb.start();
if(userInput!=null){
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
writer.println(userInput);
writer.flush();
writer.close();
}
int exitValue = p.waitFor();
if (exitValue != 0) {
print(p);
throw new MojoExecutionException(String.format("(Subprocess exit value = %s) %s", exitValue, failureMsg));
}
} catch (IOException ioe) {
throw new MojoExecutionException(ioExceptionMsg + " :" + ioe.getMessage(), ioe);
} catch (InterruptedException ie) {
// Cannot happen.
throw new MojoExecutionException("InterruptedException", ie);
}
return p.getInputStream();
}
/**
* Stores the contents of an input stream in a file. This is used to copy a
* resource from the classpath.
*
* @param is
* @param file
* @param ioExceptionMsg
* @throws MojoExecutionException
*/
public static void storeInputStream(InputStream is, File file, String ioExceptionMsg) throws MojoExecutionException {
if (is == null){
throw new MojoExecutionException("InputStream must not be null.");
}
try {
FileOutputStream fos = new FileOutputStream(file);
IOUtils.copy(is, fos);
is.close();
fos.close();
} catch (IOException ioe) {
throw new MojoExecutionException(ioExceptionMsg, ioe);
}
}
/**
* This method can be used to debug the output of processes.
*
* @param p
*/
public static void print(Process p) {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
while (br.ready()) {
System.err.println("*** Process output ***");
System.err.println(br.readLine());
System.err.println("**********************");
}
} catch (IOException ioe) {
// foo
}
}
public static long copyProjectArtifact(Log l, File src, File dst) throws MojoExecutionException {
if (l!=null){
l.info("copying artifact: " + src.getAbsolutePath());
l.info("destination: " + dst.getAbsolutePath());
}
Utils.createFile(dst, "destination artifact");
try {
FileUtils.copyFile(src, dst);
return src.length();
} catch (IOException ioe) {
throw new MojoExecutionException("IOException while copying artifact file.", ioe);
}
}
/**
* Convert the artifactId into a Debian package name which contains gcj
* precompiled binaries.
*
* @param artifactId
* @return
*/
public static String gcjise(String artifactId, String section, boolean debianise) {
return debianise && section.equals("libs") ? "lib" + artifactId + "-gcj" : artifactId + "-gcj";
}
/**
* Concatenates two dependency lines. If both parts (prefix and suffix) are
* non-empty the lines will be joined with a comma in between.
* <p>
* If one of the parts is empty the other will be returned.
* </p>
*
* @param prefix
* @param suffix
* @return
*/
public static String joinDependencyLines(String prefix, String suffix) {
return (prefix.length() == 0) ? suffix : (suffix.length() == 0) ? prefix : prefix + ", " + suffix;
}
public static long copyFiles(Log l, File srcDir, File dstDir, List<? extends AuxFile> auxFiles, String type)
throws MojoExecutionException {
return copyFiles(l, srcDir, dstDir, auxFiles, type, false);
}
/**
* Copies the <code>AuxFile</code> instances contained within the set. It
* takes the <code>srcAuxFilesDir</code> and <code>auxFileDstDir</code>
* arguments into account to specify the parent source and destination
* directory of the files.
*
* By default files are copied into directories. If the <code>rename</code>
* property of the <code>AuxFile</code> instance is set however the file is
* copied and renamed to the last part of the path.
*
* The return value is the amount of copied bytes.
*
* @param l
* @param srcAuxFilesDir
* @param dstDir
* @param auxFiles
* @param makeExecutable
* @return
* @throws MojoExecutionException
*/
public static long copyFiles(Log l, File srcDir, File dstDir, List<? extends AuxFile> auxFiles, String type,
boolean makeExecutable) throws MojoExecutionException {
long size = 0;
Iterator<? extends AuxFile> ite = auxFiles.iterator();
while (ite.hasNext()) {
AuxFile af = (AuxFile) ite.next();
File from = new File(srcDir, af.from);
File to = new File(dstDir, af.to);
l.info("copying " + type + ": " + from.toString());
l.info("destination: " + to.toString());
if (!from.exists()){
throw new MojoExecutionException("File to copy does not exist: " + from.toString());
}
createParentDirs(to, type);
try {
if (from.isDirectory()) {
to = new File(to, from.getName());
FileUtils.copyDirectory(from, to, FILTER);
for (final Iterator<File> files = FileUtils.iterateFiles(from, FILTER, FILTER); files.hasNext(); ) {
final File nextFile = files.next();
size += nextFile.length();
}
} else if (af.isRename()) {
FileUtils.copyFile(from, to);
size += from.length();
if (makeExecutable){
makeExecutable(l, to.getAbsolutePath());
}
} else {
FileUtils.copyFileToDirectory(from, to);
size += from.length();
if (makeExecutable){
makeExecutable(l, to.getAbsolutePath() + File.separator + from.getName());
}
}
} catch (IOException ioe) {
throw new MojoExecutionException("IOException while copying " + type, ioe);
}
}
return size;
}
/**
* Converts the artifactId into a package name. Currently this only
* applies to libraries which get a "lib" prefix and a "-java" suffix.
*
* <p>An optional packageNameSuffix can be specified which is appended
* to the artifact id.</p>
*
* <p>When <code>debianise</code> is set the name will be lowercased.</p>
*
* @param artifactId
* @return
*/
public static String createPackageName(String artifactId, String packageNameSuffix, String section, boolean debianise) {
String baseName = (packageNameSuffix != null) ? (artifactId + "-" + packageNameSuffix) : artifactId;
if (debianise) {
// Debian naming does not allow any uppercase characters.
baseName = baseName.toLowerCase();
// Debian java libraries are called lib${FOO}-java
if (section.equals("libs")) {
baseName = "lib" + baseName + "-java";
}
}
return baseName;
}
/**
* Batch creates the package names for the given {@link TargetConfiguration} instances using the method {@link #createPackageName}.
*
* @param artifactId
* @param tcs
* @param debianise
* @return
*/
public static List<String> createPackageNames(String artifactId, List<TargetConfiguration> tcs, boolean debianise) {
ArrayList<String> pns = new ArrayList<String>(tcs.size());
for (TargetConfiguration tc : tcs) {
pns.add(createPackageName(artifactId, tc.getPackageNameSuffix(), tc.getSection(), debianise));
}
return pns;
}
/**
* Copies the starter classfile to the starter path, prepares the classpath
* properties file and stores it at that location, too.
*
* @param dstStarterRoot
* @param dependencies
* @param libraryPrefix
* @throws MojoExecutionException
*/
public static void setupStarter(Log l, String mainClass, File dstStarterRoot, Path classpath)
throws MojoExecutionException {
File destStarterClassFile = new File(dstStarterRoot, STARTER_CLASS);
Utils.createFile(destStarterClassFile, "starter class");
Utils.storeInputStream(Utils.class.getResourceAsStream("/" + STARTER_CLASS), destStarterClassFile,
"Unable to store starter class file in destination.");
File destClasspathFile = new File(dstStarterRoot, "_classpath");
Utils.createFile(destClasspathFile, "starter classpath");
PrintWriter writer = null;
try {
writer = new PrintWriter(destClasspathFile);
writer.println("# This file controls the application's classpath and is autogenerated.");
writer.println("# Slashes (/) in the filenames are replaced with the platform-specific");
writer.println("# separator char at runtime.");
writer.println("# The next line is the fully-classified name of the main class:");
writer.println(mainClass);
writer.println("# The following lines are the classpath entries:");
for (String e : classpath) {
writer.println(e);
}
l.info("created library entries");
} catch (IOException e) {
throw new MojoExecutionException("storing the classpath entries failed", e);
} finally {
if (writer != null){
writer.close();
}
}
}
/**
* Copies the Artifacts contained in the set to the folder denoted by
* <code>dst</code> and returns the amount of bytes copied.
*
* <p>
* If an artifact is a zip archive it is unzipped in this folder.
* </p>
*
* @param l
* @param artifacts
* @param dst
* @return
* @throws MojoExecutionException
*/
public static long copyArtifacts(Log l, Set<Artifact> artifacts, File dst) throws MojoExecutionException {
long byteAmount = 0;
if (artifacts.size() == 0) {
l.info("no artifact to copy.");
return byteAmount;
}
l.info("copying " + artifacts.size() + " dependency artifacts.");
l.info("destination: " + dst.toString());
try {
Iterator<Artifact> ite = artifacts.iterator();
while (ite.hasNext()) {
Artifact a = (Artifact) ite.next();
l.info("copying artifact: " + a);
File f = a.getFile();
if (f != null) {
l.debug("from file: " + f);
if (a.getType().equals("zip")) {
// Assume that this is a ZIP file with native libraries
// inside.
// TODO: Determine size of all entries and add this
// to the byteAmount.
unpack(a.getFile(), dst);
} else {
FileUtils.copyFileToDirectory(f, dst);
byteAmount += (long) f.length();
}
} else {
throw new MojoExecutionException("Unable to copy Artifact " + a
+ " because it is not locally available.");
}
}
} catch (IOException ioe) {
throw new MojoExecutionException("IOException while copying dependency artifacts.", ioe);
}
return byteAmount;
}
/**
* Unpacks the given file.
*
* @param file
* File to be unpacked.
* @param dst
* Location where to put the unpacked files.
*/
protected static void unpack(File file, File dst) throws MojoExecutionException {
try {
dst.mkdirs();
UnArchiver unArchiver = archiverManager.getUnArchiver(file);
unArchiver.setSourceFile(file);
unArchiver.setDestDirectory(dst);
unArchiver.extract();
} catch (NoSuchArchiverException e) {
throw new MojoExecutionException("Unknown archiver type", e);
} catch (ArchiverException e) {
throw new MojoExecutionException("Error unpacking file: " + file + " to: " + dst + "\r\n" + e.toString(), e);
}
}
/**
* Makes a valid and useful package version string from one that cannot be
* used or is unsuitable.
*
* <p>
* At the moment the method removes underscores only.
* </p>
*
* @param string
* The string which might contain underscores
* @return The given string without underscores
*/
public static String sanitizePackageVersion(String string) {
return string.replaceAll("_", "");
}
/**
* Gathers the project's artifacts and the artifacts of all its (transitive)
* dependencies filtered by the given filter instance.
*
* @param filter
* @return
* @throws ArtifactResolutionException
* @throws ArtifactNotFoundException
* @throws ProjectBuildingException
* @throws InvalidDependencyVersionException
*/
@SuppressWarnings("unchecked")
public static Set<Artifact> findArtifacts(ArtifactFilter filter,
ArtifactFactory factory,
ArtifactResolver resolver,
MavenProject project,
Artifact artifact,
ArtifactRepository local,
List<ArtifactRepository> remoteRepos,
ArtifactMetadataSource metadataSource)
throws ArtifactResolutionException,ArtifactNotFoundException,
ProjectBuildingException,InvalidDependencyVersionException {
ArtifactResolutionResult result = resolver.resolveTransitively(project.getDependencyArtifacts(),
artifact,
local,
remoteRepos,
metadataSource,
filter);
return (Set<Artifact>) result.getArtifacts();
}
/**
* Returns a TargetConfiguration object that matches the desired target String.
* @param target
* @param targetConfigurations
* @return
* @throws MojoExecutionException
*/
public static TargetConfiguration getTargetConfigurationFromString(String target,
List<TargetConfiguration> targetConfigurations) throws MojoExecutionException{
for (TargetConfiguration currentTargetConfiguration : targetConfigurations) {
if (currentTargetConfiguration.getTarget().equals(target)) {
return currentTargetConfiguration;
}
}
throw new MojoExecutionException("Target " + target + " not found. Check your spelling or configuration (is this target being defined in relation to another, but does not exist anymore?).");
}
/**
* Returns the default Distro to use for a certain TargetConfiguration.
* @param configuration
* @return
* @throws MojoExecutionException
*/
public static String getDefaultDistro(String targetString, List<TargetConfiguration> targetConfigurations, Log l) throws MojoExecutionException {
String distro = null;
TargetConfiguration target = Utils.getTargetConfigurationFromString(targetString, targetConfigurations);
if (target.getDefaultDistro() != null) {
distro = target.getDefaultDistro();
l.info("Default distribution is set to \"" + distro + "\".");
} else
switch (target.getDistros().size()) {
case 0:
throw new MojoExecutionException(
"No distros defined for configuration " + targetString);
case 1:
distro = (String) target.getDistros().iterator().next();
l.info(String.format("Only one distro defined, using '%s' as default", distro));
break;
default:
String m = "No default configuration given for distro '"
+ targetString
+ "', and more than one distro is supported. Please provide one.";
l.error(m);
throw new MojoExecutionException(m);
}
return distro;
}
/**
* Returns a string with the license(s) of a MavenProject.
*
* @param project
* @return
* @throws MojoExecutionException
*/
@SuppressWarnings("unchecked")
public static String getConsolidatedLicenseString(MavenProject project) throws MojoExecutionException {
StringBuilder license = new StringBuilder();
Iterator<License> ite = null;
try {
ite = (Iterator<License>) project.getLicenses().iterator();
license.append(((License) ite.next()).getName());
} catch (Exception ex) {
throw new MojoExecutionException("Please provide at least one license in your POM.",ex);
}
while (ite.hasNext()) {
license.append(", ");
license.append(((License) ite.next()).getName());
}
return license.toString();
}
/**
* Simple function to grab information from an URL
* @param url
* @return
* @throws IOException
*/
public static String getTextFromUrl(String url) throws IOException{
InputStream stream = null;
try {
stream = new URL(url).openStream();
return IOUtils.toString(stream);
} finally {
IOUtils.closeQuietly(stream);
}
}
/**
* Converts a byte amount to the unit used by the Debian control file
* (usually KiB). That value can then be used in a ControlFileGenerator
* instance.
*
* @param byteAmount
* @return
*/
public static long getInstalledSize(long byteAmount) {
return byteAmount / 1024L;
}
/**
* A <code>TargetConfiguration</code> can depend on another and so multiple
* build processes might need to be run for a single <code>TargetConfiguration</code>.
*
* <p>The list of <code>TargetConfiguration</code> instance that need to be built is
* called a build chain. A build chain with <code>n</code> entries contains <code>n-1</code>
* instances that need to be built before. The last element in the build chain is the
* one that was initially requested and must be build last.</p>
*
* @param target
* @param distro
* @return
* @throws MojoExecutionException
*/
public static List<TargetConfiguration> createBuildChain(
String target,
String distro,
List<TargetConfiguration> targetConfigurations)
throws MojoExecutionException
{
LinkedList<TargetConfiguration> tcs = new LinkedList<TargetConfiguration>();
// Merges vertically, that means through the 'parent' property.
TargetConfiguration tc = Utils.getTargetConfigurationFromString(target, targetConfigurations);
//Utils.getMergedConfigurationImpl(target, distro, targetConfigurations, true);
// In getMergedConfiguraion we check if targets that are hierarchically related
// support the same distro. Here we will have to check again, as there may not
// be parent-child relationship between them.
if(tc.getDistros().contains(distro)){
tcs.addFirst(tc);
List<String> relations = tc.getRelations();
for (String relation : relations) {
tcs.addAll(0, createBuildChain(relation, distro, targetConfigurations));
}
return tcs;
}else{
throw new MojoExecutionException("target configuration '" + tc.getTarget() +
"' does not support distro: " + distro);
}
}
/**
* Returns a Packager Object for a certain packaging type (deb, rpm, etc.)
*
* <p>Conveniently throws a {@link MojoExecutionException} if there is no
* {@link Packager} instance for the given package type.</p>
*
* @param packaging
* @return
*/
public static Packager getPackagerForPackaging(String packaging)
throws MojoExecutionException {
Map<String, Class<? extends Packager>> extPackagerMap = new HashMap<String, Class<? extends Packager>>();
extPackagerMap.put("deb", DebPackager.class);
extPackagerMap.put("ipk", IpkPackager.class);
extPackagerMap.put("izpack", IzPackPackager.class);
extPackagerMap.put("rpm", RPMPackager.class);
Class<? extends Packager> klass = extPackagerMap.get(packaging);
try {
return klass.newInstance();
} catch (InstantiationException e) {
throw new MojoExecutionException("Unsupported packaging type: "+ packaging, e);
} catch (IllegalAccessException e) {
throw new MojoExecutionException("Unsupported packaging type: "+ packaging, e);
}
}
/**
* Conveniently converts a list of target configurations into a map where
* each instance can be accessed by its name (ie. the target property).
*
* <p>Super conveniently this method throws an exception if during the
* conversion it is found out that there is more than one entry with the
* same target.</p>
*
* @param tcs
*/
public static Map<String, TargetConfiguration> toMap(List<TargetConfiguration> tcs)
throws MojoExecutionException {
HashMap<String, TargetConfiguration> m = new HashMap<String, TargetConfiguration>();
for (TargetConfiguration tc : tcs) {
if (m.put(tc.getTarget(), tc) != null) {
throw new MojoExecutionException("Target with name '" + tc.getTarget() + " exists more than once. Fix the plugin configuration!");
}
}
return m;
}
/**
* Given a list of target names resolves them into their actual {@link TargetConfiguration}
* instances. The resolution is done using the given map.
*
* <p>Additionally this method throws an exception if an entry could not be found in the map
* as this means something is configured wrongly.</p>
*
* @param targetNames
* @param map
* @return
* @throws MojoExecutionException
*/
public static List<TargetConfiguration> resolveConfigurations(List<String> targetNames, Map<String, TargetConfiguration> map)
throws MojoExecutionException {
ArrayList<TargetConfiguration> tcs = new ArrayList<TargetConfiguration>(targetNames.size());
for (String s : targetNames) {
TargetConfiguration tc = map.get(s);
if (tc == null) {
throw new MojoExecutionException("Target configuration '" + tc + "' is requested as a related target configuration but does not exist. Fix the plugin configuration!");
}
tcs.add(tc);
}
return tcs;
}
/**
* Sets all unset properties, either to the values of the parent or to a
* (hard-coded) default value if the property is not set in the parent.
*
* <p>
* Using this method the packaging plugin can generate a merge of the
* default and a distro-specific configuration.
* </p>
*
* @param child
* @param parent
* @return
* @throws MojoExecutionException
*/
public static TargetConfiguration mergeConfigurations(TargetConfiguration child,
TargetConfiguration parent) throws MojoExecutionException{
if (child.isReady()){
throw new MojoExecutionException(String.format("target configuration '%s' is already merged.", child.getTarget()));
}
Field[] allFields = TargetConfiguration.class.getDeclaredFields();
for (Field field : allFields){
field.setAccessible(true);
if(field.getAnnotation(MergeMe.class) != null){
try {
Object defaultValue = new Object();
IMerge merger;
if(field.getAnnotation(MergeMe.class).defaultValueIsNull()){
defaultValue=null;
}
if(field.getType()==Properties.class){
if(defaultValue!=null){
defaultValue = new Properties();
}
merger = new PropertiesMerger();
}else if(field.getType()==List.class){
if(defaultValue!=null){
defaultValue = new ArrayList<Object>();
}
merger = new CollectionMerger();
}else if(field.getType()==Set.class){
if(defaultValue!=null){
defaultValue = new HashSet<Object>();
}
merger = new CollectionMerger();
}else if(field.getType()==String.class){
if(defaultValue!=null){
defaultValue =field.getAnnotation(MergeMe.class).defaultString();
}
merger = new ObjectMerger();
}else if(field.getType()==Boolean.class){
defaultValue = field.getAnnotation(MergeMe.class).defaultBoolean();
merger = new ObjectMerger();
}else{
merger = new ObjectMerger();
}
Object childValue = field.get(child);
Object parentValue = field.get(parent);
try {
field.set(child, merger.merge(childValue,
parentValue,
defaultValue));
} catch (InstantiationException e) {
throw new MojoExecutionException("Error merging configurations",e);
}
}catch (SecurityException e){
throw new MojoExecutionException(e.getMessage(),e);
}catch (IllegalArgumentException e){
throw new MojoExecutionException(e.getMessage(),e);
}catch (IllegalAccessException e){
throw new MojoExecutionException(e.getMessage(),e);
}
}
}
child.setReady(true);
return child;
}
/**
* Recursively merges all configurations with their parents and returns a
* list of the available targetConfigurations ready to be consumed by the
* plugin.
*
* @param targetConfigurations
* @return
* @throws MojoExecutionException
*/
public static void mergeAllConfigurations(List<TargetConfiguration> targetConfigurations)
throws MojoExecutionException {
// We will loop through all targets
for (TargetConfiguration tc : targetConfigurations) {
// If tc is ready it means that this list has already been merged
if (tc.isReady()) {
throw new MojoExecutionException("This targetConfiguration list has already been merged.");
} else {
// Check if we are at the top of the hierarchy
if (tc.parent == null) {
// If we are at the top we will just fixate the configuration
tc.fixate();
} else {
// If there is a parent we will merge recursivelly tc's hierarchy
mergeAncestorsRecursively(tc,targetConfigurations);
}
}
}
}
/**
* Recursively merge the ancestors for a certain configuration.
*
* @param tc
* @param parent
* @param targetConfigurations
* @return
* @throws MojoExecutionException
*/
private static void mergeAncestorsRecursively(TargetConfiguration tc, List<TargetConfiguration> targetConfigurations) throws MojoExecutionException {
TargetConfiguration parent = getTargetConfigurationFromString(tc.parent, targetConfigurations);
// If the top of the hierarchy has not been reached yet,
// all remaining ancestors will be merged.
// The ready flag of the parent will also be checked
// in order to avoid redundant work.
if (parent.parent != null && !parent.isReady()) {
mergeAncestorsRecursively(parent, targetConfigurations);
}
// Once done checking all ancestors
// the child will be merged with the parent
mergeConfigurations(tc, parent);
}
/**
* Extracts a file from an archive and stores it in a temporary location.
* The file will be deleted when the virtual machine exits.
*
* @param archive
* @param needle
* @return
* @throws MojoExecutionException
*/
@SuppressWarnings("unchecked")
public static File getFileFromArchive(ArchiveFile archive, String needle) throws MojoExecutionException{
final int BUFFER = 2048;
BufferedOutputStream dest = null;
BufferedInputStream is = null;
Entry entry;
Enumeration<? extends Entry> e;
try {
e = archive.getEntries();
} catch (IOException ex) {
throw new MojoExecutionException("Error getting entries from archive",ex);
}
while (e.hasMoreElements()){
entry = e.nextElement();
// If the entry we are in matches the needle we will store its contents to a temp file
if (entry.getName().equals(needle)){
// The file will be saved in the temporary directory
File tempDir = new File(System.getProperty("java.io.tmpdir"));
File extractedFile;
try {
extractedFile = File.createTempFile("mvn-pkg-plugin",
"temp",
tempDir);
} catch (IOException ex) {
throw new MojoExecutionException("Error creating temporary file found",ex);
}
try {
is = new BufferedInputStream
(archive.getInputStream(entry));
} catch (IOException ex) {
throw new MojoExecutionException("Error reading entry from archive",ex);
}
int count;
byte data[] = new byte[BUFFER];
FileOutputStream fos;
try {
fos = new FileOutputStream(extractedFile);
} catch (FileNotFoundException ex) {
throw new MojoExecutionException("Error reading entry from archive",ex);
}
dest = new
BufferedOutputStream(fos, BUFFER);
try {
while ((count = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
} catch (IOException ex) {
throw new MojoExecutionException("Error writing to temporary file",ex);
}finally{
try {
dest.flush();
dest.close();
is.close();
} catch (IOException ex) {
throw new MojoExecutionException("Error closing streams.",ex);
}
}
extractedFile.deleteOnExit();
return extractedFile;
}
}
throw new MojoExecutionException("Desired file not found");
}
/**
* Tries to match a string representing a debian package name against the convention.
* <a href="http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Source">http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Source</a>
* @param string
* @return True if matches
*/
public static boolean checkDebianPackageNameConvention(String string){
Pattern pattern = Pattern.compile("[a-z0-9][a-z0-9+.-]*[a-z0-9+.]");
Matcher m = pattern.matcher(string);
if(m.matches()){
return true;
}else{
return false;
}
}
/**
* Tries to match a string representing a debian package version against the convention.<br/>
* <a href="http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version">http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Version</a>
* @param string
* @return True if matches
*/
public static boolean checkDebianPackageVersionConvention(String string){
boolean compliant = true;
Pattern pattern = Pattern.compile("[0-9][A-Za-z0-9.+~:-]*");
Matcher m = pattern.matcher(string);
if(!m.matches()){
compliant = false;
}
// A version must never end with a hyphen
if(string.endsWith("-")){
compliant = false;
}
// A version should never contain a colon if it does not start with an epoch
Pattern epoch = Pattern.compile("^[0-9][0-9]*:.*");
m = epoch.matcher(string);
if(!m.matches() && string.contains(":")){
compliant= false;
}
return compliant;
}
}
|
diff --git a/src/vooga/rts/leveleditor/components/MapLoader.java b/src/vooga/rts/leveleditor/components/MapLoader.java
index 14d043d3..fe6ad521 100644
--- a/src/vooga/rts/leveleditor/components/MapLoader.java
+++ b/src/vooga/rts/leveleditor/components/MapLoader.java
@@ -1,159 +1,159 @@
package vooga.rts.leveleditor.components;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import vooga.rts.leveleditor.Exceptions.MapNotMatchException;
/**
* this class is responsible for generating a XML format map file
*
* @author Richard Yang
*
*/
public class MapLoader {
private Scanner myScanner;
private EditableMap myMap;
private Map<Integer, String> myTileInformation;
private Map<Integer, String> myTerrainInformation;
private XMLParser myXMLParser;
public MapLoader() {
myMap = new EditableMap();
myTileInformation = new HashMap<Integer, String>();
myTerrainInformation = new HashMap<Integer, String>();
myXMLParser = new XMLParser();
}
public void loadMapFile(File resourceFile) throws FileNotFoundException {
myScanner = new Scanner(resourceFile);
loadTitle();
try {
loadPlayers();
loadSize();
+ loadTileIndex();
}
catch (MapNotMatchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
- loadTileIndex();
loadTerrainIndex();
loadTiles();
loadTerrains();
loadResources();
myScanner.close();
}
public void loadMapFile(String filePath) throws FileNotFoundException {
File bufferFile = new File(filePath);
loadMapFile(bufferFile);
}
private void loadTitle() {
String line = myScanner.nextLine();
line = myScanner.nextLine();
line = myScanner.nextLine();
myMap.setMyMapName(myXMLParser.getTitle(line));
line = myScanner.nextLine();
myMap.setMyDescription(myXMLParser.getTitle(line));
}
private void loadPlayers() throws MapNotMatchException {
String line = myScanner.nextLine();
line = myScanner.nextLine();
while(line.contains("player") && line.contains("ID")) {
String[] content = myXMLParser.splitByBlanks(myXMLParser.splitContent(line));
if(content.length != 4) throw new MapNotMatchException();
String x = myXMLParser.cutKeyAndValue(content[2])[1];
String y = myXMLParser.cutKeyAndValue(content[3])[1];
myMap.addPlayer(Integer.parseInt(x),Integer.parseInt(y));
line = myScanner.nextLine();
}
}
private void loadSize() throws MapNotMatchException {
String line = myScanner.nextLine();
while( !line.contains("tilesize")) {
line = myScanner.nextLine();
}
String[] sizeContent = myXMLParser.splitByBlanks(myXMLParser.splitContent(line));
if(sizeContent.length != 3) throw new MapNotMatchException();
String tileWidth = myXMLParser.cutKeyAndValue(sizeContent[1])[1];
String tileHeight = myXMLParser.cutKeyAndValue(sizeContent[1])[1];
line = myScanner.nextLine();
String[] amountContent = myXMLParser.splitByBlanks(myXMLParser.splitContent(line));
if(sizeContent.length != 3) throw new MapNotMatchException();
String xCount = myXMLParser.cutKeyAndValue(amountContent[1])[1];
String yCount = myXMLParser.cutKeyAndValue(amountContent[2])[1];
myMap.setMyXSize(Integer.parseInt(xCount));
myMap.setMyYSize(Integer.parseInt(yCount));
myMap.initializeMap(Integer.parseInt(tileWidth), Integer.parseInt(tileHeight));
}
private void loadTileIndex() throws MapNotMatchException {
String line = myScanner.nextLine();
while (!(line.contains("tile") && line.contains("ID"))) {
line = myScanner.nextLine();
}
while(line.contains("tile") && line.contains("ID")) {
String[] tileContent = myXMLParser.splitByBlanks(myXMLParser.splitContent(line));
if(tileContent.length != 4) throw new MapNotMatchException();
String tileID = myXMLParser.cutKeyAndValue(tileContent[1])[1];
String tileImagePath = myXMLParser.cutKeyAndValue(tileContent[2])[1];
String tileName = myXMLParser.cutKeyAndValue(tileContent[3])[1];
myTileInformation.put(Integer.parseInt(tileID), tileName + "&" + tileImagePath);
line = myScanner.nextLine();
}
}
private void loadTerrainIndex() {
}
private void loadTiles() {
}
private void loadTerrains() {
}
private void loadResources() {
}
public static void main(String[] args) {
MapLoader myLoader = new MapLoader();
try {
myLoader.loadMapFile(System.getProperty("user.dir") + "./src/test.xml");
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| false | true | public void loadMapFile(File resourceFile) throws FileNotFoundException {
myScanner = new Scanner(resourceFile);
loadTitle();
try {
loadPlayers();
loadSize();
}
catch (MapNotMatchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadTileIndex();
loadTerrainIndex();
loadTiles();
loadTerrains();
loadResources();
myScanner.close();
}
| public void loadMapFile(File resourceFile) throws FileNotFoundException {
myScanner = new Scanner(resourceFile);
loadTitle();
try {
loadPlayers();
loadSize();
loadTileIndex();
}
catch (MapNotMatchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadTerrainIndex();
loadTiles();
loadTerrains();
loadResources();
myScanner.close();
}
|
diff --git a/src/main/java/org/tal/basiccircuits/BasicCircuits.java b/src/main/java/org/tal/basiccircuits/BasicCircuits.java
index 048180e..4aaecd6 100644
--- a/src/main/java/org/tal/basiccircuits/BasicCircuits.java
+++ b/src/main/java/org/tal/basiccircuits/BasicCircuits.java
@@ -1,43 +1,44 @@
package org.tal.basiccircuits;
import java.io.File;
import java.util.logging.Level;
import org.tal.redstonechips.RedstoneChips;
import org.tal.redstonechips.circuit.CircuitLibrary;
/**
*
* @author Tal Eisenberg
*/
public class BasicCircuits extends CircuitLibrary {
@Override
public Class[] getCircuitClasses() {
return new Class[] { adder.class, and.class, clock.class, counter.class, demultiplexer.class, divider.class, flipflop.class,
multiplexer.class, multiplier.class, or.class, pisoregister.class, print.class, random.class, receiver.class,
shiftregister.class, transmitter.class, xor.class, decoder.class, encoder.class, pixel.class, pulse.class, not.class,
synth.class, srnor.class, terminal.class, router.class, ringcounter.class, iptransmitter.class, ipreceiver.class,
comparator.class, delay.class, repeater.class, nand.class, nor.class, xnor.class, segdriver.class, dregister.class,
sram.class, bintobcd.class, display.class, burst.class };
}
@Override
public void onRedstoneChipsEnable(RedstoneChips rc) {
// add new pref keys.
rc.getPrefs().registerCircuitPreference(iptransmitter.class, "ports", "25600..25699");
// set sram data folder.
sram.dataFolder = new File(rc.getDataFolder(), "sram");
if (!sram.dataFolder.exists()) {
if (sram.dataFolder.mkdir()) rc.log(Level.INFO, "[BasicCircuits] Created new sram folder: " + sram.dataFolder.getAbsolutePath());
else rc.log(Level.SEVERE, "[BasicCircuits] Can't make folder " + sram.dataFolder.getAbsolutePath());
}
// move any sram files in rc data folder.
+ if (rc.getDataFolder()==null || !rc.getDataFolder().exists() || rc.getDataFolder().listFiles()==null) return;
for (File f : rc.getDataFolder().listFiles()) {
if (f.isFile() && f.getName().startsWith("sram-") &&
f.getName().endsWith(".data")) {
f.renameTo(new File(sram.dataFolder, f.getName()));
}
}
}
}
| true | true | public void onRedstoneChipsEnable(RedstoneChips rc) {
// add new pref keys.
rc.getPrefs().registerCircuitPreference(iptransmitter.class, "ports", "25600..25699");
// set sram data folder.
sram.dataFolder = new File(rc.getDataFolder(), "sram");
if (!sram.dataFolder.exists()) {
if (sram.dataFolder.mkdir()) rc.log(Level.INFO, "[BasicCircuits] Created new sram folder: " + sram.dataFolder.getAbsolutePath());
else rc.log(Level.SEVERE, "[BasicCircuits] Can't make folder " + sram.dataFolder.getAbsolutePath());
}
// move any sram files in rc data folder.
for (File f : rc.getDataFolder().listFiles()) {
if (f.isFile() && f.getName().startsWith("sram-") &&
f.getName().endsWith(".data")) {
f.renameTo(new File(sram.dataFolder, f.getName()));
}
}
}
| public void onRedstoneChipsEnable(RedstoneChips rc) {
// add new pref keys.
rc.getPrefs().registerCircuitPreference(iptransmitter.class, "ports", "25600..25699");
// set sram data folder.
sram.dataFolder = new File(rc.getDataFolder(), "sram");
if (!sram.dataFolder.exists()) {
if (sram.dataFolder.mkdir()) rc.log(Level.INFO, "[BasicCircuits] Created new sram folder: " + sram.dataFolder.getAbsolutePath());
else rc.log(Level.SEVERE, "[BasicCircuits] Can't make folder " + sram.dataFolder.getAbsolutePath());
}
// move any sram files in rc data folder.
if (rc.getDataFolder()==null || !rc.getDataFolder().exists() || rc.getDataFolder().listFiles()==null) return;
for (File f : rc.getDataFolder().listFiles()) {
if (f.isFile() && f.getName().startsWith("sram-") &&
f.getName().endsWith(".data")) {
f.renameTo(new File(sram.dataFolder, f.getName()));
}
}
}
|
diff --git a/src/com/ferg/awful/network/NetworkUtils.java b/src/com/ferg/awful/network/NetworkUtils.java
index 581e53c4..6d5e0523 100644
--- a/src/com/ferg/awful/network/NetworkUtils.java
+++ b/src/com/ferg/awful/network/NetworkUtils.java
@@ -1,326 +1,326 @@
/********************************************************************************
* Copyright (c) 2011, Scott Ferguson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the software nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY SCOTT FERGUSON ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SCOTT FERGUSON BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
package com.ferg.awful.network;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.CleanerTransformations;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.TagTransformation;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import com.ferg.awful.constants.Constants;
public class NetworkUtils {
private static final String TAG = "NetworkUtils";
private static DefaultHttpClient sHttpClient;
private static HtmlCleaner sCleaner;
/**
* Attempts to initialize the HttpClient with cookie values
* stored in the given Context's SharedPreferences through the
* {@link #saveLoginCookies(Context)} method.
*
* @return Whether stored cookie values were found & initialized
*/
public static boolean restoreLoginCookies(Context ctx) {
SharedPreferences prefs = ctx.getSharedPreferences(
Constants.COOKIE_PREFERENCE,
Context.MODE_PRIVATE);
String useridCookieValue = prefs.getString(Constants.COOKIE_PREF_USERID, null);
String passwordCookieValue = prefs.getString(Constants.COOKIE_PREF_PASSWORD, null);
long expiry = prefs.getLong (Constants.COOKIE_PREF_EXPIRY_DATE, -1);
if(useridCookieValue != null && passwordCookieValue != null && expiry != -1) {
Date expiryDate = new Date(expiry);
BasicClientCookie useridCookie = new BasicClientCookie(Constants.COOKIE_NAME_USERID, useridCookieValue);
useridCookie.setDomain(Constants.COOKIE_DOMAIN);
useridCookie.setExpiryDate(expiryDate);
useridCookie.setPath(Constants.COOKIE_PATH);
BasicClientCookie passwordCookie = new BasicClientCookie(Constants.COOKIE_NAME_PASSWORD, passwordCookieValue);
passwordCookie.setDomain(Constants.COOKIE_DOMAIN);
passwordCookie.setExpiryDate(expiryDate);
passwordCookie.setPath(Constants.COOKIE_PATH);
CookieStore jar = new BasicCookieStore();
jar.addCookie(useridCookie);
jar.addCookie(passwordCookie);
sHttpClient.setCookieStore(jar);
return true;
}
return false;
}
/**
* Clears cookies from both the current client's store and
* the persistent SharedPreferences. Effectively, logs out.
*/
public static void clearLoginCookies(Context ctx) {
// First clear out the persistent preferences...
SharedPreferences prefs = ctx.getSharedPreferences(
Constants.COOKIE_PREFERENCE,
Context.MODE_PRIVATE);
prefs.edit().clear().commit();
// Then the memory store
sHttpClient.getCookieStore().clear();
}
/**
* Saves SomethingAwful login cookies that the client has received
* during this session to the given Context's SharedPreferences. They
* can be later restored with {@link #restoreLoginCookies(Context)}.
*
* @return Whether any login cookies were successfully saved
*/
public static boolean saveLoginCookies(Context ctx) {
SharedPreferences prefs = ctx.getSharedPreferences(
Constants.COOKIE_PREFERENCE,
Context.MODE_PRIVATE);
String useridValue = null;
String passwordValue = null;
Date expires = null;
List<Cookie> cookies = sHttpClient.getCookieStore().getCookies();
for(Cookie cookie : cookies) {
if(cookie.getDomain().equals(Constants.COOKIE_DOMAIN)) {
if(cookie.getName().equals(Constants.COOKIE_NAME_USERID)) {
useridValue = cookie.getValue();
expires = cookie.getExpiryDate();
} else if(cookie.getName().equals(Constants.COOKIE_NAME_PASSWORD)) {
passwordValue = cookie.getValue();
expires = cookie.getExpiryDate();
}
}
}
if(useridValue != null && passwordValue != null) {
Editor edit = prefs.edit();
edit.putString(Constants.COOKIE_PREF_USERID, useridValue);
edit.putString(Constants.COOKIE_PREF_PASSWORD, passwordValue);
edit.putLong(Constants.COOKIE_PREF_EXPIRY_DATE, expires.getTime());
return edit.commit();
}
return false;
}
public static TagNode get(String aUrl) throws Exception {
return get(aUrl, null);
}
public static TagNode get(String aUrl, HashMap<String, String> aParams) throws Exception {
TagNode response = null;
String parameters = getQueryStringParameters(aParams);
Log.i(TAG, "Fetching "+ aUrl + parameters);
HttpGet httpGet = new HttpGet(aUrl + parameters);
HttpResponse httpResponse = sHttpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
response = sCleaner.clean(new InputStreamReader(entity.getContent(), "ISO-8859-1"));
}
Log.i(TAG, "Fetched "+ aUrl + parameters);
return response;
}
public static TagNode getWithRedirects(String aUrl, List<URI> redirects)
throws Exception {
return getWithRedirects(aUrl, null, redirects);
}
public static TagNode getWithRedirects(String aUrl, HashMap<String, String> aParams,
List<URI> redirects) throws Exception {
TagNode response = null;
String parameters = getQueryStringParameters(aParams);
Log.i(TAG, "Fetching " + aUrl + parameters);
URI location = new URI(aUrl + parameters);
HttpGet httpGet;
HttpResponse httpResponse;
do {
httpGet = new HttpGet(location);
redirects.add(location);
HttpClientParams.setRedirecting(httpGet.getParams(), false);
httpResponse = sHttpClient.execute(httpGet);
if (httpResponse.containsHeader("location")) {
location = location.resolve(httpResponse.getFirstHeader(
"location").getValue());
Log.i(TAG, "Redirecting to " + location.toString());
}
} while (httpResponse.containsHeader("location"));
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
response = sCleaner
- .clean(new InputStreamReader(entity.getContent()));
+ .clean(new InputStreamReader(entity.getContent(), "ISO-8859-1"));
}
Log.i(TAG, "Fetched " + location.toString());
return response;
}
public static TagNode post(String aUrl, HashMap<String, String> aParams) throws Exception {
TagNode response = null;
Log.i(TAG, aUrl);
HttpPost httpPost = new HttpPost(aUrl);
httpPost.setEntity(
new UrlEncodedFormEntity(getPostParameters(aParams)));
HttpResponse httpResponse = sHttpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
response = sCleaner.clean(new InputStreamReader(entity.getContent(), "ISO-8859-1"));
}
return response;
}
private static ArrayList<NameValuePair> getPostParameters(HashMap<String, String> aParams) {
// Append parameters
ArrayList<NameValuePair> result = new ArrayList<NameValuePair>();
if (aParams != null) {
Iterator<?> iter = aParams.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> param = (Map.Entry<String, String>) iter.next();
result.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
}
return result;
}
public static String getQueryStringParameters(HashMap<String, String> aParams) {
StringBuffer result = new StringBuffer("?");
if (aParams != null) {
try {
// Loop over each parameter and add it to the query string
Iterator<?> iter = aParams.entrySet().iterator();
while (iter.hasNext()) {
@SuppressWarnings("unchecked")
Map.Entry<String, String> param = (Map.Entry<String, String>) iter.next();
result.append(param.getKey() + "=" + URLEncoder.encode((String) param.getValue(), "UTF-8"));
if (iter.hasNext()) {
result.append("&");
}
}
} catch (UnsupportedEncodingException e) {
Log.i(TAG, e.toString());
}
} else {
return "";
}
return result.toString();
}
static {
if (sHttpClient == null) {
sHttpClient = new DefaultHttpClient();
}
sCleaner = new HtmlCleaner();
CleanerTransformations ct = new CleanerTransformations();
ct.addTransformation(new TagTransformation("script"));
ct.addTransformation(new TagTransformation("meta"));
ct.addTransformation(new TagTransformation("head"));
sCleaner.setTransformations(ct);
CleanerProperties properties = sCleaner.getProperties();
properties.setOmitComments(true);
properties.setRecognizeUnicodeChars(false);
}
public static void logCookies() {
Log.i(TAG, "---BEGIN COOKIE DUMP---");
List<Cookie> cookies = sHttpClient.getCookieStore().getCookies();
for(Cookie c : cookies) {
Log.i(TAG, c.toString());
}
Log.i(TAG, "---END COOKIE DUMP---");
}
public static String getAsString(TagNode pc) {
return sCleaner.getInnerHtml(pc);
}
}
| true | true | public static TagNode getWithRedirects(String aUrl, HashMap<String, String> aParams,
List<URI> redirects) throws Exception {
TagNode response = null;
String parameters = getQueryStringParameters(aParams);
Log.i(TAG, "Fetching " + aUrl + parameters);
URI location = new URI(aUrl + parameters);
HttpGet httpGet;
HttpResponse httpResponse;
do {
httpGet = new HttpGet(location);
redirects.add(location);
HttpClientParams.setRedirecting(httpGet.getParams(), false);
httpResponse = sHttpClient.execute(httpGet);
if (httpResponse.containsHeader("location")) {
location = location.resolve(httpResponse.getFirstHeader(
"location").getValue());
Log.i(TAG, "Redirecting to " + location.toString());
}
} while (httpResponse.containsHeader("location"));
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
response = sCleaner
.clean(new InputStreamReader(entity.getContent()));
}
Log.i(TAG, "Fetched " + location.toString());
return response;
}
| public static TagNode getWithRedirects(String aUrl, HashMap<String, String> aParams,
List<URI> redirects) throws Exception {
TagNode response = null;
String parameters = getQueryStringParameters(aParams);
Log.i(TAG, "Fetching " + aUrl + parameters);
URI location = new URI(aUrl + parameters);
HttpGet httpGet;
HttpResponse httpResponse;
do {
httpGet = new HttpGet(location);
redirects.add(location);
HttpClientParams.setRedirecting(httpGet.getParams(), false);
httpResponse = sHttpClient.execute(httpGet);
if (httpResponse.containsHeader("location")) {
location = location.resolve(httpResponse.getFirstHeader(
"location").getValue());
Log.i(TAG, "Redirecting to " + location.toString());
}
} while (httpResponse.containsHeader("location"));
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
response = sCleaner
.clean(new InputStreamReader(entity.getContent(), "ISO-8859-1"));
}
Log.i(TAG, "Fetched " + location.toString());
return response;
}
|
diff --git a/server/src/org/oryxeditor/server/AlternativesRenderer.java b/server/src/org/oryxeditor/server/AlternativesRenderer.java
index cd089e3d..b5974bd9 100644
--- a/server/src/org/oryxeditor/server/AlternativesRenderer.java
+++ b/server/src/org/oryxeditor/server/AlternativesRenderer.java
@@ -1,83 +1,83 @@
package org.oryxeditor.server;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.fop.svg.PDFTranscoder;
public class AlternativesRenderer extends HttpServlet {
private static final long serialVersionUID = 8526319871562210085L;
private String baseFilename;
private String inFile;
private String outFile;
protected void doPost(HttpServletRequest req, HttpServletResponse res) {
String resource = req.getParameter("resource");
String data = req.getParameter("data");
String format = req.getParameter("format");
String tmpPath = this.getServletContext().getRealPath("/")
+ File.separator + "tmp" + File.separator;
this.baseFilename = String.valueOf(System.currentTimeMillis());
this.inFile = tmpPath + this.baseFilename + ".svg";
this.outFile = tmpPath + this.baseFilename + ".pdf";
System.out.println(inFile);
try {
// store model in temporary svg file.
BufferedWriter out = new BufferedWriter(new FileWriter(inFile));
out.write(data);
out.close();
makePDF();
- res.getOutputStream().print("./tmp/" + this.baseFilename + ".pdf");
+ res.getOutputStream().print("/oryx/tmp/" + this.baseFilename + ".pdf");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void makePDF() throws TranscoderException, IOException {
PDFTranscoder transcoder = new PDFTranscoder();
InputStream in = new java.io.FileInputStream(inFile);
try {
TranscoderInput input = new TranscoderInput(in);
// Setup output
OutputStream out = new java.io.FileOutputStream(outFile);
out = new java.io.BufferedOutputStream(out);
try {
TranscoderOutput output = new TranscoderOutput(out);
// Do the transformation
transcoder.transcode(input, output);
} finally {
out.close();
}
} finally {
in.close();
}
}
}
| true | true | protected void doPost(HttpServletRequest req, HttpServletResponse res) {
String resource = req.getParameter("resource");
String data = req.getParameter("data");
String format = req.getParameter("format");
String tmpPath = this.getServletContext().getRealPath("/")
+ File.separator + "tmp" + File.separator;
this.baseFilename = String.valueOf(System.currentTimeMillis());
this.inFile = tmpPath + this.baseFilename + ".svg";
this.outFile = tmpPath + this.baseFilename + ".pdf";
System.out.println(inFile);
try {
// store model in temporary svg file.
BufferedWriter out = new BufferedWriter(new FileWriter(inFile));
out.write(data);
out.close();
makePDF();
res.getOutputStream().print("./tmp/" + this.baseFilename + ".pdf");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| protected void doPost(HttpServletRequest req, HttpServletResponse res) {
String resource = req.getParameter("resource");
String data = req.getParameter("data");
String format = req.getParameter("format");
String tmpPath = this.getServletContext().getRealPath("/")
+ File.separator + "tmp" + File.separator;
this.baseFilename = String.valueOf(System.currentTimeMillis());
this.inFile = tmpPath + this.baseFilename + ".svg";
this.outFile = tmpPath + this.baseFilename + ".pdf";
System.out.println(inFile);
try {
// store model in temporary svg file.
BufferedWriter out = new BufferedWriter(new FileWriter(inFile));
out.write(data);
out.close();
makePDF();
res.getOutputStream().print("/oryx/tmp/" + this.baseFilename + ".pdf");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/src/org/apache/xerces/dom/CharacterDataImpl.java b/src/org/apache/xerces/dom/CharacterDataImpl.java
index 873e9df90..ee17c3a85 100644
--- a/src/org/apache/xerces/dom/CharacterDataImpl.java
+++ b/src/org/apache/xerces/dom/CharacterDataImpl.java
@@ -1,431 +1,431 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. 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 "Xerces" 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 (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.dom;
import org.w3c.dom.*;
import org.apache.xerces.dom.events.MutationEventImpl;
import org.w3c.dom.events.*;
/**
* CharacterData is an abstract Node that can carry character data as its
* Value. It provides shared behavior for Text, CData, and
* possibly other node types. All offsets are 0-based.
* <p>
* This implementation includes support for DOM Level 2 Mutation Events.
* If the static boolean NodeImpl.MUTATIONEVENTS is not set true, that support
* is disabled and can be optimized out to reduce code size.
*
* Since this ProcessingInstructionImpl inherits from this class to reuse the
* setNodeValue method, this class isn't declared as implementing the interface
* CharacterData. This is done by relevant subclasses (TexImpl, CommentImpl).
*
* @version
* @since PR-DOM-Level-1-19980818.
*/
public abstract class CharacterDataImpl
extends ChildNode {
//
// Constants
//
/** Serialization version. */
static final long serialVersionUID = 7931170150428474230L;
//
// Data
//
protected String data;
/** Empty child nodes. */
private static transient NodeList singletonNodeList = new NodeList() {
public Node item(int index) { return null; }
public int getLength() { return 0; }
};
//
// Constructors
//
/** Factory constructor. */
protected CharacterDataImpl(DocumentImpl ownerDocument, String data) {
super(ownerDocument);
this.data = data;
}
//
// Node methods
//
/** Returns an empty node list. */
public NodeList getChildNodes() {
return singletonNodeList;
}
/*
* returns the content of this node
*/
public String getNodeValue() {
if (needsSyncData()) {
synchronizeData();
}
return data;
}
/** This function added so that we can distinguish whether
* setNodeValue has been called from some other DOM functions.
* or by the client.<p>
* This is important, because we do one type of Range fix-up,
* from the high-level functions in CharacterData, and another
* type if the client simply calls setNodeValue(value).
*/
void setNodeValueInternal(String value) {
/** flag to indicate whether setNodeValue was called by the
* client or from the DOM.
*/
setValueCalled(true);
setNodeValue(value);
setValueCalled(false);
}
/**
* Sets the content, possibly firing related events,
* and updating ranges (via notification to the document)
*/
public void setNodeValue(String value) {
if (isReadOnly())
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
// revisit: may want to set the value in ownerDocument.
// Default behavior, overridden in some subclasses
if (needsSyncData()) {
synchronizeData();
}
// Cache old value for DOMCharacterDataModified.
- String oldvalue = value;
+ String oldvalue = this.data;
EnclosingAttr enclosingAttr=null;
if(MUTATIONEVENTS)
{
// MUTATION PREPROCESSING AND PRE-EVENTS:
// If we're within the scope of an Attr and DOMAttrModified
// was requested, we need to preserve its previous value for
// that event.
LCount lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
if(lc.captures+lc.bubbles+lc.defaults>0)
{
enclosingAttr=getEnclosingAttr();
}
} // End mutation preprocessing
this.data = value;
if (!setValueCalled()) {
// notify document
ownerDocument().replacedText(this);
}
if(MUTATIONEVENTS)
{
// MUTATION POST-EVENTS:
LCount lc =
LCount.lookup(MutationEventImpl.DOM_CHARACTER_DATA_MODIFIED);
if(lc.captures+lc.bubbles+lc.defaults>0)
{
MutationEvent me= new MutationEventImpl();
//?????ownerDocument.createEvent("MutationEvents");
me.initMutationEvent(
MutationEventImpl.DOM_CHARACTER_DATA_MODIFIED,
true,false,null,oldvalue,value,null);
dispatchEvent(me);
}
// Subroutine: Transmit DOMAttrModified and DOMSubtreeModified,
// if required. (Common to most kinds of mutation)
dispatchAggregateEvents(enclosingAttr);
} // End mutation postprocessing
} // setNodeValue(String)
//
// CharacterData methods
//
/**
* Retrieve character data currently stored in this node.
*
* @throws DOMExcpetion(DOMSTRING_SIZE_ERR) In some implementations,
* the stored data may exceed the permitted length of strings. If so,
* getData() will throw this DOMException advising the user to
* instead retrieve the data in chunks via the substring() operation.
*/
public String getData() {
if (needsSyncData()) {
synchronizeData();
}
return data;
}
/**
* Report number of characters currently stored in this node's
* data. It may be 0, meaning that the value is an empty string.
*/
public int getLength() {
if (needsSyncData()) {
synchronizeData();
}
return data.length();
}
/**
* Concatenate additional characters onto the end of the data
* stored in this node. Note that this, and insert(), are the paths
* by which a DOM could wind up accumulating more data than the
* language's strings can easily handle. (See above discussion.)
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if node is readonly.
*/
public void appendData(String data) {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
// Handles mutation event generation, if any
setNodeValue(this.data + data);
} // appendData(String)
/**
* Remove a range of characters from the node's value. Throws a
* DOMException if the offset is beyond the end of the
* string. However, a deletion _count_ that exceeds the available
* data is accepted as a delete-to-end request.
*
* @throws DOMException(INDEX_SIZE_ERR) if offset is negative or
* greater than length, or if count is negative.
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if node is
* readonly.
*/
public void deleteData(int offset, int count)
throws DOMException {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (count < 0) {
throw new DOMExceptionImpl(DOMException.INDEX_SIZE_ERR,
"DOM004 Index out of bounds");
}
if (needsSyncData()) {
synchronizeData();
}
int tailLength = Math.max(data.length() - count - offset, 0);
try {
// Handles mutation event generation, if any
setNodeValueInternal(data.substring(0, offset) +
(tailLength > 0
? data.substring(offset + count, offset + count + tailLength)
: "") );
// notify document
ownerDocument().deletedText(this, offset, count);
}
catch (StringIndexOutOfBoundsException e) {
throw new DOMExceptionImpl(DOMException.INDEX_SIZE_ERR,
"DOM004 Index out of bounds");
}
} // deleteData(int,int)
/**
* Insert additional characters into the data stored in this node,
* at the offset specified.
*
* @throws DOMException(INDEX_SIZE_ERR) if offset is negative or
* greater than length.
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if node is readonly.
*/
public void insertData(int offset, String data)
throws DOMException {
if (isReadOnly()) {
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
}
if (needsSyncData()) {
synchronizeData();
}
try {
// Handles mutation event generation, if any
setNodeValueInternal(
new StringBuffer(this.data).insert(offset, data).toString()
);
// notify document
ownerDocument().insertedText(this, offset, data.length());
}
catch (StringIndexOutOfBoundsException e) {
throw new DOMExceptionImpl(DOMException.INDEX_SIZE_ERR,
"DOM004 Index out of bounds");
}
} // insertData(int,int)
/**
* Replace a series of characters at the specified (zero-based)
* offset with a new string, NOT necessarily of the same
* length. Convenience method, equivalent to a delete followed by an
* insert. Throws a DOMException if the specified offset is beyond
* the end of the existing data.
*
* @param offset The offset at which to begin replacing.
*
* @param count The number of characters to remove,
* interpreted as in the delete() method.
*
* @param data The new string to be inserted at offset in place of
* the removed data. Note that the entire string will
* be inserted -- the count parameter does not affect
* insertion, and the new data may be longer or shorter
* than the substring it replaces.
*
* @throws DOMException(INDEX_SIZE_ERR) if offset is negative or
* greater than length, or if count is negative.
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if node is
* readonly.
*/
public void replaceData(int offset, int count, String data)
throws DOMException {
// The read-only check is done by deleteData()
// ***** This could be more efficient w/r/t Mutation Events,
// specifically by aggregating DOMAttrModified and
// DOMSubtreeModified. But mutation events are
// underspecified; I don't feel compelled
// to deal with it right now.
deleteData(offset, count);
insertData(offset, data);
} // replaceData(int,int,String)
/**
* Store character data into this node.
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if node is readonly.
*/
public void setData(String value)
throws DOMException {
setNodeValue(value);
}
/**
* Substring is more than a convenience function. In some
* implementations of the DOM, where the stored data may exceed the
* length that can be returned in a single string, the only way to
* read it all is to extract it in chunks via this method.
*
* @param offset Zero-based offset of first character to retrieve.
* @param count Number of characters to retrieve.
*
* If the sum of offset and count exceeds the length, all characters
* to end of data are returned.
*
* @throws DOMException(INDEX_SIZE_ERR) if offset is negative or
* greater than length, or if count is negative.
*
* @throws DOMException(WSTRING_SIZE_ERR) In some implementations,
* count may exceed the permitted length of strings. If so,
* substring() will throw this DOMException advising the user to
* instead retrieve the data in smaller chunks.
*/
public String substringData(int offset, int count)
throws DOMException {
if (needsSyncData()) {
synchronizeData();
}
int length = data.length();
if (count < 0 || offset < 0 || offset > length - 1) {
throw new DOMExceptionImpl(DOMException.INDEX_SIZE_ERR,
"DOM004 Index out of bounds");
}
int tailIndex = Math.min(offset + count, length);
return data.substring(offset, tailIndex);
} // substringData(int,int):String
} // class CharacterDataImpl
| true | true | public void setNodeValue(String value) {
if (isReadOnly())
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
// revisit: may want to set the value in ownerDocument.
// Default behavior, overridden in some subclasses
if (needsSyncData()) {
synchronizeData();
}
// Cache old value for DOMCharacterDataModified.
String oldvalue = value;
EnclosingAttr enclosingAttr=null;
if(MUTATIONEVENTS)
{
// MUTATION PREPROCESSING AND PRE-EVENTS:
// If we're within the scope of an Attr and DOMAttrModified
// was requested, we need to preserve its previous value for
// that event.
LCount lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
if(lc.captures+lc.bubbles+lc.defaults>0)
{
enclosingAttr=getEnclosingAttr();
}
} // End mutation preprocessing
this.data = value;
if (!setValueCalled()) {
// notify document
ownerDocument().replacedText(this);
}
if(MUTATIONEVENTS)
{
// MUTATION POST-EVENTS:
LCount lc =
LCount.lookup(MutationEventImpl.DOM_CHARACTER_DATA_MODIFIED);
if(lc.captures+lc.bubbles+lc.defaults>0)
{
MutationEvent me= new MutationEventImpl();
//?????ownerDocument.createEvent("MutationEvents");
me.initMutationEvent(
MutationEventImpl.DOM_CHARACTER_DATA_MODIFIED,
true,false,null,oldvalue,value,null);
dispatchEvent(me);
}
// Subroutine: Transmit DOMAttrModified and DOMSubtreeModified,
// if required. (Common to most kinds of mutation)
dispatchAggregateEvents(enclosingAttr);
} // End mutation postprocessing
} // setNodeValue(String)
| public void setNodeValue(String value) {
if (isReadOnly())
throw new DOMExceptionImpl(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
"DOM001 Modification not allowed");
// revisit: may want to set the value in ownerDocument.
// Default behavior, overridden in some subclasses
if (needsSyncData()) {
synchronizeData();
}
// Cache old value for DOMCharacterDataModified.
String oldvalue = this.data;
EnclosingAttr enclosingAttr=null;
if(MUTATIONEVENTS)
{
// MUTATION PREPROCESSING AND PRE-EVENTS:
// If we're within the scope of an Attr and DOMAttrModified
// was requested, we need to preserve its previous value for
// that event.
LCount lc=LCount.lookup(MutationEventImpl.DOM_ATTR_MODIFIED);
if(lc.captures+lc.bubbles+lc.defaults>0)
{
enclosingAttr=getEnclosingAttr();
}
} // End mutation preprocessing
this.data = value;
if (!setValueCalled()) {
// notify document
ownerDocument().replacedText(this);
}
if(MUTATIONEVENTS)
{
// MUTATION POST-EVENTS:
LCount lc =
LCount.lookup(MutationEventImpl.DOM_CHARACTER_DATA_MODIFIED);
if(lc.captures+lc.bubbles+lc.defaults>0)
{
MutationEvent me= new MutationEventImpl();
//?????ownerDocument.createEvent("MutationEvents");
me.initMutationEvent(
MutationEventImpl.DOM_CHARACTER_DATA_MODIFIED,
true,false,null,oldvalue,value,null);
dispatchEvent(me);
}
// Subroutine: Transmit DOMAttrModified and DOMSubtreeModified,
// if required. (Common to most kinds of mutation)
dispatchAggregateEvents(enclosingAttr);
} // End mutation postprocessing
} // setNodeValue(String)
|
diff --git a/frost-wot/source/frost/threads/insertThread.java b/frost-wot/source/frost/threads/insertThread.java
index 7c2404e7..e07a15b7 100644
--- a/frost-wot/source/frost/threads/insertThread.java
+++ b/frost-wot/source/frost/threads/insertThread.java
@@ -1,244 +1,244 @@
/*
insertThread.java / Frost
Copyright (C) 2001 Jan-Thomas Czornack <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.threads;
import java.io.File;
import java.util.Random;
import frost.*;
import frost.gui.model.UploadTableModel;
import frost.gui.objects.*;
import frost.FcpTools.*;
public class insertThread extends Thread
{
static java.util.ResourceBundle LangRes = java.util.ResourceBundle.getBundle("res.LangRes")/*#BundleType=List*/;
public static final int MODE_GENERATE_SHA1 = 1;
public static final int MODE_GENERATE_CHK = 2;
public static final int MODE_UPLOAD = 3;
private int nextState; // the state to set on uploadItem when finished, or -1 for default (IDLE)
private String destination;
private File file;
private int htl;
private FrostBoardObject board;
private int mode;
private static int fileIndex=1;
private static Random r = new Random();
//this is gonna be ugly
private static String batchId = frame1.getMyBatches().values().size() == 0 ?
(new Long(r.nextLong())).toString() :
(String) frame1.getMyBatches().values().iterator().next();
private static final int batchSize = 100; //TODO: get this from options
//private static final Object putIt = frame1.getMyBatches().put(batchId,batchId);
//^^ ugly trick to put the initial batch number
FrostUploadItemObject uploadItem;
public void run()
{
try
{
String lastUploadDate = null; // NEVER uploaded
boolean success = false;
String[] result = { "Error", "Error" };
String currentDate = DateFun.getExtendedDate();
boolean sign = frame1.frostSettings.getBoolValue("signUploads");
if( mode == MODE_UPLOAD )
{ //real upload
System.out.println("Upload of " + file + " with HTL " + htl + " started.");
synchronized (frame1.threadCountLock)
{
frame1.activeUploadThreads++;
}
result =
FcpInsert.putFile(
"CHK@",
file,
htl,
true,
true, // real upload
board.getBoardFilename());
if( result[0].equals("Success") ||
result[0].equals("KeyCollision") )
{
success = true;
System.out.println("Upload of " + file + " was successful.");
uploadItem.setKey(result[1]);
lastUploadDate = currentDate;
}
else
{
System.out.println("Upload of " + file + " was NOT successful.");
}
// item uploaded (maybe)
// REDFLAG: but this also resets upload date of yesterday, ... !
if( lastUploadDate != null )
uploadItem.setLastUploadDate(lastUploadDate);
// if NULL then upload failed -> shows NEVER in table
uploadItem.setState(this.nextState);
synchronized (frame1.threadCountLock)
{
frame1.activeUploadThreads--;
}
//now update the files.xml with the CHK
// REDFLAG: was this really intented to run even if upload failed?
if( success == true )
{
KeyClass current = new KeyClass(uploadItem.getKey());
if (sign)
current.setOwner(frame1.getMyId().getUniqueName());
current.setFilename(uploadItem.getFileName());
current.setSHA1(uploadItem.getSHA1());
current.setBatch(uploadItem.getBatch());
current.setSize(uploadItem.getFileSize().longValue());
current.setDate(lastUploadDate);
Index.addMine(current, board);
Index.add(current, board);
}
}
else if( mode == MODE_GENERATE_SHA1 )
{
frame1.setGeneratingCHK(true);
//if this is the first startup, put at least one batch in
/* if (frame1.getMyBatches().values().size() == 0) //
frame1.getMyBatches().put(batchId,batchId);
else {
//take the first patch we come upon
}*/
if (fileIndex % batchSize == 0)
{
frame1.getMyBatches().put(batchId, batchId);
while (frame1.getMyBatches().contains(batchId))
batchId = (new Long(r.nextLong())).toString();
frame1.getMyBatches().put(batchId, batchId);
}
long now = System.currentTimeMillis();
String SHA1 = frame1.getCrypto().digest(file);
System.out.println(
"digest generated in "
+ (System.currentTimeMillis() - now)
+ " "
+ SHA1);
//create new KeyClass
KeyClass newKey = new KeyClass();
newKey.setKey(null);
newKey.setDate(null);
newKey.setLastSharedDate(DateFun.getDate());
newKey.setSHA1(SHA1);
newKey.setFilename(destination);
newKey.setSize(file.length());
newKey.setBatch(batchId);
if (sign)
newKey.setOwner(frame1.getMyId().getUniqueName());
//update the gui
uploadItem.setSHA1(SHA1);
uploadItem.setKey(null);
uploadItem.setLastUploadDate(null);
uploadItem.setBatch(batchId);
fileIndex++;
//add to index
Index.addMine(newKey, board);
Index.add(newKey, board);
uploadItem.setState(this.nextState);
frame1.setGeneratingCHK(false);
}
else if( mode == MODE_GENERATE_CHK )
{
frame1.setGeneratingCHK(true);
System.out.println("CHK generation started for file: " + file);
FecSplitfile splitfile = new FecSplitfile( file );
boolean alreadyEncoded = splitfile.uploadInit();
if( !alreadyEncoded )
{
try {
splitfile.encode();
}
catch(Throwable t)
{
System.out.println("Encoding failed:");
t.printStackTrace();
return;
}
}
// yes, this destroys any upload progress, but we come only here if
// chkKey == null, so the file should'nt be uploaded until now
- splitfile.finishUpload();
+ splitfile.createRedirectFile(false); // gen normal redirect file for CHK generation
String chkkey = FecTools.generateCHK(splitfile.getRedirectFile(), splitfile.getRedirectFile().length());
if( chkkey != null )
{
String prefix = new String("freenet:");
if( chkkey.startsWith(prefix) ) chkkey = chkkey.substring(prefix.length());
}
else
{
System.out.println("Could not generate CHK key for redirect file.");
}
uploadItem.setKey(chkkey);
uploadItem.setState(this.nextState);
frame1.setGeneratingCHK(false);
}
((UploadTableModel)frame1.getInstance().getUploadTable().getModel()).updateRow(uploadItem);
}
catch (Throwable t)
{
t.printStackTrace(System.out);
}
}
/**Constructor*/
public insertThread(FrostUploadItemObject ulItem, SettingsClass config, int mode)
{
this(ulItem, config, mode, -1);
}
public insertThread(FrostUploadItemObject ulItem, SettingsClass config, int mode, int nextState)
{
this.destination = ulItem.getFileName();
this.file = new File(ulItem.getFilePath());
this.uploadItem = ulItem;
this.htl = config.getIntValue("htlUpload");
this.board = ulItem.getTargetBoard();
this.mode = mode; // true=upload file false=generate chk (do not upload)
this.nextState = nextState;
if( this.nextState < 0 )
{
this.nextState = FrostUploadItemObject.STATE_IDLE;
}
}
}
| true | true | public void run()
{
try
{
String lastUploadDate = null; // NEVER uploaded
boolean success = false;
String[] result = { "Error", "Error" };
String currentDate = DateFun.getExtendedDate();
boolean sign = frame1.frostSettings.getBoolValue("signUploads");
if( mode == MODE_UPLOAD )
{ //real upload
System.out.println("Upload of " + file + " with HTL " + htl + " started.");
synchronized (frame1.threadCountLock)
{
frame1.activeUploadThreads++;
}
result =
FcpInsert.putFile(
"CHK@",
file,
htl,
true,
true, // real upload
board.getBoardFilename());
if( result[0].equals("Success") ||
result[0].equals("KeyCollision") )
{
success = true;
System.out.println("Upload of " + file + " was successful.");
uploadItem.setKey(result[1]);
lastUploadDate = currentDate;
}
else
{
System.out.println("Upload of " + file + " was NOT successful.");
}
// item uploaded (maybe)
// REDFLAG: but this also resets upload date of yesterday, ... !
if( lastUploadDate != null )
uploadItem.setLastUploadDate(lastUploadDate);
// if NULL then upload failed -> shows NEVER in table
uploadItem.setState(this.nextState);
synchronized (frame1.threadCountLock)
{
frame1.activeUploadThreads--;
}
//now update the files.xml with the CHK
// REDFLAG: was this really intented to run even if upload failed?
if( success == true )
{
KeyClass current = new KeyClass(uploadItem.getKey());
if (sign)
current.setOwner(frame1.getMyId().getUniqueName());
current.setFilename(uploadItem.getFileName());
current.setSHA1(uploadItem.getSHA1());
current.setBatch(uploadItem.getBatch());
current.setSize(uploadItem.getFileSize().longValue());
current.setDate(lastUploadDate);
Index.addMine(current, board);
Index.add(current, board);
}
}
else if( mode == MODE_GENERATE_SHA1 )
{
frame1.setGeneratingCHK(true);
//if this is the first startup, put at least one batch in
/* if (frame1.getMyBatches().values().size() == 0) //
frame1.getMyBatches().put(batchId,batchId);
else {
//take the first patch we come upon
}*/
if (fileIndex % batchSize == 0)
{
frame1.getMyBatches().put(batchId, batchId);
while (frame1.getMyBatches().contains(batchId))
batchId = (new Long(r.nextLong())).toString();
frame1.getMyBatches().put(batchId, batchId);
}
long now = System.currentTimeMillis();
String SHA1 = frame1.getCrypto().digest(file);
System.out.println(
"digest generated in "
+ (System.currentTimeMillis() - now)
+ " "
+ SHA1);
//create new KeyClass
KeyClass newKey = new KeyClass();
newKey.setKey(null);
newKey.setDate(null);
newKey.setLastSharedDate(DateFun.getDate());
newKey.setSHA1(SHA1);
newKey.setFilename(destination);
newKey.setSize(file.length());
newKey.setBatch(batchId);
if (sign)
newKey.setOwner(frame1.getMyId().getUniqueName());
//update the gui
uploadItem.setSHA1(SHA1);
uploadItem.setKey(null);
uploadItem.setLastUploadDate(null);
uploadItem.setBatch(batchId);
fileIndex++;
//add to index
Index.addMine(newKey, board);
Index.add(newKey, board);
uploadItem.setState(this.nextState);
frame1.setGeneratingCHK(false);
}
else if( mode == MODE_GENERATE_CHK )
{
frame1.setGeneratingCHK(true);
System.out.println("CHK generation started for file: " + file);
FecSplitfile splitfile = new FecSplitfile( file );
boolean alreadyEncoded = splitfile.uploadInit();
if( !alreadyEncoded )
{
try {
splitfile.encode();
}
catch(Throwable t)
{
System.out.println("Encoding failed:");
t.printStackTrace();
return;
}
}
// yes, this destroys any upload progress, but we come only here if
// chkKey == null, so the file should'nt be uploaded until now
splitfile.finishUpload();
String chkkey = FecTools.generateCHK(splitfile.getRedirectFile(), splitfile.getRedirectFile().length());
if( chkkey != null )
{
String prefix = new String("freenet:");
if( chkkey.startsWith(prefix) ) chkkey = chkkey.substring(prefix.length());
}
else
{
System.out.println("Could not generate CHK key for redirect file.");
}
uploadItem.setKey(chkkey);
uploadItem.setState(this.nextState);
frame1.setGeneratingCHK(false);
}
((UploadTableModel)frame1.getInstance().getUploadTable().getModel()).updateRow(uploadItem);
}
catch (Throwable t)
{
t.printStackTrace(System.out);
}
}
| public void run()
{
try
{
String lastUploadDate = null; // NEVER uploaded
boolean success = false;
String[] result = { "Error", "Error" };
String currentDate = DateFun.getExtendedDate();
boolean sign = frame1.frostSettings.getBoolValue("signUploads");
if( mode == MODE_UPLOAD )
{ //real upload
System.out.println("Upload of " + file + " with HTL " + htl + " started.");
synchronized (frame1.threadCountLock)
{
frame1.activeUploadThreads++;
}
result =
FcpInsert.putFile(
"CHK@",
file,
htl,
true,
true, // real upload
board.getBoardFilename());
if( result[0].equals("Success") ||
result[0].equals("KeyCollision") )
{
success = true;
System.out.println("Upload of " + file + " was successful.");
uploadItem.setKey(result[1]);
lastUploadDate = currentDate;
}
else
{
System.out.println("Upload of " + file + " was NOT successful.");
}
// item uploaded (maybe)
// REDFLAG: but this also resets upload date of yesterday, ... !
if( lastUploadDate != null )
uploadItem.setLastUploadDate(lastUploadDate);
// if NULL then upload failed -> shows NEVER in table
uploadItem.setState(this.nextState);
synchronized (frame1.threadCountLock)
{
frame1.activeUploadThreads--;
}
//now update the files.xml with the CHK
// REDFLAG: was this really intented to run even if upload failed?
if( success == true )
{
KeyClass current = new KeyClass(uploadItem.getKey());
if (sign)
current.setOwner(frame1.getMyId().getUniqueName());
current.setFilename(uploadItem.getFileName());
current.setSHA1(uploadItem.getSHA1());
current.setBatch(uploadItem.getBatch());
current.setSize(uploadItem.getFileSize().longValue());
current.setDate(lastUploadDate);
Index.addMine(current, board);
Index.add(current, board);
}
}
else if( mode == MODE_GENERATE_SHA1 )
{
frame1.setGeneratingCHK(true);
//if this is the first startup, put at least one batch in
/* if (frame1.getMyBatches().values().size() == 0) //
frame1.getMyBatches().put(batchId,batchId);
else {
//take the first patch we come upon
}*/
if (fileIndex % batchSize == 0)
{
frame1.getMyBatches().put(batchId, batchId);
while (frame1.getMyBatches().contains(batchId))
batchId = (new Long(r.nextLong())).toString();
frame1.getMyBatches().put(batchId, batchId);
}
long now = System.currentTimeMillis();
String SHA1 = frame1.getCrypto().digest(file);
System.out.println(
"digest generated in "
+ (System.currentTimeMillis() - now)
+ " "
+ SHA1);
//create new KeyClass
KeyClass newKey = new KeyClass();
newKey.setKey(null);
newKey.setDate(null);
newKey.setLastSharedDate(DateFun.getDate());
newKey.setSHA1(SHA1);
newKey.setFilename(destination);
newKey.setSize(file.length());
newKey.setBatch(batchId);
if (sign)
newKey.setOwner(frame1.getMyId().getUniqueName());
//update the gui
uploadItem.setSHA1(SHA1);
uploadItem.setKey(null);
uploadItem.setLastUploadDate(null);
uploadItem.setBatch(batchId);
fileIndex++;
//add to index
Index.addMine(newKey, board);
Index.add(newKey, board);
uploadItem.setState(this.nextState);
frame1.setGeneratingCHK(false);
}
else if( mode == MODE_GENERATE_CHK )
{
frame1.setGeneratingCHK(true);
System.out.println("CHK generation started for file: " + file);
FecSplitfile splitfile = new FecSplitfile( file );
boolean alreadyEncoded = splitfile.uploadInit();
if( !alreadyEncoded )
{
try {
splitfile.encode();
}
catch(Throwable t)
{
System.out.println("Encoding failed:");
t.printStackTrace();
return;
}
}
// yes, this destroys any upload progress, but we come only here if
// chkKey == null, so the file should'nt be uploaded until now
splitfile.createRedirectFile(false); // gen normal redirect file for CHK generation
String chkkey = FecTools.generateCHK(splitfile.getRedirectFile(), splitfile.getRedirectFile().length());
if( chkkey != null )
{
String prefix = new String("freenet:");
if( chkkey.startsWith(prefix) ) chkkey = chkkey.substring(prefix.length());
}
else
{
System.out.println("Could not generate CHK key for redirect file.");
}
uploadItem.setKey(chkkey);
uploadItem.setState(this.nextState);
frame1.setGeneratingCHK(false);
}
((UploadTableModel)frame1.getInstance().getUploadTable().getModel()).updateRow(uploadItem);
}
catch (Throwable t)
{
t.printStackTrace(System.out);
}
}
|
diff --git a/astrid/src/com/todoroo/astrid/service/UpgradeService.java b/astrid/src/com/todoroo/astrid/service/UpgradeService.java
index b1fd7a259..45f36b4f6 100644
--- a/astrid/src/com/todoroo/astrid/service/UpgradeService.java
+++ b/astrid/src/com/todoroo/astrid/service/UpgradeService.java
@@ -1,780 +1,780 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.service;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import com.timsu.astrid.GCMIntentService;
import com.timsu.astrid.R;
import com.todoroo.andlib.data.TodorooCursor;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.sql.Criterion;
import com.todoroo.andlib.sql.Query;
import com.todoroo.andlib.utility.DialogUtilities;
import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.actfm.sync.ActFmPreferenceService;
import com.todoroo.astrid.actfm.sync.AstridNewSyncMigrator;
import com.todoroo.astrid.activity.AstridActivity;
import com.todoroo.astrid.activity.Eula;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.core.PluginServices;
import com.todoroo.astrid.core.SavedFilter;
import com.todoroo.astrid.core.SortHelper;
import com.todoroo.astrid.dao.Database;
import com.todoroo.astrid.data.StoreObject;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.gtasks.GtasksPreferenceService;
import com.todoroo.astrid.helper.DueDateTimeMigrator;
import com.todoroo.astrid.service.abtesting.ABChooser;
import com.todoroo.astrid.subtasks.SubtasksMetadataMigration;
import com.todoroo.astrid.tags.TagCaseMigrator;
import com.todoroo.astrid.utility.AstridPreferences;
import com.todoroo.astrid.utility.Constants;
public final class UpgradeService {
public static final int V4_6_0 = 300;
public static final int V4_5_3 = 294;
public static final int V4_5_2 = 293;
public static final int V4_5_1 = 292;
public static final int V4_5_0 = 291;
public static final int V4_4_4_1 = 290;
public static final int V4_4_4 = 289;
public static final int V4_4_3 = 288;
public static final int V4_4_2 = 287;
public static final int V4_4_1 = 286;
public static final int V4_4 = 285;
public static final int V4_3_4_2 = 284;
public static final int V4_3_4_1 = 283;
public static final int V4_3_4 = 282;
public static final int V4_3_3 = 281;
public static final int V4_3_2 = 280;
public static final int V4_3_1 = 279;
public static final int V4_3_0 = 278;
public static final int V4_2_6 = 277;
public static final int V4_2_5 = 276;
public static final int V4_2_4 = 275;
public static final int V4_2_3 = 274;
public static final int V4_2_2_1 = 273;
public static final int V4_2_2 = 272;
public static final int V4_2_1 = 271;
public static final int V4_2_0 = 270;
public static final int V4_1_3_1 = 269;
public static final int V4_1_3 = 268;
public static final int V4_1_2 = 267;
public static final int V4_1_1 = 266;
public static final int V4_1_0 = 265;
public static final int V4_0_6_2 = 264;
public static final int V4_0_6_1 = 263;
public static final int V4_0_6 = 262;
public static final int V4_0_5_1 = 261;
public static final int V4_0_5 = 260;
public static final int V4_0_4_3 = 259;
public static final int V4_0_4_2 = 258;
public static final int V4_0_4_1 = 257;
public static final int V4_0_4 = 256;
public static final int V4_0_3 = 255;
public static final int V4_0_2_1 = 254;
public static final int V4_0_2 = 253;
public static final int V4_0_1 = 252;
public static final int V4_0_0 = 251;
public static final int V3_9_2_3 = 210;
public static final int V3_9_2_2 = 209;
public static final int V3_9_2_1 = 208;
public static final int V3_9_2 = 207;
public static final int V3_9_1_1 = 206;
public static final int V3_9_1 = 205;
public static final int V3_9_0_2 = 204;
public static final int V3_9_0_1 = 203;
public static final int V3_9_0 = 202;
public static final int V3_8_5_1 = 201;
public static final int V3_8_5 = 200;
public static final int V3_8_4_4 = 199;
public static final int V3_8_4_3 = 198;
public static final int V3_8_4_2 = 197;
public static final int V3_8_4_1 = 196;
public static final int V3_8_4 = 195;
public static final int V3_8_3_1 = 194;
public static final int V3_8_3 = 192;
public static final int V3_8_2 = 191;
public static final int V3_8_0_2 = 188;
public static final int V3_8_0 = 186;
public static final int V3_7_7 = 184;
public static final int V3_7_6 = 182;
public static final int V3_7_5 = 179;
public static final int V3_7_4 = 178;
public static final int V3_7_3 = 175;
public static final int V3_7_2 = 174;
public static final int V3_7_1 = 173;
public static final int V3_7_0 = 172;
public static final int V3_6_4 = 170;
public static final int V3_6_3 = 169;
public static final int V3_6_2 = 168;
public static final int V3_6_0 = 166;
public static final int V3_5_0 = 165;
public static final int V3_4_0 = 162;
public static final int V3_3_0 = 155;
public static final int V3_2_0 = 147;
public static final int V3_1_0 = 146;
public static final int V3_0_0 = 136;
public static final int V2_14_4 = 135;
@Autowired Database database;
@Autowired TaskService taskService;
@Autowired MetadataService metadataService;
@Autowired GtasksPreferenceService gtasksPreferenceService;
@Autowired ABChooser abChooser;
@Autowired AddOnService addOnService;
@Autowired ActFmPreferenceService actFmPreferenceService;
public UpgradeService() {
DependencyInjectionService.getInstance().inject(this);
}
/**
* Perform upgrade from one version to the next. Needs to be called
* on the UI thread so it can display a progress bar and then
* show users a change log.
*
* @param from
* @param to
*/
public void performUpgrade(final Activity context, final int from) {
if(from == 135)
AddOnService.recordOem();
if(from > 0 && from < V3_8_2) {
if(Preferences.getBoolean(R.string.p_transparent_deprecated, false))
Preferences.setString(R.string.p_theme, "transparent"); //$NON-NLS-1$
else
Preferences.setString(R.string.p_theme, "black"); //$NON-NLS-1$
}
if(from <= V3_9_1_1) {
actFmPreferenceService.clearLastSyncDate();
}
final String lastSetVersionName = AstridPreferences.getCurrentVersionName();
Preferences.setInt(AstridPreferences.P_UPGRADE_FROM, from);
int maxWithUpgrade = V4_6_0; // The last version that required a migration
Preferences.setInt(AstridPreferences.P_UPGRADE_FROM, from);
inlineUpgrades(context, from); // Migrations that are short or don't require launching a separate activity
if(from < maxWithUpgrade) {
Intent upgrade = new Intent(context, UpgradeActivity.class);
upgrade.putExtra(UpgradeActivity.TOKEN_FROM_VERSION, from);
context.startActivityForResult(upgrade, 0);
}
}
public static class UpgradeActivity extends Activity {
@Autowired
private TaskService taskService;
private ProgressDialog dialog;
public static final String TOKEN_FROM_VERSION = "from_version"; //$NON-NLS-1$
private int from;
private boolean finished = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DependencyInjectionService.getInstance().inject(this);
from = getIntent().getIntExtra(TOKEN_FROM_VERSION, -1);
if (from > 0) {
dialog = DialogUtilities.progressDialog(this,
getString(R.string.DLG_upgrading));
new Thread() {
@Override
public void run() {
try {
if(from < V3_0_0)
new Astrid2To3UpgradeHelper().upgrade2To3(UpgradeActivity.this, from);
if(from < V3_1_0)
new Astrid2To3UpgradeHelper().upgrade3To3_1(UpgradeActivity.this, from);
if(from < V3_8_3_1)
new TagCaseMigrator().performTagCaseMigration(UpgradeActivity.this);
if(from < V3_8_4 && Preferences.getBoolean(R.string.p_showNotes, false))
taskService.clearDetails(Task.NOTES.neq("")); //$NON-NLS-1$
if (from < V4_0_6)
new DueDateTimeMigrator().migrateDueTimes();
if (from < V4_4_2)
new SubtasksMetadataMigration().performMigration();
if (from < V4_6_0) {
if (Preferences.getBoolean(R.string.p_use_filters, false)) {
TodorooCursor<StoreObject> cursor = PluginServices.getStoreObjectDao().query(Query.select(StoreObject.PROPERTIES).where(
StoreObject.TYPE.eq(SavedFilter.TYPE)).limit(1));
try {
if (cursor.getCount() == 0)
Preferences.setBoolean(R.string.p_use_filters, false);
} finally {
cursor.close();
}
}
new AstridNewSyncMigrator().performMigration();
new GCMIntentService.GCMMigration().performMigration(UpgradeActivity.this);
}
} finally {
finished = true;
DialogUtilities.dismissDialog(UpgradeActivity.this, dialog);
sendBroadcast(new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH));
setResult(AstridActivity.RESULT_RESTART_ACTIVITY);
finish();
}
};
}.start();
} else {
finished = true;
finish();
}
}
@Override
public void onBackPressed() {
// Don't allow the back button to finish this activity before things are done
if (finished)
super.onBackPressed();
}
}
private void inlineUpgrades(Context context, int from) {
if (from < V4_5_1) {
String key = context.getString(R.string.p_taskRowStyle);
if (Preferences.isSet(key)) {
boolean value = Preferences.getBoolean(key, false);
Preferences.clear(key);
Preferences.setString(R.string.p_taskRowStyle_v2, value ? "1" : "0"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
/**
* Return a change log string. Releases occur often enough that we don't
* expect change sets to be localized.
*
* @param from
* @param to
* @return
*/
@SuppressWarnings("nls")
public void showChangeLog(Context context, int from) {
if(!(context instanceof Activity) || from == 0)
return;
Preferences.clear(TagCaseMigrator.PREF_SHOW_MIGRATION_ALERT);
Preferences.clear(AstridPreferences.P_UPGRADE_FROM);
StringBuilder changeLog = new StringBuilder();
if (from < V4_6_0) {
newVersionString(changeLog, "4.6.0 (4/01/13)", new String[] {
"4.6 is a big step towards FLAWLESS sync with Astrid.com! This update also includes numerous bug fixes and UI improvements. " +
- "Note: Simultaneous sync with Google Tasks and Astrid.com is no longer supported. Still want to with your tasks in Gmail? Remind Me by Astrid on the Chrome Store."
+ "Note: Simultaneous sync with Google Tasks and Astrid.com is no longer supported. Still want to view your tasks in Gmail? Try Remind Me by Astrid on the Chrome Store."
});
}
if (from >= V4_5_0 && from < V4_5_3) {
newVersionString(changeLog, "4.5.3 (2/04/13)", new String[] {
"Performance improvements when scrolling in lists",
"Some crash fixes"
});
}
if (from >= V4_5_0 && from < V4_5_2) {
newVersionString(changeLog, "4.5.2 (1/17/13)", new String[] {
"Fixed a crash that could affect some Google Tasks users",
"UI polish"
});
}
if (from >= V4_5_0 && from < V4_5_1) {
newVersionString(changeLog, "4.5.1 (1/16/13)", new String[] {
"New 'Titles only' style option for task lists (Settings > Appearance > Task row appearance)",
"Bug and crash fixes"
});
}
if (from < V4_5_0) {
newVersionString(changeLog, "4.5.0 (12/19/12)", new String[] {
"Several interface and usability enhancements",
"Fixed Power Pack display bug affecting certain phones",
"Better organized preferences",
"New 'Sky Blue' theme",
"'Lite mode' preference defaults available in Settings > Appearance > Set configuration",
"Minor bug and crash fixes"
});
}
if (from >= V4_4_4 && from < V4_4_4_1) {
newVersionString(changeLog, "4.4.4.1 (12/13/12)", new String[] {
"Crash fixes"
});
}
if (from >= V4_4 && from < V4_4_4) {
newVersionString(changeLog, "4.4.4 (12/12/12)", new String[] {
"Manual ordering and subtasks for 'Active Tasks' and 'Today' filters now sync with Astrid.com",
"Minor polish and bug fixes"
});
}
if (from >= V4_4 && from < V4_4_3) {
newVersionString(changeLog, "4.4.3 (11/28/12)", new String[] {
"Minor bug fixes"
});
}
if (from < V4_4_2) {
newVersionString(changeLog, "4.4.2 (11/19/12)", new String[] {
"Manual order and subtasks for lists now sync with your Astrid.com account!",
"Significant performance improvements to manual ordering and subtasks",
"Show assigned user images in the premium widgets",
"Minor bug and crash fixes"
});
}
if (from >= V4_4 && from < V4_4_1) {
newVersionString(changeLog, "4.4.1 (10/30/12)", new String[] {
"Fixed an issue where the calendar assistant could remind you about the wrong events",
"Fixed a crash that could occur when swipe between lists is enabled"
});
}
if (from < V4_4) {
newVersionString(changeLog, "4.4 (10/25/12)", new String[] {
"Astrid calendar assistant will help you prepare for meetings! Enable or " +
"disable in Settings -> Premium and misc. settings -> Calendar assistant",
"Full Chinese translation",
"Widgets will now reflect manual ordering",
"Accept pending friend requests from the people view",
"Several minor bug and crash fixes"
});
}
if (from >= V4_3_0 && from < V4_3_4) {
newVersionString(changeLog, "4.3.4 (10/2/12)", new String[] {
"Magic words in task title now correctly removed when placed in parentheses",
"Bug fix for viewing Featured Lists with swipe enabled",
"Bug fixes for rare crashes"
});
}
if (from >= V4_3_0 && from < V4_3_3) {
newVersionString(changeLog, "4.3.3 (9/19/12)", new String[] {
"Reverse sort works again!",
"Swipe between lists is faster",
"Option for a new style of task row (Try it: Settings -> Appearance -> Task row appearance and choose \"Simple\")",
"A few other small bugs fixed"
});
}
if (from >= V4_3_0 && from < V4_3_2) {
newVersionString(changeLog, "4.3.2 (9/07/12)", new String[] {
"Fixed issues with Google Tasks shortcuts"
});
}
if (from >= V4_3_0 && from < V4_3_1) {
newVersionString(changeLog, "4.3.1 (9/06/12)", new String[] {
"Fixed crashes for Google Tasks users and certain filters",
"Added ability to complete shared tasks from list view"
});
}
if (from < V4_3_0) {
newVersionString(changeLog, "4.3.0 (9/05/12)", new String[] {
"Significant performance improvements",
"Voice-add now enabled for all users!",
"New feature: Featured lists (Enable in Settings -> Appearance)",
"New and improved premium widget design",
"Redesigned settings page",
"Improved translations",
"Lots of bug fixes and UI polish"
});
}
if (from >= V4_2_0 && from < V4_2_6) {
newVersionString(changeLog, "4.2.6 (8/14/12)", new String[] {
"Tablet users can opt to use the single-pane phone layout (Settings -> Astrid Labs)",
"Minor polish and bug fixes"
});
}
if (from >= V4_2_0 && from < V4_2_5) {
newVersionString(changeLog, "4.2.5 (8/13/12)", new String[] {
"Improved tablet UX",
"More customizable task edit screen",
"Add to calendar now starts at task due time (by default)",
"Updated translations for several languages",
"Numerous bug fixes"
});
}
if (from >= V4_2_0 && from < V4_2_4) {
newVersionString(changeLog, "4.2.4 (7/11/12)", new String[] {
"Ability to specify end date on repeating tasks",
"Improved sync of comments made while offline",
"Crash fixes"
});
}
if (from >= V4_2_0 && from < V4_2_3) {
newVersionString(changeLog, "4.2.3 (6/25/12)", new String[] {
"Fixes for Google Tasks and Astrid.com sync",
"New layout for tablets in portrait mode",
"Minor UI polish and bugfixes"
});
}
if (from >= V4_2_0 && from < V4_2_2_1) {
newVersionString(changeLog, "4.2.2.1 (6/13/12)", new String[] {
"Fixed a crash affecting the Nook"
});
}
if (from >= V4_2_0 && from < V4_2_2) {
newVersionString(changeLog, "4.2.2 (6/12/12)", new String[] {
"Fix for people views displaying the wrong list of tasks",
"Fixed a bug with Astrid Smart Sort",
"Fixed a bug when adding photo comments"
});
}
if (from >= V4_2_0 && from < V4_2_1) {
newVersionString(changeLog, "4.2.1 (6/08/12)", new String[] {
"Fix for MyTouch 4G Lists",
"Fixed a crash when adding tasks with due times to Google Calendar",
"Better syncing of the people list",
"Minor UI polish and bugfixes"
});
}
if (from < V4_2_0) {
newVersionString(changeLog, "4.2.0 (6/05/12)", new String[] {
"Support for the Nook",
"Fixed crash on large image attachments",
"Minor bugfixes"
});
}
if (from >= V4_1_3 && from < V4_1_3_1) {
newVersionString(changeLog, "4.1.3.1 (5/18/12)", new String[] {
"Fixed reminders for ICS"
});
}
if (from >= V4_1_2 && from < V4_1_3) {
newVersionString(changeLog, "4.1.3 (5/17/12)", new String[] {
"Added ability to see shared tasks sorted by friend! Enable or disable " +
"in Settings > Astrid Labs",
"Fixed desktop shortcuts",
"Fixed adding tasks from the Power Pack widget",
"Fixed selecting photos on the Kindle Fire",
"Various other minor bug and crash fixes"
});
}
if (from >= V4_1_1 && from < V4_1_2) {
newVersionString(changeLog, "4.1.2 (5/05/12)", new String[] {
"Fixed some crashes and minor bugs"
});
}
if (from < V4_1_1) {
newVersionString(changeLog, "4.1.1 (5/04/12)", new String[] {
"Respond to or set reminders for missed calls. This feature requires a new permission to read " +
"the phone state.",
});
}
if (from < V4_1_0) {
newVersionString(changeLog, "4.1.0 (5/03/12)", new String[] {
"Swipe between lists! Swipe left and right to move through your lists. Enable or adjust " +
"in Settings > Astrid Labs",
"Assign tasks to contacts without typing",
"Links to tasks in comments",
"Astrid.com sync improvements",
"Other minor bugfixes",
});
}
if (from >= V4_0_6 && from < V4_0_6_2) {
newVersionString(changeLog, "4.0.6.2 (4/03/12)", new String[] {
"Minor fix to backup migration fix to handle deleted tasks as well as completed tasks."
});
}
if (from >= V4_0_6 && from < V4_0_6_1) {
newVersionString(changeLog, "4.0.6.1 (4/03/12)", new String[] {
"Fixed a bug where old tasks could become uncompleted. Sorry to those of you" +
" who were affected by this! To recover, you can import your old tasks" +
" from any backup file created before April 3 by clicking Menu -> Settings ->" +
" Backups -> Manage Backups -> Import Tasks. Backup files from April 3 will start" +
" with 'auto.120403'."
});
}
if (from < V4_0_6) {
newVersionString(changeLog, "4.0.6 (4/02/12)", new String[] {
"Fixes and performance improvements to Astrid.com and Google Tasks sync",
"Google TV support! (Beta)",
"Fixed a bug that could put duetimes on tasks when changing timezones",
"Fixed a rare crash when starting a task timer"
});
}
if (from >= V4_0_0 && from < V4_0_5) {
newVersionString(changeLog, "4.0.5 (3/22/12)", new String[] {
"Better conflict resolution for Astrid.com sync",
"Fixes and improvements to Gtasks sync",
"Added option to report sync errors in sync preference screen"
});
}
if (from >= V4_0_0 && from < V4_0_4) {
newVersionString(changeLog, "4.0.4 (3/7/12)", new String[] {
"Fixed crashes related to error reporting",
"Fixed a crash when creating a task from the widget",
"Fixed a bug where a manual sync wouldn't always start"
});
}
if (from >= V4_0_0 && from < V4_0_3) {
newVersionString(changeLog, "4.0.3 (3/6/12)", new String[] {
"Fix some issues with Google Tasks sync. We're sorry to " +
"everyone who's been having trouble with it!",
"Updated translations for Portuguese, Chinese, German, Russian, and Dutch",
"Centralize Android's menu key with in-app navigation",
"Fixed crashes & improve crash logging",
});
}
if (from >= V4_0_0 && from < V4_0_2) {
newVersionString(changeLog, "4.0.2 (2/29/12)", new String[] {
"Removed GPS permission - no longer needed",
"Fixes for some subtasks issues",
"No longer need to run the Crittercism service in the background",
"Fixed a crash that could occur when cloning tasks",
"Fixed a bug that prevented certain comments from syncing correctly",
"Fixed issues where voice add wouldn't work correctly",
});
}
if (from >= V4_0_0 && from < V4_0_1) {
newVersionString(changeLog, "4.0.1 (2/23/12)", new String[] {
"Fixed a database issue affecting Android 2.1 users",
"Fixed a crash when using drag and drop in Google Tasks lists",
"Other small bugfixes"
});
}
if (from < V4_0_0) {
newVersionString(changeLog, "4.0.0 (2/23/12)", new String[] {
"Welcome to Astrid 4.0! Here's what's new:",
"<b>Subtasks!!!</b><br>Press the Menu key and select 'Sort' to access",
"<b>New Look!</b><br>Customize how Astrid looks from the Settings menu",
"<b>Task Rabbit!</b><br>Outsource your tasks with the help of trustworthy people",
"<b>More Reliable Sync</b><br>Including fixes to Astrid.com and Google Tasks sync",
"<b>Tablet version</b><br>Enjoy Astrid on your luxurious Android tablet",
"Many bug and usability fixes"
});
}
// --- old messages
if (from >= V3_0_0 && from < V3_9_0) {
newVersionString(changeLog, "3.9 (12/09/11)", new String[] {
"Cleaner design (especially the task edit page)!",
"Customize the edit page (\"Beast Mode\" in preferences)",
"Make shared lists with tasks open to anyone (perfect for potlucks, road trips etc)",
"Fixes for some ICS crashes (full support coming soon)",
"Google Tasks sync improvement - Note: If you have been experiencing \"Sync with errors\", try logging out and logging back in to Google Tasks.",
"Other minor bug fixes",
"Feedback welcomed!"
});
}
if(from >= V3_0_0 && from < V3_8_0) {
newVersionString(changeLog, "3.8.0 (7/15/11)", new String[] {
"Astrid.com: sync & share tasks / lists with others!",
"GTasks Sync using Google's official task API! Gtasks users " +
"will need to perform a manual sync to set everything up.",
"Renamed \"Tags\" to \"Lists\" (see blog.astrid.com for details)",
"New style for \"Task Edit\" page!",
"Purge completed or deleted tasks from settings menu!",
});
gtasksPreferenceService.setToken(null);
}
if(from >= V3_0_0 && from < V3_7_0) {
newVersionString(changeLog, "3.7.0 (2/7/11)", new String[] {
"Improved UI for displaying task actions. Tap a task to " +
"bring up actions, tap again to dismiss.",
"Task notes can be viewed by tapping the note icon to " +
"the right of the task.",
"Added Astrid as 'Send-To' choice in Android Browser and " +
"other apps.",
"Add tags and importance in quick-add, e.g. " +
"\"call mom #family @phone !4\"",
"Fixed bug with custom filters & tasks being hidden.",
});
upgrade3To3_7();
if(gtasksPreferenceService.isLoggedIn())
taskService.clearDetails(Criterion.all);
Preferences.setBoolean(Eula.PREFERENCE_EULA_ACCEPTED, true);
}
if(from >= V3_0_0 && from < V3_6_0) {
newVersionString(changeLog, "3.6.0 (11/13/10)", new String[] {
"Astrid Power Pack is now launched to the Android Market. " +
"New Power Pack features include 4x2 and 4x4 widgets and voice " +
"task reminders and creation. Go to the add-ons page to find out more!",
"Fix for Google Tasks: due times got lost on sync, repeating tasks not repeated",
"Fix for task alarms not always firing if multiple set",
"Fix for various force closes",
});
upgrade3To3_6(context);
}
if(from >= V3_0_0 && from < V3_5_0)
newVersionString(changeLog, "3.5.0 (10/25/10)", new String[] {
"Google Tasks Sync (beta!)",
"Bug fix with RMilk & new tasks not getting synced",
"Fixed Force Closes and other bugs",
});
if(from >= V3_0_0 && from < V3_4_0) {
newVersionString(changeLog, "3.4.0 (10/08/10)", new String[] {
"End User License Agreement",
"Option to disable usage statistics",
"Bug fixes with Producteev",
});
}
if(from >= V3_0_0 && from < V3_3_0)
newVersionString(changeLog, "3.3.0 (9/17/10)", new String[] {
"Fixed some RTM duplicated tasks issues",
"UI updates based on your feedback",
"Snooze now overrides other alarms",
"Added preference option for selecting snooze style",
"Hide until: now allows you to pick a specific time",
});
if(from >= V3_0_0 && from < V3_2_0)
newVersionString(changeLog, "3.2.0 (8/16/10)", new String[] {
"Build your own custom filters from the Filter page",
"Easy task sorting (in the task list menu)",
"Create widgets from any of your filters",
"Synchronize with Producteev! (producteev.com)",
"Select tags by drop-down box",
"Cosmetic improvements, calendar & sync bug fixes",
});
if(from >= V3_0_0 && from < V3_1_0)
newVersionString(changeLog, "3.1.0 (8/9/10)", new String[] {
"Linkify phone numbers, e-mails, and web pages",
"Swipe L => R to go from tasks to filters",
"Moved task priority bar to left side",
"Added ability to create fixed alerts for a task",
"Restored tag hiding when tag begins with underscore (_)",
"FROYO: disabled moving app to SD card, it would break alarms and widget",
"Also gone: a couple force closes, bugs with repeating tasks",
});
if(changeLog.length() == 0)
return;
changeLog.append("Enjoy!</body></html>");
String color = ThemeService.getDialogTextColorString();
String changeLogHtml = "<html><body style='color: " + color +"'>" + changeLog;
DialogUtilities.htmlDialog(context, changeLogHtml,
R.string.UpS_changelog_title);
}
/**
* Helper for adding a single version to the changelog
* @param changeLog
* @param version
* @param changes
*/
@SuppressWarnings("nls")
private void newVersionString(StringBuilder changeLog, String version, String[] changes) {
if (Constants.ASTRID_LITE)
version = "0" + version.substring(1);
changeLog.append("<font style='text-align: center; color=#ffaa00'><b>Version ").append(version).append(":</b></font><br><ul>");
for(String change : changes)
changeLog.append("<li>").append(change).append("</li>\n");
changeLog.append("</ul>");
}
// --- upgrade functions
/**
* Fixes task filter missing tasks bug, migrate PDV/RTM notes
*/
@SuppressWarnings("nls")
private void upgrade3To3_7() {
TodorooCursor<Task> t = taskService.query(Query.select(Task.ID, Task.DUE_DATE).where(Task.DUE_DATE.gt(0)));
Task task = new Task();
for(t.moveToFirst(); !t.isAfterLast(); t.moveToNext()) {
task.readFromCursor(t);
if(task.hasDueDate()) {
task.setValue(Task.DUE_DATE, task.getValue(Task.DUE_DATE) / 1000L * 1000L);
taskService.save(task);
}
}
t.close();
}
/**
* Moves sorting prefs to public pref store
* @param context
*/
private void upgrade3To3_6(final Context context) {
SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(context);
Editor editor = publicPrefs.edit();
editor.putInt(SortHelper.PREF_SORT_FLAGS,
Preferences.getInt(SortHelper.PREF_SORT_FLAGS, 0));
editor.putInt(SortHelper.PREF_SORT_SORT,
Preferences.getInt(SortHelper.PREF_SORT_SORT, 0));
editor.commit();
}
// --- secondary upgrade
/**
* If primary upgrade doesn't work for some reason (corrupt SharedPreferences,
* for example), this will catch some cases
*/
public void performSecondaryUpgrade(Context context) {
if(!context.getDatabasePath(database.getName()).exists() &&
context.getDatabasePath("tasks").exists()) { //$NON-NLS-1$
new Astrid2To3UpgradeHelper().upgrade2To3(context, 1);
}
}
}
| true | true | public void showChangeLog(Context context, int from) {
if(!(context instanceof Activity) || from == 0)
return;
Preferences.clear(TagCaseMigrator.PREF_SHOW_MIGRATION_ALERT);
Preferences.clear(AstridPreferences.P_UPGRADE_FROM);
StringBuilder changeLog = new StringBuilder();
if (from < V4_6_0) {
newVersionString(changeLog, "4.6.0 (4/01/13)", new String[] {
"4.6 is a big step towards FLAWLESS sync with Astrid.com! This update also includes numerous bug fixes and UI improvements. " +
"Note: Simultaneous sync with Google Tasks and Astrid.com is no longer supported. Still want to with your tasks in Gmail? Remind Me by Astrid on the Chrome Store."
});
}
if (from >= V4_5_0 && from < V4_5_3) {
newVersionString(changeLog, "4.5.3 (2/04/13)", new String[] {
"Performance improvements when scrolling in lists",
"Some crash fixes"
});
}
if (from >= V4_5_0 && from < V4_5_2) {
newVersionString(changeLog, "4.5.2 (1/17/13)", new String[] {
"Fixed a crash that could affect some Google Tasks users",
"UI polish"
});
}
if (from >= V4_5_0 && from < V4_5_1) {
newVersionString(changeLog, "4.5.1 (1/16/13)", new String[] {
"New 'Titles only' style option for task lists (Settings > Appearance > Task row appearance)",
"Bug and crash fixes"
});
}
if (from < V4_5_0) {
newVersionString(changeLog, "4.5.0 (12/19/12)", new String[] {
"Several interface and usability enhancements",
"Fixed Power Pack display bug affecting certain phones",
"Better organized preferences",
"New 'Sky Blue' theme",
"'Lite mode' preference defaults available in Settings > Appearance > Set configuration",
"Minor bug and crash fixes"
});
}
if (from >= V4_4_4 && from < V4_4_4_1) {
newVersionString(changeLog, "4.4.4.1 (12/13/12)", new String[] {
"Crash fixes"
});
}
if (from >= V4_4 && from < V4_4_4) {
newVersionString(changeLog, "4.4.4 (12/12/12)", new String[] {
"Manual ordering and subtasks for 'Active Tasks' and 'Today' filters now sync with Astrid.com",
"Minor polish and bug fixes"
});
}
if (from >= V4_4 && from < V4_4_3) {
newVersionString(changeLog, "4.4.3 (11/28/12)", new String[] {
"Minor bug fixes"
});
}
if (from < V4_4_2) {
newVersionString(changeLog, "4.4.2 (11/19/12)", new String[] {
"Manual order and subtasks for lists now sync with your Astrid.com account!",
"Significant performance improvements to manual ordering and subtasks",
"Show assigned user images in the premium widgets",
"Minor bug and crash fixes"
});
}
if (from >= V4_4 && from < V4_4_1) {
newVersionString(changeLog, "4.4.1 (10/30/12)", new String[] {
"Fixed an issue where the calendar assistant could remind you about the wrong events",
"Fixed a crash that could occur when swipe between lists is enabled"
});
}
if (from < V4_4) {
newVersionString(changeLog, "4.4 (10/25/12)", new String[] {
"Astrid calendar assistant will help you prepare for meetings! Enable or " +
"disable in Settings -> Premium and misc. settings -> Calendar assistant",
"Full Chinese translation",
"Widgets will now reflect manual ordering",
"Accept pending friend requests from the people view",
"Several minor bug and crash fixes"
});
}
if (from >= V4_3_0 && from < V4_3_4) {
newVersionString(changeLog, "4.3.4 (10/2/12)", new String[] {
"Magic words in task title now correctly removed when placed in parentheses",
"Bug fix for viewing Featured Lists with swipe enabled",
"Bug fixes for rare crashes"
});
}
if (from >= V4_3_0 && from < V4_3_3) {
newVersionString(changeLog, "4.3.3 (9/19/12)", new String[] {
"Reverse sort works again!",
"Swipe between lists is faster",
"Option for a new style of task row (Try it: Settings -> Appearance -> Task row appearance and choose \"Simple\")",
"A few other small bugs fixed"
});
}
if (from >= V4_3_0 && from < V4_3_2) {
newVersionString(changeLog, "4.3.2 (9/07/12)", new String[] {
"Fixed issues with Google Tasks shortcuts"
});
}
if (from >= V4_3_0 && from < V4_3_1) {
newVersionString(changeLog, "4.3.1 (9/06/12)", new String[] {
"Fixed crashes for Google Tasks users and certain filters",
"Added ability to complete shared tasks from list view"
});
}
if (from < V4_3_0) {
newVersionString(changeLog, "4.3.0 (9/05/12)", new String[] {
"Significant performance improvements",
"Voice-add now enabled for all users!",
"New feature: Featured lists (Enable in Settings -> Appearance)",
"New and improved premium widget design",
"Redesigned settings page",
"Improved translations",
"Lots of bug fixes and UI polish"
});
}
if (from >= V4_2_0 && from < V4_2_6) {
newVersionString(changeLog, "4.2.6 (8/14/12)", new String[] {
"Tablet users can opt to use the single-pane phone layout (Settings -> Astrid Labs)",
"Minor polish and bug fixes"
});
}
if (from >= V4_2_0 && from < V4_2_5) {
newVersionString(changeLog, "4.2.5 (8/13/12)", new String[] {
"Improved tablet UX",
"More customizable task edit screen",
"Add to calendar now starts at task due time (by default)",
"Updated translations for several languages",
"Numerous bug fixes"
});
}
if (from >= V4_2_0 && from < V4_2_4) {
newVersionString(changeLog, "4.2.4 (7/11/12)", new String[] {
"Ability to specify end date on repeating tasks",
"Improved sync of comments made while offline",
"Crash fixes"
});
}
if (from >= V4_2_0 && from < V4_2_3) {
newVersionString(changeLog, "4.2.3 (6/25/12)", new String[] {
"Fixes for Google Tasks and Astrid.com sync",
"New layout for tablets in portrait mode",
"Minor UI polish and bugfixes"
});
}
if (from >= V4_2_0 && from < V4_2_2_1) {
newVersionString(changeLog, "4.2.2.1 (6/13/12)", new String[] {
"Fixed a crash affecting the Nook"
});
}
if (from >= V4_2_0 && from < V4_2_2) {
newVersionString(changeLog, "4.2.2 (6/12/12)", new String[] {
"Fix for people views displaying the wrong list of tasks",
"Fixed a bug with Astrid Smart Sort",
"Fixed a bug when adding photo comments"
});
}
if (from >= V4_2_0 && from < V4_2_1) {
newVersionString(changeLog, "4.2.1 (6/08/12)", new String[] {
"Fix for MyTouch 4G Lists",
"Fixed a crash when adding tasks with due times to Google Calendar",
"Better syncing of the people list",
"Minor UI polish and bugfixes"
});
}
if (from < V4_2_0) {
newVersionString(changeLog, "4.2.0 (6/05/12)", new String[] {
"Support for the Nook",
"Fixed crash on large image attachments",
"Minor bugfixes"
});
}
if (from >= V4_1_3 && from < V4_1_3_1) {
newVersionString(changeLog, "4.1.3.1 (5/18/12)", new String[] {
"Fixed reminders for ICS"
});
}
if (from >= V4_1_2 && from < V4_1_3) {
newVersionString(changeLog, "4.1.3 (5/17/12)", new String[] {
"Added ability to see shared tasks sorted by friend! Enable or disable " +
"in Settings > Astrid Labs",
"Fixed desktop shortcuts",
"Fixed adding tasks from the Power Pack widget",
"Fixed selecting photos on the Kindle Fire",
"Various other minor bug and crash fixes"
});
}
if (from >= V4_1_1 && from < V4_1_2) {
newVersionString(changeLog, "4.1.2 (5/05/12)", new String[] {
"Fixed some crashes and minor bugs"
});
}
if (from < V4_1_1) {
newVersionString(changeLog, "4.1.1 (5/04/12)", new String[] {
"Respond to or set reminders for missed calls. This feature requires a new permission to read " +
"the phone state.",
});
}
if (from < V4_1_0) {
newVersionString(changeLog, "4.1.0 (5/03/12)", new String[] {
"Swipe between lists! Swipe left and right to move through your lists. Enable or adjust " +
"in Settings > Astrid Labs",
"Assign tasks to contacts without typing",
"Links to tasks in comments",
"Astrid.com sync improvements",
"Other minor bugfixes",
});
}
if (from >= V4_0_6 && from < V4_0_6_2) {
newVersionString(changeLog, "4.0.6.2 (4/03/12)", new String[] {
"Minor fix to backup migration fix to handle deleted tasks as well as completed tasks."
});
}
if (from >= V4_0_6 && from < V4_0_6_1) {
newVersionString(changeLog, "4.0.6.1 (4/03/12)", new String[] {
"Fixed a bug where old tasks could become uncompleted. Sorry to those of you" +
" who were affected by this! To recover, you can import your old tasks" +
" from any backup file created before April 3 by clicking Menu -> Settings ->" +
" Backups -> Manage Backups -> Import Tasks. Backup files from April 3 will start" +
" with 'auto.120403'."
});
}
if (from < V4_0_6) {
newVersionString(changeLog, "4.0.6 (4/02/12)", new String[] {
"Fixes and performance improvements to Astrid.com and Google Tasks sync",
"Google TV support! (Beta)",
"Fixed a bug that could put duetimes on tasks when changing timezones",
"Fixed a rare crash when starting a task timer"
});
}
if (from >= V4_0_0 && from < V4_0_5) {
newVersionString(changeLog, "4.0.5 (3/22/12)", new String[] {
"Better conflict resolution for Astrid.com sync",
"Fixes and improvements to Gtasks sync",
"Added option to report sync errors in sync preference screen"
});
}
if (from >= V4_0_0 && from < V4_0_4) {
newVersionString(changeLog, "4.0.4 (3/7/12)", new String[] {
"Fixed crashes related to error reporting",
"Fixed a crash when creating a task from the widget",
"Fixed a bug where a manual sync wouldn't always start"
});
}
if (from >= V4_0_0 && from < V4_0_3) {
newVersionString(changeLog, "4.0.3 (3/6/12)", new String[] {
"Fix some issues with Google Tasks sync. We're sorry to " +
"everyone who's been having trouble with it!",
"Updated translations for Portuguese, Chinese, German, Russian, and Dutch",
"Centralize Android's menu key with in-app navigation",
"Fixed crashes & improve crash logging",
});
}
if (from >= V4_0_0 && from < V4_0_2) {
newVersionString(changeLog, "4.0.2 (2/29/12)", new String[] {
"Removed GPS permission - no longer needed",
"Fixes for some subtasks issues",
"No longer need to run the Crittercism service in the background",
"Fixed a crash that could occur when cloning tasks",
"Fixed a bug that prevented certain comments from syncing correctly",
"Fixed issues where voice add wouldn't work correctly",
});
}
if (from >= V4_0_0 && from < V4_0_1) {
newVersionString(changeLog, "4.0.1 (2/23/12)", new String[] {
"Fixed a database issue affecting Android 2.1 users",
"Fixed a crash when using drag and drop in Google Tasks lists",
"Other small bugfixes"
});
}
if (from < V4_0_0) {
newVersionString(changeLog, "4.0.0 (2/23/12)", new String[] {
"Welcome to Astrid 4.0! Here's what's new:",
"<b>Subtasks!!!</b><br>Press the Menu key and select 'Sort' to access",
"<b>New Look!</b><br>Customize how Astrid looks from the Settings menu",
"<b>Task Rabbit!</b><br>Outsource your tasks with the help of trustworthy people",
"<b>More Reliable Sync</b><br>Including fixes to Astrid.com and Google Tasks sync",
"<b>Tablet version</b><br>Enjoy Astrid on your luxurious Android tablet",
"Many bug and usability fixes"
});
}
// --- old messages
if (from >= V3_0_0 && from < V3_9_0) {
newVersionString(changeLog, "3.9 (12/09/11)", new String[] {
"Cleaner design (especially the task edit page)!",
"Customize the edit page (\"Beast Mode\" in preferences)",
"Make shared lists with tasks open to anyone (perfect for potlucks, road trips etc)",
"Fixes for some ICS crashes (full support coming soon)",
"Google Tasks sync improvement - Note: If you have been experiencing \"Sync with errors\", try logging out and logging back in to Google Tasks.",
"Other minor bug fixes",
"Feedback welcomed!"
});
}
if(from >= V3_0_0 && from < V3_8_0) {
newVersionString(changeLog, "3.8.0 (7/15/11)", new String[] {
"Astrid.com: sync & share tasks / lists with others!",
"GTasks Sync using Google's official task API! Gtasks users " +
"will need to perform a manual sync to set everything up.",
"Renamed \"Tags\" to \"Lists\" (see blog.astrid.com for details)",
"New style for \"Task Edit\" page!",
"Purge completed or deleted tasks from settings menu!",
});
gtasksPreferenceService.setToken(null);
}
if(from >= V3_0_0 && from < V3_7_0) {
newVersionString(changeLog, "3.7.0 (2/7/11)", new String[] {
"Improved UI for displaying task actions. Tap a task to " +
"bring up actions, tap again to dismiss.",
"Task notes can be viewed by tapping the note icon to " +
"the right of the task.",
"Added Astrid as 'Send-To' choice in Android Browser and " +
"other apps.",
"Add tags and importance in quick-add, e.g. " +
"\"call mom #family @phone !4\"",
"Fixed bug with custom filters & tasks being hidden.",
});
upgrade3To3_7();
if(gtasksPreferenceService.isLoggedIn())
taskService.clearDetails(Criterion.all);
Preferences.setBoolean(Eula.PREFERENCE_EULA_ACCEPTED, true);
}
if(from >= V3_0_0 && from < V3_6_0) {
newVersionString(changeLog, "3.6.0 (11/13/10)", new String[] {
"Astrid Power Pack is now launched to the Android Market. " +
"New Power Pack features include 4x2 and 4x4 widgets and voice " +
"task reminders and creation. Go to the add-ons page to find out more!",
"Fix for Google Tasks: due times got lost on sync, repeating tasks not repeated",
"Fix for task alarms not always firing if multiple set",
"Fix for various force closes",
});
upgrade3To3_6(context);
}
if(from >= V3_0_0 && from < V3_5_0)
newVersionString(changeLog, "3.5.0 (10/25/10)", new String[] {
"Google Tasks Sync (beta!)",
"Bug fix with RMilk & new tasks not getting synced",
"Fixed Force Closes and other bugs",
});
if(from >= V3_0_0 && from < V3_4_0) {
newVersionString(changeLog, "3.4.0 (10/08/10)", new String[] {
"End User License Agreement",
"Option to disable usage statistics",
"Bug fixes with Producteev",
});
}
if(from >= V3_0_0 && from < V3_3_0)
newVersionString(changeLog, "3.3.0 (9/17/10)", new String[] {
"Fixed some RTM duplicated tasks issues",
"UI updates based on your feedback",
"Snooze now overrides other alarms",
"Added preference option for selecting snooze style",
"Hide until: now allows you to pick a specific time",
});
if(from >= V3_0_0 && from < V3_2_0)
newVersionString(changeLog, "3.2.0 (8/16/10)", new String[] {
"Build your own custom filters from the Filter page",
"Easy task sorting (in the task list menu)",
"Create widgets from any of your filters",
"Synchronize with Producteev! (producteev.com)",
"Select tags by drop-down box",
"Cosmetic improvements, calendar & sync bug fixes",
});
if(from >= V3_0_0 && from < V3_1_0)
newVersionString(changeLog, "3.1.0 (8/9/10)", new String[] {
"Linkify phone numbers, e-mails, and web pages",
"Swipe L => R to go from tasks to filters",
"Moved task priority bar to left side",
"Added ability to create fixed alerts for a task",
"Restored tag hiding when tag begins with underscore (_)",
"FROYO: disabled moving app to SD card, it would break alarms and widget",
"Also gone: a couple force closes, bugs with repeating tasks",
});
if(changeLog.length() == 0)
return;
changeLog.append("Enjoy!</body></html>");
String color = ThemeService.getDialogTextColorString();
String changeLogHtml = "<html><body style='color: " + color +"'>" + changeLog;
DialogUtilities.htmlDialog(context, changeLogHtml,
R.string.UpS_changelog_title);
}
| public void showChangeLog(Context context, int from) {
if(!(context instanceof Activity) || from == 0)
return;
Preferences.clear(TagCaseMigrator.PREF_SHOW_MIGRATION_ALERT);
Preferences.clear(AstridPreferences.P_UPGRADE_FROM);
StringBuilder changeLog = new StringBuilder();
if (from < V4_6_0) {
newVersionString(changeLog, "4.6.0 (4/01/13)", new String[] {
"4.6 is a big step towards FLAWLESS sync with Astrid.com! This update also includes numerous bug fixes and UI improvements. " +
"Note: Simultaneous sync with Google Tasks and Astrid.com is no longer supported. Still want to view your tasks in Gmail? Try Remind Me by Astrid on the Chrome Store."
});
}
if (from >= V4_5_0 && from < V4_5_3) {
newVersionString(changeLog, "4.5.3 (2/04/13)", new String[] {
"Performance improvements when scrolling in lists",
"Some crash fixes"
});
}
if (from >= V4_5_0 && from < V4_5_2) {
newVersionString(changeLog, "4.5.2 (1/17/13)", new String[] {
"Fixed a crash that could affect some Google Tasks users",
"UI polish"
});
}
if (from >= V4_5_0 && from < V4_5_1) {
newVersionString(changeLog, "4.5.1 (1/16/13)", new String[] {
"New 'Titles only' style option for task lists (Settings > Appearance > Task row appearance)",
"Bug and crash fixes"
});
}
if (from < V4_5_0) {
newVersionString(changeLog, "4.5.0 (12/19/12)", new String[] {
"Several interface and usability enhancements",
"Fixed Power Pack display bug affecting certain phones",
"Better organized preferences",
"New 'Sky Blue' theme",
"'Lite mode' preference defaults available in Settings > Appearance > Set configuration",
"Minor bug and crash fixes"
});
}
if (from >= V4_4_4 && from < V4_4_4_1) {
newVersionString(changeLog, "4.4.4.1 (12/13/12)", new String[] {
"Crash fixes"
});
}
if (from >= V4_4 && from < V4_4_4) {
newVersionString(changeLog, "4.4.4 (12/12/12)", new String[] {
"Manual ordering and subtasks for 'Active Tasks' and 'Today' filters now sync with Astrid.com",
"Minor polish and bug fixes"
});
}
if (from >= V4_4 && from < V4_4_3) {
newVersionString(changeLog, "4.4.3 (11/28/12)", new String[] {
"Minor bug fixes"
});
}
if (from < V4_4_2) {
newVersionString(changeLog, "4.4.2 (11/19/12)", new String[] {
"Manual order and subtasks for lists now sync with your Astrid.com account!",
"Significant performance improvements to manual ordering and subtasks",
"Show assigned user images in the premium widgets",
"Minor bug and crash fixes"
});
}
if (from >= V4_4 && from < V4_4_1) {
newVersionString(changeLog, "4.4.1 (10/30/12)", new String[] {
"Fixed an issue where the calendar assistant could remind you about the wrong events",
"Fixed a crash that could occur when swipe between lists is enabled"
});
}
if (from < V4_4) {
newVersionString(changeLog, "4.4 (10/25/12)", new String[] {
"Astrid calendar assistant will help you prepare for meetings! Enable or " +
"disable in Settings -> Premium and misc. settings -> Calendar assistant",
"Full Chinese translation",
"Widgets will now reflect manual ordering",
"Accept pending friend requests from the people view",
"Several minor bug and crash fixes"
});
}
if (from >= V4_3_0 && from < V4_3_4) {
newVersionString(changeLog, "4.3.4 (10/2/12)", new String[] {
"Magic words in task title now correctly removed when placed in parentheses",
"Bug fix for viewing Featured Lists with swipe enabled",
"Bug fixes for rare crashes"
});
}
if (from >= V4_3_0 && from < V4_3_3) {
newVersionString(changeLog, "4.3.3 (9/19/12)", new String[] {
"Reverse sort works again!",
"Swipe between lists is faster",
"Option for a new style of task row (Try it: Settings -> Appearance -> Task row appearance and choose \"Simple\")",
"A few other small bugs fixed"
});
}
if (from >= V4_3_0 && from < V4_3_2) {
newVersionString(changeLog, "4.3.2 (9/07/12)", new String[] {
"Fixed issues with Google Tasks shortcuts"
});
}
if (from >= V4_3_0 && from < V4_3_1) {
newVersionString(changeLog, "4.3.1 (9/06/12)", new String[] {
"Fixed crashes for Google Tasks users and certain filters",
"Added ability to complete shared tasks from list view"
});
}
if (from < V4_3_0) {
newVersionString(changeLog, "4.3.0 (9/05/12)", new String[] {
"Significant performance improvements",
"Voice-add now enabled for all users!",
"New feature: Featured lists (Enable in Settings -> Appearance)",
"New and improved premium widget design",
"Redesigned settings page",
"Improved translations",
"Lots of bug fixes and UI polish"
});
}
if (from >= V4_2_0 && from < V4_2_6) {
newVersionString(changeLog, "4.2.6 (8/14/12)", new String[] {
"Tablet users can opt to use the single-pane phone layout (Settings -> Astrid Labs)",
"Minor polish and bug fixes"
});
}
if (from >= V4_2_0 && from < V4_2_5) {
newVersionString(changeLog, "4.2.5 (8/13/12)", new String[] {
"Improved tablet UX",
"More customizable task edit screen",
"Add to calendar now starts at task due time (by default)",
"Updated translations for several languages",
"Numerous bug fixes"
});
}
if (from >= V4_2_0 && from < V4_2_4) {
newVersionString(changeLog, "4.2.4 (7/11/12)", new String[] {
"Ability to specify end date on repeating tasks",
"Improved sync of comments made while offline",
"Crash fixes"
});
}
if (from >= V4_2_0 && from < V4_2_3) {
newVersionString(changeLog, "4.2.3 (6/25/12)", new String[] {
"Fixes for Google Tasks and Astrid.com sync",
"New layout for tablets in portrait mode",
"Minor UI polish and bugfixes"
});
}
if (from >= V4_2_0 && from < V4_2_2_1) {
newVersionString(changeLog, "4.2.2.1 (6/13/12)", new String[] {
"Fixed a crash affecting the Nook"
});
}
if (from >= V4_2_0 && from < V4_2_2) {
newVersionString(changeLog, "4.2.2 (6/12/12)", new String[] {
"Fix for people views displaying the wrong list of tasks",
"Fixed a bug with Astrid Smart Sort",
"Fixed a bug when adding photo comments"
});
}
if (from >= V4_2_0 && from < V4_2_1) {
newVersionString(changeLog, "4.2.1 (6/08/12)", new String[] {
"Fix for MyTouch 4G Lists",
"Fixed a crash when adding tasks with due times to Google Calendar",
"Better syncing of the people list",
"Minor UI polish and bugfixes"
});
}
if (from < V4_2_0) {
newVersionString(changeLog, "4.2.0 (6/05/12)", new String[] {
"Support for the Nook",
"Fixed crash on large image attachments",
"Minor bugfixes"
});
}
if (from >= V4_1_3 && from < V4_1_3_1) {
newVersionString(changeLog, "4.1.3.1 (5/18/12)", new String[] {
"Fixed reminders for ICS"
});
}
if (from >= V4_1_2 && from < V4_1_3) {
newVersionString(changeLog, "4.1.3 (5/17/12)", new String[] {
"Added ability to see shared tasks sorted by friend! Enable or disable " +
"in Settings > Astrid Labs",
"Fixed desktop shortcuts",
"Fixed adding tasks from the Power Pack widget",
"Fixed selecting photos on the Kindle Fire",
"Various other minor bug and crash fixes"
});
}
if (from >= V4_1_1 && from < V4_1_2) {
newVersionString(changeLog, "4.1.2 (5/05/12)", new String[] {
"Fixed some crashes and minor bugs"
});
}
if (from < V4_1_1) {
newVersionString(changeLog, "4.1.1 (5/04/12)", new String[] {
"Respond to or set reminders for missed calls. This feature requires a new permission to read " +
"the phone state.",
});
}
if (from < V4_1_0) {
newVersionString(changeLog, "4.1.0 (5/03/12)", new String[] {
"Swipe between lists! Swipe left and right to move through your lists. Enable or adjust " +
"in Settings > Astrid Labs",
"Assign tasks to contacts without typing",
"Links to tasks in comments",
"Astrid.com sync improvements",
"Other minor bugfixes",
});
}
if (from >= V4_0_6 && from < V4_0_6_2) {
newVersionString(changeLog, "4.0.6.2 (4/03/12)", new String[] {
"Minor fix to backup migration fix to handle deleted tasks as well as completed tasks."
});
}
if (from >= V4_0_6 && from < V4_0_6_1) {
newVersionString(changeLog, "4.0.6.1 (4/03/12)", new String[] {
"Fixed a bug where old tasks could become uncompleted. Sorry to those of you" +
" who were affected by this! To recover, you can import your old tasks" +
" from any backup file created before April 3 by clicking Menu -> Settings ->" +
" Backups -> Manage Backups -> Import Tasks. Backup files from April 3 will start" +
" with 'auto.120403'."
});
}
if (from < V4_0_6) {
newVersionString(changeLog, "4.0.6 (4/02/12)", new String[] {
"Fixes and performance improvements to Astrid.com and Google Tasks sync",
"Google TV support! (Beta)",
"Fixed a bug that could put duetimes on tasks when changing timezones",
"Fixed a rare crash when starting a task timer"
});
}
if (from >= V4_0_0 && from < V4_0_5) {
newVersionString(changeLog, "4.0.5 (3/22/12)", new String[] {
"Better conflict resolution for Astrid.com sync",
"Fixes and improvements to Gtasks sync",
"Added option to report sync errors in sync preference screen"
});
}
if (from >= V4_0_0 && from < V4_0_4) {
newVersionString(changeLog, "4.0.4 (3/7/12)", new String[] {
"Fixed crashes related to error reporting",
"Fixed a crash when creating a task from the widget",
"Fixed a bug where a manual sync wouldn't always start"
});
}
if (from >= V4_0_0 && from < V4_0_3) {
newVersionString(changeLog, "4.0.3 (3/6/12)", new String[] {
"Fix some issues with Google Tasks sync. We're sorry to " +
"everyone who's been having trouble with it!",
"Updated translations for Portuguese, Chinese, German, Russian, and Dutch",
"Centralize Android's menu key with in-app navigation",
"Fixed crashes & improve crash logging",
});
}
if (from >= V4_0_0 && from < V4_0_2) {
newVersionString(changeLog, "4.0.2 (2/29/12)", new String[] {
"Removed GPS permission - no longer needed",
"Fixes for some subtasks issues",
"No longer need to run the Crittercism service in the background",
"Fixed a crash that could occur when cloning tasks",
"Fixed a bug that prevented certain comments from syncing correctly",
"Fixed issues where voice add wouldn't work correctly",
});
}
if (from >= V4_0_0 && from < V4_0_1) {
newVersionString(changeLog, "4.0.1 (2/23/12)", new String[] {
"Fixed a database issue affecting Android 2.1 users",
"Fixed a crash when using drag and drop in Google Tasks lists",
"Other small bugfixes"
});
}
if (from < V4_0_0) {
newVersionString(changeLog, "4.0.0 (2/23/12)", new String[] {
"Welcome to Astrid 4.0! Here's what's new:",
"<b>Subtasks!!!</b><br>Press the Menu key and select 'Sort' to access",
"<b>New Look!</b><br>Customize how Astrid looks from the Settings menu",
"<b>Task Rabbit!</b><br>Outsource your tasks with the help of trustworthy people",
"<b>More Reliable Sync</b><br>Including fixes to Astrid.com and Google Tasks sync",
"<b>Tablet version</b><br>Enjoy Astrid on your luxurious Android tablet",
"Many bug and usability fixes"
});
}
// --- old messages
if (from >= V3_0_0 && from < V3_9_0) {
newVersionString(changeLog, "3.9 (12/09/11)", new String[] {
"Cleaner design (especially the task edit page)!",
"Customize the edit page (\"Beast Mode\" in preferences)",
"Make shared lists with tasks open to anyone (perfect for potlucks, road trips etc)",
"Fixes for some ICS crashes (full support coming soon)",
"Google Tasks sync improvement - Note: If you have been experiencing \"Sync with errors\", try logging out and logging back in to Google Tasks.",
"Other minor bug fixes",
"Feedback welcomed!"
});
}
if(from >= V3_0_0 && from < V3_8_0) {
newVersionString(changeLog, "3.8.0 (7/15/11)", new String[] {
"Astrid.com: sync & share tasks / lists with others!",
"GTasks Sync using Google's official task API! Gtasks users " +
"will need to perform a manual sync to set everything up.",
"Renamed \"Tags\" to \"Lists\" (see blog.astrid.com for details)",
"New style for \"Task Edit\" page!",
"Purge completed or deleted tasks from settings menu!",
});
gtasksPreferenceService.setToken(null);
}
if(from >= V3_0_0 && from < V3_7_0) {
newVersionString(changeLog, "3.7.0 (2/7/11)", new String[] {
"Improved UI for displaying task actions. Tap a task to " +
"bring up actions, tap again to dismiss.",
"Task notes can be viewed by tapping the note icon to " +
"the right of the task.",
"Added Astrid as 'Send-To' choice in Android Browser and " +
"other apps.",
"Add tags and importance in quick-add, e.g. " +
"\"call mom #family @phone !4\"",
"Fixed bug with custom filters & tasks being hidden.",
});
upgrade3To3_7();
if(gtasksPreferenceService.isLoggedIn())
taskService.clearDetails(Criterion.all);
Preferences.setBoolean(Eula.PREFERENCE_EULA_ACCEPTED, true);
}
if(from >= V3_0_0 && from < V3_6_0) {
newVersionString(changeLog, "3.6.0 (11/13/10)", new String[] {
"Astrid Power Pack is now launched to the Android Market. " +
"New Power Pack features include 4x2 and 4x4 widgets and voice " +
"task reminders and creation. Go to the add-ons page to find out more!",
"Fix for Google Tasks: due times got lost on sync, repeating tasks not repeated",
"Fix for task alarms not always firing if multiple set",
"Fix for various force closes",
});
upgrade3To3_6(context);
}
if(from >= V3_0_0 && from < V3_5_0)
newVersionString(changeLog, "3.5.0 (10/25/10)", new String[] {
"Google Tasks Sync (beta!)",
"Bug fix with RMilk & new tasks not getting synced",
"Fixed Force Closes and other bugs",
});
if(from >= V3_0_0 && from < V3_4_0) {
newVersionString(changeLog, "3.4.0 (10/08/10)", new String[] {
"End User License Agreement",
"Option to disable usage statistics",
"Bug fixes with Producteev",
});
}
if(from >= V3_0_0 && from < V3_3_0)
newVersionString(changeLog, "3.3.0 (9/17/10)", new String[] {
"Fixed some RTM duplicated tasks issues",
"UI updates based on your feedback",
"Snooze now overrides other alarms",
"Added preference option for selecting snooze style",
"Hide until: now allows you to pick a specific time",
});
if(from >= V3_0_0 && from < V3_2_0)
newVersionString(changeLog, "3.2.0 (8/16/10)", new String[] {
"Build your own custom filters from the Filter page",
"Easy task sorting (in the task list menu)",
"Create widgets from any of your filters",
"Synchronize with Producteev! (producteev.com)",
"Select tags by drop-down box",
"Cosmetic improvements, calendar & sync bug fixes",
});
if(from >= V3_0_0 && from < V3_1_0)
newVersionString(changeLog, "3.1.0 (8/9/10)", new String[] {
"Linkify phone numbers, e-mails, and web pages",
"Swipe L => R to go from tasks to filters",
"Moved task priority bar to left side",
"Added ability to create fixed alerts for a task",
"Restored tag hiding when tag begins with underscore (_)",
"FROYO: disabled moving app to SD card, it would break alarms and widget",
"Also gone: a couple force closes, bugs with repeating tasks",
});
if(changeLog.length() == 0)
return;
changeLog.append("Enjoy!</body></html>");
String color = ThemeService.getDialogTextColorString();
String changeLogHtml = "<html><body style='color: " + color +"'>" + changeLog;
DialogUtilities.htmlDialog(context, changeLogHtml,
R.string.UpS_changelog_title);
}
|
diff --git a/src/com/owentech/DevDrawer/utils/Database.java b/src/com/owentech/DevDrawer/utils/Database.java
index 6c7ea5d..48f2f18 100755
--- a/src/com/owentech/DevDrawer/utils/Database.java
+++ b/src/com/owentech/DevDrawer/utils/Database.java
@@ -1,352 +1,352 @@
package com.owentech.DevDrawer.utils;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: owent
* Date: 29/01/2013
* Time: 07:08
* To change this template use File | Settings | File Templates.
*/
public class Database {
SQLiteDatabase db;
Context ctx;
public static int NOT_FOUND = 1000000;
private static final String TAG = "DevDrawer-Database";
public Database(Context ctx)
{
this.ctx = ctx;
}
///////////////////////////////////
// Method to connect to database
///////////////////////////////////
public void connectDB()
{
db = ctx.openOrCreateDatabase("DevDrawer.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
}
////////////////////////////////////////
// Method to close database connection
////////////////////////////////////////
public void closeDB()
{
db.close();
}
/////////////////////////////////////////
// Method to create tables in database
/////////////////////////////////////////
public void createTables()
{
connectDB();
// create tables
String CREATE_TABLE_FILTER = "CREATE TABLE IF NOT EXISTS devdrawer_filter ("
+ "id INTEGER PRIMARY KEY, package TEXT);";
db.execSQL(CREATE_TABLE_FILTER);
String CREATE_TABLE_APPS = "CREATE TABLE IF NOT EXISTS devdrawer_app ("
+ "id INTEGER PRIMARY KEY, package TEXT, filterid INTEGER);";
db.execSQL(CREATE_TABLE_APPS);
closeDB();
}
// ////////////////////////////////////////////////
// Method to add an entry into the filter table
// ///////////////////////////////////////////////
public void addFilterToDatabase(String p)
{
// connect
connectDB();
// add accident entry
String packageInsertQuery = "INSERT INTO 'devdrawer_filter' "
+ "(package)" + "VALUES" + "('" + p + "');";
db.execSQL(packageInsertQuery);
// close
closeDB();
}
// ///////////////////////////////////////////////
// Method to add package to installed apps table
// ///////////////////////////////////////////////
public void addAppToDatabase(String p, String filterId)
{
// connect
connectDB();
// add accident entry
String packageInsertQuery = "INSERT INTO 'devdrawer_app' "
+ "(package, filterid)" + "VALUES" + "('" + p + "', " + filterId + ");";
db.execSQL(packageInsertQuery);
// close
closeDB();
}
// ////////////////////////////////////////////////////
// Method to remove an entry from the filters tables
// ////////////////////////////////////////////////////
public void removeFilterFromDatabase(String i)
{
// connect
connectDB();
// add accident entry
String packageDeleteQuery = "DELETE FROM 'devdrawer_filter' WHERE id = '" + i + "'";
db.execSQL(packageDeleteQuery);
// close
closeDB();
}
// ////////////////////////////////////////////////////
// Method to remove an entry from the filters tables
// ////////////////////////////////////////////////////
public void removeAppFromDatabase(String i)
{
// connect
connectDB();
// add accident entry
String packageDeleteQuery = "DELETE FROM 'devdrawer_app' WHERE filterid = '" + i + "'";
db.execSQL(packageDeleteQuery);
// close
closeDB();
}
//////////////////////////////////////////////////////
// Method to get all the entries in the filter table
//////////////////////////////////////////////////////
public List<PackageCollection> getAllFiltersInDatabase()
{
connectDB();
Cursor getAllCursor = db.query("devdrawer_filter", null, null, null, null, null, null, null);
List<PackageCollection> packageCollections = new ArrayList<PackageCollection>();
getAllCursor.moveToFirst();
while(!getAllCursor.isAfterLast())
{
packageCollections.add(new PackageCollection(getAllCursor.getString(0), getAllCursor.getString(1)));
getAllCursor.moveToNext();
}
getAllCursor.close();
closeDB();
return packageCollections;
}
////////////////////////////////////////////////////////////////
// Method to get all the packages in the installed apps table
////////////////////////////////////////////////////////////////
public String[] getAllAppsInDatabase()
{
String[] packages;
connectDB();
Cursor getAllCursor = db.query("devdrawer_app", null, null, null, null, null, null, null);
Log.d("DATABASE", "getAllAppsInDatabase: " + Integer.toString(getAllCursor.getCount()) );
getAllCursor.moveToFirst();
packages = new String[getAllCursor.getCount()];
int i=0;
while(!getAllCursor.isAfterLast())
{
packages[i] = getAllCursor.getString(1);
i++;
getAllCursor.moveToNext();
}
getAllCursor.close();
closeDB();
return packages;
}
// ////////////////////////////////////////////////////
// Method to get a count of rows in the filter table
// ////////////////////////////////////////////////////
public int getFiltersCount()
{
// connect
connectDB();
Cursor countCursor = db.rawQuery("SELECT count(*) FROM devdrawer_filter", null);
// get number of rows
countCursor.moveToFirst();
int count = countCursor.getInt(0);
countCursor.close();
// close
closeDB();
return count;
}
///////////////////////////////////////////////////////////////
// Method to determine whether the new filter already exists
///////////////////////////////////////////////////////////////
public boolean doesFilterExist(String s)
{
// connect
connectDB();
Cursor countCursor = db.rawQuery("SELECT count(*) FROM devdrawer_filter WHERE package = '" + s + "'", null);
// get number of rows
countCursor.moveToFirst();
int count = countCursor.getInt(0);
countCursor.close();
// close
closeDB();
if (count == 0)
return false;
else
return true;
}
// ////////////////////////////////////////////////////////////
// Method to get a count of rows in the installed apps tables
// ////////////////////////////////////////////////////////////
public int getAppsCount()
{
// connect
connectDB();
Cursor countCursor = db.rawQuery("SELECT count(*) FROM devdrawer_app", null);
// get number of rows
countCursor.moveToFirst();
int count = countCursor.getInt(0);
countCursor.close();
// close
closeDB();
return count;
}
/////////////////////////////////////////////////////////////////////////////////////////
// Method to check whether the app being install exists in the installed package table
/////////////////////////////////////////////////////////////////////////////////////////
public boolean doesAppExistInDb(String s)
{
connectDB();
Cursor cursor = db.query("devdrawer_app", null, "package = '" + s + "'", null, null, null, null, null);
int count = cursor.getCount();
cursor.close();
closeDB();
if (cursor.getCount() == 0)
return false;
else
return true;
}
////////////////////////////////////////////////////////////////
// Method to delete a package from the installed package table
////////////////////////////////////////////////////////////////
public void deleteAppFromDb(String s)
{
connectDB();
db.execSQL("DELETE FROM devdrawer_app WHERE package ='" + s + "'");
closeDB();
}
/////////////////////////////////////////////////////////////////////
// Method to parse each row and return if the new package matches
/////////////////////////////////////////////////////////////////////
// TODO: Make this work for exact package name
public int parseAndMatch(String p)
{
int match = NOT_FOUND;
connectDB();
Cursor getAllCursor = db.query("devdrawer_filter", null, null, null, null, null, null, null);
getAllCursor.moveToFirst();
while (!getAllCursor.isAfterLast())
{
String packageFilter = getAllCursor.getString(1).toLowerCase();
if (packageFilter.contains("*"))
{
if (p.toLowerCase().startsWith(packageFilter.toLowerCase().substring(0, packageFilter.indexOf("*"))))
- match = Integer.valueOf(getAllCursor.getString(2));
+ match = Integer.valueOf(getAllCursor.getString(0));
}
else
{
if (p.toLowerCase().equals(packageFilter.toLowerCase()))
- match = Integer.valueOf(getAllCursor.getString(2));
+ match = Integer.valueOf(getAllCursor.getString(0));
}
getAllCursor.moveToNext();
}
getAllCursor.close();
closeDB();
return match;
}
///////////////////////////////////
// Method to amend a filter entry
///////////////////////////////////
public void amendFilterEntryTo(String id, String newString)
{
connectDB();
db.execSQL("UPDATE devdrawer_filter SET package='" + newString + "' WHERE id ='" + id + "'");
closeDB();
}
}
| false | true | public int parseAndMatch(String p)
{
int match = NOT_FOUND;
connectDB();
Cursor getAllCursor = db.query("devdrawer_filter", null, null, null, null, null, null, null);
getAllCursor.moveToFirst();
while (!getAllCursor.isAfterLast())
{
String packageFilter = getAllCursor.getString(1).toLowerCase();
if (packageFilter.contains("*"))
{
if (p.toLowerCase().startsWith(packageFilter.toLowerCase().substring(0, packageFilter.indexOf("*"))))
match = Integer.valueOf(getAllCursor.getString(2));
}
else
{
if (p.toLowerCase().equals(packageFilter.toLowerCase()))
match = Integer.valueOf(getAllCursor.getString(2));
}
getAllCursor.moveToNext();
}
getAllCursor.close();
closeDB();
return match;
}
| public int parseAndMatch(String p)
{
int match = NOT_FOUND;
connectDB();
Cursor getAllCursor = db.query("devdrawer_filter", null, null, null, null, null, null, null);
getAllCursor.moveToFirst();
while (!getAllCursor.isAfterLast())
{
String packageFilter = getAllCursor.getString(1).toLowerCase();
if (packageFilter.contains("*"))
{
if (p.toLowerCase().startsWith(packageFilter.toLowerCase().substring(0, packageFilter.indexOf("*"))))
match = Integer.valueOf(getAllCursor.getString(0));
}
else
{
if (p.toLowerCase().equals(packageFilter.toLowerCase()))
match = Integer.valueOf(getAllCursor.getString(0));
}
getAllCursor.moveToNext();
}
getAllCursor.close();
closeDB();
return match;
}
|
diff --git a/StackBlur/src/com/enrique/stackblur/StackBlurManager.java b/StackBlur/src/com/enrique/stackblur/StackBlurManager.java
index 166b897..9265628 100644
--- a/StackBlur/src/com/enrique/stackblur/StackBlurManager.java
+++ b/StackBlur/src/com/enrique/stackblur/StackBlurManager.java
@@ -1,313 +1,318 @@
/**
* StackBlur v1.0 for Android
*
* @Author: Enrique López Mañas <[email protected]>
* http://www.neo-tech.es
*
* Author of the original algorithm: Mario Klingemann <mario.quasimondo.com>
*
* This is a compromise between Gaussian Blur and Box blur
* It creates much better looking blurs than Box Blur, but is
* 7x faster than my Gaussian Blur implementation.
* I called it Stack Blur because this describes best how this
* filter works internally: it creates a kind of moving stack
* of colors whilst scanning through the image. Thereby it
* just has to add one new block of color to the right side
* of the stack and remove the leftmost color. The remaining
* colors on the topmost layer of the stack are either added on
* or reduced by one, depending on if they are on the right or
* on the left side of the stack.
*
* @copyright: Enrique López Mañas
* @license: Apache License 2.0
*/
package com.enrique.stackblur;
import java.io.FileOutputStream;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
public class StackBlurManager {
/**
* Original set of pixels from the image
*/
private int [] originalPixels;
/**
* Current set of pixels from the image (the one that will be exported
*/
private int [] currentPixels;
/**
* Original width of the image
*/
private int _width = -1;
/**
* Original height of the image
*/
private int _height= -1;
/**
* Original image
*/
private Bitmap _image;
private boolean alpha = false;
/**
* Constructor method (basic initialization and construction of the pixel array)
* @param image The image that will be analyed
*/
public StackBlurManager(Bitmap image) {
_width=image.getWidth();
_height=image.getHeight();
_image = image;
originalPixels= new int[_width*_height];
_image.getPixels(originalPixels, 0, _width, 0, 0, _width, _height);
}
/**
* Process the image on the given radius. Radius must be at least 1
* @param radius
*/
public void process(int radius) {
if (radius < 1 )
radius = 1;
currentPixels = originalPixels.clone();
int wm=_width-1;
int hm=_height-1;
int wh=_width*_height;
int div=radius+radius+1;
int r[]=new int[wh];
int g[]=new int[wh];
int b[]=new int[wh];
int rsum,gsum,bsum,x,y,i,p,yp,yi,yw;
int vmin[] = new int[Math.max(_width,_height)];
int divsum=(div+1)>>1;
divsum*=divsum;
int dv[]=new int[256*divsum];
for (i=0;i<256*divsum;i++){
dv[i]=(i/divsum);
}
yw=yi=0;
int[][] stack=new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1=radius+1;
int routsum,goutsum,boutsum;
int rinsum,ginsum,binsum;
for (y=0;y<_height;y++){
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
for(i=-radius;i<=radius;i++){
p=currentPixels[yi+Math.min(wm,Math.max(i,0))];
sir=stack[i+radius];
sir[0]=(p & 0xff0000)>>16;
sir[1]=(p & 0x00ff00)>>8;
sir[2]=(p & 0x0000ff);
rbs=r1-Math.abs(i);
rsum+=sir[0]*rbs;
gsum+=sir[1]*rbs;
bsum+=sir[2]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
}
stackpointer=radius;
for (x=0;x<_width;x++){
- if (!alpha)
- alpha = (int)(Color.alpha(originalPixels[y*_height+x])) != 255;
+ if (!alpha) {
+ int index = y * _height + x;
+ if (index >= originalPixels.length) {
+ index = originalPixels.length - 1;
+ }
+ alpha = (int) (Color.alpha(originalPixels[index])) != 255;
+ }
r[yi]=dv[rsum];
g[yi]=dv[gsum];
b[yi]=dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer-radius+div;
sir=stack[stackstart%div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if(y==0){
vmin[x]=Math.min(x+radius+1,wm);
}
p=currentPixels[yw+vmin[x]];
sir[0]=(p & 0xff0000)>>16;
sir[1]=(p & 0x00ff00)>>8;
sir[2]=(p & 0x0000ff);
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer+1)%div;
sir=stack[(stackpointer)%div];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi++;
}
yw+=_width;
}
for (x=0;x<_width;x++){
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
yp=-radius*_width;
for(i=-radius;i<=radius;i++){
yi=Math.max(0,yp)+x;
sir=stack[i+radius];
sir[0]=r[yi];
sir[1]=g[yi];
sir[2]=b[yi];
rbs=r1-Math.abs(i);
rsum+=r[yi]*rbs;
gsum+=g[yi]*rbs;
bsum+=b[yi]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
if(i<hm){
yp+=_width;
}
}
yi=x;
stackpointer=radius;
for (y=0;y<_height;y++){
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
if ( alpha )
currentPixels[yi] = (0xff000000 & currentPixels[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
else
currentPixels[yi]=0xff000000 | (dv[rsum]<<16) | (dv[gsum]<<8) | dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer-radius+div;
sir=stack[stackstart%div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if(x==0){
vmin[y]=Math.min(y+r1,hm)*_width;
}
p=x+vmin[y];
sir[0]=r[p];
sir[1]=g[p];
sir[2]=b[p];
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer+1)%div;
sir=stack[stackpointer];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi+=_width;
}
}
}
/**
* Returns the blurred image as a bitmap
* @return blurred image
*/
public Bitmap returnBlurredImage() {
Bitmap newBmp = Bitmap.createBitmap(_image.getWidth(), _image.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(newBmp);
c.drawBitmap(_image, 0, 0, new Paint());
newBmp.setPixels(currentPixels, 0, _width, 0, 0, _width, _height);
return newBmp;
}
/**
* Save the image into the file system
* @param path The path where to save the image
*/
public void saveIntoFile(String path) {
Bitmap newBmp = Bitmap.createBitmap(_image.getWidth(), _image.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(newBmp);
c.drawBitmap(_image, 0, 0, new Paint());
newBmp.setPixels(currentPixels, 0, _width, 0, 0, _width, _height);
try {
FileOutputStream out = new FileOutputStream(path);
newBmp.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns the original image as a bitmap
* @return the original bitmap image
*/
public Bitmap getImage() {
return this._image;
}
}
| true | true | public void process(int radius) {
if (radius < 1 )
radius = 1;
currentPixels = originalPixels.clone();
int wm=_width-1;
int hm=_height-1;
int wh=_width*_height;
int div=radius+radius+1;
int r[]=new int[wh];
int g[]=new int[wh];
int b[]=new int[wh];
int rsum,gsum,bsum,x,y,i,p,yp,yi,yw;
int vmin[] = new int[Math.max(_width,_height)];
int divsum=(div+1)>>1;
divsum*=divsum;
int dv[]=new int[256*divsum];
for (i=0;i<256*divsum;i++){
dv[i]=(i/divsum);
}
yw=yi=0;
int[][] stack=new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1=radius+1;
int routsum,goutsum,boutsum;
int rinsum,ginsum,binsum;
for (y=0;y<_height;y++){
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
for(i=-radius;i<=radius;i++){
p=currentPixels[yi+Math.min(wm,Math.max(i,0))];
sir=stack[i+radius];
sir[0]=(p & 0xff0000)>>16;
sir[1]=(p & 0x00ff00)>>8;
sir[2]=(p & 0x0000ff);
rbs=r1-Math.abs(i);
rsum+=sir[0]*rbs;
gsum+=sir[1]*rbs;
bsum+=sir[2]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
}
stackpointer=radius;
for (x=0;x<_width;x++){
if (!alpha)
alpha = (int)(Color.alpha(originalPixels[y*_height+x])) != 255;
r[yi]=dv[rsum];
g[yi]=dv[gsum];
b[yi]=dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer-radius+div;
sir=stack[stackstart%div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if(y==0){
vmin[x]=Math.min(x+radius+1,wm);
}
p=currentPixels[yw+vmin[x]];
sir[0]=(p & 0xff0000)>>16;
sir[1]=(p & 0x00ff00)>>8;
sir[2]=(p & 0x0000ff);
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer+1)%div;
sir=stack[(stackpointer)%div];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi++;
}
yw+=_width;
}
for (x=0;x<_width;x++){
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
yp=-radius*_width;
for(i=-radius;i<=radius;i++){
yi=Math.max(0,yp)+x;
sir=stack[i+radius];
sir[0]=r[yi];
sir[1]=g[yi];
sir[2]=b[yi];
rbs=r1-Math.abs(i);
rsum+=r[yi]*rbs;
gsum+=g[yi]*rbs;
bsum+=b[yi]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
if(i<hm){
yp+=_width;
}
}
yi=x;
stackpointer=radius;
for (y=0;y<_height;y++){
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
if ( alpha )
currentPixels[yi] = (0xff000000 & currentPixels[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
else
currentPixels[yi]=0xff000000 | (dv[rsum]<<16) | (dv[gsum]<<8) | dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer-radius+div;
sir=stack[stackstart%div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if(x==0){
vmin[y]=Math.min(y+r1,hm)*_width;
}
p=x+vmin[y];
sir[0]=r[p];
sir[1]=g[p];
sir[2]=b[p];
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer+1)%div;
sir=stack[stackpointer];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi+=_width;
}
}
}
| public void process(int radius) {
if (radius < 1 )
radius = 1;
currentPixels = originalPixels.clone();
int wm=_width-1;
int hm=_height-1;
int wh=_width*_height;
int div=radius+radius+1;
int r[]=new int[wh];
int g[]=new int[wh];
int b[]=new int[wh];
int rsum,gsum,bsum,x,y,i,p,yp,yi,yw;
int vmin[] = new int[Math.max(_width,_height)];
int divsum=(div+1)>>1;
divsum*=divsum;
int dv[]=new int[256*divsum];
for (i=0;i<256*divsum;i++){
dv[i]=(i/divsum);
}
yw=yi=0;
int[][] stack=new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1=radius+1;
int routsum,goutsum,boutsum;
int rinsum,ginsum,binsum;
for (y=0;y<_height;y++){
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
for(i=-radius;i<=radius;i++){
p=currentPixels[yi+Math.min(wm,Math.max(i,0))];
sir=stack[i+radius];
sir[0]=(p & 0xff0000)>>16;
sir[1]=(p & 0x00ff00)>>8;
sir[2]=(p & 0x0000ff);
rbs=r1-Math.abs(i);
rsum+=sir[0]*rbs;
gsum+=sir[1]*rbs;
bsum+=sir[2]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
}
stackpointer=radius;
for (x=0;x<_width;x++){
if (!alpha) {
int index = y * _height + x;
if (index >= originalPixels.length) {
index = originalPixels.length - 1;
}
alpha = (int) (Color.alpha(originalPixels[index])) != 255;
}
r[yi]=dv[rsum];
g[yi]=dv[gsum];
b[yi]=dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer-radius+div;
sir=stack[stackstart%div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if(y==0){
vmin[x]=Math.min(x+radius+1,wm);
}
p=currentPixels[yw+vmin[x]];
sir[0]=(p & 0xff0000)>>16;
sir[1]=(p & 0x00ff00)>>8;
sir[2]=(p & 0x0000ff);
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer+1)%div;
sir=stack[(stackpointer)%div];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi++;
}
yw+=_width;
}
for (x=0;x<_width;x++){
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
yp=-radius*_width;
for(i=-radius;i<=radius;i++){
yi=Math.max(0,yp)+x;
sir=stack[i+radius];
sir[0]=r[yi];
sir[1]=g[yi];
sir[2]=b[yi];
rbs=r1-Math.abs(i);
rsum+=r[yi]*rbs;
gsum+=g[yi]*rbs;
bsum+=b[yi]*rbs;
if (i>0){
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
} else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
if(i<hm){
yp+=_width;
}
}
yi=x;
stackpointer=radius;
for (y=0;y<_height;y++){
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
if ( alpha )
currentPixels[yi] = (0xff000000 & currentPixels[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
else
currentPixels[yi]=0xff000000 | (dv[rsum]<<16) | (dv[gsum]<<8) | dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer-radius+div;
sir=stack[stackstart%div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if(x==0){
vmin[y]=Math.min(y+r1,hm)*_width;
}
p=x+vmin[y];
sir[0]=r[p];
sir[1]=g[p];
sir[2]=b[p];
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer+1)%div;
sir=stack[stackpointer];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi+=_width;
}
}
}
|
diff --git a/frost-wot/source/frost/threads/MessageUploadThread.java b/frost-wot/source/frost/threads/MessageUploadThread.java
index 7b92b44b..04e560f6 100644
--- a/frost-wot/source/frost/threads/MessageUploadThread.java
+++ b/frost-wot/source/frost/threads/MessageUploadThread.java
@@ -1,835 +1,835 @@
/*
MessageUploadThread.java / Frost
Copyright (C) 2001 Jan-Thomas Czornack <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.threads;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import org.w3c.dom.*;
import frost.*;
import frost.crypt.*;
import frost.fcp.*;
import frost.fileTransfer.upload.*;
import frost.gui.*;
import frost.gui.objects.*;
import frost.identities.*;
import frost.messages.*;
/**
* Uploads a message to a certain message board
*/
public class MessageUploadThread extends BoardUpdateThreadObject implements BoardUpdateThread {
private static Logger logger = Logger.getLogger(MessageUploadThread.class.getName());
private SettingsClass frostSettings;
private JFrame parentFrame;
private Board board;
private String destinationBase;
private String keypool;
private MessageObject message;
private File unsentMessageFile;
private int messageUploadHtl;
private String privateKey;
private String publicKey;
private boolean secure;
private byte[] signMetadata;
private File zipFile;
private Identity encryptForRecipient;
public MessageUploadThread(
Board board,
MessageObject mo,
FrostIdentities newIdentities,
SettingsClass frostSettings) {
this(board, mo, newIdentities, frostSettings, null);
}
/**
* Upload a message.
* If recipient is not null, the message will be encrypted for the recipient.
* In this case the sender must be not Anonymous!
*/
public MessageUploadThread(
Board board,
MessageObject mo,
FrostIdentities newIdentities,
SettingsClass frostSettings,
Identity recipient) {
super(board, newIdentities);
this.board = board;
this.message = mo;
this.frostSettings = frostSettings;
this.encryptForRecipient = recipient;
// we only set the date&time if they are not already set
// (in case the uploading was pending from before)
// _OR_ if the date of the message differs from current date, because
// we don't want to insert messages with another date into keyspace of today
// this also allows to do a date check when we receive a file,
// see VerifyableMessageObject.verifyDate
if (mo.getDate() == "" || mo.getDate().equals(DateFun.getDate()) == false) {
mo.setTime(DateFun.getFullExtendedTime() + "GMT");
mo.setDate(DateFun.getDate());
}
messageUploadHtl = frostSettings.getIntValue("tofUploadHtl");
keypool = frostSettings.getValue("keypool.dir");
// this class always creates a new msg file on hd and deletes the file
// after upload was successful, or keeps it for next try
String uploadMe = new StringBuffer()
.append(frostSettings.getValue("unsent.dir"))
.append("unsent")
.append(String.valueOf(System.currentTimeMillis()))
.append(".xml")
.toString();
unsentMessageFile = new File(uploadMe);
}
/**
* This method compares the message that is to be uploaded with
* a local message to see if they are equal
* @param localFile the local message to compare the message to
* be uploaded with.
* @return true if they are equal. False otherwise.
*/
private boolean checkLocalMessage(File localFile) {
try {
MessageObject localMessage = new MessageObject(localFile);
// We compare the messages by content (body), subject, from and attachments
if (!localMessage.getContent().equals(message.getContent())) {
return false;
}
if (!localMessage.getSubject().equals(message.getSubject())) {
return false;
}
if (!localMessage.getFrom().equals(message.getFrom())) {
return false;
}
AttachmentList attachments1 = message.getAllAttachments();
AttachmentList attachments2 = localMessage.getAllAttachments();
if (attachments1.size() != attachments2.size()) {
return false;
}
Iterator iterator1 = attachments1.iterator();
Iterator iterator2 = attachments2.iterator();
while (iterator1.hasNext()) {
Attachment attachment1 = (Attachment) iterator1.next();
Attachment attachment2 = (Attachment) iterator2.next();
if (attachment1.compareTo(attachment2) != 0) {
return false;
}
}
return true;
} catch (Exception exception) {
logger.log(Level.WARNING, "Handled Exception in checkLocalMessage", exception);
return false; // We assume that the local message is different (it may be corrupted)
}
}
/**
* This method is called when there has been a key collision. It checks
* if the remote message with that key is the same as the message that is
* being uploaded
* @param upKey the key of the remote message to compare with the message
* that is being uploaded.
* @return true if the remote message with the given key equals the
* message that is being uploaded. False otherwise.
*/
private boolean checkRemoteFile(int index) {
try {
File remoteFile = new File(unsentMessageFile.getPath() + ".coll");
remoteFile.delete(); // just in case it already exists
remoteFile.deleteOnExit(); // so that it is deleted when Frost exits
downloadMessage(index, remoteFile);
if (remoteFile.length() > 0) {
if( encryptForRecipient != null ) {
// we compare the local encrypted zipFile with remoteFile
boolean isEqual = FileAccess.compareFiles(zipFile, remoteFile);
remoteFile.delete();
return isEqual;
} else {
// compare contents
byte[] unzippedXml = FileAccess.readZipFileBinary(remoteFile);
if(unzippedXml == null) {
return false;
}
FileAccess.writeFile(unzippedXml, remoteFile);
boolean isEqual = checkLocalMessage(remoteFile);
remoteFile.delete();
return isEqual;
}
} else {
remoteFile.delete();
return false; // We could not retrieve the remote file. We assume they are different.
}
} catch (Throwable e) {
logger.log(Level.WARNING, "Handled exception in checkRemoteFile", e);
return false;
}
}
private void downloadMessage(int index, File targetFile) {
String downKey = composeDownKey(index);
FcpRequest.getFile(downKey, null, targetFile, messageUploadHtl, false, false);
}
/**
* This method composes the downloading key for the message, given a
* certain index number
* @param index index number to use to compose the key
* @return they composed key
*/
private String composeDownKey(int index) {
String key;
if (secure) {
key = new StringBuffer()
.append(publicKey)
.append("/")
.append(board.getBoardFilename())
.append("/")
.append(message.getDate())
.append("-")
.append(index)
.append(".xml")
.toString();
} else {
key = new StringBuffer()
.append("KSK@frost/message/")
.append(frostSettings.getValue("messageBase"))
.append("/")
.append(message.getDate())
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".xml")
.toString();
}
return key;
}
/**
* This method composes the uploading key for the message, given a
* certain index number
* @param index index number to use to compose the key
* @return they composed key
*/
private String composeUpKey(int index) {
String key;
if (secure) {
key = new StringBuffer()
.append(privateKey)
.append("/")
.append(board.getBoardFilename())
.append("/")
.append(message.getDate())
.append("-")
.append(index)
.append(".xml")
.toString();
} else {
key = new StringBuffer()
.append("KSK@frost/message/")
.append(frostSettings.getValue("messageBase"))
.append("/")
.append(message.getDate())
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".xml")
.toString();
}
return key;
}
/**
* This method returns the base path from which we look for
* existing files while looking for the next available index to use.
* That directory is also created if it doesn't exist.
* @return the base path to use when looking for existing files while
* looking for the next index.
*/
private String getDestinationBase() {
if (destinationBase == null) {
String fileSeparator = System.getProperty("file.separator");
destinationBase = new StringBuffer()
.append(keypool)
.append(board.getBoardFilename())
.append(fileSeparator)
.append(DateFun.getDate())
.append(fileSeparator)
.toString();
File makedir = new File(destinationBase);
if (!makedir.exists()) {
makedir.mkdirs();
}
}
return destinationBase;
}
/* (non-Javadoc)
* @see frost.threads.BoardUpdateThread#getThreadType()
*/
public int getThreadType() {
return BoardUpdateThread.MSG_UPLOAD;
}
/**
* This method performs several tasks before uploading the message.
* @return true if the initialization was successful. False otherwise.
*/
private boolean initialize() {
// switch public / secure board
if (board.isWriteAccessBoard()) {
privateKey = board.getPrivateKey();
publicKey = board.getPublicKey();
secure = true;
} else {
secure = false;
}
logger.info("TOFUP: Uploading message to board '" + board.getName() + "' with HTL " + messageUploadHtl);
// first save msg to be able to resend on crash
if (!saveMessage(message, unsentMessageFile)) {
logger.severe("This was a HARD error and the file to upload is lost, please report to a dev!");
return false;
}
// BBACKFLAG: ask user if uploading of X files is allowed!
// if one attachment file does not longer exists (on retry), we delete the message in uploadAttachments()!
if (!uploadAttachments(message, unsentMessageFile)) {
return false;
}
// zip the xml file to a temp file
zipFile = new File(unsentMessageFile.getPath() + ".upltmp");
zipFile.delete(); // just in case it already exists
zipFile.deleteOnExit(); // so that it is deleted when Frost exits
FileAccess.writeZipFile(FileAccess.readByteArray(unsentMessageFile), "entry", zipFile);
if( !zipFile.isFile() || zipFile.length() == 0 ) {
logger.severe("Error: zip of message xml file failed, result file not existing or empty. Please report to a dev!");
return false;
}
// encrypt and sign or just sign the zipped file if necessary
String sender = message.getFrom();
String myId = identities.getMyId().getUniqueName();
if (sender.equals(myId) // nick same as my identity
|| sender.equals(Mixed.makeFilename(myId))) // serialization may have changed it
{
byte[] zipped = FileAccess.readByteArray(zipFile);
if( encryptForRecipient != null ) {
// encrypt + sign
// first encrypt, then sign
byte[] encData = Core.getCrypto().encrypt(zipped, encryptForRecipient.getKey());
if( encData == null ) {
logger.severe("Error: could not encrypt the message, please report to a dev!");
return false;
}
zipFile.delete();
FileAccess.writeFile(encData, zipFile); // write encrypted zip file
EncryptMetaData ed = new EncryptMetaData(encData, identities.getMyId(), encryptForRecipient.getUniqueName());
signMetadata = XMLTools.getRawXMLDocument(ed);
} else {
// sign only
SignMetaData md = new SignMetaData(zipped, identities.getMyId());
signMetadata = XMLTools.getRawXMLDocument(md);
}
} else if( encryptForRecipient != null ) {
logger.log(Level.SEVERE, "TOFUP: ALERT - can't encrypt message if sender is Anonymous! Will not send message!");
return false; // unable to encrypt
}
long allLength = zipFile.length();
if( signMetadata != null ) {
allLength += signMetadata.length;
}
if( allLength > 32767 ) { // limit in FcpInsert.putFile()
String txt = "<html>The data you want to upload is too large ("+allLength+"), "+32767+" is allowed.<br>"+
"This should never happen, please report this to a Frost developer!</html>";
JOptionPane.showMessageDialog(parentFrame, txt, "Error: message too large", JOptionPane.ERROR_MESSAGE);
// TODO: the msg will be NEVER sent, we need an unsent folder in gui
// but no too large message should reach us, see MessageFrame
return false;
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
notifyThreadStarted(this);
boolean retry = true;
try {
if (initialize()) {
while (retry) {
retry = uploadMessage();
}
}
} catch (IOException ex) {
logger.log(
Level.SEVERE,
"ERROR: MessageUploadThread.run(): unexpected IOException, terminating thread ...",
ex);
// } catch (MessageAlreadyUploadedException exception) {
// logger.info("The message had already been uploaded. Therefore it will not be uploaded again.");
// messageFile.delete();
} catch (Throwable t) {
logger.log(Level.SEVERE, "Oo. EXCEPTION in MessageUploadThread", t);
}
notifyThreadFinished(this);
}
/**
* @param parentFrame
*/
public void setParentFrame(JFrame parentFrame) {
this.parentFrame = parentFrame;
}
/**
* This method saves a message to disk in XML format (using a new name)
* @param msg the MessageObject to save
* @param file the file whose path will be used to save the message
* @return true if successful. False otherwise.
*/
private boolean saveMessage(MessageObject msg, File file) {
File tmpFile = new File(file.getPath() + ".tmp");
boolean success = false;
try {
Document doc = XMLTools.createDomDocument();
doc.appendChild(msg.getXMLElement(doc));
success = XMLTools.writeXmlFile(doc, tmpFile.getPath());
} catch (Throwable ex) {
logger.log(Level.SEVERE, "Exception thrown in saveMessage()", ex);
}
if (success && tmpFile.length() > 0) {
unsentMessageFile.delete();
tmpFile.renameTo(unsentMessageFile);
return true;
} else {
tmpFile.delete();
return false;
}
}
/**
* This inserts an attached SharedFileObject into freenet
* @param attachment the SharedFileObject to upload
* @return true if successful. False otherwise.
*/
private boolean uploadAttachment(SharedFileObject attachment) {
assert attachment.getFile() != null : "message.getFile() failed!";
String[] result = { "", "" };
int uploadHtl = frostSettings.getIntValue("htlUpload");
logger.info(
"TOFUP: Uploading attachment "
+ attachment.getFile().getPath()
+ " with HTL "
+ uploadHtl);
int maxTries = 3;
int tries = 0;
while (tries < maxTries
&& !result[0].equals("KeyCollision")
&& !result[0].equals("Success")) {
try {
result = FcpInsert.putFile(
"CHK@",
attachment.getFile(),
null,
uploadHtl,
true, // doRedirect
true, // removeLocalKey, insert with full HTL even if existing in local store
new FrostUploadItem(null, null));
} catch (Exception ex) {
result = new String[1];
result[0] = "Error";
}
tries++;
}
if (result[0].equals("KeyCollision") || result[0].equals("Success")) {
logger.info(
"TOFUP: Upload of attachment '"
+ attachment.getFile().getPath()
+ "' was successful.");
String chk = result[1];
attachment.setKey(chk);
attachment.setFilename(attachment.getFile().getName()); // remove path from filename
if (attachment instanceof FECRedirectFileObject) {
logger.fine("attaching redirect to file " + attachment.getFile().getName());
FecSplitfile splitFile = new FecSplitfile(attachment.getFile());
if (!splitFile.uploadInit())
throw new Error("file was just uploaded, but .redirect missing!");
((FECRedirectFileObject) attachment).setRedirect(
new String(FileAccess.readByteArray(splitFile.getRedirectFile())));
splitFile.finishUpload(true);
} else
logger.fine("not attaching redirect");
attachment.setFile(null); // we never want to give out a real pathname, this is paranoia
return true;
} else {
logger.warning(
"TOFUP: Upload of attachment '"
+ attachment.getFile().getPath()
+ "' was NOT successful.");
return false;
}
}
/**
* Uploads all the attachments of a MessageObject and updates its
* XML representation on disk
* @param msg the MessageObject whose attachments will be uploaded
* @param file file whose path will be used to save the MessageObject to disk.
* @return true if successful. False otherwise.
*/
private boolean uploadAttachments(MessageObject msg, File file) {
boolean success = true;
List fileAttachments = msg.getOfflineFiles();
Iterator i = fileAttachments.iterator();
// check if upload files still exist
while (i.hasNext()) {
SharedFileObject attachment = (SharedFileObject) i.next();
if( attachment.getFile()== null ||
attachment.getFile().isFile() == false ||
attachment.getFile().length() == 0 )
{
JOptionPane.showMessageDialog(
parentFrame,
"The message that is currently send (maybe a send retry on next startup of Frost)\n"+
"contains a file attachment that does not longer exist!\n\n"+
"The send of the message was aborted and the message file was deleted\n"+
"to prevent another upload try on next startup of Frost.",
"Unrecoverable error",
JOptionPane.ERROR_MESSAGE);
unsentMessageFile.delete();
return false;
}
}
// upload each attachment
i = fileAttachments.iterator();
while (i.hasNext()) {
SharedFileObject attachment = (SharedFileObject) i.next();
if(uploadAttachment(attachment)) {
//If the attachment was successfully inserted, we update the message on disk.
saveMessage(msg, file);
} else {
success = false;
}
}
if (!success) {
JOptionPane.showMessageDialog(
parentFrame,
"One or more attachments failed to upload.\n"
+ "Will retry to upload attachments and message on next startup.",
"Attachment upload failed",
JOptionPane.ERROR_MESSAGE);
}
return success;
}
/**
* Composes the complete path + filename of a messagefile in the keypool for the given index.
*/
private String composeMsgFilePath(int index) {
return new StringBuffer().append(getDestinationBase()).append(message.getDate())
.append("-").append(board.getBoardFilename()).append("-").append(index).append(".xml")
.toString();
}
/**
* Composes only the filename of a messagefile in the keypool for the given index.
*/
private String composeMsgFileNameWithoutXml(int index) {
return new StringBuffer().append(message.getDate()).append("-")
.append(board.getBoardFilename()).append("-").append(index).toString();
}
/**
* Finds the next free index slot, starting at startIndex.
* If a free slot is found (no xml message exists for this index in keypool)
* the method reads some indicies ahead to check if it found a gap only.
* The final firstEmptyIndex is returned.
*
* @param startIndex
* @return index higher -1 ; or -1 if message was already uploaded
* @throws MessageAlreadyUploadedException
*/
private int findNextFreeIndex(int startIndex) {
final int maxGap = 3;
int tryIndex = startIndex;
int firstEmptyIndex = -1;
logger.fine("TOFUP: Searching free index in board "+
board.getBoardFilename()+", starting at index " + startIndex);
while(true) {
String testFilename = composeMsgFilePath(tryIndex);
File testMe = new File(testFilename);
if (testMe.exists() && testMe.length() > 0) {
// check each existing message in board if this is the msg we want to send
if (encryptForRecipient == null && checkLocalMessage(testMe)) {
return -1;
} else {
tryIndex++;
firstEmptyIndex = -1;
}
} else {
// a message file with this index does not exist
// check if there is a gap between the next existing index
if( firstEmptyIndex >= 0 ) {
if( (tryIndex - firstEmptyIndex) > maxGap ) {
break;
}
} else {
firstEmptyIndex = tryIndex;
}
tryIndex++;
}
}
logger.fine("TOFUP: Found free index in board "+board.getBoardFilename()+" at " + firstEmptyIndex);
return firstEmptyIndex;
}
/**
* @return
* @throws IOException
* @throws MessageAlreadyUploadedException
*/
private boolean uploadMessage() throws IOException {
boolean success = false;
int index = 0;
int tries = 0;
int maxTries = 8;
boolean error = false;
boolean tryAgain;
boolean retrySameIndex = false;
File lockRequestIndex = null;
while (!success) {
if( retrySameIndex == false ) {
// find next free index slot
index = findNextFreeIndex(index);
if( index < 0 ) {
// same message was already uploaded today
logger.info("TOFUP: Message seems to be already uploaded (1)");
success = true;
continue;
}
// probably empty slot, check if other threads currently try to insert to this index
lockRequestIndex = new File(composeMsgFilePath(index) + ".lock");
if (lockRequestIndex.createNewFile() == false) {
// another thread tries to insert using this index, try next
index++;
logger.fine("TOFUP: Other thread tries this index, increasing index to " + index);
continue; // while
} else {
// we try this index
lockRequestIndex.deleteOnExit();
}
} else {
// reset flag
retrySameIndex = false;
// lockfile already created
}
// try to insert message
String[] result = new String[2];
try {
// signMetadata is null for unsigned upload. Do not do redirect.
result = FcpInsert.putFile(
composeUpKey(index),
zipFile,
signMetadata,
messageUploadHtl,
false, // doRedirect
false); // removeLocalKey, we want a KeyCollision if key does already exist in local store!
} catch (Throwable t) {
logger.log(Level.SEVERE, "TOFUP: Error in run()/FcpInsert.putFile", t);
}
if (result == null || result[0] == null || result[1] == null) {
result[0] = "Error";
result[1] = "Error";
}
if (result[0].equals("Success")) {
// msg is probabilistic cached in freenet node, retrieve it to ensure it is in our store
File tmpFile = new File(unsentMessageFile.getPath() + ".down");
int dlTries = 0;
- int dlMaxTries = 3;
+ // we use same maxTries as for upload
while(dlTries < maxTries) {
Mixed.wait(10000);
tmpFile.delete(); // just in case it already exists
downloadMessage(index, tmpFile);
if( tmpFile.length() > 0 ) {
break;
} else {
logger.severe("TOFUP: Uploaded message could NOT be retrieved! "+
- "Download try "+dlTries+" of "+dlMaxTries);
+ "Download try "+dlTries+" of "+maxTries);
dlTries++;
}
}
if( tmpFile.length() > 0 ) {
logger.warning("TOFUP: Uploaded message was successfully retrieved.");
success = true;
} else {
logger.severe("TOFUP: Uploaded message could NOT be retrieved! Retrying upload. "+
"(try no. " + tries + " of " + maxTries + "), retrying index " + index);
tries++;
retrySameIndex = true;
}
tmpFile.delete();
} else {
if (result[0].equals("KeyCollision")) {
if (checkRemoteFile(index)) {
logger.warning("TOFUP: Message seems to be already uploaded (2)");
success = true;
} else {
index++;
logger.warning("TOFUP: Upload collided, increasing index to " + index);
Mixed.wait(10000);
}
} else {
if (tries > maxTries) {
success = true;
error = true;
} else {
logger.warning("TOFUP: Upload failed (try no. " + tries + " of " + maxTries
+ "), retrying index " + index);
tries++;
retrySameIndex = true;
Mixed.wait(10000);
}
}
}
// finally delete the index lock file, if we retry this index we keep it
if (retrySameIndex == false) {
lockRequestIndex.delete();
}
}
if (!error) {
logger.info("*********************************************************************\n"
+ "Message successfully uploaded to board '" + board.getName() + "'.\n"
+ "*********************************************************************");
tryAgain = false;
// move message file to sent folder
String finalName = composeMsgFileNameWithoutXml(index);
File sentTarget = new File( frostSettings.getValue("sent.dir") + finalName + ".xml" );
int counter = 2;
while( sentTarget.exists() ) {
// paranoia, target file already exists, append an increasing number
sentTarget = new File( frostSettings.getValue("sent.dir") + finalName + "-" + counter + ".xml" );
counter++;
}
boolean wasOk = unsentMessageFile.renameTo(sentTarget);
if( !wasOk ) {
logger.severe("Error: rename of '"+unsentMessageFile.getPath()+"' into '"+sentTarget.getPath()+"' failed!");
unsentMessageFile.delete(); // we must delete the file from unsent folder to prevent another upload
}
zipFile.delete();
} else {
logger.warning("TOFUP: Error while uploading message.");
boolean retrySilently = frostSettings.getBoolValue(SettingsClass.SILENTLY_RETRY_MESSAGES);
if (!retrySilently) {
// Uploading of that message failed. Ask the user if Frost
// should try to upload the message another time.
MessageUploadFailedDialog faildialog = new MessageUploadFailedDialog(parentFrame);
int answer = faildialog.startDialog();
if (answer == MessageUploadFailedDialog.RETRY_VALUE) {
logger.info("TOFUP: Will try to upload again.");
tryAgain = true;
} else if (answer == MessageUploadFailedDialog.RETRY_NEXT_STARTUP_VALUE) {
zipFile.delete();
logger.info("TOFUP: Will try to upload again on next startup.");
tryAgain = false;
} else if (answer == MessageUploadFailedDialog.DISCARD_VALUE) {
zipFile.delete();
unsentMessageFile.delete();
logger.warning("TOFUP: Will NOT try to upload message again.");
tryAgain = false;
} else { // paranoia
logger.warning("TOFUP: Paranoia - will try to upload message again.");
tryAgain = true;
}
} else {
// Retry silently
tryAgain = true;
}
}
logger.info("TOFUP: Upload Thread finished");
return tryAgain;
}
}
| false | true | private boolean uploadMessage() throws IOException {
boolean success = false;
int index = 0;
int tries = 0;
int maxTries = 8;
boolean error = false;
boolean tryAgain;
boolean retrySameIndex = false;
File lockRequestIndex = null;
while (!success) {
if( retrySameIndex == false ) {
// find next free index slot
index = findNextFreeIndex(index);
if( index < 0 ) {
// same message was already uploaded today
logger.info("TOFUP: Message seems to be already uploaded (1)");
success = true;
continue;
}
// probably empty slot, check if other threads currently try to insert to this index
lockRequestIndex = new File(composeMsgFilePath(index) + ".lock");
if (lockRequestIndex.createNewFile() == false) {
// another thread tries to insert using this index, try next
index++;
logger.fine("TOFUP: Other thread tries this index, increasing index to " + index);
continue; // while
} else {
// we try this index
lockRequestIndex.deleteOnExit();
}
} else {
// reset flag
retrySameIndex = false;
// lockfile already created
}
// try to insert message
String[] result = new String[2];
try {
// signMetadata is null for unsigned upload. Do not do redirect.
result = FcpInsert.putFile(
composeUpKey(index),
zipFile,
signMetadata,
messageUploadHtl,
false, // doRedirect
false); // removeLocalKey, we want a KeyCollision if key does already exist in local store!
} catch (Throwable t) {
logger.log(Level.SEVERE, "TOFUP: Error in run()/FcpInsert.putFile", t);
}
if (result == null || result[0] == null || result[1] == null) {
result[0] = "Error";
result[1] = "Error";
}
if (result[0].equals("Success")) {
// msg is probabilistic cached in freenet node, retrieve it to ensure it is in our store
File tmpFile = new File(unsentMessageFile.getPath() + ".down");
int dlTries = 0;
int dlMaxTries = 3;
while(dlTries < maxTries) {
Mixed.wait(10000);
tmpFile.delete(); // just in case it already exists
downloadMessage(index, tmpFile);
if( tmpFile.length() > 0 ) {
break;
} else {
logger.severe("TOFUP: Uploaded message could NOT be retrieved! "+
"Download try "+dlTries+" of "+dlMaxTries);
dlTries++;
}
}
if( tmpFile.length() > 0 ) {
logger.warning("TOFUP: Uploaded message was successfully retrieved.");
success = true;
} else {
logger.severe("TOFUP: Uploaded message could NOT be retrieved! Retrying upload. "+
"(try no. " + tries + " of " + maxTries + "), retrying index " + index);
tries++;
retrySameIndex = true;
}
tmpFile.delete();
} else {
if (result[0].equals("KeyCollision")) {
if (checkRemoteFile(index)) {
logger.warning("TOFUP: Message seems to be already uploaded (2)");
success = true;
} else {
index++;
logger.warning("TOFUP: Upload collided, increasing index to " + index);
Mixed.wait(10000);
}
} else {
if (tries > maxTries) {
success = true;
error = true;
} else {
logger.warning("TOFUP: Upload failed (try no. " + tries + " of " + maxTries
+ "), retrying index " + index);
tries++;
retrySameIndex = true;
Mixed.wait(10000);
}
}
}
// finally delete the index lock file, if we retry this index we keep it
if (retrySameIndex == false) {
lockRequestIndex.delete();
}
}
if (!error) {
logger.info("*********************************************************************\n"
+ "Message successfully uploaded to board '" + board.getName() + "'.\n"
+ "*********************************************************************");
tryAgain = false;
// move message file to sent folder
String finalName = composeMsgFileNameWithoutXml(index);
File sentTarget = new File( frostSettings.getValue("sent.dir") + finalName + ".xml" );
int counter = 2;
while( sentTarget.exists() ) {
// paranoia, target file already exists, append an increasing number
sentTarget = new File( frostSettings.getValue("sent.dir") + finalName + "-" + counter + ".xml" );
counter++;
}
boolean wasOk = unsentMessageFile.renameTo(sentTarget);
if( !wasOk ) {
logger.severe("Error: rename of '"+unsentMessageFile.getPath()+"' into '"+sentTarget.getPath()+"' failed!");
unsentMessageFile.delete(); // we must delete the file from unsent folder to prevent another upload
}
zipFile.delete();
} else {
logger.warning("TOFUP: Error while uploading message.");
boolean retrySilently = frostSettings.getBoolValue(SettingsClass.SILENTLY_RETRY_MESSAGES);
if (!retrySilently) {
// Uploading of that message failed. Ask the user if Frost
// should try to upload the message another time.
MessageUploadFailedDialog faildialog = new MessageUploadFailedDialog(parentFrame);
int answer = faildialog.startDialog();
if (answer == MessageUploadFailedDialog.RETRY_VALUE) {
logger.info("TOFUP: Will try to upload again.");
tryAgain = true;
} else if (answer == MessageUploadFailedDialog.RETRY_NEXT_STARTUP_VALUE) {
zipFile.delete();
logger.info("TOFUP: Will try to upload again on next startup.");
tryAgain = false;
} else if (answer == MessageUploadFailedDialog.DISCARD_VALUE) {
zipFile.delete();
unsentMessageFile.delete();
logger.warning("TOFUP: Will NOT try to upload message again.");
tryAgain = false;
} else { // paranoia
logger.warning("TOFUP: Paranoia - will try to upload message again.");
tryAgain = true;
}
} else {
// Retry silently
tryAgain = true;
}
}
logger.info("TOFUP: Upload Thread finished");
return tryAgain;
}
| private boolean uploadMessage() throws IOException {
boolean success = false;
int index = 0;
int tries = 0;
int maxTries = 8;
boolean error = false;
boolean tryAgain;
boolean retrySameIndex = false;
File lockRequestIndex = null;
while (!success) {
if( retrySameIndex == false ) {
// find next free index slot
index = findNextFreeIndex(index);
if( index < 0 ) {
// same message was already uploaded today
logger.info("TOFUP: Message seems to be already uploaded (1)");
success = true;
continue;
}
// probably empty slot, check if other threads currently try to insert to this index
lockRequestIndex = new File(composeMsgFilePath(index) + ".lock");
if (lockRequestIndex.createNewFile() == false) {
// another thread tries to insert using this index, try next
index++;
logger.fine("TOFUP: Other thread tries this index, increasing index to " + index);
continue; // while
} else {
// we try this index
lockRequestIndex.deleteOnExit();
}
} else {
// reset flag
retrySameIndex = false;
// lockfile already created
}
// try to insert message
String[] result = new String[2];
try {
// signMetadata is null for unsigned upload. Do not do redirect.
result = FcpInsert.putFile(
composeUpKey(index),
zipFile,
signMetadata,
messageUploadHtl,
false, // doRedirect
false); // removeLocalKey, we want a KeyCollision if key does already exist in local store!
} catch (Throwable t) {
logger.log(Level.SEVERE, "TOFUP: Error in run()/FcpInsert.putFile", t);
}
if (result == null || result[0] == null || result[1] == null) {
result[0] = "Error";
result[1] = "Error";
}
if (result[0].equals("Success")) {
// msg is probabilistic cached in freenet node, retrieve it to ensure it is in our store
File tmpFile = new File(unsentMessageFile.getPath() + ".down");
int dlTries = 0;
// we use same maxTries as for upload
while(dlTries < maxTries) {
Mixed.wait(10000);
tmpFile.delete(); // just in case it already exists
downloadMessage(index, tmpFile);
if( tmpFile.length() > 0 ) {
break;
} else {
logger.severe("TOFUP: Uploaded message could NOT be retrieved! "+
"Download try "+dlTries+" of "+maxTries);
dlTries++;
}
}
if( tmpFile.length() > 0 ) {
logger.warning("TOFUP: Uploaded message was successfully retrieved.");
success = true;
} else {
logger.severe("TOFUP: Uploaded message could NOT be retrieved! Retrying upload. "+
"(try no. " + tries + " of " + maxTries + "), retrying index " + index);
tries++;
retrySameIndex = true;
}
tmpFile.delete();
} else {
if (result[0].equals("KeyCollision")) {
if (checkRemoteFile(index)) {
logger.warning("TOFUP: Message seems to be already uploaded (2)");
success = true;
} else {
index++;
logger.warning("TOFUP: Upload collided, increasing index to " + index);
Mixed.wait(10000);
}
} else {
if (tries > maxTries) {
success = true;
error = true;
} else {
logger.warning("TOFUP: Upload failed (try no. " + tries + " of " + maxTries
+ "), retrying index " + index);
tries++;
retrySameIndex = true;
Mixed.wait(10000);
}
}
}
// finally delete the index lock file, if we retry this index we keep it
if (retrySameIndex == false) {
lockRequestIndex.delete();
}
}
if (!error) {
logger.info("*********************************************************************\n"
+ "Message successfully uploaded to board '" + board.getName() + "'.\n"
+ "*********************************************************************");
tryAgain = false;
// move message file to sent folder
String finalName = composeMsgFileNameWithoutXml(index);
File sentTarget = new File( frostSettings.getValue("sent.dir") + finalName + ".xml" );
int counter = 2;
while( sentTarget.exists() ) {
// paranoia, target file already exists, append an increasing number
sentTarget = new File( frostSettings.getValue("sent.dir") + finalName + "-" + counter + ".xml" );
counter++;
}
boolean wasOk = unsentMessageFile.renameTo(sentTarget);
if( !wasOk ) {
logger.severe("Error: rename of '"+unsentMessageFile.getPath()+"' into '"+sentTarget.getPath()+"' failed!");
unsentMessageFile.delete(); // we must delete the file from unsent folder to prevent another upload
}
zipFile.delete();
} else {
logger.warning("TOFUP: Error while uploading message.");
boolean retrySilently = frostSettings.getBoolValue(SettingsClass.SILENTLY_RETRY_MESSAGES);
if (!retrySilently) {
// Uploading of that message failed. Ask the user if Frost
// should try to upload the message another time.
MessageUploadFailedDialog faildialog = new MessageUploadFailedDialog(parentFrame);
int answer = faildialog.startDialog();
if (answer == MessageUploadFailedDialog.RETRY_VALUE) {
logger.info("TOFUP: Will try to upload again.");
tryAgain = true;
} else if (answer == MessageUploadFailedDialog.RETRY_NEXT_STARTUP_VALUE) {
zipFile.delete();
logger.info("TOFUP: Will try to upload again on next startup.");
tryAgain = false;
} else if (answer == MessageUploadFailedDialog.DISCARD_VALUE) {
zipFile.delete();
unsentMessageFile.delete();
logger.warning("TOFUP: Will NOT try to upload message again.");
tryAgain = false;
} else { // paranoia
logger.warning("TOFUP: Paranoia - will try to upload message again.");
tryAgain = true;
}
} else {
// Retry silently
tryAgain = true;
}
}
logger.info("TOFUP: Upload Thread finished");
return tryAgain;
}
|
diff --git a/MathTextField.java b/MathTextField.java
index 06c8e9b..94f1ea1 100644
--- a/MathTextField.java
+++ b/MathTextField.java
@@ -1,146 +1,146 @@
/**
*
*/
package applets.Termumformungen$in$der$Technik_01_URI;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
public class MathTextField extends JTextField {
private static final long serialVersionUID = 3991754180692357067L;
private Utils.OperatorTree operatorTree = new Utils.OperatorTree();
public Utils.OperatorTree getOperatorTree() { return operatorTree; }
public void updateByOpTree() {
setText(operatorTree.toString());
}
protected void updateByOpTree(javax.swing.text.DocumentFilter.FilterBypass fb) {
String oldStr = MathTextField.this.getText();
String newStr = operatorTree.toString();
int commonStart = Utils.equalStartLen(oldStr, newStr);
int commonEnd = Utils.equalEndLen(oldStr, newStr);
if(commonEnd + commonStart >= Math.min(oldStr.length(), newStr.length()))
commonEnd = Math.min(oldStr.length(), newStr.length()) - commonStart;
try {
fb.replace(commonStart, oldStr.length() - commonEnd - commonStart, newStr.substring(commonStart, newStr.length() - commonEnd), null);
} catch (BadLocationException e) {
// this should not happen. we should have checked this. this whole function should be safe
throw new AssertionError(e);
}
}
@Override
protected Document createDefaultModel() {
PlainDocument d = (PlainDocument) super.createDefaultModel();
d.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
replace(fb, offset, 0, string, attr);
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
replace(fb, offset, length, "", null);
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String string, AttributeSet attrs)
throws BadLocationException {
String s = MathTextField.this.getText();
boolean insertedDummyChar = false;
boolean insertedBrackets = false;
String marked = s.substring(offset, offset + length);
if(string.matches(" |\\)") && s.substring(offset, offset + 1).equals(string)) {
MathTextField.this.setCaretPosition(offset + 1);
return;
}
string = string.replace(" ", "");
if(string.isEmpty() && marked.equals("(")) {
int count = 1;
while(offset + length < s.length()) {
length++;
marked = s.substring(offset, offset + length);
if(marked.charAt(0) == '(') count++;
else if(marked.charAt(0) == ')') count--;
if(count == 0) break;
}
}
else if(string.isEmpty() && marked.equals(")")) {
int count = -1;
while(offset > 0) {
offset--;
length++;
marked = s.substring(offset, offset + length);
if(marked.charAt(0) == '(') count++;
else if(marked.charAt(0) == ')') count--;
if(count == 0) break;
}
}
if(length == 0 && string.matches("\\+|-|\\*|/|=")) {
if(s.substring(offset).matches(" *(((\\+|-|∙|/|=|\\)).*)|)")) {
string = string + "_";
insertedDummyChar = true;
} else if(s.substring(offset).matches(" .*")) {
string = "_" + string;
insertedDummyChar = true;
}
}
else if(string.matches("\\(")) {
if(length == 0 || marked.equals("_")) {
string = "(_)";
insertedDummyChar = true;
}
else {
string = "(" + marked + ")";
insertedBrackets = true;
}
}
else if(string.matches("\\)"))
return; // ignore that
// situation: A = B, press DEL -> make it A = _
- if(string.isEmpty() && offset > 0 && s.substring(offset - 1, offset).equals(" ") && !marked.equals("_")) {
+ if(string.isEmpty() && offset > 0 && length == 1 && s.substring(offset - 1, offset).equals(" ") && !marked.equals("_")) {
string = "_";
insertedDummyChar = true;
}
setNewString(fb, s.substring(0, offset) + string + s.substring(offset + length));
if(insertedDummyChar) {
int p = MathTextField.this.getText().indexOf('_');
if(p >= 0) {
MathTextField.this.setCaretPosition(p);
MathTextField.this.moveCaretPosition(p + 1);
}
}
else if(insertedBrackets) {
// move just before the ')'
if(MathTextField.this.getCaretPosition() > 0)
MathTextField.this.setCaretPosition(MathTextField.this.getCaretPosition() - 1);
}
}
synchronized void setNewString(FilterBypass fb, String tempStr) throws BadLocationException {
operatorTree = Utils.OperatorTree.parse(tempStr, "");
MathTextField.this.updateByOpTree(fb);
}
});
return d;
}
}
| true | true | protected Document createDefaultModel() {
PlainDocument d = (PlainDocument) super.createDefaultModel();
d.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
replace(fb, offset, 0, string, attr);
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
replace(fb, offset, length, "", null);
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String string, AttributeSet attrs)
throws BadLocationException {
String s = MathTextField.this.getText();
boolean insertedDummyChar = false;
boolean insertedBrackets = false;
String marked = s.substring(offset, offset + length);
if(string.matches(" |\\)") && s.substring(offset, offset + 1).equals(string)) {
MathTextField.this.setCaretPosition(offset + 1);
return;
}
string = string.replace(" ", "");
if(string.isEmpty() && marked.equals("(")) {
int count = 1;
while(offset + length < s.length()) {
length++;
marked = s.substring(offset, offset + length);
if(marked.charAt(0) == '(') count++;
else if(marked.charAt(0) == ')') count--;
if(count == 0) break;
}
}
else if(string.isEmpty() && marked.equals(")")) {
int count = -1;
while(offset > 0) {
offset--;
length++;
marked = s.substring(offset, offset + length);
if(marked.charAt(0) == '(') count++;
else if(marked.charAt(0) == ')') count--;
if(count == 0) break;
}
}
if(length == 0 && string.matches("\\+|-|\\*|/|=")) {
if(s.substring(offset).matches(" *(((\\+|-|∙|/|=|\\)).*)|)")) {
string = string + "_";
insertedDummyChar = true;
} else if(s.substring(offset).matches(" .*")) {
string = "_" + string;
insertedDummyChar = true;
}
}
else if(string.matches("\\(")) {
if(length == 0 || marked.equals("_")) {
string = "(_)";
insertedDummyChar = true;
}
else {
string = "(" + marked + ")";
insertedBrackets = true;
}
}
else if(string.matches("\\)"))
return; // ignore that
// situation: A = B, press DEL -> make it A = _
if(string.isEmpty() && offset > 0 && s.substring(offset - 1, offset).equals(" ") && !marked.equals("_")) {
string = "_";
insertedDummyChar = true;
}
setNewString(fb, s.substring(0, offset) + string + s.substring(offset + length));
if(insertedDummyChar) {
int p = MathTextField.this.getText().indexOf('_');
if(p >= 0) {
MathTextField.this.setCaretPosition(p);
MathTextField.this.moveCaretPosition(p + 1);
}
}
else if(insertedBrackets) {
// move just before the ')'
if(MathTextField.this.getCaretPosition() > 0)
MathTextField.this.setCaretPosition(MathTextField.this.getCaretPosition() - 1);
}
}
synchronized void setNewString(FilterBypass fb, String tempStr) throws BadLocationException {
operatorTree = Utils.OperatorTree.parse(tempStr, "");
MathTextField.this.updateByOpTree(fb);
}
});
return d;
}
| protected Document createDefaultModel() {
PlainDocument d = (PlainDocument) super.createDefaultModel();
d.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
replace(fb, offset, 0, string, attr);
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
replace(fb, offset, length, "", null);
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String string, AttributeSet attrs)
throws BadLocationException {
String s = MathTextField.this.getText();
boolean insertedDummyChar = false;
boolean insertedBrackets = false;
String marked = s.substring(offset, offset + length);
if(string.matches(" |\\)") && s.substring(offset, offset + 1).equals(string)) {
MathTextField.this.setCaretPosition(offset + 1);
return;
}
string = string.replace(" ", "");
if(string.isEmpty() && marked.equals("(")) {
int count = 1;
while(offset + length < s.length()) {
length++;
marked = s.substring(offset, offset + length);
if(marked.charAt(0) == '(') count++;
else if(marked.charAt(0) == ')') count--;
if(count == 0) break;
}
}
else if(string.isEmpty() && marked.equals(")")) {
int count = -1;
while(offset > 0) {
offset--;
length++;
marked = s.substring(offset, offset + length);
if(marked.charAt(0) == '(') count++;
else if(marked.charAt(0) == ')') count--;
if(count == 0) break;
}
}
if(length == 0 && string.matches("\\+|-|\\*|/|=")) {
if(s.substring(offset).matches(" *(((\\+|-|∙|/|=|\\)).*)|)")) {
string = string + "_";
insertedDummyChar = true;
} else if(s.substring(offset).matches(" .*")) {
string = "_" + string;
insertedDummyChar = true;
}
}
else if(string.matches("\\(")) {
if(length == 0 || marked.equals("_")) {
string = "(_)";
insertedDummyChar = true;
}
else {
string = "(" + marked + ")";
insertedBrackets = true;
}
}
else if(string.matches("\\)"))
return; // ignore that
// situation: A = B, press DEL -> make it A = _
if(string.isEmpty() && offset > 0 && length == 1 && s.substring(offset - 1, offset).equals(" ") && !marked.equals("_")) {
string = "_";
insertedDummyChar = true;
}
setNewString(fb, s.substring(0, offset) + string + s.substring(offset + length));
if(insertedDummyChar) {
int p = MathTextField.this.getText().indexOf('_');
if(p >= 0) {
MathTextField.this.setCaretPosition(p);
MathTextField.this.moveCaretPosition(p + 1);
}
}
else if(insertedBrackets) {
// move just before the ')'
if(MathTextField.this.getCaretPosition() > 0)
MathTextField.this.setCaretPosition(MathTextField.this.getCaretPosition() - 1);
}
}
synchronized void setNewString(FilterBypass fb, String tempStr) throws BadLocationException {
operatorTree = Utils.OperatorTree.parse(tempStr, "");
MathTextField.this.updateByOpTree(fb);
}
});
return d;
}
|
diff --git a/modules/grouping/src/test/org/apache/lucene/search/grouping/AllGroupsCollectorTest.java b/modules/grouping/src/test/org/apache/lucene/search/grouping/AllGroupsCollectorTest.java
index 00153e7f9..cff33202d 100644
--- a/modules/grouping/src/test/org/apache/lucene/search/grouping/AllGroupsCollectorTest.java
+++ b/modules/grouping/src/test/org/apache/lucene/search/grouping/AllGroupsCollectorTest.java
@@ -1,109 +1,109 @@
package org.apache.lucene.search.grouping;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.LuceneTestCase;
public class AllGroupsCollectorTest extends LuceneTestCase {
public void testTotalGroupCount() throws Exception {
final String groupField = "author";
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
// 0
Document doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "1", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 1
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "2", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 2
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random textual data", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "3", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
w.commit(); // To ensure a second segment
// 3
doc = new Document();
doc.add(new Field(groupField, "author2", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "4", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 4
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "5", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 5
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 6 -- no author field
doc = new Document();
doc.add(new Field("content", "random word stuck in alot of other text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
IndexSearcher indexSearcher = new IndexSearcher(w.getReader());
w.close();
- AllGroupsCollector c1 = new AllGroupsCollector(groupField);
+ TermAllGroupsCollector c1 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "random")), c1);
assertEquals(4, c1.getGroupCount());
- AllGroupsCollector c2 = new AllGroupsCollector(groupField);
+ TermAllGroupsCollector c2 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "some")), c2);
assertEquals(3, c2.getGroupCount());
- AllGroupsCollector c3 = new AllGroupsCollector(groupField);
+ TermAllGroupsCollector c3 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "blob")), c3);
assertEquals(2, c3.getGroupCount());
indexSearcher.getIndexReader().close();
dir.close();
}
}
| false | true | public void testTotalGroupCount() throws Exception {
final String groupField = "author";
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
// 0
Document doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "1", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 1
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "2", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 2
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random textual data", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "3", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
w.commit(); // To ensure a second segment
// 3
doc = new Document();
doc.add(new Field(groupField, "author2", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "4", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 4
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "5", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 5
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 6 -- no author field
doc = new Document();
doc.add(new Field("content", "random word stuck in alot of other text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
IndexSearcher indexSearcher = new IndexSearcher(w.getReader());
w.close();
AllGroupsCollector c1 = new AllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "random")), c1);
assertEquals(4, c1.getGroupCount());
AllGroupsCollector c2 = new AllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "some")), c2);
assertEquals(3, c2.getGroupCount());
AllGroupsCollector c3 = new AllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "blob")), c3);
assertEquals(2, c3.getGroupCount());
indexSearcher.getIndexReader().close();
dir.close();
}
| public void testTotalGroupCount() throws Exception {
final String groupField = "author";
Directory dir = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(
random,
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)).setMergePolicy(newLogMergePolicy()));
// 0
Document doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "1", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 1
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "2", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 2
doc = new Document();
doc.add(new Field(groupField, "author1", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random textual data", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "3", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
w.commit(); // To ensure a second segment
// 3
doc = new Document();
doc.add(new Field(groupField, "author2", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "4", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 4
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "some more random text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "5", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 5
doc = new Document();
doc.add(new Field(groupField, "author3", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("content", "random blob", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
// 6 -- no author field
doc = new Document();
doc.add(new Field("content", "random word stuck in alot of other text", Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("id", "6", Field.Store.YES, Field.Index.NO));
w.addDocument(doc);
IndexSearcher indexSearcher = new IndexSearcher(w.getReader());
w.close();
TermAllGroupsCollector c1 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "random")), c1);
assertEquals(4, c1.getGroupCount());
TermAllGroupsCollector c2 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "some")), c2);
assertEquals(3, c2.getGroupCount());
TermAllGroupsCollector c3 = new TermAllGroupsCollector(groupField);
indexSearcher.search(new TermQuery(new Term("content", "blob")), c3);
assertEquals(2, c3.getGroupCount());
indexSearcher.getIndexReader().close();
dir.close();
}
|
diff --git a/src/Core/org/objectweb/proactive/core/UniqueID.java b/src/Core/org/objectweb/proactive/core/UniqueID.java
index 748885845..8b654ff26 100644
--- a/src/Core/org/objectweb/proactive/core/UniqueID.java
+++ b/src/Core/org/objectweb/proactive/core/UniqueID.java
@@ -1,173 +1,173 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2008 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.core;
import org.apache.log4j.Logger;
import org.objectweb.proactive.annotation.PublicAPI;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
/**
* <p>
* UniqueID is a unique object identifier across all jvm. It is made of a unique VMID combined
* with a unique UID on that VM.
* </p><p>
* The UniqueID is used to identify object globally, even in case of migration.
* </p>
* @author The ProActive Team
* @version 1.0, 2001/10/23
* @since ProActive 0.9
*
*/
@PublicAPI
public class UniqueID implements java.io.Serializable, Comparable<UniqueID> {
private java.rmi.server.UID id;
private java.rmi.dgc.VMID vmID;
//the Unique ID of the JVM
private static java.rmi.dgc.VMID uniqueVMID = new java.rmi.dgc.VMID();
final protected static Logger logger = ProActiveLogger.getLogger(Loggers.CORE);
// Optim
private transient String cachedShortString;
private transient String cachedCanonString;
//
// -- CONSTRUCTORS -----------------------------------------------
//
/**
* Creates a new UniqueID
*/
public UniqueID() {
this.id = new java.rmi.server.UID();
this.vmID = uniqueVMID;
}
//
// -- PUBLIC STATIC METHODS -----------------------------------------------
//
/**
* Returns the VMID of the current VM in which this class has been loaded.
* @return the VMID of the current VM
*/
public static java.rmi.dgc.VMID getCurrentVMID() {
return uniqueVMID;
}
//
// -- PUBLIC METHODS -----------------------------------------------
//
/**
* Returns the VMID of this UniqueID. Note that the VMID of one UniqueID may differ
* from the local VMID (that one can get using <code>getCurrentVMID()</code> in case
* this UniqueID is attached to an object that has migrated.
* @return the VMID part of this UniqueID
*/
public java.rmi.dgc.VMID getVMID() {
return this.vmID;
}
/**
* Returns the UID part of this UniqueID.
* @return the UID part of this UniqueID
*/
public java.rmi.server.UID getUID() {
return this.id;
}
/**
* Returns a string representation of this UniqueID.
* @return a string representation of this UniqueID
*/
@Override
public String toString() {
if (logger.isDebugEnabled()) {
return shortString();
} else {
return getCanonString();
}
}
public String shortString() {
if (this.cachedShortString == null) {
this.cachedShortString = "" + Math.abs(this.getCanonString().hashCode() % 100000);
}
return this.cachedShortString;
}
public String getCanonString() {
if (this.cachedCanonString == null) {
this.cachedCanonString = ("" + this.id + "--" + this.vmID).replace(':', '-');
}
return this.cachedCanonString;
}
public int compareTo(UniqueID u) {
return getCanonString().compareTo(u.getCanonString());
}
/**
* Overrides hashCode to take into account the two part of this UniqueID.
* @return the hashcode of this object
*/
@Override
public int hashCode() {
return this.id.hashCode() + this.vmID.hashCode();
}
/**
* Overrides equals to take into account the two part of this UniqueID.
* @return the true if and only if o is an UniqueID equals to this UniqueID
*/
@Override
public boolean equals(Object o) {
//System.out.println("Now checking for equality");
if (o instanceof UniqueID) {
- return ((this.id.equals(((UniqueID) o).id)) && (this.vmID.equals(((UniqueID) o).vmID)));
+ return ((this.id.equals(((UniqueID) o).getUID())) && (this.vmID.equals(((UniqueID) o).getVMID())));
} else {
return false;
}
}
/**
* for debug purpose
*/
public void echo() {
logger.info("UniqueID The Id is " + this.id + " and the address is " + this.vmID);
}
}
| true | true | public boolean equals(Object o) {
//System.out.println("Now checking for equality");
if (o instanceof UniqueID) {
return ((this.id.equals(((UniqueID) o).id)) && (this.vmID.equals(((UniqueID) o).vmID)));
} else {
return false;
}
}
| public boolean equals(Object o) {
//System.out.println("Now checking for equality");
if (o instanceof UniqueID) {
return ((this.id.equals(((UniqueID) o).getUID())) && (this.vmID.equals(((UniqueID) o).getVMID())));
} else {
return false;
}
}
|
diff --git a/brjs-core/src/main/java/org/bladerunnerjs/model/ChildSourceAssetLocation.java b/brjs-core/src/main/java/org/bladerunnerjs/model/ChildSourceAssetLocation.java
index 3013b6cf6..ee5f30eb3 100644
--- a/brjs-core/src/main/java/org/bladerunnerjs/model/ChildSourceAssetLocation.java
+++ b/brjs-core/src/main/java/org/bladerunnerjs/model/ChildSourceAssetLocation.java
@@ -1,36 +1,36 @@
package org.bladerunnerjs.model;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.bladerunnerjs.model.engine.Node;
import org.bladerunnerjs.model.engine.RootNode;
import org.bladerunnerjs.model.exception.InvalidRequirePathException;
import org.bladerunnerjs.model.exception.RequirePathException;
public class ChildSourceAssetLocation extends ShallowAssetLocation {
private List<AssetLocation> dependentAssetLocations = new ArrayList<>();
public ChildSourceAssetLocation(RootNode rootNode, Node parent, File dir, AssetLocation parentAssetLocation) {
super(rootNode, parent, dir);
dependentAssetLocations.add(parentAssetLocation);
}
@Override
public String requirePrefix() throws RequirePathException {
String containerRequirePrefix = assetContainer.requirePrefix();
String locationRequirePrefix = assetContainer.file("src").toURI().relativize(dir().toURI()).getPath().replaceAll("/$", "");
if(!locationRequirePrefix.startsWith(containerRequirePrefix)) {
throw new InvalidRequirePathException("Source module containing directory '" + locationRequirePrefix + "' does not start with correct require prefix '" + containerRequirePrefix + "'.");
}
- return assetContainer.requirePrefix() + "/" + locationRequirePrefix;
+ return locationRequirePrefix;
}
@Override
public List<AssetLocation> getDependentAssetLocations() {
return dependentAssetLocations;
}
}
| true | true | public String requirePrefix() throws RequirePathException {
String containerRequirePrefix = assetContainer.requirePrefix();
String locationRequirePrefix = assetContainer.file("src").toURI().relativize(dir().toURI()).getPath().replaceAll("/$", "");
if(!locationRequirePrefix.startsWith(containerRequirePrefix)) {
throw new InvalidRequirePathException("Source module containing directory '" + locationRequirePrefix + "' does not start with correct require prefix '" + containerRequirePrefix + "'.");
}
return assetContainer.requirePrefix() + "/" + locationRequirePrefix;
}
| public String requirePrefix() throws RequirePathException {
String containerRequirePrefix = assetContainer.requirePrefix();
String locationRequirePrefix = assetContainer.file("src").toURI().relativize(dir().toURI()).getPath().replaceAll("/$", "");
if(!locationRequirePrefix.startsWith(containerRequirePrefix)) {
throw new InvalidRequirePathException("Source module containing directory '" + locationRequirePrefix + "' does not start with correct require prefix '" + containerRequirePrefix + "'.");
}
return locationRequirePrefix;
}
|
diff --git a/src/Exec.java b/src/Exec.java
index e194c6e..7307253 100644
--- a/src/Exec.java
+++ b/src/Exec.java
@@ -1,176 +1,176 @@
import java.awt.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.awt.image.*;
@SuppressWarnings("serial")
public class Exec extends JFrame
{
Image grid;
Image i;
Graphics g;
public int selected=1;
public ArrayList<Ship> ships;
public Exec(){
ships = new ArrayList<Ship>();
ships.add(new AircraftCarrier(400,150,1,0));
ships.add(new BattleShip(400,250,2,0));
ships.add(new BattleShip(400,350,3,0));
ships.add(new Submarine(400,450,4,0));
init();
}
public void init()
{
grid = new BufferedImage(800,600,BufferedImage.TYPE_INT_ARGB);
Graphics gs = grid.getGraphics();
gs.setColor(Color.black);
for (int x = 0; x < 800; x += 50) {
gs.drawLine(x,0,x,600);
}
for (int y = 0; y < 600; y += 50){
gs.drawLine(0,y,800,y);
}
reset();
this.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_LEFT){
// ships.get(selected).addX(-50);
- ships.get(selected).addAngle(-45);
+ ships.get(selected).addAngle(45);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_RIGHT){
// ships.get(selected).addX(50);
- ships.get(selected).addAngle(45);
+ ships.get(selected).addAngle(-45);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_UP){
ships.get(selected).addY(-50);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_DOWN){
ships.get(selected).addY(50);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_PAGE_UP){
if(selected>0){
selected--;
}
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_PAGE_DOWN){
if(selected<3){
selected++;
}
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_HOME){
selected = 1;
ships = new ArrayList<Ship>();
ships.add(new BattleShip(400,350,1,0));
ships.add(new BattleShip(400,250,2,0));
ships.add(new AircraftCarrier(400,150,1,0));
ships.add(new Submarine(400,450,2,0));
repaint();
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent arg0) {
}
});
MouseListener mouse = new MouseAdapter() {public void mousePressed(MouseEvent e){mousePressed2(e);}
public void mouseReleased(MouseEvent e){mouseReleased2(e);}};
this.addMouseListener(mouse);
MouseMotionListener mouse1 = new MouseAdapter() {public void mouseMoved(MouseEvent md){mouseM(md);}
public void mouseDragged(MouseEvent md){mouseDrag(md);}};
this.addMouseMotionListener(mouse1);
g = newBackground();
}
public void reset() {
g = newBackground();
repaint();
}
public Graphics newBackground() {
i = clearBuffer();
return i.getGraphics();
}
public Image clearBuffer() {
return new BufferedImage(800+16, 600+38, BufferedImage.TYPE_INT_ARGB);
}
public static void main(String[] args){
Exec battleship = new Exec();
battleship.setSize(800,600);
battleship.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
battleship.setVisible(true);
}
public void paint(Graphics g2){
g.setColor(Color.white);
g.fillRect(0,0,800,600);
g.drawImage(grid, 0,0, null);
g.setColor(Color.black);
g.drawString("Left moves the ship left", 55, 100);
g.drawString("Right moves the ship right",55, 125);
g.drawString("Down moves the ship down", 55, 150);
g.drawString("Up moves the ship up", 55, 175);
g.drawString("Page-Down selects the next ship", 55, 200);
g.drawString("Page-Up selects the previous ship", 55, 225);
g.drawString("Currently selected ship "+" "+ships.get(selected).getClass(),55,250);
for(int index = 0; index<ships.size();index++){
ships.get(index).drawShip(g);
}
g2.drawImage(i,8,32,this);
if(needsRepaint())
repaint();
}
public void update(Graphics g) {
paint(g);
delay(10);
}
public void delay(int n){
try {Thread.sleep(n);} catch (Exception e) {System.out.println("Sleep failed");}
}
public boolean needsRepaint(){
for(int index = 0; index<ships.size();index++){
if(ships.get(index).needsRepaint()){
return true;
}
}
return false;
}
public void mouseM(MouseEvent e){
int x = e.getX()-8;
int y = e.getY()-32;
ships.get(selected).MouseMoved(x,y);
repaint();
}
public void mouseReleased2(MouseEvent e)
{
repaint();
}
public void mousePressed2(MouseEvent e)
{
int x = e.getX()-8;
int y = e.getY()-32;
ships.get(selected).MouseClicked(x,y);
repaint();
}
public void mouseDrag(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
ships.get(selected).MouseMoved(x,y);
repaint();
}
}
| false | true | public void init()
{
grid = new BufferedImage(800,600,BufferedImage.TYPE_INT_ARGB);
Graphics gs = grid.getGraphics();
gs.setColor(Color.black);
for (int x = 0; x < 800; x += 50) {
gs.drawLine(x,0,x,600);
}
for (int y = 0; y < 600; y += 50){
gs.drawLine(0,y,800,y);
}
reset();
this.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_LEFT){
// ships.get(selected).addX(-50);
ships.get(selected).addAngle(-45);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_RIGHT){
// ships.get(selected).addX(50);
ships.get(selected).addAngle(45);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_UP){
ships.get(selected).addY(-50);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_DOWN){
ships.get(selected).addY(50);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_PAGE_UP){
if(selected>0){
selected--;
}
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_PAGE_DOWN){
if(selected<3){
selected++;
}
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_HOME){
selected = 1;
ships = new ArrayList<Ship>();
ships.add(new BattleShip(400,350,1,0));
ships.add(new BattleShip(400,250,2,0));
ships.add(new AircraftCarrier(400,150,1,0));
ships.add(new Submarine(400,450,2,0));
repaint();
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent arg0) {
}
});
MouseListener mouse = new MouseAdapter() {public void mousePressed(MouseEvent e){mousePressed2(e);}
public void mouseReleased(MouseEvent e){mouseReleased2(e);}};
this.addMouseListener(mouse);
MouseMotionListener mouse1 = new MouseAdapter() {public void mouseMoved(MouseEvent md){mouseM(md);}
public void mouseDragged(MouseEvent md){mouseDrag(md);}};
this.addMouseMotionListener(mouse1);
g = newBackground();
}
| public void init()
{
grid = new BufferedImage(800,600,BufferedImage.TYPE_INT_ARGB);
Graphics gs = grid.getGraphics();
gs.setColor(Color.black);
for (int x = 0; x < 800; x += 50) {
gs.drawLine(x,0,x,600);
}
for (int y = 0; y < 600; y += 50){
gs.drawLine(0,y,800,y);
}
reset();
this.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_LEFT){
// ships.get(selected).addX(-50);
ships.get(selected).addAngle(45);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_RIGHT){
// ships.get(selected).addX(50);
ships.get(selected).addAngle(-45);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_UP){
ships.get(selected).addY(-50);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_DOWN){
ships.get(selected).addY(50);
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_PAGE_UP){
if(selected>0){
selected--;
}
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_PAGE_DOWN){
if(selected<3){
selected++;
}
repaint();
}
if(k.getKeyCode() == KeyEvent.VK_HOME){
selected = 1;
ships = new ArrayList<Ship>();
ships.add(new BattleShip(400,350,1,0));
ships.add(new BattleShip(400,250,2,0));
ships.add(new AircraftCarrier(400,150,1,0));
ships.add(new Submarine(400,450,2,0));
repaint();
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent arg0) {
}
});
MouseListener mouse = new MouseAdapter() {public void mousePressed(MouseEvent e){mousePressed2(e);}
public void mouseReleased(MouseEvent e){mouseReleased2(e);}};
this.addMouseListener(mouse);
MouseMotionListener mouse1 = new MouseAdapter() {public void mouseMoved(MouseEvent md){mouseM(md);}
public void mouseDragged(MouseEvent md){mouseDrag(md);}};
this.addMouseMotionListener(mouse1);
g = newBackground();
}
|
diff --git a/src/main/java/org/jboss/fpak/generator/FpakGenerator.java b/src/main/java/org/jboss/fpak/generator/FpakGenerator.java
index d9a18d2..2fc71fb 100644
--- a/src/main/java/org/jboss/fpak/generator/FpakGenerator.java
+++ b/src/main/java/org/jboss/fpak/generator/FpakGenerator.java
@@ -1,86 +1,87 @@
package org.jboss.fpak.generator;
import org.jboss.fpak.Runner;
import org.jboss.fpak.parser.FPakParser;
import java.io.*;
/**
* @author Mike Brock .
*/
public class FPakGenerator {
private File workingDirectory = new File("").getAbsoluteFile();
private File targetFile = new File("out" + Runner.DEFAULT_FILE_EXTENSION);
public void generate() throws IOException {
if (targetFile.exists()) {
throw new RuntimeException("file already exists: " + targetFile.getAbsolutePath());
}
FileOutputStream outputStream = new FileOutputStream(targetFile);
PrintWriter writer = new PrintWriter(outputStream);
_generate(workingDirectory, writer);
System.out.println("generated: " + targetFile.getAbsolutePath());
}
private void _generate(File file, PrintWriter out) throws IOException {
if (file.isHidden()) return;
if (file.isDirectory()) {
for (File f : file.listFiles()) {
_generate(f, out);
}
} else if (!(file.getAbsolutePath().equals(targetFile.getAbsolutePath()))) {
writeFile(file, out);
}
}
private void writeFile(File file, PrintWriter out) throws IOException {
System.out.println(file.getAbsolutePath());
String fileName = file.getAbsolutePath().substring(workingDirectory.getAbsolutePath().length());
if (fileName.charAt(0) == '/') {
fileName = fileName.substring(1);
}
out.print("++");
out.print(fileName);
out.print(":{\n");
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
int read;
while ((read = inputStream.read()) != -1) {
switch (read) {
+ case '\\':
case '{':
case '}':
case '@':
case '$':
out.print('\\');
if (read == '@' || read == '$') {
out.print((char) read);
}
out.print((char) read);
break;
default:
out.print((char) read);
}
}
out.print("\n}\n\n");
out.flush();
}
public static void main(String[] args) throws IOException {
FPakGenerator gen = new FPakGenerator();
if (args.length > 0) {
gen.targetFile = new File(args[0]);
}
gen.generate();
}
}
| true | true | private void writeFile(File file, PrintWriter out) throws IOException {
System.out.println(file.getAbsolutePath());
String fileName = file.getAbsolutePath().substring(workingDirectory.getAbsolutePath().length());
if (fileName.charAt(0) == '/') {
fileName = fileName.substring(1);
}
out.print("++");
out.print(fileName);
out.print(":{\n");
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
int read;
while ((read = inputStream.read()) != -1) {
switch (read) {
case '{':
case '}':
case '@':
case '$':
out.print('\\');
if (read == '@' || read == '$') {
out.print((char) read);
}
out.print((char) read);
break;
default:
out.print((char) read);
}
}
out.print("\n}\n\n");
out.flush();
}
| private void writeFile(File file, PrintWriter out) throws IOException {
System.out.println(file.getAbsolutePath());
String fileName = file.getAbsolutePath().substring(workingDirectory.getAbsolutePath().length());
if (fileName.charAt(0) == '/') {
fileName = fileName.substring(1);
}
out.print("++");
out.print(fileName);
out.print(":{\n");
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
int read;
while ((read = inputStream.read()) != -1) {
switch (read) {
case '\\':
case '{':
case '}':
case '@':
case '$':
out.print('\\');
if (read == '@' || read == '$') {
out.print((char) read);
}
out.print((char) read);
break;
default:
out.print((char) read);
}
}
out.print("\n}\n\n");
out.flush();
}
|
diff --git a/src/com/nexus/users/User.java b/src/com/nexus/users/User.java
index 174c612..c47e753 100644
--- a/src/com/nexus/users/User.java
+++ b/src/com/nexus/users/User.java
@@ -1,118 +1,118 @@
package com.nexus.users;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import com.nexus.NexusServer;
import com.nexus.json.IProvideJsonMap;
import com.nexus.json.JSONPacket;
import com.nexus.logging.NexusLog;
import com.nexus.mysql.MySQLHelper;
import com.nexus.mysql.TableList;
import com.nexus.utils.Utils;
public class User implements IProvideJsonMap{
private int ID;
public String Username;
public String Fullname;
public String Email;
public String Role;
public String ImageURL = "";
public boolean CanReceiveNotify = true;
public UserPrivilleges Capabilities;
public RequestToken TwitterRequestToken;
public AccessToken TwitterAccessToken;
public static User FromID(int ID){
return NexusServer.instance().UserPool.GetUser(ID);
}
public static User FromUsername(String Username){
return NexusServer.instance().UserPool.GetUser(Username);
}
public static User FromResultSet(ResultSet rs){
User u = new User();
try{
u.ID = rs.getInt("UID");
u.Username = rs.getString("Username");
u.Fullname = rs.getString("FullName");
u.Email = rs.getString("Email");
u.Role = rs.getString("Role");
u.Capabilities = new UserPrivilleges(u.Role);
if(!rs.getString("TwitterAccessToken").isEmpty()){
u.TwitterAccessToken = new AccessToken(rs.getString("TwitterAccessToken"), rs.getString("TwitterAccessTokenSecret"));
}
}catch(SQLException e){
NexusLog.log(Level.SEVERE, e, "Error while constructing user from an ResultSet");
return null;
}
return u;
}
@Override
public JSONPacket toJsonMap(){
JSONPacket Packet = new JSONPacket();
Packet.put("ID", this.ID);
Packet.put("Username", this.Username);
Packet.put("Email", this.Email);
Packet.put("Role", this.Role);
Packet.put("Fullname", this.Fullname);
return Packet;
}
@Override
public String toString(){
return Utils.Gson.toJson(this.toJsonMap());
}
public void SaveData(){
try{
Connection conn = MySQLHelper.GetConnection();
Statement stmt = conn.createStatement();
//@formatter:off
stmt.execute(String.format("UPDATE %s SET ", TableList.TABLE_USERS) +
"Username = '" + this.Username + "', " +
"Fullname = '" + this.Fullname + "', " +
"Email = '" + this.Email + "', " +
"Role = '" + this.Role +"', " +
- "TwitterAccessToken = '" + this.TwitterAccessToken == null ? "" : this.TwitterAccessToken.getToken() +"', " +
- "TwitterAccessTokenSecret = '" + this.TwitterAccessToken == null ? "" : this.TwitterAccessToken.getTokenSecret() +
+ "TwitterAccessToken = '" + (this.TwitterAccessToken == null ? "" : this.TwitterAccessToken.getToken()) + "', " +
+ "TwitterAccessTokenSecret = '" + (this.TwitterAccessToken == null ? "" : this.TwitterAccessToken.getTokenSecret()) +
"' WHERE UID='" + this.ID + "'");
//@formatter:on
stmt.close();
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
public int getID(){
return this.ID;
}
@Override
@Deprecated
public boolean equals(Object obj){
if(obj instanceof User){
return this.Username.equals(((User) obj).Username);
}
return false;
}
@Override
@Deprecated
public int hashCode(){
return this.Username.hashCode();
}
}
| true | true | public void SaveData(){
try{
Connection conn = MySQLHelper.GetConnection();
Statement stmt = conn.createStatement();
//@formatter:off
stmt.execute(String.format("UPDATE %s SET ", TableList.TABLE_USERS) +
"Username = '" + this.Username + "', " +
"Fullname = '" + this.Fullname + "', " +
"Email = '" + this.Email + "', " +
"Role = '" + this.Role +"', " +
"TwitterAccessToken = '" + this.TwitterAccessToken == null ? "" : this.TwitterAccessToken.getToken() +"', " +
"TwitterAccessTokenSecret = '" + this.TwitterAccessToken == null ? "" : this.TwitterAccessToken.getTokenSecret() +
"' WHERE UID='" + this.ID + "'");
//@formatter:on
stmt.close();
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
| public void SaveData(){
try{
Connection conn = MySQLHelper.GetConnection();
Statement stmt = conn.createStatement();
//@formatter:off
stmt.execute(String.format("UPDATE %s SET ", TableList.TABLE_USERS) +
"Username = '" + this.Username + "', " +
"Fullname = '" + this.Fullname + "', " +
"Email = '" + this.Email + "', " +
"Role = '" + this.Role +"', " +
"TwitterAccessToken = '" + (this.TwitterAccessToken == null ? "" : this.TwitterAccessToken.getToken()) + "', " +
"TwitterAccessTokenSecret = '" + (this.TwitterAccessToken == null ? "" : this.TwitterAccessToken.getTokenSecret()) +
"' WHERE UID='" + this.ID + "'");
//@formatter:on
stmt.close();
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
|
diff --git a/src/main/java/dk/statsbiblioteket/doms/ingest/reklamepbcoremapper/BiografPBCoreMapper.java b/src/main/java/dk/statsbiblioteket/doms/ingest/reklamepbcoremapper/BiografPBCoreMapper.java
index 82a130b..e59eeeb 100644
--- a/src/main/java/dk/statsbiblioteket/doms/ingest/reklamepbcoremapper/BiografPBCoreMapper.java
+++ b/src/main/java/dk/statsbiblioteket/doms/ingest/reklamepbcoremapper/BiografPBCoreMapper.java
@@ -1,394 +1,394 @@
package dk.statsbiblioteket.doms.ingest.reklamepbcoremapper;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import dk.statsbiblioteket.util.xml.DOM;
import dk.statsbiblioteket.util.xml.XPathSelector;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Pattern;
/**
* Map all biografreklamefilm data to PBCore.
*/
public class BiografPBCoreMapper {
private static final SimpleDateFormat OUTPUT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-ddZ");
private static final SimpleDateFormat DURATION_FORMAT = new SimpleDateFormat("HH:mm:ss");
static {
DURATION_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC"));
}
private static final XPathSelector XPATH_SELECTOR = DOM
.createXPathSelector("p", "http://www.pbcore.org/PBCore/PBCoreNamespace.html");
private static final String SQL_QUERY_AD = "SELECT "
+ "ad.AdID," // 1
+ "ad.title," // 2
+ "ad.titleAlternative," // 3
+ "ad.subject," // 4
+ "substring(ad.description,0,charindex('$',ad.description)) AS description1," // 5
+ "substring(ad.description,charindex('$',description) + 1,char_length(ad.description)) AS description2,"// 6
+ "ad.descriptionExt," // 7
+ "ad.dateCensorship," // 8
+ "ad.datePremiere," // 9
+ "ad.formatExtentDigital," //10
+ "ad.formatExtentAnalogue," //11
+ "ad.identifierCensorshipCard," //12
+ "ad.identifierCensorshipCardNo," //13
+ "ad.registrant," //14
+ "ad.registerDate," //15
+ "ad.lastModifiedBy," //16
+ "ad.lastModified," //17
+ "ad.recordIDcensor," //18
+ "ad.fileName," //19
+ "ad.covSpatial " //20
+ "FROM Advertisement ad "
+ "WHERE ad.fileName != NULL";
private static final String SQL_QUERY_SUBJECT_KEYWORD = "SELECT "
+ "subject.word "
+ "FROM SubjectKeyword subject, AdvSubjectKeyword "
+ "WHERE AdvSubjectKeyword.AdID=?"
+ " AND AdvSubjectKeyword.subjectKeywordID = subject.subjectKeywordID";
private static final String SQL_QUERY_SUBJECT_REKLAMEFILM = "SELECT "
+ "child.word as subjectChild,"
+ "parent.word as subjectParent "
+ "FROM SubjectReklamefilm child, SubjectReklamefilm parent, AdvSubjectReklamefilm "
+ "WHERE AdvSubjectReklamefilm.AdID=?"
+ " AND AdvSubjectReklamefilm.subjectReklameID = child.subjectReklameID"
+ " AND child.parentID = parent.subjectReklameID";
private static final String SQL_QUERY_DECADE = "SELECT "
+ "decade.decade "
+ "FROM Decade decade, AdvDecade "
+ "WHERE AdvDecade.AdID=?"
+ " AND AdvDecade.decadeID = decade.decadeID";
private static final String SQL_QUERY_LANGUAGE = "SELECT "
+ "lan.abbreviation "
+ "FROM Language lan, AdvLanguage "
+ "WHERE AdvLanguage.AdID=? "
+ "AND lan.languageID=AdvLanguage.languageID";
private static final String SQL_QUERY_CONTRIBUTOR = "SELECT conrole.description, con.name FROM Contributor con, ContributorRole conrole, AdvContributor "
+ "WHERE con.contributorID=AdvContributor.contributorID "
+ "AND conrole.contributorRoleID = con.contributorRoleID "
+ "AND AdvContributor.AdID=?";
private static final String SQL_QUERY_CREATOR = "SELECT crerole.description, cre.name FROM Creator cre, CreatorRole crerole, AdvCreator "
+ "WHERE cre.creatorID=AdvCreator.creatorID "
+ "AND crerole.creatorRoleID = cre.creatorRoleID "
+ "AND AdvCreator.AdID=?";
//TODO: What to do with audit data (registrant etc.) 13,14,15,16
private static class MappingTuple {
enum Type {STRING, INT, DURATION, DATE, FILE, EXTENSIONCENSORCARDDATA1, EXTENSIONCENSORCARDDATA2, EXTENSIONCENSORCARDDATA3, EXTENSIONCENSORDATE, EXTENSIONCENSORESTIMATEDREELLENGTH, EXTENSIONCENSORCARD}
final int resultindex;
final String xpath;
final Type type;
boolean parent;
private MappingTuple(int resultindex, String xpath, Type type, boolean parent) {
this.resultindex = resultindex;
this.xpath = xpath;
this.type = type;
this.parent = parent;
}
}
private final List<MappingTuple> pbcoreBiografTemplateMappingTuples = new ArrayList<MappingTuple>(Arrays.asList(
new MappingTuple(1, "/p:PBCoreDescriptionDocument/p:pbcoreIdentifier[1]/p:identifier",
MappingTuple.Type.INT, true),
new MappingTuple(1, "/p:PBCoreDescriptionDocument/p:pbcoreInstantiation/p:pbcoreFormatID/p:formatIdentifier",
MappingTuple.Type.INT, true),
new MappingTuple(2, "/p:PBCoreDescriptionDocument/p:pbcoreTitle[1]/p:title",
MappingTuple.Type.STRING, true),
new MappingTuple(3, "/p:PBCoreDescriptionDocument/p:pbcoreTitle[2]/p:title",
MappingTuple.Type.STRING, true),
new MappingTuple(4, "/p:PBCoreDescriptionDocument/p:pbcoreSubject[4]/p:subject",
MappingTuple.Type.STRING, true),
new MappingTuple(5, "/p:PBCoreDescriptionDocument/p:pbcoreExtension[1]/p:extension",
MappingTuple.Type.EXTENSIONCENSORCARDDATA1, true),
new MappingTuple(6, "/p:PBCoreDescriptionDocument/p:pbcoreExtension[2]/p:extension",
MappingTuple.Type.EXTENSIONCENSORCARDDATA2, true),
new MappingTuple(7, "/p:PBCoreDescriptionDocument/p:pbcoreExtension[3]/p:extension",
MappingTuple.Type.EXTENSIONCENSORCARDDATA3, true),
new MappingTuple(8, "/p:PBCoreDescriptionDocument/p:pbcoreExtension[4]/p:extension",
MappingTuple.Type.EXTENSIONCENSORDATE, true),
new MappingTuple(9, "/p:PBCoreDescriptionDocument/p:pbcoreInstantiation/p:dateIssued",
MappingTuple.Type.DATE, false),
new MappingTuple(10, "/p:PBCoreDescriptionDocument/p:pbcoreInstantiation/p:formatDuration",
MappingTuple.Type.DURATION, false),
new MappingTuple(11, "/p:PBCoreDescriptionDocument/p:pbcoreExtension[5]/p:extension",
MappingTuple.Type.EXTENSIONCENSORESTIMATEDREELLENGTH, true),
new MappingTuple(12, "/p:PBCoreDescriptionDocument/p:pbcoreIdentifier[3]/p:identifier",
MappingTuple.Type.STRING, true),
new MappingTuple(13, "/p:PBCoreDescriptionDocument/p:pbcoreIdentifier[2]/p:identifier",
MappingTuple.Type.INT, true),
new MappingTuple(18, "/p:PBCoreDescriptionDocument/p:pbcoreExtension[6]/p:extension",
MappingTuple.Type.EXTENSIONCENSORCARD, true),
new MappingTuple(19, "/p:PBCoreDescriptionDocument/p:pbcoreInstantiation/p:formatLocation",
MappingTuple.Type.FILE, false),
new MappingTuple(20, "/p:PBCoreDescriptionDocument/p:pbcoreCoverage[1]/p:coverage",
MappingTuple.Type.STRING, true)));
public void mapSQLDataToPBCoreFiles(File outputdir, Connection c) throws SQLException, ClassNotFoundException {
Statement statement = c.createStatement();
statement.execute(SQL_QUERY_AD);
ResultSet resultSet = statement.getResultSet();
mapSQLDataToPBCoreFiles(resultSet, outputdir, c);
}
private void mapSQLDataToPBCoreFiles(ResultSet resultSet, File outputdir, Connection c) throws SQLException {
while (resultSet.next()) {
try {
mapResultSetToPBCoreFile(resultSet, outputdir, c);
} catch (Exception e) {
//TODO logging
e.printStackTrace(System.err);
}
}
}
private void mapResultSetToPBCoreFile(ResultSet resultSet, File outputdir, Connection c)
throws ParseException, IOException, TransformerException, SQLException {
// Initiate pbcore template
Document pbcoreDocument = DOM
.streamToDOM(getClass().getClassLoader().getResourceAsStream("pbcorebiograftemplate.xml"), true);
// Inject data
List<Node> nodesToDelete = new ArrayList<Node>();
for (MappingTuple pbcoreBiografTemplateMappingTuple : pbcoreBiografTemplateMappingTuples) {
String value;
switch (pbcoreBiografTemplateMappingTuple.type) {
case STRING:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
break;
case DATE:
Date date = resultSet.getDate(pbcoreBiografTemplateMappingTuple.resultindex);
value = date == null ? null : OUTPUT_DATE_FORMAT.format(date);
break;
case DURATION:
int duration = resultSet.getInt(pbcoreBiografTemplateMappingTuple.resultindex);
value = DURATION_FORMAT.format(new Date(duration * 1000L));
break;
case INT:
int number = resultSet.getInt(pbcoreBiografTemplateMappingTuple.resultindex);
value = Integer.toString(number);
break;
case FILE:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex).replaceAll(Pattern.quote("+"), " ");
break;
case EXTENSIONCENSORCARDDATA1:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcarddata1: " + value;
break;
case EXTENSIONCENSORCARDDATA2:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcarddata2: " + value;
break;
case EXTENSIONCENSORCARDDATA3:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcarddata3: " + value;
break;
case EXTENSIONCENSORDATE:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censordate: " + value;
break;
case EXTENSIONCENSORESTIMATEDREELLENGTH:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorestimatedreellength: " + value;
break;
case EXTENSIONCENSORCARD:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcard: " + value;
break;
default:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
break;
}
Node node = XPATH_SELECTOR.selectNode(pbcoreDocument, pbcoreBiografTemplateMappingTuple.xpath);
if (value != null) {
node.setTextContent(value);
} else {
if (pbcoreBiografTemplateMappingTuple.parent) {
nodesToDelete.add(node.getParentNode());
} else {
nodesToDelete.add(node);
}
}
}
int adID = resultSet.getInt(1);
//subject reklamefilm
PreparedStatement subjectStatement = c.prepareStatement(SQL_QUERY_SUBJECT_REKLAMEFILM);
subjectStatement.setInt(1, adID);
subjectStatement.execute();
ResultSet subjects = subjectStatement.getResultSet();
Node subjectNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreSubject[2]/p:subject");
Node subjectNode2 = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreSubject[3]/p:subject");
if (subjects.next()) {
String subjectString = subjects.getString(1);
if (subjectString.isEmpty()) {
- nodesToDelete.add(subjectNode);
+ nodesToDelete.add(subjectNode.getParentNode());
} else {
subjectNode.setTextContent(subjectString);
}
String subjectString2 = subjects.getString(2);
if (subjectString2.isEmpty()) {
- nodesToDelete.add(subjectNode2);
+ nodesToDelete.add(subjectNode2.getParentNode());
} else {
subjectNode2.setTextContent(subjectString2);
}
} else {
- nodesToDelete.add(subjectNode);
- nodesToDelete.add(subjectNode2);
+ nodesToDelete.add(subjectNode.getParentNode());
+ nodesToDelete.add(subjectNode2.getParentNode());
}
subjectStatement.close();
//subject keyword
PreparedStatement subjectKeywordStatement = c.prepareStatement(SQL_QUERY_SUBJECT_KEYWORD);
subjectKeywordStatement.setInt(1, adID);
subjectKeywordStatement.execute();
ResultSet subjectKeywords = subjectKeywordStatement.getResultSet();
Node subjectKeywordNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreSubject[1]/p:subject");
if (subjectKeywords.next()) {
String subjectKeywordString = subjectKeywords.getString(1);
if (subjectKeywordString.isEmpty()) {
nodesToDelete.add(subjectKeywordNode);
} else {
subjectKeywordNode.setTextContent(subjectKeywordString);
}
} else {
nodesToDelete.add(subjectKeywordNode);
}
subjectKeywordStatement.close();
//decade
PreparedStatement decadeStatement = c.prepareStatement(SQL_QUERY_DECADE);
decadeStatement.setInt(1, adID);
decadeStatement.execute();
ResultSet decades = decadeStatement.getResultSet();
Node decadeNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreCoverage[2]/p:coverage");
if (decades.next()) {
String decadeString = decades.getString(1);
if (decadeString.isEmpty()) {
nodesToDelete.add(decadeNode);
} else {
decadeNode.setTextContent(decadeString);
}
} else {
nodesToDelete.add(decadeNode);
}
decadeStatement.close();
//languages
PreparedStatement langStatement = c.prepareStatement(SQL_QUERY_LANGUAGE);
langStatement.setInt(1, adID);
langStatement.execute();
ResultSet languages = langStatement.getResultSet();
Node langNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreInstantiation/p:language");
String languageString = "";
while (languages.next()) {
if (!languageString.isEmpty()) {
languageString = languageString + ";";
}
languageString = languageString + languages.getString(1);
}
if (languageString.isEmpty()) {
nodesToDelete.add(langNode);
} else {
langNode.setTextContent(languageString);
}
langStatement.close();
//creators & contributors
Node createTemplateNode = XPATH_SELECTOR.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreCreator");
Node contributorTemplateNode = XPATH_SELECTOR.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreContributor");
nodesToDelete.add(createTemplateNode);
nodesToDelete.add(contributorTemplateNode);
PreparedStatement creatorStatement = c.prepareStatement(SQL_QUERY_CREATOR);
creatorStatement.setInt(1, adID);
creatorStatement.execute();
ResultSet creators = creatorStatement.getResultSet();
while (creators.next()) {
addCreatorOrContributor(createTemplateNode, contributorTemplateNode, creators.getString(2),
creators.getString(1));
}
creatorStatement.close();
PreparedStatement contributorStatement = c.prepareStatement(SQL_QUERY_CONTRIBUTOR);
contributorStatement.setInt(1, adID);
contributorStatement.execute();
ResultSet contributors = contributorStatement.getResultSet();
while (contributors.next()) {
addCreatorOrContributor(createTemplateNode, contributorTemplateNode, contributors.getString(2),
contributors.getString(1));
}
contributorStatement.close();
//Nodes are deleted last, to avoid affecting the XPath paths.
for (Node node : nodesToDelete) {
node.getParentNode().removeChild(node);
}
//Write pbcore to template with file name
String filename = resultSet.getString(19).replace(".mpg", ".xml").replaceAll(Pattern.quote("+"), " ");
new FileOutputStream(new File(outputdir, filename)).write(
DOM.domToString(pbcoreDocument, true).getBytes());
}
private void addCreatorOrContributor(Node creatorTemplate, Node contributorTemplate, String name, String role) {
if (role.equals("Instruktør")) {
cloneNode(creatorTemplate, name, "Director", "p:creator", "p:creatorRole");
} else if (role.equals("Tegner")) {
cloneNode(creatorTemplate, name, "Illustrator", "p:creator", "p:creatorRole");
} else if (role.equals("Oversætter")) {
cloneNode(contributorTemplate, name, "Translator", "p:contributor", "p:contributorRole");
} else if (role.equals("Medvirkende")) {
cloneNode(contributorTemplate, name, "Actor", "p:contributor", "p:contributorRole");
} else if (role.equals("Tekniske arbejder")) {
cloneNode(contributorTemplate, name, "Technical Production", "p:contributor", "p:contributorRole");
} else if (role.equals("Bureau")) {
cloneNode(creatorTemplate, name, "Production Unit", "p:creator", "p:creatorRole");
} else if (role.equals("Producent")) {
cloneNode(creatorTemplate, name, "Producer", "p:creator", "p:creatorRole");
} else {
throw new UnsupportedOperationException("Unsupported role: " + role);
}
}
private void cloneNode(Node template, String role, String name, String rolePath, String creatorPath) {
Node creatorNode = template.cloneNode(true);
Node roleNode = XPATH_SELECTOR.selectNode(creatorNode, rolePath);
Node nameNode = XPATH_SELECTOR.selectNode(creatorNode, creatorPath);
roleNode.setTextContent(role);
nameNode.setTextContent(name);
template.getParentNode().insertBefore(creatorNode, template);
}
}
| false | true | private void mapResultSetToPBCoreFile(ResultSet resultSet, File outputdir, Connection c)
throws ParseException, IOException, TransformerException, SQLException {
// Initiate pbcore template
Document pbcoreDocument = DOM
.streamToDOM(getClass().getClassLoader().getResourceAsStream("pbcorebiograftemplate.xml"), true);
// Inject data
List<Node> nodesToDelete = new ArrayList<Node>();
for (MappingTuple pbcoreBiografTemplateMappingTuple : pbcoreBiografTemplateMappingTuples) {
String value;
switch (pbcoreBiografTemplateMappingTuple.type) {
case STRING:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
break;
case DATE:
Date date = resultSet.getDate(pbcoreBiografTemplateMappingTuple.resultindex);
value = date == null ? null : OUTPUT_DATE_FORMAT.format(date);
break;
case DURATION:
int duration = resultSet.getInt(pbcoreBiografTemplateMappingTuple.resultindex);
value = DURATION_FORMAT.format(new Date(duration * 1000L));
break;
case INT:
int number = resultSet.getInt(pbcoreBiografTemplateMappingTuple.resultindex);
value = Integer.toString(number);
break;
case FILE:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex).replaceAll(Pattern.quote("+"), " ");
break;
case EXTENSIONCENSORCARDDATA1:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcarddata1: " + value;
break;
case EXTENSIONCENSORCARDDATA2:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcarddata2: " + value;
break;
case EXTENSIONCENSORCARDDATA3:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcarddata3: " + value;
break;
case EXTENSIONCENSORDATE:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censordate: " + value;
break;
case EXTENSIONCENSORESTIMATEDREELLENGTH:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorestimatedreellength: " + value;
break;
case EXTENSIONCENSORCARD:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcard: " + value;
break;
default:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
break;
}
Node node = XPATH_SELECTOR.selectNode(pbcoreDocument, pbcoreBiografTemplateMappingTuple.xpath);
if (value != null) {
node.setTextContent(value);
} else {
if (pbcoreBiografTemplateMappingTuple.parent) {
nodesToDelete.add(node.getParentNode());
} else {
nodesToDelete.add(node);
}
}
}
int adID = resultSet.getInt(1);
//subject reklamefilm
PreparedStatement subjectStatement = c.prepareStatement(SQL_QUERY_SUBJECT_REKLAMEFILM);
subjectStatement.setInt(1, adID);
subjectStatement.execute();
ResultSet subjects = subjectStatement.getResultSet();
Node subjectNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreSubject[2]/p:subject");
Node subjectNode2 = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreSubject[3]/p:subject");
if (subjects.next()) {
String subjectString = subjects.getString(1);
if (subjectString.isEmpty()) {
nodesToDelete.add(subjectNode);
} else {
subjectNode.setTextContent(subjectString);
}
String subjectString2 = subjects.getString(2);
if (subjectString2.isEmpty()) {
nodesToDelete.add(subjectNode2);
} else {
subjectNode2.setTextContent(subjectString2);
}
} else {
nodesToDelete.add(subjectNode);
nodesToDelete.add(subjectNode2);
}
subjectStatement.close();
//subject keyword
PreparedStatement subjectKeywordStatement = c.prepareStatement(SQL_QUERY_SUBJECT_KEYWORD);
subjectKeywordStatement.setInt(1, adID);
subjectKeywordStatement.execute();
ResultSet subjectKeywords = subjectKeywordStatement.getResultSet();
Node subjectKeywordNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreSubject[1]/p:subject");
if (subjectKeywords.next()) {
String subjectKeywordString = subjectKeywords.getString(1);
if (subjectKeywordString.isEmpty()) {
nodesToDelete.add(subjectKeywordNode);
} else {
subjectKeywordNode.setTextContent(subjectKeywordString);
}
} else {
nodesToDelete.add(subjectKeywordNode);
}
subjectKeywordStatement.close();
//decade
PreparedStatement decadeStatement = c.prepareStatement(SQL_QUERY_DECADE);
decadeStatement.setInt(1, adID);
decadeStatement.execute();
ResultSet decades = decadeStatement.getResultSet();
Node decadeNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreCoverage[2]/p:coverage");
if (decades.next()) {
String decadeString = decades.getString(1);
if (decadeString.isEmpty()) {
nodesToDelete.add(decadeNode);
} else {
decadeNode.setTextContent(decadeString);
}
} else {
nodesToDelete.add(decadeNode);
}
decadeStatement.close();
//languages
PreparedStatement langStatement = c.prepareStatement(SQL_QUERY_LANGUAGE);
langStatement.setInt(1, adID);
langStatement.execute();
ResultSet languages = langStatement.getResultSet();
Node langNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreInstantiation/p:language");
String languageString = "";
while (languages.next()) {
if (!languageString.isEmpty()) {
languageString = languageString + ";";
}
languageString = languageString + languages.getString(1);
}
if (languageString.isEmpty()) {
nodesToDelete.add(langNode);
} else {
langNode.setTextContent(languageString);
}
langStatement.close();
//creators & contributors
Node createTemplateNode = XPATH_SELECTOR.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreCreator");
Node contributorTemplateNode = XPATH_SELECTOR.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreContributor");
nodesToDelete.add(createTemplateNode);
nodesToDelete.add(contributorTemplateNode);
PreparedStatement creatorStatement = c.prepareStatement(SQL_QUERY_CREATOR);
creatorStatement.setInt(1, adID);
creatorStatement.execute();
ResultSet creators = creatorStatement.getResultSet();
while (creators.next()) {
addCreatorOrContributor(createTemplateNode, contributorTemplateNode, creators.getString(2),
creators.getString(1));
}
creatorStatement.close();
PreparedStatement contributorStatement = c.prepareStatement(SQL_QUERY_CONTRIBUTOR);
contributorStatement.setInt(1, adID);
contributorStatement.execute();
ResultSet contributors = contributorStatement.getResultSet();
while (contributors.next()) {
addCreatorOrContributor(createTemplateNode, contributorTemplateNode, contributors.getString(2),
contributors.getString(1));
}
contributorStatement.close();
//Nodes are deleted last, to avoid affecting the XPath paths.
for (Node node : nodesToDelete) {
node.getParentNode().removeChild(node);
}
//Write pbcore to template with file name
String filename = resultSet.getString(19).replace(".mpg", ".xml").replaceAll(Pattern.quote("+"), " ");
new FileOutputStream(new File(outputdir, filename)).write(
DOM.domToString(pbcoreDocument, true).getBytes());
}
| private void mapResultSetToPBCoreFile(ResultSet resultSet, File outputdir, Connection c)
throws ParseException, IOException, TransformerException, SQLException {
// Initiate pbcore template
Document pbcoreDocument = DOM
.streamToDOM(getClass().getClassLoader().getResourceAsStream("pbcorebiograftemplate.xml"), true);
// Inject data
List<Node> nodesToDelete = new ArrayList<Node>();
for (MappingTuple pbcoreBiografTemplateMappingTuple : pbcoreBiografTemplateMappingTuples) {
String value;
switch (pbcoreBiografTemplateMappingTuple.type) {
case STRING:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
break;
case DATE:
Date date = resultSet.getDate(pbcoreBiografTemplateMappingTuple.resultindex);
value = date == null ? null : OUTPUT_DATE_FORMAT.format(date);
break;
case DURATION:
int duration = resultSet.getInt(pbcoreBiografTemplateMappingTuple.resultindex);
value = DURATION_FORMAT.format(new Date(duration * 1000L));
break;
case INT:
int number = resultSet.getInt(pbcoreBiografTemplateMappingTuple.resultindex);
value = Integer.toString(number);
break;
case FILE:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex).replaceAll(Pattern.quote("+"), " ");
break;
case EXTENSIONCENSORCARDDATA1:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcarddata1: " + value;
break;
case EXTENSIONCENSORCARDDATA2:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcarddata2: " + value;
break;
case EXTENSIONCENSORCARDDATA3:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcarddata3: " + value;
break;
case EXTENSIONCENSORDATE:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censordate: " + value;
break;
case EXTENSIONCENSORESTIMATEDREELLENGTH:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorestimatedreellength: " + value;
break;
case EXTENSIONCENSORCARD:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
value = value == null ? null : "censorcard: " + value;
break;
default:
value = resultSet.getString(pbcoreBiografTemplateMappingTuple.resultindex);
break;
}
Node node = XPATH_SELECTOR.selectNode(pbcoreDocument, pbcoreBiografTemplateMappingTuple.xpath);
if (value != null) {
node.setTextContent(value);
} else {
if (pbcoreBiografTemplateMappingTuple.parent) {
nodesToDelete.add(node.getParentNode());
} else {
nodesToDelete.add(node);
}
}
}
int adID = resultSet.getInt(1);
//subject reklamefilm
PreparedStatement subjectStatement = c.prepareStatement(SQL_QUERY_SUBJECT_REKLAMEFILM);
subjectStatement.setInt(1, adID);
subjectStatement.execute();
ResultSet subjects = subjectStatement.getResultSet();
Node subjectNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreSubject[2]/p:subject");
Node subjectNode2 = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreSubject[3]/p:subject");
if (subjects.next()) {
String subjectString = subjects.getString(1);
if (subjectString.isEmpty()) {
nodesToDelete.add(subjectNode.getParentNode());
} else {
subjectNode.setTextContent(subjectString);
}
String subjectString2 = subjects.getString(2);
if (subjectString2.isEmpty()) {
nodesToDelete.add(subjectNode2.getParentNode());
} else {
subjectNode2.setTextContent(subjectString2);
}
} else {
nodesToDelete.add(subjectNode.getParentNode());
nodesToDelete.add(subjectNode2.getParentNode());
}
subjectStatement.close();
//subject keyword
PreparedStatement subjectKeywordStatement = c.prepareStatement(SQL_QUERY_SUBJECT_KEYWORD);
subjectKeywordStatement.setInt(1, adID);
subjectKeywordStatement.execute();
ResultSet subjectKeywords = subjectKeywordStatement.getResultSet();
Node subjectKeywordNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreSubject[1]/p:subject");
if (subjectKeywords.next()) {
String subjectKeywordString = subjectKeywords.getString(1);
if (subjectKeywordString.isEmpty()) {
nodesToDelete.add(subjectKeywordNode);
} else {
subjectKeywordNode.setTextContent(subjectKeywordString);
}
} else {
nodesToDelete.add(subjectKeywordNode);
}
subjectKeywordStatement.close();
//decade
PreparedStatement decadeStatement = c.prepareStatement(SQL_QUERY_DECADE);
decadeStatement.setInt(1, adID);
decadeStatement.execute();
ResultSet decades = decadeStatement.getResultSet();
Node decadeNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreCoverage[2]/p:coverage");
if (decades.next()) {
String decadeString = decades.getString(1);
if (decadeString.isEmpty()) {
nodesToDelete.add(decadeNode);
} else {
decadeNode.setTextContent(decadeString);
}
} else {
nodesToDelete.add(decadeNode);
}
decadeStatement.close();
//languages
PreparedStatement langStatement = c.prepareStatement(SQL_QUERY_LANGUAGE);
langStatement.setInt(1, adID);
langStatement.execute();
ResultSet languages = langStatement.getResultSet();
Node langNode = XPATH_SELECTOR
.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreInstantiation/p:language");
String languageString = "";
while (languages.next()) {
if (!languageString.isEmpty()) {
languageString = languageString + ";";
}
languageString = languageString + languages.getString(1);
}
if (languageString.isEmpty()) {
nodesToDelete.add(langNode);
} else {
langNode.setTextContent(languageString);
}
langStatement.close();
//creators & contributors
Node createTemplateNode = XPATH_SELECTOR.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreCreator");
Node contributorTemplateNode = XPATH_SELECTOR.selectNode(pbcoreDocument, "/p:PBCoreDescriptionDocument/p:pbcoreContributor");
nodesToDelete.add(createTemplateNode);
nodesToDelete.add(contributorTemplateNode);
PreparedStatement creatorStatement = c.prepareStatement(SQL_QUERY_CREATOR);
creatorStatement.setInt(1, adID);
creatorStatement.execute();
ResultSet creators = creatorStatement.getResultSet();
while (creators.next()) {
addCreatorOrContributor(createTemplateNode, contributorTemplateNode, creators.getString(2),
creators.getString(1));
}
creatorStatement.close();
PreparedStatement contributorStatement = c.prepareStatement(SQL_QUERY_CONTRIBUTOR);
contributorStatement.setInt(1, adID);
contributorStatement.execute();
ResultSet contributors = contributorStatement.getResultSet();
while (contributors.next()) {
addCreatorOrContributor(createTemplateNode, contributorTemplateNode, contributors.getString(2),
contributors.getString(1));
}
contributorStatement.close();
//Nodes are deleted last, to avoid affecting the XPath paths.
for (Node node : nodesToDelete) {
node.getParentNode().removeChild(node);
}
//Write pbcore to template with file name
String filename = resultSet.getString(19).replace(".mpg", ".xml").replaceAll(Pattern.quote("+"), " ");
new FileOutputStream(new File(outputdir, filename)).write(
DOM.domToString(pbcoreDocument, true).getBytes());
}
|
diff --git a/src/main/java/com/rogue/playtime/command/OnlineCommand.java b/src/main/java/com/rogue/playtime/command/OnlineCommand.java
index 30f7a0b..1efeafc 100644
--- a/src/main/java/com/rogue/playtime/command/OnlineCommand.java
+++ b/src/main/java/com/rogue/playtime/command/OnlineCommand.java
@@ -1,65 +1,65 @@
/*
* Copyright (C) 2013 Spencer Alderman
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.rogue.playtime.command;
import static com.rogue.playtime.Playtime._;
import static com.rogue.playtime.command.CommandBase.plugin;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
*
* @since 1.3.0
* @author 1Rogue
* @version 1.3.0
*/
public class OnlineCommand implements CommandBase {
@Override
public boolean execute(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String check;
- String perm = "playtime.use";
+ String perm = "playtime.online";
if (args.length == 0 && sender instanceof Player) {
check = sender.getName();
} else if (args.length == 1) {
check = plugin.getBestPlayer(args[0]);
perm += ".others";
} else {
sender.sendMessage("You cannot check the online time of a non-player!");
return true;
}
if (sender.hasPermission(perm)) {
int time = plugin.getDataManager().getDataHandler().getValue("onlinetime", check);
int minutes = time % 60;
if (time >= 60) {
int hours = time / 60;
sender.sendMessage(_("[&ePlayTime&f] &6" + check + " has been online for " + hours + " hour" + (hours == 1 ? "" : "s") + " and " + minutes + " minute" + (minutes == 1 ? "" : "s") + "."));
} else {
sender.sendMessage(_("[&ePlayTime&f] &6" + check + " has been online for " + minutes + " minute" + (minutes == 1 ? "" : "s") + "."));
}
} else {
sender.sendMessage(_("[&ePlayTime&f] &6You do not have permission to do that!"));
}
return false;
}
public String getName() {
return "onlinetime";
}
}
| true | true | public boolean execute(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String check;
String perm = "playtime.use";
if (args.length == 0 && sender instanceof Player) {
check = sender.getName();
} else if (args.length == 1) {
check = plugin.getBestPlayer(args[0]);
perm += ".others";
} else {
sender.sendMessage("You cannot check the online time of a non-player!");
return true;
}
if (sender.hasPermission(perm)) {
int time = plugin.getDataManager().getDataHandler().getValue("onlinetime", check);
int minutes = time % 60;
if (time >= 60) {
int hours = time / 60;
sender.sendMessage(_("[&ePlayTime&f] &6" + check + " has been online for " + hours + " hour" + (hours == 1 ? "" : "s") + " and " + minutes + " minute" + (minutes == 1 ? "" : "s") + "."));
} else {
sender.sendMessage(_("[&ePlayTime&f] &6" + check + " has been online for " + minutes + " minute" + (minutes == 1 ? "" : "s") + "."));
}
} else {
sender.sendMessage(_("[&ePlayTime&f] &6You do not have permission to do that!"));
}
return false;
}
| public boolean execute(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String check;
String perm = "playtime.online";
if (args.length == 0 && sender instanceof Player) {
check = sender.getName();
} else if (args.length == 1) {
check = plugin.getBestPlayer(args[0]);
perm += ".others";
} else {
sender.sendMessage("You cannot check the online time of a non-player!");
return true;
}
if (sender.hasPermission(perm)) {
int time = plugin.getDataManager().getDataHandler().getValue("onlinetime", check);
int minutes = time % 60;
if (time >= 60) {
int hours = time / 60;
sender.sendMessage(_("[&ePlayTime&f] &6" + check + " has been online for " + hours + " hour" + (hours == 1 ? "" : "s") + " and " + minutes + " minute" + (minutes == 1 ? "" : "s") + "."));
} else {
sender.sendMessage(_("[&ePlayTime&f] &6" + check + " has been online for " + minutes + " minute" + (minutes == 1 ? "" : "s") + "."));
}
} else {
sender.sendMessage(_("[&ePlayTime&f] &6You do not have permission to do that!"));
}
return false;
}
|
diff --git a/src/main/java/org/jboss/aesh/util/FileLister.java b/src/main/java/org/jboss/aesh/util/FileLister.java
index 03694001..b72c6557 100644
--- a/src/main/java/org/jboss/aesh/util/FileLister.java
+++ b/src/main/java/org/jboss/aesh/util/FileLister.java
@@ -1,353 +1,353 @@
/*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.aesh.util;
import org.jboss.aesh.complete.CompleteOperation;
import org.jboss.aesh.console.Config;
import org.jboss.aesh.parser.Parser;
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Helper class to list possible files during a complete operation.
*
* @author <a href="mailto:[email protected]">Ståle W. Pedersen</a>
*/
public class FileLister {
private static final Pattern startsWithParent = Pattern.compile("^\\.\\..*");
private static final Pattern startsWithHomePattern = Pattern.compile("^~/*");
private static final Pattern containParent = Config.isOSPOSIXCompatible() ?
Pattern.compile("[\\.\\.["+ Config.getPathSeparator()+"]?]+") : Pattern.compile("[\\.\\.[\\\\]?]+");
private static final Pattern space = Pattern.compile(".+\\s+.+");
private static final Pattern startsWithSlash = Config.isOSPOSIXCompatible() ?
Pattern.compile("^\\"+Config.getPathSeparator()+".*") : Pattern.compile("^\\\\.*");
private static final Pattern endsWithSlash = Config.isOSPOSIXCompatible() ?
Pattern.compile(".*\\"+Config.getPathSeparator()+"$") : Pattern.compile(".*\\\\$");
private String incDir;
private File cwd;
private String rest;
private String lastDir;
private FileFilter fileFilter;
public FileLister(String incDir, File cwd) {
if(incDir == null)
throw new IllegalArgumentException("Incoming directory cannot be null");
if(cwd == null)
throw new IllegalArgumentException("Current working directory cannot be null");
this.incDir = Parser.switchEscapedSpacesToSpacesInWord(incDir);
this.cwd = cwd;
findRestAndLastDir();
setFileFilter(Filter.ALL);
}
public FileLister(String incDir, File cwd, Filter filter) {
this(incDir, cwd);
setFileFilter(filter);
}
public FileLister(String incDir, File cwd, FileFilter fileFilter) {
this(incDir, cwd);
this.fileFilter = fileFilter;
}
private void setFileFilter(Filter filter) {
if(filter == Filter.ALL)
fileFilter = new FileAndDirectoryFilter();
else if(filter == Filter.FILE)
fileFilter = new OnlyFileFilter();
else
fileFilter = new DirectoryFileFilter();
}
/**
* findMatchingDirectories will try to populate the CompleteOperation
* object based on it initial params.
*
* @param completion
*/
public void findMatchingDirectories(CompleteOperation completion) {
completion.doAppendSeparator(false);
//if incDir is empty, just list cwd
if(incDir.trim().isEmpty()) {
completion.addCompletionCandidates( listDirectory(cwd, null));
}
else if(startWithHome()) {
if(isHomeAndIncDirADirectory()) {
if(endWithSlash()) {
completion.addCompletionCandidates(
listDirectory(new File(Config.getHomeDir()+incDir.substring(1)), null));
}
else
completion.addCompletionCandidate(Config.getPathSeparator());
}
else if(isHomeAndIncDirAFile()) {
completion.addCompletionCandidate("");
//append when we have a file
completion.doAppendSeparator(true);
}
//not a directory or file, list what we find
else {
listPossibleDirectories(completion);
}
}
else if(!startWithSlash()) {
if(isCwdAndIncDirADirectory()) {
if(endWithSlash()) {
completion.addCompletionCandidates(
listDirectory(new File(cwd.getAbsolutePath() +
Config.getPathSeparator()+incDir), null));
}
else
completion.addCompletionCandidate(Config.getPathSeparator());
}
else if(isCwdAndIncDirAFile()) {
listPossibleDirectories(completion);
if(completion.getCompletionCandidates().size() == 1) {
completion.getCompletionCandidates().set(0, "");
//append when we have a file
completion.doAppendSeparator(true);
}
}
//not a directory or file, list what we find
else {
listPossibleDirectories(completion);
}
}
else if(startWithSlash()) {
if(isIncDirADirectory()) {
if(endWithSlash()) {
completion.addCompletionCandidates(
listDirectory(new File(incDir), null));
}
else
completion.addCompletionCandidate(Config.getPathSeparator());
}
else if(isIncDirAFile()) {
listPossibleDirectories(completion);
if(completion.getCompletionCandidates().size() == 1) {
completion.getCompletionCandidates().set(0, "");
//completion.addCompletionCandidate("");
//append when we have a file
completion.doAppendSeparator(true);
}
}
//not a directory or file, list what we find
else {
listPossibleDirectories(completion);
}
}
//try to find if more than one filename start with the same word
if(completion.getCompletionCandidates().size() > 1) {
String startsWith = Parser.findStartsWith(completion.getCompletionCandidates());
if(startsWith.contains(" "))
startsWith = Parser.switchEscapedSpacesToSpacesInWord(startsWith);
- if(startsWith != null && startsWith.length() > 0 &&
+ if(startsWith != null && startsWith.length() > 0 && rest != null &&
startsWith.length() > rest.length()) {
completion.getCompletionCandidates().clear();
completion.addCompletionCandidate(Parser.switchSpacesToEscapedSpacesInWord(startsWith));
}
}
//new offset tweaking to match the "common" way of returning completions
if(completion.getCompletionCandidates().size() == 1) {
if(isIncDirADirectory() && !endWithSlash()) {
completion.getCompletionCandidates().set(0, incDir +
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
}
else if(isIncDirAFile()) {
completion.getCompletionCandidates().set(0, incDir +
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
completion.doAppendSeparator(true);
}
else if(incDir != null) {
if(rest != null && incDir.length() > rest.length()) {
completion.getCompletionCandidates().set(0,
Parser.switchSpacesToEscapedSpacesInWord(
incDir.substring(0, incDir.length()-rest.length() )) +
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
}
else if(rest != null && incDir.length() == rest.length()) {
completion.setOffset(completion.getCursor()-(rest.length()+Parser.findNumberOfSpacesInWord(rest)));
}
else {
if(incDir.endsWith(Config.getPathSeparator()))
completion.getCompletionCandidates().set(0, Parser.switchSpacesToEscapedSpacesInWord(incDir) +
completion.getCompletionCandidates().get(0));
else
completion.getCompletionCandidates().set(0, Parser.switchSpacesToEscapedSpacesInWord(incDir) +
Config.getPathSeparator()+
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
}
}
else {
completion.setOffset(completion.getCursor());
}
}
else if(completion.getCompletionCandidates().size() > 1) {
if(rest != null && rest.length() > 0)
completion.setOffset(completion.getCursor() - rest.length());
}
}
private void listPossibleDirectories(CompleteOperation completion) {
List<String> returnFiles;
if(startWithSlash()) {
if(lastDir != null && lastDir.startsWith(Config.getPathSeparator()))
returnFiles = listDirectory(new File(lastDir), rest);
else
returnFiles = listDirectory(new File(Config.getPathSeparator()+lastDir), rest);
}
else if(startWithHome()) {
if(lastDir != null) {
returnFiles = listDirectory(new File(Config.getHomeDir()+lastDir.substring(1)), rest);
}
else
returnFiles = listDirectory(new File(Config.getHomeDir()+Config.getPathSeparator()), rest);
}
else if(lastDir != null) {
returnFiles = listDirectory(new File(cwd+
Config.getPathSeparator()+lastDir), rest);
}
else
returnFiles = listDirectory(cwd, rest);
completion.addCompletionCandidates(returnFiles);
}
private void findRestAndLastDir() {
if(incDir.contains(Config.getPathSeparator())) {
lastDir = incDir.substring(0, incDir.lastIndexOf(Config.getPathSeparator()));
rest = incDir.substring(incDir.lastIndexOf(Config.getPathSeparator())+1);
}
else {
if(new File(cwd+Config.getPathSeparator()+incDir).exists())
lastDir = incDir;
else {
rest = incDir;
}
}
}
private boolean isIncDirADirectory() {
return new File(incDir).isDirectory();
}
private boolean isIncDirAFile() {
return new File(incDir).isFile();
}
private boolean isCwdAndIncDirADirectory() {
return new File(cwd.getAbsolutePath() +
Config.getPathSeparator() + incDir).isDirectory();
}
private boolean isCwdAndIncDirAFile() {
return new File(cwd.getAbsolutePath() +
Config.getPathSeparator() + incDir).isFile();
}
private boolean isHomeAndIncDirADirectory() {
return new File(Config.getHomeDir()+
incDir.substring(1)).isDirectory();
}
private boolean isHomeAndIncDirAFile() {
return new File(Config.getHomeDir()+
incDir.substring(1)).isFile();
}
private boolean startWithParent() {
return startsWithParent.matcher(incDir).matches();
}
private boolean startWithHome() {
return incDir.startsWith("~/");
}
private boolean startWithSlash() {
return startsWithSlash.matcher(incDir).matches();
}
private boolean endWithSlash() {
return endsWithSlash.matcher(incDir).matches();
}
private List<String> listDirectory(File path, String rest) {
List<String> fileNames = new ArrayList<String>();
if(path != null && path.isDirectory()) {
for(File file : path.listFiles(fileFilter)) {
if(rest == null || rest.length() == 0)
if(file.isDirectory())
fileNames.add(Parser.switchSpacesToEscapedSpacesInWord(file.getName())+Config.getPathSeparator());
else
fileNames.add(Parser.switchSpacesToEscapedSpacesInWord(file.getName()));
else {
if(file.getName().startsWith(rest)) {
if(file.isDirectory())
fileNames.add(Parser.switchSpacesToEscapedSpacesInWord(file.getName())+Config.getPathSeparator());
else
fileNames.add(Parser.switchSpacesToEscapedSpacesInWord(file.getName()));
}
}
}
}
return fileNames;
}
@Override
public String toString() {
return "FileLister{" +
"incDir='" + incDir + '\'' +
", cwd=" + cwd +
", rest='" + rest + '\'' +
", lastDir='" + lastDir + '\'' +
'}';
}
class DirectoryFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
}
class FileAndDirectoryFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory() || pathname.isFile();
}
}
//love this name :)
class OnlyFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.isFile();
}
}
public enum Filter { FILE,DIRECTORY,ALL}
}
| true | true | public void findMatchingDirectories(CompleteOperation completion) {
completion.doAppendSeparator(false);
//if incDir is empty, just list cwd
if(incDir.trim().isEmpty()) {
completion.addCompletionCandidates( listDirectory(cwd, null));
}
else if(startWithHome()) {
if(isHomeAndIncDirADirectory()) {
if(endWithSlash()) {
completion.addCompletionCandidates(
listDirectory(new File(Config.getHomeDir()+incDir.substring(1)), null));
}
else
completion.addCompletionCandidate(Config.getPathSeparator());
}
else if(isHomeAndIncDirAFile()) {
completion.addCompletionCandidate("");
//append when we have a file
completion.doAppendSeparator(true);
}
//not a directory or file, list what we find
else {
listPossibleDirectories(completion);
}
}
else if(!startWithSlash()) {
if(isCwdAndIncDirADirectory()) {
if(endWithSlash()) {
completion.addCompletionCandidates(
listDirectory(new File(cwd.getAbsolutePath() +
Config.getPathSeparator()+incDir), null));
}
else
completion.addCompletionCandidate(Config.getPathSeparator());
}
else if(isCwdAndIncDirAFile()) {
listPossibleDirectories(completion);
if(completion.getCompletionCandidates().size() == 1) {
completion.getCompletionCandidates().set(0, "");
//append when we have a file
completion.doAppendSeparator(true);
}
}
//not a directory or file, list what we find
else {
listPossibleDirectories(completion);
}
}
else if(startWithSlash()) {
if(isIncDirADirectory()) {
if(endWithSlash()) {
completion.addCompletionCandidates(
listDirectory(new File(incDir), null));
}
else
completion.addCompletionCandidate(Config.getPathSeparator());
}
else if(isIncDirAFile()) {
listPossibleDirectories(completion);
if(completion.getCompletionCandidates().size() == 1) {
completion.getCompletionCandidates().set(0, "");
//completion.addCompletionCandidate("");
//append when we have a file
completion.doAppendSeparator(true);
}
}
//not a directory or file, list what we find
else {
listPossibleDirectories(completion);
}
}
//try to find if more than one filename start with the same word
if(completion.getCompletionCandidates().size() > 1) {
String startsWith = Parser.findStartsWith(completion.getCompletionCandidates());
if(startsWith.contains(" "))
startsWith = Parser.switchEscapedSpacesToSpacesInWord(startsWith);
if(startsWith != null && startsWith.length() > 0 &&
startsWith.length() > rest.length()) {
completion.getCompletionCandidates().clear();
completion.addCompletionCandidate(Parser.switchSpacesToEscapedSpacesInWord(startsWith));
}
}
//new offset tweaking to match the "common" way of returning completions
if(completion.getCompletionCandidates().size() == 1) {
if(isIncDirADirectory() && !endWithSlash()) {
completion.getCompletionCandidates().set(0, incDir +
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
}
else if(isIncDirAFile()) {
completion.getCompletionCandidates().set(0, incDir +
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
completion.doAppendSeparator(true);
}
else if(incDir != null) {
if(rest != null && incDir.length() > rest.length()) {
completion.getCompletionCandidates().set(0,
Parser.switchSpacesToEscapedSpacesInWord(
incDir.substring(0, incDir.length()-rest.length() )) +
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
}
else if(rest != null && incDir.length() == rest.length()) {
completion.setOffset(completion.getCursor()-(rest.length()+Parser.findNumberOfSpacesInWord(rest)));
}
else {
if(incDir.endsWith(Config.getPathSeparator()))
completion.getCompletionCandidates().set(0, Parser.switchSpacesToEscapedSpacesInWord(incDir) +
completion.getCompletionCandidates().get(0));
else
completion.getCompletionCandidates().set(0, Parser.switchSpacesToEscapedSpacesInWord(incDir) +
Config.getPathSeparator()+
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
}
}
else {
completion.setOffset(completion.getCursor());
}
}
else if(completion.getCompletionCandidates().size() > 1) {
if(rest != null && rest.length() > 0)
completion.setOffset(completion.getCursor() - rest.length());
}
}
| public void findMatchingDirectories(CompleteOperation completion) {
completion.doAppendSeparator(false);
//if incDir is empty, just list cwd
if(incDir.trim().isEmpty()) {
completion.addCompletionCandidates( listDirectory(cwd, null));
}
else if(startWithHome()) {
if(isHomeAndIncDirADirectory()) {
if(endWithSlash()) {
completion.addCompletionCandidates(
listDirectory(new File(Config.getHomeDir()+incDir.substring(1)), null));
}
else
completion.addCompletionCandidate(Config.getPathSeparator());
}
else if(isHomeAndIncDirAFile()) {
completion.addCompletionCandidate("");
//append when we have a file
completion.doAppendSeparator(true);
}
//not a directory or file, list what we find
else {
listPossibleDirectories(completion);
}
}
else if(!startWithSlash()) {
if(isCwdAndIncDirADirectory()) {
if(endWithSlash()) {
completion.addCompletionCandidates(
listDirectory(new File(cwd.getAbsolutePath() +
Config.getPathSeparator()+incDir), null));
}
else
completion.addCompletionCandidate(Config.getPathSeparator());
}
else if(isCwdAndIncDirAFile()) {
listPossibleDirectories(completion);
if(completion.getCompletionCandidates().size() == 1) {
completion.getCompletionCandidates().set(0, "");
//append when we have a file
completion.doAppendSeparator(true);
}
}
//not a directory or file, list what we find
else {
listPossibleDirectories(completion);
}
}
else if(startWithSlash()) {
if(isIncDirADirectory()) {
if(endWithSlash()) {
completion.addCompletionCandidates(
listDirectory(new File(incDir), null));
}
else
completion.addCompletionCandidate(Config.getPathSeparator());
}
else if(isIncDirAFile()) {
listPossibleDirectories(completion);
if(completion.getCompletionCandidates().size() == 1) {
completion.getCompletionCandidates().set(0, "");
//completion.addCompletionCandidate("");
//append when we have a file
completion.doAppendSeparator(true);
}
}
//not a directory or file, list what we find
else {
listPossibleDirectories(completion);
}
}
//try to find if more than one filename start with the same word
if(completion.getCompletionCandidates().size() > 1) {
String startsWith = Parser.findStartsWith(completion.getCompletionCandidates());
if(startsWith.contains(" "))
startsWith = Parser.switchEscapedSpacesToSpacesInWord(startsWith);
if(startsWith != null && startsWith.length() > 0 && rest != null &&
startsWith.length() > rest.length()) {
completion.getCompletionCandidates().clear();
completion.addCompletionCandidate(Parser.switchSpacesToEscapedSpacesInWord(startsWith));
}
}
//new offset tweaking to match the "common" way of returning completions
if(completion.getCompletionCandidates().size() == 1) {
if(isIncDirADirectory() && !endWithSlash()) {
completion.getCompletionCandidates().set(0, incDir +
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
}
else if(isIncDirAFile()) {
completion.getCompletionCandidates().set(0, incDir +
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
completion.doAppendSeparator(true);
}
else if(incDir != null) {
if(rest != null && incDir.length() > rest.length()) {
completion.getCompletionCandidates().set(0,
Parser.switchSpacesToEscapedSpacesInWord(
incDir.substring(0, incDir.length()-rest.length() )) +
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
}
else if(rest != null && incDir.length() == rest.length()) {
completion.setOffset(completion.getCursor()-(rest.length()+Parser.findNumberOfSpacesInWord(rest)));
}
else {
if(incDir.endsWith(Config.getPathSeparator()))
completion.getCompletionCandidates().set(0, Parser.switchSpacesToEscapedSpacesInWord(incDir) +
completion.getCompletionCandidates().get(0));
else
completion.getCompletionCandidates().set(0, Parser.switchSpacesToEscapedSpacesInWord(incDir) +
Config.getPathSeparator()+
completion.getCompletionCandidates().get(0));
completion.setOffset(completion.getCursor()-incDir.length());
}
}
else {
completion.setOffset(completion.getCursor());
}
}
else if(completion.getCompletionCandidates().size() > 1) {
if(rest != null && rest.length() > 0)
completion.setOffset(completion.getCursor() - rest.length());
}
}
|
diff --git a/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxConfigTemplate.java b/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxConfigTemplate.java
index f42c3c67c..23269a433 100644
--- a/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxConfigTemplate.java
+++ b/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxConfigTemplate.java
@@ -1,72 +1,76 @@
/*
* Copyright 2012-2013 by Cloudsoft Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package brooklyn.entity.proxy.nginx;
import java.util.Collection;
import java.util.Map;
import brooklyn.entity.proxy.ProxySslConfig;
import brooklyn.util.ResourceUtils;
import brooklyn.util.collections.MutableMap;
import brooklyn.util.text.Strings;
import brooklyn.util.text.TemplateProcessor;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
/**
* Processes a FreeMarker template for an {@link NginxController} configuration file.
*/
public class NginxConfigTemplate {
private NginxDriver driver;
public static NginxConfigTemplate generator(NginxDriver driver) {
return new NginxConfigTemplate(driver);
}
private NginxConfigTemplate(NginxDriver driver) {
this.driver = driver;
}
public String configFile() {
// Check template URL exists
String templateUrl = driver.getEntity().getConfig(NginxController.SERVER_CONF_TEMPLATE_URL);
ResourceUtils.create(this).checkUrlExists(templateUrl);
// Check SSL configuration
ProxySslConfig ssl = driver.getEntity().getConfig(NginxController.SSL_CONFIG);
if (ssl != null && Strings.isEmpty(ssl.getCertificateDestination()) && Strings.isEmpty(ssl.getCertificateSourceUrl())) {
throw new IllegalStateException("ProxySslConfig can't have a null certificateDestination and null certificateSourceUrl. One or both need to be set");
}
// For mapping by URL
Iterable<UrlMapping> mappings = ((NginxController) driver.getEntity()).getUrlMappings();
Multimap<String, UrlMapping> mappingsByDomain = LinkedHashMultimap.create();
for (UrlMapping mapping : mappings) {
Collection<String> addrs = mapping.getAttribute(UrlMapping.TARGET_ADDRESSES);
if (addrs != null && addrs.size() > 0) {
mappingsByDomain.put(mapping.getDomain(), mapping);
}
}
- Map<String, Object> substitutions = MutableMap.<String, Object>of("ssl", ssl, "urlMappings", mappings, "domainMappings", mappingsByDomain);
+ MutableMap.Builder<String, Object> builder = MutableMap.<String, Object>builder()
+ .put("urlMappings", mappings)
+ .put("domainMappings", mappingsByDomain);
+ if (ssl != null) builder.put("ssl", ssl);
+ Map<String, Object> substitutions = builder.build();
// Get template contents and process
String contents = ResourceUtils.create(driver.getEntity()).getResourceAsString(templateUrl);
return TemplateProcessor.processTemplateContents(contents, driver, substitutions);
}
}
| true | true | public String configFile() {
// Check template URL exists
String templateUrl = driver.getEntity().getConfig(NginxController.SERVER_CONF_TEMPLATE_URL);
ResourceUtils.create(this).checkUrlExists(templateUrl);
// Check SSL configuration
ProxySslConfig ssl = driver.getEntity().getConfig(NginxController.SSL_CONFIG);
if (ssl != null && Strings.isEmpty(ssl.getCertificateDestination()) && Strings.isEmpty(ssl.getCertificateSourceUrl())) {
throw new IllegalStateException("ProxySslConfig can't have a null certificateDestination and null certificateSourceUrl. One or both need to be set");
}
// For mapping by URL
Iterable<UrlMapping> mappings = ((NginxController) driver.getEntity()).getUrlMappings();
Multimap<String, UrlMapping> mappingsByDomain = LinkedHashMultimap.create();
for (UrlMapping mapping : mappings) {
Collection<String> addrs = mapping.getAttribute(UrlMapping.TARGET_ADDRESSES);
if (addrs != null && addrs.size() > 0) {
mappingsByDomain.put(mapping.getDomain(), mapping);
}
}
Map<String, Object> substitutions = MutableMap.<String, Object>of("ssl", ssl, "urlMappings", mappings, "domainMappings", mappingsByDomain);
// Get template contents and process
String contents = ResourceUtils.create(driver.getEntity()).getResourceAsString(templateUrl);
return TemplateProcessor.processTemplateContents(contents, driver, substitutions);
}
| public String configFile() {
// Check template URL exists
String templateUrl = driver.getEntity().getConfig(NginxController.SERVER_CONF_TEMPLATE_URL);
ResourceUtils.create(this).checkUrlExists(templateUrl);
// Check SSL configuration
ProxySslConfig ssl = driver.getEntity().getConfig(NginxController.SSL_CONFIG);
if (ssl != null && Strings.isEmpty(ssl.getCertificateDestination()) && Strings.isEmpty(ssl.getCertificateSourceUrl())) {
throw new IllegalStateException("ProxySslConfig can't have a null certificateDestination and null certificateSourceUrl. One or both need to be set");
}
// For mapping by URL
Iterable<UrlMapping> mappings = ((NginxController) driver.getEntity()).getUrlMappings();
Multimap<String, UrlMapping> mappingsByDomain = LinkedHashMultimap.create();
for (UrlMapping mapping : mappings) {
Collection<String> addrs = mapping.getAttribute(UrlMapping.TARGET_ADDRESSES);
if (addrs != null && addrs.size() > 0) {
mappingsByDomain.put(mapping.getDomain(), mapping);
}
}
MutableMap.Builder<String, Object> builder = MutableMap.<String, Object>builder()
.put("urlMappings", mappings)
.put("domainMappings", mappingsByDomain);
if (ssl != null) builder.put("ssl", ssl);
Map<String, Object> substitutions = builder.build();
// Get template contents and process
String contents = ResourceUtils.create(driver.getEntity()).getResourceAsString(templateUrl);
return TemplateProcessor.processTemplateContents(contents, driver, substitutions);
}
|
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutWizard.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutWizard.java
index 8fbfb562a..2cd65dd6d 100644
--- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutWizard.java
+++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/wizards/CheckoutWizard.java
@@ -1,275 +1,278 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ccvs.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ccvs.core.*;
import org.eclipse.team.internal.ccvs.core.util.KnownRepositories;
import org.eclipse.team.internal.ccvs.ui.*;
import org.eclipse.team.internal.ccvs.ui.Policy;
import org.eclipse.team.internal.ccvs.ui.operations.CheckoutMultipleProjectsOperation;
import org.eclipse.team.internal.ccvs.ui.operations.HasProjectMetaFileOperation;
import org.eclipse.ui.*;
/**
* Gathers all information necesary for a checkout from a repository.
*/
public class CheckoutWizard extends Wizard implements ICVSWizard, INewWizard {
private RepositorySelectionPage locationPage;
private ConfigurationWizardMainPage createLocationPage;
private ModuleSelectionPage modulePage;
private CheckoutAsWizard wizard;
private ICVSRepositoryLocation location;
private boolean isNewLocation;
private CVSWizardPage dummyPage;
public CheckoutWizard() {
setWindowTitle("Checkout from CVS"); //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#addPages()
*/
public void addPages() {
setNeedsProgressMonitor(true);
ImageDescriptor substImage = CVSUIPlugin.getPlugin().getImageDescriptor(ICVSUIConstants.IMG_WIZBAN_CHECKOUT);
ICVSRepositoryLocation[] locations = CVSUIPlugin.getPlugin().getRepositoryManager().getKnownRepositoryLocations();
if (locations.length > 0) {
locationPage = new RepositorySelectionPage("locationSelection", Policy.bind("CheckoutWizard.7"), substImage); //$NON-NLS-1$ //$NON-NLS-2$
locationPage.setDescription(Policy.bind("SharingWizard.importTitleDescription")); //$NON-NLS-1$
locationPage.setExtendedDescription(Policy.bind("CheckoutWizard.8")); //$NON-NLS-1$
addPage(locationPage);
}
createLocationPage = new ConfigurationWizardMainPage("createLocationPage", Policy.bind("SharingWizard.enterInformation"), substImage); //$NON-NLS-1$ //$NON-NLS-2$
createLocationPage.setDescription(Policy.bind("SharingWizard.enterInformationDescription")); //$NON-NLS-1$
addPage(createLocationPage);
createLocationPage.setDialogSettings(NewLocationWizard.getLocationDialogSettings());
modulePage = new ModuleSelectionPage("moduleSelection", Policy.bind("CheckoutWizard.10"), substImage); //$NON-NLS-1$ //$NON-NLS-2$
modulePage.setDescription(Policy.bind("CheckoutWizard.11")); //$NON-NLS-1$
modulePage.setHelpContxtId(IHelpContextIds.CHECKOUT_MODULE_SELECTION_PAGE);
addPage(modulePage);
// Dummy page to allow lazy creation of CheckoutAsWizard
dummyPage = new CVSWizardPage("dummyPage") { //$NON-NLS-1$
public void createControl(Composite parent) {
Composite composite = createComposite(parent, 1);
setControl(composite);
}
};
addPage(dummyPage);
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish() {
return (wizard == null && getSelectedModule() != null) ||
(wizard != null && wizard.canFinish());
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.IWizard#performFinish()
*/
public boolean performFinish() {
if (wizard != null) {
// The finish of the child wizard will get called directly.
// We only get here if it completed successfully
if (isNewLocation) {
KnownRepositories.getInstance().addRepository(location, true /* broadcast */);
}
return true;
} else {
try {
new CheckoutMultipleProjectsOperation(getPart(), new ICVSRemoteFolder[] { getSelectedModule() }, null)
.run();
if (isNewLocation) {
KnownRepositories.getInstance().addRepository(location, true /* broadcast */);
}
return true;
} catch (InvocationTargetException e) {
CVSUIPlugin.openError(getShell(), null, null, e);
} catch (InterruptedException e) {
// Cancelled. fall through.
}
return false;
}
}
private IWorkbenchPart getPart() {
// This wizard doesn't have a part
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#performCancel()
*/
public boolean performCancel() {
if (location != null && isNewLocation) {
KnownRepositories.getInstance().disposeRepository(location);
location = null;
}
return wizard == null || wizard.performCancel();
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.IWizard#getNextPage(org.eclipse.jface.wizard.IWizardPage)
*/
public IWizardPage getNextPage(IWizardPage page) {
// Assume the page is about to be shown when this method is
// invoked
return getNextPage(page, true /* about to show*/);
}
/* (non-Javadoc)
* @see org.eclipse.team.internal.ccvs.ui.wizards.ICVSWizard#getNextPage(org.eclipse.jface.wizard.IWizardPage, boolean)
*/
public IWizardPage getNextPage(IWizardPage page, boolean aboutToShow) {
if (page == locationPage) {
if (locationPage.getLocation() == null) {
return createLocationPage;
} else {
if (aboutToShow) {
try {
modulePage.setLocation(getLocation());
} catch (TeamException e1) {
CVSUIPlugin.log(e1);
}
}
return modulePage;
}
}
if (page == createLocationPage) {
if (aboutToShow) {
try {
- modulePage.setLocation(getLocation());
+ ICVSRepositoryLocation l = getLocation();
+ if (l != null) {
+ modulePage.setLocation(l);
+ }
} catch (TeamException e1) {
CVSUIPlugin.log(e1);
}
}
return modulePage;
}
if (page == modulePage) {
ICVSRemoteFolder selectedModule = getSelectedModule();
if (selectedModule != null && selectedModule.isDefinedModule()) {
// No further configuration is possible for defined modules
return null;
}
if (aboutToShow) {
try {
boolean hasMetafile = hasProjectMetafile(selectedModule);
wizard = new CheckoutAsWizard(getPart(), new ICVSRemoteFolder[] { selectedModule }, ! hasMetafile /* allow configuration */);
wizard.addPages();
return wizard.getStartingPage();
} catch (InvocationTargetException e) {
// Show the error and fall through to return null as the next page
CVSUIPlugin.openError(getShell(), null, null, e);
} catch (InterruptedException e) {
// Cancelled by user. Fall through and return null
}
return null;
} else {
if (wizard == null) {
return dummyPage;
} else {
return wizard.getStartingPage();
}
}
}
if (wizard != null) {
return wizard.getNextPage(page);
}
return null;
}
private boolean hasProjectMetafile(final ICVSRemoteFolder selectedModule) throws InvocationTargetException, InterruptedException {
final boolean[] result = new boolean[] { true };
getContainer().run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
HasProjectMetaFileOperation op = new HasProjectMetaFileOperation(getPart(), selectedModule);
op.run(monitor);
result[0] = op.metaFileExists();
}
});
return result[0];
}
private ICVSRemoteFolder getSelectedModule() {
if (modulePage == null) return null;
return modulePage.getSelectedModule();
}
/**
* Return an ICVSRepositoryLocation
*/
private ICVSRepositoryLocation getLocation() throws TeamException {
// If the location page has a location, use it.
if (locationPage != null) {
ICVSRepositoryLocation newLocation = locationPage.getLocation();
if (newLocation != null) {
return recordLocation(newLocation);
}
}
// Otherwise, get the location from the create location page
final ICVSRepositoryLocation[] locations = new ICVSRepositoryLocation[] { null };
final CVSException[] exception = new CVSException[] { null };
getShell().getDisplay().syncExec(new Runnable() {
public void run() {
try {
locations[0] = createLocationPage.getLocation();
} catch (CVSException e) {
exception[0] = e;
}
}
});
if (exception[0] != null) {
throw exception[0];
}
return recordLocation(locations[0]);
}
private ICVSRepositoryLocation recordLocation(ICVSRepositoryLocation newLocation) {
if (newLocation == null) return location;
if (location == null || !newLocation.equals(location)) {
if (location != null && isNewLocation) {
// Dispose of the previous location
KnownRepositories.getInstance().disposeRepository(location);
}
location = newLocation;
isNewLocation = !KnownRepositories.getInstance().isKnownRepository(newLocation.getLocation());
if (isNewLocation) {
// Add the location silently so we can work with it
location = KnownRepositories.getInstance().addRepository(location, false /* silently */);
}
}
return location;
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
*/
public void init(IWorkbench workbench, IStructuredSelection selection) {
}
}
| true | true | public IWizardPage getNextPage(IWizardPage page, boolean aboutToShow) {
if (page == locationPage) {
if (locationPage.getLocation() == null) {
return createLocationPage;
} else {
if (aboutToShow) {
try {
modulePage.setLocation(getLocation());
} catch (TeamException e1) {
CVSUIPlugin.log(e1);
}
}
return modulePage;
}
}
if (page == createLocationPage) {
if (aboutToShow) {
try {
modulePage.setLocation(getLocation());
} catch (TeamException e1) {
CVSUIPlugin.log(e1);
}
}
return modulePage;
}
if (page == modulePage) {
ICVSRemoteFolder selectedModule = getSelectedModule();
if (selectedModule != null && selectedModule.isDefinedModule()) {
// No further configuration is possible for defined modules
return null;
}
if (aboutToShow) {
try {
boolean hasMetafile = hasProjectMetafile(selectedModule);
wizard = new CheckoutAsWizard(getPart(), new ICVSRemoteFolder[] { selectedModule }, ! hasMetafile /* allow configuration */);
wizard.addPages();
return wizard.getStartingPage();
} catch (InvocationTargetException e) {
// Show the error and fall through to return null as the next page
CVSUIPlugin.openError(getShell(), null, null, e);
} catch (InterruptedException e) {
// Cancelled by user. Fall through and return null
}
return null;
} else {
if (wizard == null) {
return dummyPage;
} else {
return wizard.getStartingPage();
}
}
}
if (wizard != null) {
return wizard.getNextPage(page);
}
return null;
}
| public IWizardPage getNextPage(IWizardPage page, boolean aboutToShow) {
if (page == locationPage) {
if (locationPage.getLocation() == null) {
return createLocationPage;
} else {
if (aboutToShow) {
try {
modulePage.setLocation(getLocation());
} catch (TeamException e1) {
CVSUIPlugin.log(e1);
}
}
return modulePage;
}
}
if (page == createLocationPage) {
if (aboutToShow) {
try {
ICVSRepositoryLocation l = getLocation();
if (l != null) {
modulePage.setLocation(l);
}
} catch (TeamException e1) {
CVSUIPlugin.log(e1);
}
}
return modulePage;
}
if (page == modulePage) {
ICVSRemoteFolder selectedModule = getSelectedModule();
if (selectedModule != null && selectedModule.isDefinedModule()) {
// No further configuration is possible for defined modules
return null;
}
if (aboutToShow) {
try {
boolean hasMetafile = hasProjectMetafile(selectedModule);
wizard = new CheckoutAsWizard(getPart(), new ICVSRemoteFolder[] { selectedModule }, ! hasMetafile /* allow configuration */);
wizard.addPages();
return wizard.getStartingPage();
} catch (InvocationTargetException e) {
// Show the error and fall through to return null as the next page
CVSUIPlugin.openError(getShell(), null, null, e);
} catch (InterruptedException e) {
// Cancelled by user. Fall through and return null
}
return null;
} else {
if (wizard == null) {
return dummyPage;
} else {
return wizard.getStartingPage();
}
}
}
if (wizard != null) {
return wizard.getNextPage(page);
}
return null;
}
|
diff --git a/metadata/src/main/java/org/apache/oodt/cas/metadata/extractors/ExternConfigReader.java b/metadata/src/main/java/org/apache/oodt/cas/metadata/extractors/ExternConfigReader.java
index 7d05bcd88..c7707632e 100644
--- a/metadata/src/main/java/org/apache/oodt/cas/metadata/extractors/ExternConfigReader.java
+++ b/metadata/src/main/java/org/apache/oodt/cas/metadata/extractors/ExternConfigReader.java
@@ -1,135 +1,135 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.oodt.cas.metadata.extractors;
//OODT imports
import org.apache.oodt.cas.metadata.MetExtractorConfig;
import org.apache.oodt.cas.metadata.MetExtractorConfigReader;
import org.apache.oodt.cas.metadata.exceptions.MetExtractorConfigReaderException;
import org.apache.oodt.cas.metadata.util.PathUtils;
import org.apache.oodt.commons.xml.XMLUtils;
//JDK imports
import java.io.File;
import java.io.FileInputStream;
import java.util.Vector;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* @author mattmann
* @author bfoster
* @version $Revision$
*
* <p>
* Reader that reads {@link ExternalMetExtractorConfig}s from an XML file.
* </p>.
*/
public final class ExternConfigReader implements MetExtractorConfigReader,
ExternMetExtractorMetKeys, ExternConfigReaderMetKeys {
/*
* (non-Javadoc)
*
* @see org.apache.oodt.cas.metadata.MetExtractorConfigReader#parseConfigFile(java.io.File)
*/
public MetExtractorConfig parseConfigFile(File file)
throws MetExtractorConfigReaderException {
try {
Document doc = XMLUtils.getDocumentRoot(new FileInputStream(file));
ExternalMetExtractorConfig config = new ExternalMetExtractorConfig();
Element docElem = doc.getDocumentElement();
Element execElement = XMLUtils.getFirstElement(EXEC_TAG, docElem);
config.setWorkingDirPath(PathUtils.replaceEnvVariables(execElement
.getAttribute(WORKING_DIR_ATTR)));
String metFileExt = PathUtils.replaceEnvVariables(execElement
.getAttribute(MET_FILE_EXT_ATTR));
if (!metFileExt.equals(""))
config.setMetFileExt(metFileExt);
Element binPathElem = XMLUtils.getFirstElement(
EXTRACTOR_BIN_PATH_TAG, execElement);
String binPath = XMLUtils.getSimpleElementText(binPathElem);
if (Boolean.valueOf(binPathElem.getAttribute(ENV_REPLACE_ATTR))
.booleanValue()) {
binPath = PathUtils.replaceEnvVariables(binPath);
}
// make sure to do path replacement on binPath because it's always
// going
// to be
// a path
- binPath = binPath.replaceAll("\\s", "\\\\ ");
+ binPath = binPath.replaceAll("^\\s+", "").replaceAll("\\s+$", "").replaceAll("\\s", "\\\\ ");
config.setExtractorBinPath(binPath);
Element argsElem = XMLUtils.getFirstElement(ARGS_TAG, execElement);
if (argsElem != null) {
NodeList argNodes = argsElem.getElementsByTagName(ARG_TAG);
if (argNodes != null && argNodes.getLength() > 0) {
Vector argVector = new Vector();
for (int i = 0; i < argNodes.getLength(); i++) {
Element argElem = (Element) argNodes.item(i);
String argStr = null;
if (Boolean.valueOf(
argElem.getAttribute(IS_DATA_FILE_ATTR)
.toLowerCase()).booleanValue())
argStr = DATA_FILE_PLACE_HOLDER;
else if (Boolean.valueOf(
argElem.getAttribute(IS_MET_FILE_ATTR)
.toLowerCase()).booleanValue())
argStr = MET_FILE_PLACE_HOLDER;
else
argStr = XMLUtils.getSimpleElementText(argElem);
String appendExt = null;
if (!(appendExt = argElem.getAttribute(APPEND_EXT_ATTR))
.equals(""))
argStr += "." + appendExt;
if (Boolean.valueOf(
argElem.getAttribute(ENV_REPLACE_ATTR))
.booleanValue()) {
argStr = PathUtils.replaceEnvVariables(argStr);
}
if (Boolean.valueOf(argElem.getAttribute(IS_PATH_ATTR))
.booleanValue()) {
argStr = argStr.replaceAll("\\s", "\\\\ ");
}
argVector.add(argStr);
}
config.setArgList((String[]) argVector
.toArray(new String[] {}));
}
}
return config;
} catch (Exception e) {
throw new MetExtractorConfigReaderException("Failed to parser '"
+ file + "' : " + e.getMessage());
}
}
}
| true | true | public MetExtractorConfig parseConfigFile(File file)
throws MetExtractorConfigReaderException {
try {
Document doc = XMLUtils.getDocumentRoot(new FileInputStream(file));
ExternalMetExtractorConfig config = new ExternalMetExtractorConfig();
Element docElem = doc.getDocumentElement();
Element execElement = XMLUtils.getFirstElement(EXEC_TAG, docElem);
config.setWorkingDirPath(PathUtils.replaceEnvVariables(execElement
.getAttribute(WORKING_DIR_ATTR)));
String metFileExt = PathUtils.replaceEnvVariables(execElement
.getAttribute(MET_FILE_EXT_ATTR));
if (!metFileExt.equals(""))
config.setMetFileExt(metFileExt);
Element binPathElem = XMLUtils.getFirstElement(
EXTRACTOR_BIN_PATH_TAG, execElement);
String binPath = XMLUtils.getSimpleElementText(binPathElem);
if (Boolean.valueOf(binPathElem.getAttribute(ENV_REPLACE_ATTR))
.booleanValue()) {
binPath = PathUtils.replaceEnvVariables(binPath);
}
// make sure to do path replacement on binPath because it's always
// going
// to be
// a path
binPath = binPath.replaceAll("\\s", "\\\\ ");
config.setExtractorBinPath(binPath);
Element argsElem = XMLUtils.getFirstElement(ARGS_TAG, execElement);
if (argsElem != null) {
NodeList argNodes = argsElem.getElementsByTagName(ARG_TAG);
if (argNodes != null && argNodes.getLength() > 0) {
Vector argVector = new Vector();
for (int i = 0; i < argNodes.getLength(); i++) {
Element argElem = (Element) argNodes.item(i);
String argStr = null;
if (Boolean.valueOf(
argElem.getAttribute(IS_DATA_FILE_ATTR)
.toLowerCase()).booleanValue())
argStr = DATA_FILE_PLACE_HOLDER;
else if (Boolean.valueOf(
argElem.getAttribute(IS_MET_FILE_ATTR)
.toLowerCase()).booleanValue())
argStr = MET_FILE_PLACE_HOLDER;
else
argStr = XMLUtils.getSimpleElementText(argElem);
String appendExt = null;
if (!(appendExt = argElem.getAttribute(APPEND_EXT_ATTR))
.equals(""))
argStr += "." + appendExt;
if (Boolean.valueOf(
argElem.getAttribute(ENV_REPLACE_ATTR))
.booleanValue()) {
argStr = PathUtils.replaceEnvVariables(argStr);
}
if (Boolean.valueOf(argElem.getAttribute(IS_PATH_ATTR))
.booleanValue()) {
argStr = argStr.replaceAll("\\s", "\\\\ ");
}
argVector.add(argStr);
}
config.setArgList((String[]) argVector
.toArray(new String[] {}));
}
}
return config;
} catch (Exception e) {
throw new MetExtractorConfigReaderException("Failed to parser '"
+ file + "' : " + e.getMessage());
}
}
| public MetExtractorConfig parseConfigFile(File file)
throws MetExtractorConfigReaderException {
try {
Document doc = XMLUtils.getDocumentRoot(new FileInputStream(file));
ExternalMetExtractorConfig config = new ExternalMetExtractorConfig();
Element docElem = doc.getDocumentElement();
Element execElement = XMLUtils.getFirstElement(EXEC_TAG, docElem);
config.setWorkingDirPath(PathUtils.replaceEnvVariables(execElement
.getAttribute(WORKING_DIR_ATTR)));
String metFileExt = PathUtils.replaceEnvVariables(execElement
.getAttribute(MET_FILE_EXT_ATTR));
if (!metFileExt.equals(""))
config.setMetFileExt(metFileExt);
Element binPathElem = XMLUtils.getFirstElement(
EXTRACTOR_BIN_PATH_TAG, execElement);
String binPath = XMLUtils.getSimpleElementText(binPathElem);
if (Boolean.valueOf(binPathElem.getAttribute(ENV_REPLACE_ATTR))
.booleanValue()) {
binPath = PathUtils.replaceEnvVariables(binPath);
}
// make sure to do path replacement on binPath because it's always
// going
// to be
// a path
binPath = binPath.replaceAll("^\\s+", "").replaceAll("\\s+$", "").replaceAll("\\s", "\\\\ ");
config.setExtractorBinPath(binPath);
Element argsElem = XMLUtils.getFirstElement(ARGS_TAG, execElement);
if (argsElem != null) {
NodeList argNodes = argsElem.getElementsByTagName(ARG_TAG);
if (argNodes != null && argNodes.getLength() > 0) {
Vector argVector = new Vector();
for (int i = 0; i < argNodes.getLength(); i++) {
Element argElem = (Element) argNodes.item(i);
String argStr = null;
if (Boolean.valueOf(
argElem.getAttribute(IS_DATA_FILE_ATTR)
.toLowerCase()).booleanValue())
argStr = DATA_FILE_PLACE_HOLDER;
else if (Boolean.valueOf(
argElem.getAttribute(IS_MET_FILE_ATTR)
.toLowerCase()).booleanValue())
argStr = MET_FILE_PLACE_HOLDER;
else
argStr = XMLUtils.getSimpleElementText(argElem);
String appendExt = null;
if (!(appendExt = argElem.getAttribute(APPEND_EXT_ATTR))
.equals(""))
argStr += "." + appendExt;
if (Boolean.valueOf(
argElem.getAttribute(ENV_REPLACE_ATTR))
.booleanValue()) {
argStr = PathUtils.replaceEnvVariables(argStr);
}
if (Boolean.valueOf(argElem.getAttribute(IS_PATH_ATTR))
.booleanValue()) {
argStr = argStr.replaceAll("\\s", "\\\\ ");
}
argVector.add(argStr);
}
config.setArgList((String[]) argVector
.toArray(new String[] {}));
}
}
return config;
} catch (Exception e) {
throw new MetExtractorConfigReaderException("Failed to parser '"
+ file + "' : " + e.getMessage());
}
}
|
diff --git a/server/src/main/java/org/eurekastreams/server/action/validation/CreateGroupValidation.java b/server/src/main/java/org/eurekastreams/server/action/validation/CreateGroupValidation.java
index 723b72dd6..ab5b370a2 100644
--- a/server/src/main/java/org/eurekastreams/server/action/validation/CreateGroupValidation.java
+++ b/server/src/main/java/org/eurekastreams/server/action/validation/CreateGroupValidation.java
@@ -1,136 +1,145 @@
/*
* Copyright (c) 2010-2011 Lockheed Martin Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.eurekastreams.server.action.validation;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import org.eurekastreams.commons.actions.ValidationStrategy;
import org.eurekastreams.commons.actions.context.ActionContext;
import org.eurekastreams.commons.exceptions.ValidationException;
import org.eurekastreams.server.domain.DomainGroup;
import org.eurekastreams.server.persistence.mappers.stream.GetDomainGroupsByShortNames;
import org.eurekastreams.server.search.modelview.DomainGroupModelView;
/**
*
* Validates values entered for a Group.
*
*/
public class CreateGroupValidation implements ValidationStrategy<ActionContext>
{
/**
* {@link GetDomainGroupsByShortNames}.
*/
private final GetDomainGroupsByShortNames groupMapper;
/**
* @param inGroupMapper
* the mapper to use to get groups.
*/
public CreateGroupValidation(final GetDomainGroupsByShortNames inGroupMapper)
{
groupMapper = inGroupMapper;
}
/**
* These are one off messages that are only used for this validation if these need to be reused move them to the
* DTO. These are package protected so that test can access them.
*/
/**
* Message to display if name is taken.
*/
static final String SHORTNAME_TAKEN_MESSAGE = "A group with this web address already exist.";
/**
*
*/
static final String PRIVACY_KEY_MESSAGE = "Privacy key excepted.";
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public void validate(final ActionContext inActionContext) throws ValidationException
{
Map<String, Serializable> fields = (Map<String, Serializable>) inActionContext.getParams();
ValidationException ve = new ValidationException();
ValidationHelper vHelper = new ValidationHelper();
String groupName = (String) vHelper
.getAndCheckStringFieldExist(fields, DomainGroupModelView.NAME_KEY, true, ve);
if (groupName == null || groupName.isEmpty())
{
ve.addError(DomainGroupModelView.NAME_KEY, DomainGroup.NAME_REQUIRED);
}
else
{
vHelper.stringMeetsRequirments(DomainGroupModelView.NAME_KEY, groupName, ve,
DomainGroup.NAME_LENGTH_MESSAGE, DomainGroup.MAX_NAME_LENGTH, DomainGroup.NAME_LENGTH_MESSAGE,
null, null);
}
String groupShortName = (String) vHelper.getAndCheckStringFieldExist(fields,
DomainGroupModelView.SHORT_NAME_KEY, true, ve);
if (groupShortName == null || groupShortName.isEmpty())
{
ve.addError(DomainGroupModelView.SHORT_NAME_KEY, DomainGroup.SHORTNAME_REQUIRED);
}
else if (vHelper.stringMeetsRequirments(DomainGroupModelView.SHORT_NAME_KEY, groupShortName, ve,
DomainGroup.SHORT_NAME_LENGTH_MESSAGE, DomainGroup.MAX_SHORT_NAME_LENGTH,
DomainGroup.SHORT_NAME_LENGTH_MESSAGE, DomainGroup.ALPHA_NUMERIC_PATTERN,
DomainGroup.SHORT_NAME_CHARACTERS))
{
- if (groupMapper.fetchUniqueResult(groupShortName.toLowerCase()) != null)
+ // TODO This is a less than ideal fix due to time constraints for the 1.5 release.
+ // Recommend removing try/catch and evaluating why group creation is broken
+ try
{
- ve.addError(DomainGroupModelView.SHORT_NAME_KEY, SHORTNAME_TAKEN_MESSAGE);
+ if (groupMapper.fetchUniqueResult(groupShortName.toLowerCase()) != null)
+ {
+ ve.addError(DomainGroupModelView.SHORT_NAME_KEY, SHORTNAME_TAKEN_MESSAGE);
+ }
+ }
+ catch (Exception ex)
+ {
+ int x = 0;
}
}
String groupDesc = (String) vHelper.getAndCheckStringFieldExist(fields, DomainGroupModelView.DESCRIPTION_KEY,
true, ve);
if (groupDesc == null || groupDesc.isEmpty())
{
ve.addError(DomainGroupModelView.DESCRIPTION_KEY, DomainGroup.DESCRIPTION_REQUIRED);
}
else
{
vHelper.stringMeetsRequirments(DomainGroupModelView.DESCRIPTION_KEY, groupDesc, ve,
DomainGroup.DESCRIPTION_LENGTH_MESSAGE, DomainGroup.MAX_DESCRIPTION_LENGTH,
DomainGroup.DESCRIPTION_LENGTH_MESSAGE, null, null);
}
Set coordinators = (Set) vHelper.getAndCheckStringFieldExist(fields, DomainGroupModelView.COORDINATORS_KEY,
true, ve);
if (coordinators == null || coordinators.isEmpty())
{
ve.addError(DomainGroupModelView.COORDINATORS_KEY, DomainGroup.MIN_COORDINATORS_MESSAGE);
}
vHelper.getAndCheckStringFieldExist(fields, DomainGroupModelView.PRIVACY_KEY, true, ve);
if (!ve.getErrors().isEmpty())
{
throw ve;
}
}
}
| false | true | public void validate(final ActionContext inActionContext) throws ValidationException
{
Map<String, Serializable> fields = (Map<String, Serializable>) inActionContext.getParams();
ValidationException ve = new ValidationException();
ValidationHelper vHelper = new ValidationHelper();
String groupName = (String) vHelper
.getAndCheckStringFieldExist(fields, DomainGroupModelView.NAME_KEY, true, ve);
if (groupName == null || groupName.isEmpty())
{
ve.addError(DomainGroupModelView.NAME_KEY, DomainGroup.NAME_REQUIRED);
}
else
{
vHelper.stringMeetsRequirments(DomainGroupModelView.NAME_KEY, groupName, ve,
DomainGroup.NAME_LENGTH_MESSAGE, DomainGroup.MAX_NAME_LENGTH, DomainGroup.NAME_LENGTH_MESSAGE,
null, null);
}
String groupShortName = (String) vHelper.getAndCheckStringFieldExist(fields,
DomainGroupModelView.SHORT_NAME_KEY, true, ve);
if (groupShortName == null || groupShortName.isEmpty())
{
ve.addError(DomainGroupModelView.SHORT_NAME_KEY, DomainGroup.SHORTNAME_REQUIRED);
}
else if (vHelper.stringMeetsRequirments(DomainGroupModelView.SHORT_NAME_KEY, groupShortName, ve,
DomainGroup.SHORT_NAME_LENGTH_MESSAGE, DomainGroup.MAX_SHORT_NAME_LENGTH,
DomainGroup.SHORT_NAME_LENGTH_MESSAGE, DomainGroup.ALPHA_NUMERIC_PATTERN,
DomainGroup.SHORT_NAME_CHARACTERS))
{
if (groupMapper.fetchUniqueResult(groupShortName.toLowerCase()) != null)
{
ve.addError(DomainGroupModelView.SHORT_NAME_KEY, SHORTNAME_TAKEN_MESSAGE);
}
}
String groupDesc = (String) vHelper.getAndCheckStringFieldExist(fields, DomainGroupModelView.DESCRIPTION_KEY,
true, ve);
if (groupDesc == null || groupDesc.isEmpty())
{
ve.addError(DomainGroupModelView.DESCRIPTION_KEY, DomainGroup.DESCRIPTION_REQUIRED);
}
else
{
vHelper.stringMeetsRequirments(DomainGroupModelView.DESCRIPTION_KEY, groupDesc, ve,
DomainGroup.DESCRIPTION_LENGTH_MESSAGE, DomainGroup.MAX_DESCRIPTION_LENGTH,
DomainGroup.DESCRIPTION_LENGTH_MESSAGE, null, null);
}
Set coordinators = (Set) vHelper.getAndCheckStringFieldExist(fields, DomainGroupModelView.COORDINATORS_KEY,
true, ve);
if (coordinators == null || coordinators.isEmpty())
{
ve.addError(DomainGroupModelView.COORDINATORS_KEY, DomainGroup.MIN_COORDINATORS_MESSAGE);
}
vHelper.getAndCheckStringFieldExist(fields, DomainGroupModelView.PRIVACY_KEY, true, ve);
if (!ve.getErrors().isEmpty())
{
throw ve;
}
}
| public void validate(final ActionContext inActionContext) throws ValidationException
{
Map<String, Serializable> fields = (Map<String, Serializable>) inActionContext.getParams();
ValidationException ve = new ValidationException();
ValidationHelper vHelper = new ValidationHelper();
String groupName = (String) vHelper
.getAndCheckStringFieldExist(fields, DomainGroupModelView.NAME_KEY, true, ve);
if (groupName == null || groupName.isEmpty())
{
ve.addError(DomainGroupModelView.NAME_KEY, DomainGroup.NAME_REQUIRED);
}
else
{
vHelper.stringMeetsRequirments(DomainGroupModelView.NAME_KEY, groupName, ve,
DomainGroup.NAME_LENGTH_MESSAGE, DomainGroup.MAX_NAME_LENGTH, DomainGroup.NAME_LENGTH_MESSAGE,
null, null);
}
String groupShortName = (String) vHelper.getAndCheckStringFieldExist(fields,
DomainGroupModelView.SHORT_NAME_KEY, true, ve);
if (groupShortName == null || groupShortName.isEmpty())
{
ve.addError(DomainGroupModelView.SHORT_NAME_KEY, DomainGroup.SHORTNAME_REQUIRED);
}
else if (vHelper.stringMeetsRequirments(DomainGroupModelView.SHORT_NAME_KEY, groupShortName, ve,
DomainGroup.SHORT_NAME_LENGTH_MESSAGE, DomainGroup.MAX_SHORT_NAME_LENGTH,
DomainGroup.SHORT_NAME_LENGTH_MESSAGE, DomainGroup.ALPHA_NUMERIC_PATTERN,
DomainGroup.SHORT_NAME_CHARACTERS))
{
// TODO This is a less than ideal fix due to time constraints for the 1.5 release.
// Recommend removing try/catch and evaluating why group creation is broken
try
{
if (groupMapper.fetchUniqueResult(groupShortName.toLowerCase()) != null)
{
ve.addError(DomainGroupModelView.SHORT_NAME_KEY, SHORTNAME_TAKEN_MESSAGE);
}
}
catch (Exception ex)
{
int x = 0;
}
}
String groupDesc = (String) vHelper.getAndCheckStringFieldExist(fields, DomainGroupModelView.DESCRIPTION_KEY,
true, ve);
if (groupDesc == null || groupDesc.isEmpty())
{
ve.addError(DomainGroupModelView.DESCRIPTION_KEY, DomainGroup.DESCRIPTION_REQUIRED);
}
else
{
vHelper.stringMeetsRequirments(DomainGroupModelView.DESCRIPTION_KEY, groupDesc, ve,
DomainGroup.DESCRIPTION_LENGTH_MESSAGE, DomainGroup.MAX_DESCRIPTION_LENGTH,
DomainGroup.DESCRIPTION_LENGTH_MESSAGE, null, null);
}
Set coordinators = (Set) vHelper.getAndCheckStringFieldExist(fields, DomainGroupModelView.COORDINATORS_KEY,
true, ve);
if (coordinators == null || coordinators.isEmpty())
{
ve.addError(DomainGroupModelView.COORDINATORS_KEY, DomainGroup.MIN_COORDINATORS_MESSAGE);
}
vHelper.getAndCheckStringFieldExist(fields, DomainGroupModelView.PRIVACY_KEY, true, ve);
if (!ve.getErrors().isEmpty())
{
throw ve;
}
}
|
diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/SolrZooKeeper.java b/solr/solrj/src/java/org/apache/solr/common/cloud/SolrZooKeeper.java
index c4212ef09e..a926afc313 100644
--- a/solr/solrj/src/java/org/apache/solr/common/cloud/SolrZooKeeper.java
+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/SolrZooKeeper.java
@@ -1,99 +1,99 @@
package org.apache.solr.common.cloud;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.zookeeper.ClientCnxn;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
// we use this class to expose nasty stuff for tests
public class SolrZooKeeper extends ZooKeeper {
List<Thread> spawnedThreads = new CopyOnWriteArrayList<Thread>();
// for test debug
//static Map<SolrZooKeeper,Exception> clients = new ConcurrentHashMap<SolrZooKeeper,Exception>();
public SolrZooKeeper(String connectString, int sessionTimeout,
Watcher watcher) throws IOException {
super(connectString, sessionTimeout, watcher);
//clients.put(this, new RuntimeException());
}
public ClientCnxn getConnection() {
return cnxn;
}
SelectableChannel getSendThreadChannel() throws Exception {
final Field sendThreadFld = cnxn.getClass().getDeclaredField("sendThread");
sendThreadFld.setAccessible(true);
Object sendThread = sendThreadFld.get(cnxn);
final Field sockKeyFld = sendThread.getClass().getDeclaredField("sockKey");
sockKeyFld.setAccessible(true);
final SelectionKey sockKey = (SelectionKey) sockKeyFld.get(sendThread);
return sockKey.channel();
}
/**
* Cause this ZooKeeper object to stop receiving from the ZooKeeperServer
* for the given number of milliseconds.
* @param ms the number of milliseconds to pause.
*/
public void pauseCnxn(final long ms) {
Thread t = new Thread() {
public void run() {
try {
synchronized (cnxn) {
try {
getSendThreadChannel().close();
} catch (Exception e) {
- throw new RuntimeException("Closing zookeper send channel failed.", e);
+ throw new RuntimeException("Closing Zookeeper send channel failed.", e);
}
Thread.sleep(ms);
}
} catch (InterruptedException e) {}
}
};
t.start();
spawnedThreads.add(t);
}
@Override
public synchronized void close() throws InterruptedException {
for (Thread t : spawnedThreads) {
if (t.isAlive()) t.interrupt();
}
super.close();
}
// public static void assertCloses() {
// if (clients.size() > 0) {
// Iterator<Exception> stacktraces = clients.values().iterator();
// Exception cause = null;
// cause = stacktraces.next();
// throw new RuntimeException("Found a bad one!", cause);
// }
// }
}
| true | true | public void pauseCnxn(final long ms) {
Thread t = new Thread() {
public void run() {
try {
synchronized (cnxn) {
try {
getSendThreadChannel().close();
} catch (Exception e) {
throw new RuntimeException("Closing zookeper send channel failed.", e);
}
Thread.sleep(ms);
}
} catch (InterruptedException e) {}
}
};
t.start();
spawnedThreads.add(t);
}
| public void pauseCnxn(final long ms) {
Thread t = new Thread() {
public void run() {
try {
synchronized (cnxn) {
try {
getSendThreadChannel().close();
} catch (Exception e) {
throw new RuntimeException("Closing Zookeeper send channel failed.", e);
}
Thread.sleep(ms);
}
} catch (InterruptedException e) {}
}
};
t.start();
spawnedThreads.add(t);
}
|
diff --git a/trunk/src/edu/umich/lsa/cscs/gridsweeper/DateUtils.java b/trunk/src/edu/umich/lsa/cscs/gridsweeper/DateUtils.java
index bbfd06e..357ef66 100644
--- a/trunk/src/edu/umich/lsa/cscs/gridsweeper/DateUtils.java
+++ b/trunk/src/edu/umich/lsa/cscs/gridsweeper/DateUtils.java
@@ -1,43 +1,43 @@
package edu.umich.lsa.cscs.gridsweeper;
import java.util.Calendar;
import static java.lang.String.format;
/**
* A utility class with methods for converting date objects
* into strings for use in directory names, etc.
* @author Ed Baskerville
*
*/
public class DateUtils
{
/**
* Converts a {@code java.util.Calendar} object to a string representation
* of the date represented, in the format YYYY-MM-DD.
* @param cal The {@code Calendar} object representing the date.
* @return The string representation of the date.
*/
public static String getDateString(Calendar cal)
{
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
- int day = cal.get(Calendar.DAY_OF_MONTH);
+ int day = cal.get(Calendar.DAY_OF_MONTH) + 1;
return format("%d-%02d-%02d", year, month, day);
}
/**
* Converts a @{code java.util.Calendar} object to a string representation
* of the time represented, in the format HH-MM-SS.
* @param cal
* @return The string representation of the time.
*/
public static String getTimeString(Calendar cal)
{
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
return format("%02d-%02d-%02d", hour, minute, second);
}
}
| true | true | public static String getDateString(Calendar cal)
{
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
return format("%d-%02d-%02d", year, month, day);
}
| public static String getDateString(Calendar cal)
{
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH) + 1;
return format("%d-%02d-%02d", year, month, day);
}
|
diff --git a/src/me/ivantheforth/srotater/listeners/PlayerJoin.java b/src/me/ivantheforth/srotater/listeners/PlayerJoin.java
index 4b5125b..68bd72d 100644
--- a/src/me/ivantheforth/srotater/listeners/PlayerJoin.java
+++ b/src/me/ivantheforth/srotater/listeners/PlayerJoin.java
@@ -1,51 +1,51 @@
package me.ivantheforth.srotater.listeners;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import me.ivantheforth.srotater.SRotater;
import me.ivantheforth.srotater.utils.PlanetMinecraft;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
public class PlayerJoin implements Listener
{
static SRotater sRotater;
public PlayerJoin(SRotater sRotater)
{
PlayerJoin.sRotater = sRotater;
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e)
{
String ip = PlanetMinecraft.getIp();
e.getPlayer().sendMessage(ip);
- ByteArrayOutputStream b = new ByteArrayOutputStream();
+ /*ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
try {
out.writeUTF("Connect");
out.writeUTF(ip);
} catch (IOException ex) {
ex.printStackTrace();
}
- e.getPlayer().sendPluginMessage(sRotater, "BungeeCord", b.toByteArray());
+ e.getPlayer().sendPluginMessage(sRotater, "BungeeCord", b.toByteArray());*/
}
}
| false | true | public void onPlayerJoin(PlayerJoinEvent e)
{
String ip = PlanetMinecraft.getIp();
e.getPlayer().sendMessage(ip);
ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
try {
out.writeUTF("Connect");
out.writeUTF(ip);
} catch (IOException ex) {
ex.printStackTrace();
}
e.getPlayer().sendPluginMessage(sRotater, "BungeeCord", b.toByteArray());
}
| public void onPlayerJoin(PlayerJoinEvent e)
{
String ip = PlanetMinecraft.getIp();
e.getPlayer().sendMessage(ip);
/*ByteArrayOutputStream b = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(b);
try {
out.writeUTF("Connect");
out.writeUTF(ip);
} catch (IOException ex) {
ex.printStackTrace();
}
e.getPlayer().sendPluginMessage(sRotater, "BungeeCord", b.toByteArray());*/
}
|
diff --git a/test/org/plovr/ManifestTest.java b/test/org/plovr/ManifestTest.java
index fc7a28b5..c0f5ebd0 100644
--- a/test/org/plovr/ManifestTest.java
+++ b/test/org/plovr/ManifestTest.java
@@ -1,138 +1,138 @@
package org.plovr;
import java.io.File;
import java.util.Collection;
import java.util.List;
import junit.framework.TestCase;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.javascript.jscomp.JSSourceFile;
/**
* {@link ManifestTest} is a unit test for {@link Manifest}.
*
* @author [email protected] (Michael Bolin)
*/
public class ManifestTest extends TestCase {
/** Converts a {@link JSSourceFile} to its name. */
private static Function<JSSourceFile, String> JS_SOURCE_FILE_TO_NAME =
new Function<JSSourceFile, String>() {
@Override
public String apply(JSSourceFile jsSourceFile) {
return jsSourceFile.getName();
}
};
/** Converts a {@link JsInput} to its name. */
private static Function<JsInput, String> JS_INPUT_TO_NAME =
new Function<JsInput, String>() {
@Override
public String apply(JsInput jsInput) {
return jsInput.getName();
}
};
public void testSimpleManifest() throws CompilationException {
- File closureLibraryDirectory = new File("../closure-library/closure/goog/");
+ File closureLibraryDirectory = new File("closure/closure-library/closure/goog/");
final List<File> dependencies = ImmutableList.of();
String path = "test/org/plovr/example.js";
File testFile = new File(path);
JsSourceFile requiredInput = new JsSourceFile(path, testFile);
final List<File> externs = ImmutableList.of();
final boolean customExternsOnly = false;
Manifest manifest = new Manifest(
closureLibraryDirectory,
dependencies,
ImmutableList.<JsInput>of(requiredInput),
externs,
customExternsOnly);
final ModuleConfig moduleConfig = null;
Compilation compilerArguments = manifest.getCompilerArguments(moduleConfig);
List<JSSourceFile> inputs = compilerArguments.getInputs();
List<String> expectedNames = ImmutableList.copyOf(
new String[] {
"base.js",
"/goog/debug/error.js",
"/goog/string/string.js",
"/goog/asserts/asserts.js",
"/goog/array/array.js",
"/goog/debug/entrypointregistry.js",
"/goog/debug/errorhandlerweakdep.js",
"/goog/useragent/useragent.js",
"/goog/events/browserfeature.js",
"/goog/disposable/disposable.js",
"/goog/events/event.js",
"/goog/events/eventtype.js",
"/goog/reflect/reflect.js",
"/goog/events/browserevent.js",
"/goog/events/eventwrapper.js",
"/goog/events/listener.js",
"/goog/structs/simplepool.js",
"/goog/useragent/jscript.js",
"/goog/events/pools.js",
"/goog/object/object.js",
"/goog/events/events.js",
"test/org/plovr/example.js"
}
);
assertEquals(expectedNames, Lists.transform(inputs, JS_SOURCE_FILE_TO_NAME));
}
public void testCompilationOrder() throws CompilationException {
File closureLibraryDirectory = new File("../closure-library/closure/goog/");
final List<File> dependencies = ImmutableList.of();
final List<File> externs = ImmutableList.of();
final boolean customExternsOnly = false;
// Set up a set of files so that there's a dependency loop of
// a -> b -> c -> a
DummyJsInput a, b, c;
a = new DummyJsInput("a", "", ImmutableList.of("a"), ImmutableList.of("b"));
b = new DummyJsInput("b", "", ImmutableList.of("b"), ImmutableList.of("c"));
c = new DummyJsInput("c", "", ImmutableList.of("c"), ImmutableList.of("a"));
Manifest manifest = new Manifest(
closureLibraryDirectory,
dependencies,
ImmutableList.<JsInput>of(a, b, c),
externs,
customExternsOnly);
List<JsInput> order;
try {
order = manifest.getInputsInCompilationOrder();
fail("Got order for unorderable inputs: " + order);
} catch (CircularDependencyException e) {
Collection<JsInput> circularDepdenency = e.getCircularDependency();
assertEquals(ImmutableList.copyOf(circularDepdenency),
ImmutableList.of(a, b, c));
}
// Now adjust c so that it no longer creates a loop
c = new DummyJsInput("c", "", ImmutableList.of("c"), null);
manifest = new Manifest(
closureLibraryDirectory,
dependencies,
ImmutableList.<JsInput>of(a, b, c),
externs,
customExternsOnly);
order = manifest.getInputsInCompilationOrder();
List<String> expectedNames = ImmutableList.of("base.js", "c", "b", "a");
assertEquals(expectedNames, Lists.transform(order, JS_INPUT_TO_NAME));
}
}
| true | true | public void testSimpleManifest() throws CompilationException {
File closureLibraryDirectory = new File("../closure-library/closure/goog/");
final List<File> dependencies = ImmutableList.of();
String path = "test/org/plovr/example.js";
File testFile = new File(path);
JsSourceFile requiredInput = new JsSourceFile(path, testFile);
final List<File> externs = ImmutableList.of();
final boolean customExternsOnly = false;
Manifest manifest = new Manifest(
closureLibraryDirectory,
dependencies,
ImmutableList.<JsInput>of(requiredInput),
externs,
customExternsOnly);
final ModuleConfig moduleConfig = null;
Compilation compilerArguments = manifest.getCompilerArguments(moduleConfig);
List<JSSourceFile> inputs = compilerArguments.getInputs();
List<String> expectedNames = ImmutableList.copyOf(
new String[] {
"base.js",
"/goog/debug/error.js",
"/goog/string/string.js",
"/goog/asserts/asserts.js",
"/goog/array/array.js",
"/goog/debug/entrypointregistry.js",
"/goog/debug/errorhandlerweakdep.js",
"/goog/useragent/useragent.js",
"/goog/events/browserfeature.js",
"/goog/disposable/disposable.js",
"/goog/events/event.js",
"/goog/events/eventtype.js",
"/goog/reflect/reflect.js",
"/goog/events/browserevent.js",
"/goog/events/eventwrapper.js",
"/goog/events/listener.js",
"/goog/structs/simplepool.js",
"/goog/useragent/jscript.js",
"/goog/events/pools.js",
"/goog/object/object.js",
"/goog/events/events.js",
"test/org/plovr/example.js"
}
);
assertEquals(expectedNames, Lists.transform(inputs, JS_SOURCE_FILE_TO_NAME));
}
| public void testSimpleManifest() throws CompilationException {
File closureLibraryDirectory = new File("closure/closure-library/closure/goog/");
final List<File> dependencies = ImmutableList.of();
String path = "test/org/plovr/example.js";
File testFile = new File(path);
JsSourceFile requiredInput = new JsSourceFile(path, testFile);
final List<File> externs = ImmutableList.of();
final boolean customExternsOnly = false;
Manifest manifest = new Manifest(
closureLibraryDirectory,
dependencies,
ImmutableList.<JsInput>of(requiredInput),
externs,
customExternsOnly);
final ModuleConfig moduleConfig = null;
Compilation compilerArguments = manifest.getCompilerArguments(moduleConfig);
List<JSSourceFile> inputs = compilerArguments.getInputs();
List<String> expectedNames = ImmutableList.copyOf(
new String[] {
"base.js",
"/goog/debug/error.js",
"/goog/string/string.js",
"/goog/asserts/asserts.js",
"/goog/array/array.js",
"/goog/debug/entrypointregistry.js",
"/goog/debug/errorhandlerweakdep.js",
"/goog/useragent/useragent.js",
"/goog/events/browserfeature.js",
"/goog/disposable/disposable.js",
"/goog/events/event.js",
"/goog/events/eventtype.js",
"/goog/reflect/reflect.js",
"/goog/events/browserevent.js",
"/goog/events/eventwrapper.js",
"/goog/events/listener.js",
"/goog/structs/simplepool.js",
"/goog/useragent/jscript.js",
"/goog/events/pools.js",
"/goog/object/object.js",
"/goog/events/events.js",
"test/org/plovr/example.js"
}
);
assertEquals(expectedNames, Lists.transform(inputs, JS_SOURCE_FILE_TO_NAME));
}
|
diff --git a/src/net/cscott/sdr/calls/FormationList.java b/src/net/cscott/sdr/calls/FormationList.java
index 03852b7..cd0aa93 100644
--- a/src/net/cscott/sdr/calls/FormationList.java
+++ b/src/net/cscott/sdr/calls/FormationList.java
@@ -1,168 +1,171 @@
package net.cscott.sdr.calls;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import net.cscott.jdoctest.JDoctestRunner;
import org.junit.runner.RunWith;
/**
* A list of common formations, specified with phantoms.
* The actual formation definitions are in the package-scope
* {@link FormationListSlow}, which is post-processed into
* {@link FormationListFast}. This class is a public wrapper for those
* definitions and contains doc tests on the formations.
*
* @doc.test Almost all standard formations are maximally "breathed in".
* This includes single diamonds, which are defined on a 2x3 grid, but
* twin diamonds have unbreathed points.
* (EXPECT FAIL: our breather is pushing in the points of twin diamonds)
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> for (f in Iterator(FormationList.all)) {
* > if (!Breather.breathe(f).equals(f)) {
* > print("Unbreathed formation: "+f.getName());
* > }
* > }
* js> // note: no output from the above
* @doc.test Canonical formations should be centered.
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> for (f in Iterator(FormationList.all)) {
* > if (!f.isCentered()) {
* > print("Uncentered formation: "+f.getName());
* > }
* > } ; undefined
* js> // note no output from the above.
* @doc.test Canonical formations should be oriented so that "most"
* dancers are facing north or south. This seems to match standard
* diagrams best.
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> ns = Rotation.fromAbsoluteString("|");
* 0 mod 1/2
* js> for (f in Iterator(FormationList.all)) {
* > facing = [f.location(d).facing for (d in Iterator(f.dancers()))]
* > l=[(ns.includes(dir) || dir.includes(ns)) for each (dir in facing)]
* > if ([b for each (b in l) if (b)].length <
* > [b for each (b in l) if (!b)].length) {
* > print("Unexpected orientation: "+f.getName());
* > }
* > } ; undefined
* js> // note no output from the above.
* @doc.test Formations in the formation list should be named to match their
* field name, except that underscores become spaces (and some other
* minor abbreviations/tweaks occur, see below).
* js> flc = java.lang.Class.forName('net.cscott.sdr.calls.FormationList')
* class net.cscott.sdr.calls.FormationList
* js> flds = [f for each (f in flc.getFields()) if
* > (java.lang.reflect.Modifier.isPublic(f.getModifiers()) &&
* > java.lang.reflect.Modifier.isStatic(f.getModifiers()) &&
* > !f.getName().equals("all"))]; undefined
* js> FormationListJS = FormationListJS.initJS(this); undefined;
* js> flds.every(function(f) {
* > name = f.getName();
* > return (FormationListJS[name].getName()
* > .replace(' ','_').replace('-','_')
* > .replace("1/4","QUARTER")
* > .replace("3/4","THREE_QUARTER")
* > .replace("1x2", "_1x2")
* > .replace("1x4", "_1x4")
* > .replace("1x8", "_1x8")
* > .replace("2x2", "_2x2")
* > .replace("2x4", "_2x4")
* > .equals(name));
* > })
* true
* @doc.test There should be a matcher for every formation. (Although there
* are more matchers than there are formations.)
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> for (f in Iterator(FormationList.all)) {
* > let name = (f.getName()
* > .replace("1/4","QUARTER")
* > .replace("3/4","THREE_QUARTER")
* > .replace("1x2", "_1_X2")
* > .replace("1x4", "_1_X4")
* > .replace("1x8", "_1_X8")
* > .replace("2x2", "_2_X2")
* > .replace("2x4", "_2_X4"));
* > try {
* > if (Matcher.valueOf(name).toString() != f.getName())
* > print("Matcher name mismatch: "+f.getName());
* > } catch (e) {
* > print("No matcher for "+f.getName());
* > }
* > }; undefined
* js> // note: no output
* @doc.test The "slow" and "fast" versions of the formations should be
* identical (modulo the exact identity of the phantom dancers)
* js> FormationListSlow = FormationListJS.initJS(this, FormationListSlow)
* [object FormationListJS]
* js> FormationListFast = FormationListJS.initJS(this, FormationList)
* [object FormationListJS]
* js> len = FormationListSlow.all.size(); undefined
* js> [f for (f in FormationListSlow)].length == len
* true
* js> FormationListFast.all.size() == len
* true
* js> [f for (f in FormationListFast)].length == len
* true
* js> function compare(a, b) {
* > if (!a.getName().equals(b.getName())) return false;
* > d1=a.sortedDancers(); d2=b.sortedDancers();
* > if (d1.size() != d2.size()) return false;
* > // make all phantoms equivalent
* > m=new java.util.HashMap();
* > for (let i=0; i<d1.size(); i++) {
* > if (!(d1.get(i) instanceof PhantomDancer)) return false;
* > if (!(d2.get(i) instanceof PhantomDancer)) return false;
* > m.put(d1.get(i), d2.get(i));
* > }
* > aa=a.map(m);
* > return aa.equals(b);
* > }
* js> matches=0
* 0
* js> for (f in FormationListFast) {
* > if (compare(FormationListSlow[f], FormationListFast[f]))
* > matches++;
* > }; matches == len;
* true
*/
// can use MatcherList to associate phantoms with real dancers.
@RunWith(value=JDoctestRunner.class)
public abstract class FormationList extends FormationListFast {
// no implementation: all the interesting stuff is in FormationListSlow.
/** Return the named formation. Case-insensitive. */
public static NamedTaggedFormation valueOf(String s) {
s = s.toUpperCase()
.replace(' ','_')
.replace("1/4","QUARTER")
.replace("3/4","THREE_QUARTER")
- .replace("1x2", "_1X2")
- .replace("1x4", "_1X4")
- .replace("2x2", "_2X2");
+ .replace("1X2", "_1x2")
+ .replace("1X4", "_1x4")
+ .replace("2X2", "_2x2")
+ .replace("1_X2", "_1x2")
+ .replace("1_X4", "_1x4")
+ .replace("2_X2", "_2x2");
try {
return (NamedTaggedFormation)
FormationList.class.getField(s).get(null);
} catch (IllegalAccessException e) {
throw new RuntimeException("No such formation: "+s);
} catch (NoSuchFieldException e) {
throw new RuntimeException("No such formation: "+s);
}
}
/** Show all the defined formations. */
public static void main(String[] args) throws Exception {
for (Field f : FormationList.class.getFields()) {
if (Modifier.isPublic(f.getModifiers()) &&
Modifier.isStatic(f.getModifiers()) &&
f.getName().toUpperCase().equals(f.getName())) {
NamedTaggedFormation ff = (NamedTaggedFormation) f.get(null);
System.out.println("FormationList."+f.getName());
System.out.println(ff.toStringDiagram());
System.out.println(ff.toString());
System.out.println();
}
}
}
}
| true | true | public static NamedTaggedFormation valueOf(String s) {
s = s.toUpperCase()
.replace(' ','_')
.replace("1/4","QUARTER")
.replace("3/4","THREE_QUARTER")
.replace("1x2", "_1X2")
.replace("1x4", "_1X4")
.replace("2x2", "_2X2");
try {
return (NamedTaggedFormation)
FormationList.class.getField(s).get(null);
} catch (IllegalAccessException e) {
throw new RuntimeException("No such formation: "+s);
} catch (NoSuchFieldException e) {
throw new RuntimeException("No such formation: "+s);
}
}
| public static NamedTaggedFormation valueOf(String s) {
s = s.toUpperCase()
.replace(' ','_')
.replace("1/4","QUARTER")
.replace("3/4","THREE_QUARTER")
.replace("1X2", "_1x2")
.replace("1X4", "_1x4")
.replace("2X2", "_2x2")
.replace("1_X2", "_1x2")
.replace("1_X4", "_1x4")
.replace("2_X2", "_2x2");
try {
return (NamedTaggedFormation)
FormationList.class.getField(s).get(null);
} catch (IllegalAccessException e) {
throw new RuntimeException("No such formation: "+s);
} catch (NoSuchFieldException e) {
throw new RuntimeException("No such formation: "+s);
}
}
|
diff --git a/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/dataTable/DataTableGrouping.java b/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/dataTable/DataTableGrouping.java
index a149cd4f0..46407d7ce 100644
--- a/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/dataTable/DataTableGrouping.java
+++ b/samples/showcase/showcase/src/main/java/org/icefaces/samples/showcase/example/ace/dataTable/DataTableGrouping.java
@@ -1,103 +1,103 @@
/*
* Copyright 2004-2012 ICEsoft Technologies Canada Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.icefaces.samples.showcase.example.ace.dataTable;
import org.icefaces.ace.component.datatable.DataTable;
import org.icefaces.samples.showcase.dataGenerators.utilityClasses.DataTableData;
import org.icefaces.samples.showcase.example.compat.dataTable.Car;
import org.icefaces.samples.showcase.metadata.annotation.ComponentExample;
import org.icefaces.samples.showcase.metadata.annotation.ExampleResource;
import org.icefaces.samples.showcase.metadata.annotation.ExampleResources;
import org.icefaces.samples.showcase.metadata.annotation.ResourceType;
import org.icefaces.samples.showcase.metadata.context.ComponentExampleImpl;
import javax.faces.application.Application;
import javax.faces.bean.CustomScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@ComponentExample(
parent = DataTableBean.BEAN_NAME,
title = "example.ace.dataTable.grouping.title",
description = "example.ace.dataTable.grouping.description",
example = "/resources/examples/ace/dataTable/dataTableGrouping.xhtml"
)
@ExampleResources(
resources ={
// xhtml
@ExampleResource(type = ResourceType.xhtml,
title="dataTableGrouping.xhtml",
resource = "/resources/examples/ace/dataTable/dataTableGrouping.xhtml"),
// Java Source
@ExampleResource(type = ResourceType.java,
title="DataTableGrouping.java",
resource = "/WEB-INF/classes/org/icefaces/samples/showcase"+
"/example/ace/dataTable/DataTableGrouping.java")
}
)
@ManagedBean(name= DataTableGrouping.BEAN_NAME)
@CustomScoped(value = "#{window}")
public class DataTableGrouping extends ComponentExampleImpl<DataTableGrouping> implements Serializable {
public static final String BEAN_NAME = "dataTableGrouping";
private DataTable table;
private List<Car> carsData;
/////////////---- CONSTRUCTOR BEGIN
public DataTableGrouping() {
super(DataTableGrouping.class);
carsData = new ArrayList<Car>(DataTableData.getDefaultData());
}
/////////////---- GETTERS & SETTERS BEGIN
public List<Car> getCarsData() { return carsData; }
public void setCarsData(List<Car> carsData) { this.carsData = carsData; }
public DataTable getTable() { return table; }
public void setTable(DataTable table) { this.table = table; }
/////////////---- METHOD INVOCATION VIA VIEW EL
public double groupTotal(String groupProperty, String valueProperty, Object i) {
// Fix for bugged method invocation in early TC7 releases
int index = (Integer) i;
double total = 0;
boolean nextRowInGroup = false;
FacesContext context = FacesContext.getCurrentInstance();
Application application = context.getApplication();
int currentIndex = table.getRowIndex();
table.setRowIndex(index);
Object groupValue = application.evaluateExpressionGet(context, "#{"+groupProperty+"}", Object.class);
do {
total += application.evaluateExpressionGet(context, "#{"+valueProperty+"}", Double.class);
table.setRowIndex(--index);
Object obj = application.evaluateExpressionGet(context, "#{"+groupProperty+"}", Object.class);
if (table.isRowAvailable() && groupValue.equals(obj))
nextRowInGroup = true;
else
nextRowInGroup = false;
} while (nextRowInGroup);
table.setRowIndex(currentIndex);
- return 0.0;
+ return total;
}
}
| true | true | public double groupTotal(String groupProperty, String valueProperty, Object i) {
// Fix for bugged method invocation in early TC7 releases
int index = (Integer) i;
double total = 0;
boolean nextRowInGroup = false;
FacesContext context = FacesContext.getCurrentInstance();
Application application = context.getApplication();
int currentIndex = table.getRowIndex();
table.setRowIndex(index);
Object groupValue = application.evaluateExpressionGet(context, "#{"+groupProperty+"}", Object.class);
do {
total += application.evaluateExpressionGet(context, "#{"+valueProperty+"}", Double.class);
table.setRowIndex(--index);
Object obj = application.evaluateExpressionGet(context, "#{"+groupProperty+"}", Object.class);
if (table.isRowAvailable() && groupValue.equals(obj))
nextRowInGroup = true;
else
nextRowInGroup = false;
} while (nextRowInGroup);
table.setRowIndex(currentIndex);
return 0.0;
}
| public double groupTotal(String groupProperty, String valueProperty, Object i) {
// Fix for bugged method invocation in early TC7 releases
int index = (Integer) i;
double total = 0;
boolean nextRowInGroup = false;
FacesContext context = FacesContext.getCurrentInstance();
Application application = context.getApplication();
int currentIndex = table.getRowIndex();
table.setRowIndex(index);
Object groupValue = application.evaluateExpressionGet(context, "#{"+groupProperty+"}", Object.class);
do {
total += application.evaluateExpressionGet(context, "#{"+valueProperty+"}", Double.class);
table.setRowIndex(--index);
Object obj = application.evaluateExpressionGet(context, "#{"+groupProperty+"}", Object.class);
if (table.isRowAvailable() && groupValue.equals(obj))
nextRowInGroup = true;
else
nextRowInGroup = false;
} while (nextRowInGroup);
table.setRowIndex(currentIndex);
return total;
}
|
diff --git a/src/test/java/com/testmonkey/app/test/TestScheduleTest.java b/src/test/java/com/testmonkey/app/test/TestScheduleTest.java
index 0fc7f82..d8cb6f3 100644
--- a/src/test/java/com/testmonkey/app/test/TestScheduleTest.java
+++ b/src/test/java/com/testmonkey/app/test/TestScheduleTest.java
@@ -1,96 +1,96 @@
/**
*
*/
package com.testmonkey.app.test;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.StringReader;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;
import javax.xml.xpath.XPathExpressionException;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Test;
import org.xml.sax.InputSource;
import com.testmonkey.app.GlobalConfig;
import com.testmonkey.app.TestSchedule;
import com.testmonkey.exceptions.VarNotFoundException;
import com.testmonkey.model.TestModule;
import com.testmonkey.util.HashMethodFactory;
import com.testmonkey.util.IHashMethod;
import com.testmonkey.util.InputSourceFactory;
/**
* @author phil
*
*/
public class TestScheduleTest {
Mockery context = new Mockery();
/**
* Test TestSchedule.getTestModuleListFromSchedule
* @throws IOException
* @throws VarNotFoundException
* @throws NoSuchAlgorithmException
* @throws XPathExpressionException
* @throws IllegalArgumentException
*/
@Test
public void getTestModuleListFromScheduleTest() throws IllegalArgumentException, XPathExpressionException, NoSuchAlgorithmException, VarNotFoundException, IOException {
// create mock hash object
final IHashMethod mockHash = context.mock(IHashMethod.class);
// register mock object factory
HashMethodFactory.registerHashMethodProvider(new HashMethodFactory() {
@Override
protected IHashMethod createHashMethod() {
return mockHash;
}
});
// expectations
context.checking(new Expectations() {{
oneOf (mockHash).getFileHash(with(any(String.class))); will(returnValue(UUID.randomUUID().toString()));
}});
// add var to global config object
GlobalConfig config = GlobalConfig.getConfig();
config.processCommandLine(new String[] {"/test/fakeGTestApp", "TestVariableReplacement=replaced" });
// define an InputSourceFactory that returns a stubbed InputSource (can't use a mock in this instance
// as InputSource isn't an interface, but a stub will do)
InputSourceFactory.registerInputSourceProvider(new InputSourceFactory() {
// define some gtest format output xml that has a test failure
private static final String testXmlOutput =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<UnitTestSchedule runallfrom=\"/test/directory/$(TestVariableReplacement)/ping\">\n" +
" <UnitTestModule name=\"fakeApp\" testfilter=\"*\" enabled=\"true\" description=\"A fake unit test module\">fakeGTestApp</UnitTestModule>\n" +
" <UnitTestModule name=\"ignored\" testfilter=\"*\" enabled=\"false\">AnIgnoredModule</UnitTestModule>\n" +
"</UnitTestSchedule>";
@Override
protected InputSource createInputSource(String sourceIdentifier) {
return new InputSource(new StringReader(testXmlOutput));
}
});
TestSchedule testSchedule = new TestSchedule("dummyFile");
// execute
List<TestModule> testModules = testSchedule.getTestModuleListFromSchedule();
// verify
context.assertIsSatisfied(); // were the mocks called with the right params in the right order?
assertEquals(1, testModules.size());
- assertEquals("/test/directory/replaced/ping/fakeGTestApp", testModules.get(0).getModuleFilePath());
+ assertEquals("/test/directory/replaced/ping" + System.getProperty("file.separator") + "fakeGTestApp", testModules.get(0).getModuleFilePath());
}
}
| true | true | public void getTestModuleListFromScheduleTest() throws IllegalArgumentException, XPathExpressionException, NoSuchAlgorithmException, VarNotFoundException, IOException {
// create mock hash object
final IHashMethod mockHash = context.mock(IHashMethod.class);
// register mock object factory
HashMethodFactory.registerHashMethodProvider(new HashMethodFactory() {
@Override
protected IHashMethod createHashMethod() {
return mockHash;
}
});
// expectations
context.checking(new Expectations() {{
oneOf (mockHash).getFileHash(with(any(String.class))); will(returnValue(UUID.randomUUID().toString()));
}});
// add var to global config object
GlobalConfig config = GlobalConfig.getConfig();
config.processCommandLine(new String[] {"/test/fakeGTestApp", "TestVariableReplacement=replaced" });
// define an InputSourceFactory that returns a stubbed InputSource (can't use a mock in this instance
// as InputSource isn't an interface, but a stub will do)
InputSourceFactory.registerInputSourceProvider(new InputSourceFactory() {
// define some gtest format output xml that has a test failure
private static final String testXmlOutput =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<UnitTestSchedule runallfrom=\"/test/directory/$(TestVariableReplacement)/ping\">\n" +
" <UnitTestModule name=\"fakeApp\" testfilter=\"*\" enabled=\"true\" description=\"A fake unit test module\">fakeGTestApp</UnitTestModule>\n" +
" <UnitTestModule name=\"ignored\" testfilter=\"*\" enabled=\"false\">AnIgnoredModule</UnitTestModule>\n" +
"</UnitTestSchedule>";
@Override
protected InputSource createInputSource(String sourceIdentifier) {
return new InputSource(new StringReader(testXmlOutput));
}
});
TestSchedule testSchedule = new TestSchedule("dummyFile");
// execute
List<TestModule> testModules = testSchedule.getTestModuleListFromSchedule();
// verify
context.assertIsSatisfied(); // were the mocks called with the right params in the right order?
assertEquals(1, testModules.size());
assertEquals("/test/directory/replaced/ping/fakeGTestApp", testModules.get(0).getModuleFilePath());
}
| public void getTestModuleListFromScheduleTest() throws IllegalArgumentException, XPathExpressionException, NoSuchAlgorithmException, VarNotFoundException, IOException {
// create mock hash object
final IHashMethod mockHash = context.mock(IHashMethod.class);
// register mock object factory
HashMethodFactory.registerHashMethodProvider(new HashMethodFactory() {
@Override
protected IHashMethod createHashMethod() {
return mockHash;
}
});
// expectations
context.checking(new Expectations() {{
oneOf (mockHash).getFileHash(with(any(String.class))); will(returnValue(UUID.randomUUID().toString()));
}});
// add var to global config object
GlobalConfig config = GlobalConfig.getConfig();
config.processCommandLine(new String[] {"/test/fakeGTestApp", "TestVariableReplacement=replaced" });
// define an InputSourceFactory that returns a stubbed InputSource (can't use a mock in this instance
// as InputSource isn't an interface, but a stub will do)
InputSourceFactory.registerInputSourceProvider(new InputSourceFactory() {
// define some gtest format output xml that has a test failure
private static final String testXmlOutput =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<UnitTestSchedule runallfrom=\"/test/directory/$(TestVariableReplacement)/ping\">\n" +
" <UnitTestModule name=\"fakeApp\" testfilter=\"*\" enabled=\"true\" description=\"A fake unit test module\">fakeGTestApp</UnitTestModule>\n" +
" <UnitTestModule name=\"ignored\" testfilter=\"*\" enabled=\"false\">AnIgnoredModule</UnitTestModule>\n" +
"</UnitTestSchedule>";
@Override
protected InputSource createInputSource(String sourceIdentifier) {
return new InputSource(new StringReader(testXmlOutput));
}
});
TestSchedule testSchedule = new TestSchedule("dummyFile");
// execute
List<TestModule> testModules = testSchedule.getTestModuleListFromSchedule();
// verify
context.assertIsSatisfied(); // were the mocks called with the right params in the right order?
assertEquals(1, testModules.size());
assertEquals("/test/directory/replaced/ping" + System.getProperty("file.separator") + "fakeGTestApp", testModules.get(0).getModuleFilePath());
}
|
diff --git a/tests/jdbc/src/test/java/org/apache/manifoldcf/jdbc_tests/NavigationDerbyUI.java b/tests/jdbc/src/test/java/org/apache/manifoldcf/jdbc_tests/NavigationDerbyUI.java
index 9be6f6d76..63cd86273 100644
--- a/tests/jdbc/src/test/java/org/apache/manifoldcf/jdbc_tests/NavigationDerbyUI.java
+++ b/tests/jdbc/src/test/java/org/apache/manifoldcf/jdbc_tests/NavigationDerbyUI.java
@@ -1,286 +1,300 @@
/* $Id$ */
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.jdbc_tests;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.agents.interfaces.*;
import org.apache.manifoldcf.crawler.interfaces.*;
import org.apache.manifoldcf.crawler.system.ManifoldCF;
import java.io.*;
import java.util.*;
import org.junit.*;
import org.apache.manifoldcf.core.tests.HTMLTester;
/** Basic UI navigation tests */
public class NavigationDerbyUI extends BaseUIDerby
{
@Test
public void createConnectionsAndJob()
throws Exception
{
testerInstance.newTest(Locale.US);
HTMLTester.Window window;
HTMLTester.Link link;
HTMLTester.Form form;
HTMLTester.Textarea textarea;
HTMLTester.Selectbox selectbox;
HTMLTester.Button button;
HTMLTester.Radiobutton radiobutton;
HTMLTester.Loop loop;
window = testerInstance.openMainWindow("http://localhost:8346/mcf-crawler-ui/index.jsp");
// Login
form = window.findForm(testerInstance.createStringDescription("loginform"));
textarea = form.findTextarea(testerInstance.createStringDescription("userID"));
textarea.setValue(testerInstance.createStringDescription("admin"));
textarea = form.findTextarea(testerInstance.createStringDescription("password"));
textarea.setValue(testerInstance.createStringDescription("admin"));
button = window.findButton(testerInstance.createStringDescription("Login"));
button.click();
window = testerInstance.findWindow(null);
// Define an output connection via the UI
link = window.findLink(testerInstance.createStringDescription("List output connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add an output connection"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("connname"));
textarea.setValue(testerInstance.createStringDescription("MyOutputConnection"));
link = window.findLink(testerInstance.createStringDescription("Type tab"));
link.click();
// Select a type
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("classname"));
selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.agents.output.nullconnector.NullConnector"));
button = window.findButton(testerInstance.createStringDescription("Continue to next page"));
button.click();
// Visit the Throttling tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Throttling tab"));
link.click();
// Go back to the Name tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Name tab"));
link.click();
// Now save the connection.
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this output connection"));
button.click();
// Define a repository connection via the UI
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List repository connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add a connection"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("connname"));
textarea.setValue(testerInstance.createStringDescription("MyRepositoryConnection"));
link = window.findLink(testerInstance.createStringDescription("Type tab"));
link.click();
// Select a type
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("classname"));
selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.crawler.connectors.jdbc.JDBCConnector"));
button = window.findButton(testerInstance.createStringDescription("Continue to next page"));
button.click();
window = testerInstance.findWindow(null);
// Credentials tab
link = window.findLink(testerInstance.createStringDescription("Credentials tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("username"));
textarea.setValue(testerInstance.createStringDescription("foo"));
// Server
link = window.findLink(testerInstance.createStringDescription("Server tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
// Database Type
link = window.findLink(testerInstance.createStringDescription("Database Type tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
// Go back to the Name tab
link = window.findLink(testerInstance.createStringDescription("Name tab"));
link.click();
// Now save the connection.
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this connection"));
button.click();
// Create a job
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List jobs"));
link.click();
// Add a job
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add a job"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
textarea = form.findTextarea(testerInstance.createStringDescription("description"));
textarea.setValue(testerInstance.createStringDescription("MyJob"));
link = window.findLink(testerInstance.createStringDescription("Connection tab"));
link.click();
// Select the connections
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("outputname"));
selectbox.selectValue(testerInstance.createStringDescription("MyOutputConnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("connectionname"));
selectbox.selectValue(testerInstance.createStringDescription("MyRepositoryConnection"));
button = window.findButton(testerInstance.createStringDescription("Continue to next screen"));
button.click();
// Visit all the connector tabs.
// Queries
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
link = window.findLink(testerInstance.createStringDescription("Queries tab"));
link.click();
// Security
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
link = window.findLink(testerInstance.createStringDescription("Security tab"));
link.click();
// Save the job
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this job"));
button.click();
// Delete the job
window = testerInstance.findWindow(null);
HTMLTester.StringDescription jobID = window.findMatch(testerInstance.createStringDescription("<!--jobid=(.*?)-->"),0);
testerInstance.printValue(jobID);
link = window.findLink(testerInstance.createStringDescription("Delete this job"));
link.click();
// Wait for the job to go away
loop = testerInstance.beginLoop(120);
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Manage jobs"));
link.click();
window = testerInstance.findWindow(null);
HTMLTester.StringDescription isJobNotPresent = window.isNotPresent(jobID);
testerInstance.printValue(isJobNotPresent);
loop.breakWhenTrue(isJobNotPresent);
loop.endLoop();
// Delete the repository connection
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List repository connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Delete MyRepositoryConnection"));
link.click();
// Delete the output connection
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List output connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Delete MyOutputConnection"));
link.click();
// Now go on to execute the authority test
window = testerInstance.openMainWindow("http://localhost:8346/mcf-crawler-ui/index.jsp");
// Define an authority connection via the UI
window = testerInstance.findWindow(null);
+ link = window.findLink(testerInstance.createStringDescription("List authority groups"));
+ link.click();
+ window = testerInstance.findWindow(null);
+ link = window.findLink(testerInstance.createStringDescription("Add new authority group"));
+ link.click();
+ window = testerInstance.findWindow(null);
+ form = window.findForm(testerInstance.createStringDescription("editgroup"));
+ textarea = form.findTextarea(testerInstance.createStringDescription("groupname"));
+ textarea.setValue(testerInstance.createStringDescription("MyAuthorityConnection"));
+ button = window.findButton(testerInstance.createStringDescription("Save this authority group"));
+ button.click();
+ window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List authorities"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add a new connection"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("connname"));
textarea.setValue(testerInstance.createStringDescription("MyAuthorityConnection"));
link = window.findLink(testerInstance.createStringDescription("Type tab"));
link.click();
// Select a type
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("classname"));
selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.authorities.authorities.jdbc.JDBCAuthority"));
+ selectbox = form.findSelectbox(testerInstance.createStringDescription("authoritygroup"));
+ selectbox.selectValue(testerInstance.createStringDescription("MyAuthorityConnection"));
button = window.findButton(testerInstance.createStringDescription("Continue to next page"));
button.click();
// Credentials tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Credentials tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("username"));
textarea.setValue(testerInstance.createStringDescription("foo"));
// Server
link = window.findLink(testerInstance.createStringDescription("Server tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
// Database Type
link = window.findLink(testerInstance.createStringDescription("Database Type tab"));
link.click();
// Visit all the connector tabs.
// Queries
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
link = window.findLink(testerInstance.createStringDescription("Queries tab"));
link.click();
// Go back to the Name tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Name tab"));
link.click();
// Now save the connection.
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this authority connection"));
button.click();
// Delete the authority connection
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List authorities"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Delete MyAuthorityConnection"));
link.click();
testerInstance.executeTest();
}
}
| false | true | public void createConnectionsAndJob()
throws Exception
{
testerInstance.newTest(Locale.US);
HTMLTester.Window window;
HTMLTester.Link link;
HTMLTester.Form form;
HTMLTester.Textarea textarea;
HTMLTester.Selectbox selectbox;
HTMLTester.Button button;
HTMLTester.Radiobutton radiobutton;
HTMLTester.Loop loop;
window = testerInstance.openMainWindow("http://localhost:8346/mcf-crawler-ui/index.jsp");
// Login
form = window.findForm(testerInstance.createStringDescription("loginform"));
textarea = form.findTextarea(testerInstance.createStringDescription("userID"));
textarea.setValue(testerInstance.createStringDescription("admin"));
textarea = form.findTextarea(testerInstance.createStringDescription("password"));
textarea.setValue(testerInstance.createStringDescription("admin"));
button = window.findButton(testerInstance.createStringDescription("Login"));
button.click();
window = testerInstance.findWindow(null);
// Define an output connection via the UI
link = window.findLink(testerInstance.createStringDescription("List output connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add an output connection"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("connname"));
textarea.setValue(testerInstance.createStringDescription("MyOutputConnection"));
link = window.findLink(testerInstance.createStringDescription("Type tab"));
link.click();
// Select a type
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("classname"));
selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.agents.output.nullconnector.NullConnector"));
button = window.findButton(testerInstance.createStringDescription("Continue to next page"));
button.click();
// Visit the Throttling tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Throttling tab"));
link.click();
// Go back to the Name tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Name tab"));
link.click();
// Now save the connection.
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this output connection"));
button.click();
// Define a repository connection via the UI
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List repository connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add a connection"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("connname"));
textarea.setValue(testerInstance.createStringDescription("MyRepositoryConnection"));
link = window.findLink(testerInstance.createStringDescription("Type tab"));
link.click();
// Select a type
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("classname"));
selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.crawler.connectors.jdbc.JDBCConnector"));
button = window.findButton(testerInstance.createStringDescription("Continue to next page"));
button.click();
window = testerInstance.findWindow(null);
// Credentials tab
link = window.findLink(testerInstance.createStringDescription("Credentials tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("username"));
textarea.setValue(testerInstance.createStringDescription("foo"));
// Server
link = window.findLink(testerInstance.createStringDescription("Server tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
// Database Type
link = window.findLink(testerInstance.createStringDescription("Database Type tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
// Go back to the Name tab
link = window.findLink(testerInstance.createStringDescription("Name tab"));
link.click();
// Now save the connection.
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this connection"));
button.click();
// Create a job
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List jobs"));
link.click();
// Add a job
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add a job"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
textarea = form.findTextarea(testerInstance.createStringDescription("description"));
textarea.setValue(testerInstance.createStringDescription("MyJob"));
link = window.findLink(testerInstance.createStringDescription("Connection tab"));
link.click();
// Select the connections
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("outputname"));
selectbox.selectValue(testerInstance.createStringDescription("MyOutputConnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("connectionname"));
selectbox.selectValue(testerInstance.createStringDescription("MyRepositoryConnection"));
button = window.findButton(testerInstance.createStringDescription("Continue to next screen"));
button.click();
// Visit all the connector tabs.
// Queries
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
link = window.findLink(testerInstance.createStringDescription("Queries tab"));
link.click();
// Security
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
link = window.findLink(testerInstance.createStringDescription("Security tab"));
link.click();
// Save the job
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this job"));
button.click();
// Delete the job
window = testerInstance.findWindow(null);
HTMLTester.StringDescription jobID = window.findMatch(testerInstance.createStringDescription("<!--jobid=(.*?)-->"),0);
testerInstance.printValue(jobID);
link = window.findLink(testerInstance.createStringDescription("Delete this job"));
link.click();
// Wait for the job to go away
loop = testerInstance.beginLoop(120);
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Manage jobs"));
link.click();
window = testerInstance.findWindow(null);
HTMLTester.StringDescription isJobNotPresent = window.isNotPresent(jobID);
testerInstance.printValue(isJobNotPresent);
loop.breakWhenTrue(isJobNotPresent);
loop.endLoop();
// Delete the repository connection
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List repository connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Delete MyRepositoryConnection"));
link.click();
// Delete the output connection
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List output connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Delete MyOutputConnection"));
link.click();
// Now go on to execute the authority test
window = testerInstance.openMainWindow("http://localhost:8346/mcf-crawler-ui/index.jsp");
// Define an authority connection via the UI
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List authorities"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add a new connection"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("connname"));
textarea.setValue(testerInstance.createStringDescription("MyAuthorityConnection"));
link = window.findLink(testerInstance.createStringDescription("Type tab"));
link.click();
// Select a type
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("classname"));
selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.authorities.authorities.jdbc.JDBCAuthority"));
button = window.findButton(testerInstance.createStringDescription("Continue to next page"));
button.click();
// Credentials tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Credentials tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("username"));
textarea.setValue(testerInstance.createStringDescription("foo"));
// Server
link = window.findLink(testerInstance.createStringDescription("Server tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
// Database Type
link = window.findLink(testerInstance.createStringDescription("Database Type tab"));
link.click();
// Visit all the connector tabs.
// Queries
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
link = window.findLink(testerInstance.createStringDescription("Queries tab"));
link.click();
// Go back to the Name tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Name tab"));
link.click();
// Now save the connection.
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this authority connection"));
button.click();
// Delete the authority connection
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List authorities"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Delete MyAuthorityConnection"));
link.click();
testerInstance.executeTest();
}
| public void createConnectionsAndJob()
throws Exception
{
testerInstance.newTest(Locale.US);
HTMLTester.Window window;
HTMLTester.Link link;
HTMLTester.Form form;
HTMLTester.Textarea textarea;
HTMLTester.Selectbox selectbox;
HTMLTester.Button button;
HTMLTester.Radiobutton radiobutton;
HTMLTester.Loop loop;
window = testerInstance.openMainWindow("http://localhost:8346/mcf-crawler-ui/index.jsp");
// Login
form = window.findForm(testerInstance.createStringDescription("loginform"));
textarea = form.findTextarea(testerInstance.createStringDescription("userID"));
textarea.setValue(testerInstance.createStringDescription("admin"));
textarea = form.findTextarea(testerInstance.createStringDescription("password"));
textarea.setValue(testerInstance.createStringDescription("admin"));
button = window.findButton(testerInstance.createStringDescription("Login"));
button.click();
window = testerInstance.findWindow(null);
// Define an output connection via the UI
link = window.findLink(testerInstance.createStringDescription("List output connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add an output connection"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("connname"));
textarea.setValue(testerInstance.createStringDescription("MyOutputConnection"));
link = window.findLink(testerInstance.createStringDescription("Type tab"));
link.click();
// Select a type
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("classname"));
selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.agents.output.nullconnector.NullConnector"));
button = window.findButton(testerInstance.createStringDescription("Continue to next page"));
button.click();
// Visit the Throttling tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Throttling tab"));
link.click();
// Go back to the Name tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Name tab"));
link.click();
// Now save the connection.
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this output connection"));
button.click();
// Define a repository connection via the UI
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List repository connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add a connection"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("connname"));
textarea.setValue(testerInstance.createStringDescription("MyRepositoryConnection"));
link = window.findLink(testerInstance.createStringDescription("Type tab"));
link.click();
// Select a type
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("classname"));
selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.crawler.connectors.jdbc.JDBCConnector"));
button = window.findButton(testerInstance.createStringDescription("Continue to next page"));
button.click();
window = testerInstance.findWindow(null);
// Credentials tab
link = window.findLink(testerInstance.createStringDescription("Credentials tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("username"));
textarea.setValue(testerInstance.createStringDescription("foo"));
// Server
link = window.findLink(testerInstance.createStringDescription("Server tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
// Database Type
link = window.findLink(testerInstance.createStringDescription("Database Type tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
// Go back to the Name tab
link = window.findLink(testerInstance.createStringDescription("Name tab"));
link.click();
// Now save the connection.
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this connection"));
button.click();
// Create a job
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List jobs"));
link.click();
// Add a job
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add a job"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
textarea = form.findTextarea(testerInstance.createStringDescription("description"));
textarea.setValue(testerInstance.createStringDescription("MyJob"));
link = window.findLink(testerInstance.createStringDescription("Connection tab"));
link.click();
// Select the connections
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("outputname"));
selectbox.selectValue(testerInstance.createStringDescription("MyOutputConnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("connectionname"));
selectbox.selectValue(testerInstance.createStringDescription("MyRepositoryConnection"));
button = window.findButton(testerInstance.createStringDescription("Continue to next screen"));
button.click();
// Visit all the connector tabs.
// Queries
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
link = window.findLink(testerInstance.createStringDescription("Queries tab"));
link.click();
// Security
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editjob"));
link = window.findLink(testerInstance.createStringDescription("Security tab"));
link.click();
// Save the job
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this job"));
button.click();
// Delete the job
window = testerInstance.findWindow(null);
HTMLTester.StringDescription jobID = window.findMatch(testerInstance.createStringDescription("<!--jobid=(.*?)-->"),0);
testerInstance.printValue(jobID);
link = window.findLink(testerInstance.createStringDescription("Delete this job"));
link.click();
// Wait for the job to go away
loop = testerInstance.beginLoop(120);
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Manage jobs"));
link.click();
window = testerInstance.findWindow(null);
HTMLTester.StringDescription isJobNotPresent = window.isNotPresent(jobID);
testerInstance.printValue(isJobNotPresent);
loop.breakWhenTrue(isJobNotPresent);
loop.endLoop();
// Delete the repository connection
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List repository connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Delete MyRepositoryConnection"));
link.click();
// Delete the output connection
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List output connections"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Delete MyOutputConnection"));
link.click();
// Now go on to execute the authority test
window = testerInstance.openMainWindow("http://localhost:8346/mcf-crawler-ui/index.jsp");
// Define an authority connection via the UI
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List authority groups"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add new authority group"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editgroup"));
textarea = form.findTextarea(testerInstance.createStringDescription("groupname"));
textarea.setValue(testerInstance.createStringDescription("MyAuthorityConnection"));
button = window.findButton(testerInstance.createStringDescription("Save this authority group"));
button.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List authorities"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Add a new connection"));
link.click();
// Fill in a name
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("connname"));
textarea.setValue(testerInstance.createStringDescription("MyAuthorityConnection"));
link = window.findLink(testerInstance.createStringDescription("Type tab"));
link.click();
// Select a type
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("classname"));
selectbox.selectValue(testerInstance.createStringDescription("org.apache.manifoldcf.authorities.authorities.jdbc.JDBCAuthority"));
selectbox = form.findSelectbox(testerInstance.createStringDescription("authoritygroup"));
selectbox.selectValue(testerInstance.createStringDescription("MyAuthorityConnection"));
button = window.findButton(testerInstance.createStringDescription("Continue to next page"));
button.click();
// Credentials tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Credentials tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
textarea = form.findTextarea(testerInstance.createStringDescription("username"));
textarea.setValue(testerInstance.createStringDescription("foo"));
// Server
link = window.findLink(testerInstance.createStringDescription("Server tab"));
link.click();
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
// Database Type
link = window.findLink(testerInstance.createStringDescription("Database Type tab"));
link.click();
// Visit all the connector tabs.
// Queries
window = testerInstance.findWindow(null);
form = window.findForm(testerInstance.createStringDescription("editconnection"));
link = window.findLink(testerInstance.createStringDescription("Queries tab"));
link.click();
// Go back to the Name tab
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Name tab"));
link.click();
// Now save the connection.
window = testerInstance.findWindow(null);
button = window.findButton(testerInstance.createStringDescription("Save this authority connection"));
button.click();
// Delete the authority connection
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("List authorities"));
link.click();
window = testerInstance.findWindow(null);
link = window.findLink(testerInstance.createStringDescription("Delete MyAuthorityConnection"));
link.click();
testerInstance.executeTest();
}
|
diff --git a/src/org/accesointeligente/server/robots/SIAC.java b/src/org/accesointeligente/server/robots/SIAC.java
index 922d216..0ec4d3e 100644
--- a/src/org/accesointeligente/server/robots/SIAC.java
+++ b/src/org/accesointeligente/server/robots/SIAC.java
@@ -1,309 +1,309 @@
/**
* Acceso Inteligente
*
* Copyright (C) 2010-2011 Fundación Ciudadano Inteligente
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.accesointeligente.server.robots;
import org.accesointeligente.model.Request;
import org.accesointeligente.server.ApplicationProperties;
import org.accesointeligente.shared.RequestStatus;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import java.beans.ConstructorProperties;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SIAC extends Robot {
private HttpClient client;
private HtmlCleaner cleaner;
private Boolean loggedIn = false;
private String characterEncoding = null;
private String baseUrl;
private String userId;
public SIAC() {
client = new DefaultHttpClient();
HttpProtocolParams.setUserAgent(client.getParams(), "Mozilla/5.0 (X11; U; Linux x86_64; es-CL; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.10 (maverick) Firefox/3.6.12");
HttpProtocolParams.setVersion(client.getParams(), HttpVersion.HTTP_1_0);
cleaner = new HtmlCleaner();
}
@ConstructorProperties({"idEntidad", "baseUrl"})
public SIAC(String idEntidad, String baseUrl) {
this();
setIdEntidad(idEntidad);
setBaseUrl(baseUrl);
}
@Override
public void login() throws RobotException {
if (characterEncoding == null) {
detectCharacterEncoding();
}
List<NameValuePair> formParams;
HttpPost post;
HttpResponse response;
TagNode document, hiddenUser;
try {
formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("usuario", username));
formParams.add(new BasicNameValuePair("clave", password));
formParams.add(new BasicNameValuePair("accion", "login"));
post = new HttpPost(baseUrl);
post.addHeader("Referer", baseUrl + "?accion=ingresa");
post.setEntity(new UrlEncodedFormEntity(formParams, characterEncoding));
response = client.execute(post);
document = cleaner.clean(new InputStreamReader(response.getEntity().getContent(), characterEncoding));
hiddenUser = document.findElementByAttValue("id", "user", true, true);
if (hiddenUser == null || !hiddenUser.hasAttribute("value") || hiddenUser.getAttributeByName("value").equals("0")) {
throw new Exception();
}
userId = hiddenUser.getAttributeByName("value");
loggedIn = true;
} catch (Throwable ex) {
throw new RobotException();
}
}
@Override
public Request makeRequest(Request request) throws RobotException {
if (!loggedIn) {
login();
}
List<NameValuePair> formParams;
HttpPost post;
HttpResponse response;
TagNode document;
Pattern pattern = Pattern.compile("^Solicitud ingresada exitosamente, el número de su solicitud es: ([A-Z]{2}[0-9]{3}[A-Z][0-9]{7})$");
Matcher matcher;
try {
formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("user", userId));
formParams.add(new BasicNameValuePair("accion", "registrar"));
formParams.add(new BasicNameValuePair("tipo", "7"));
formParams.add(new BasicNameValuePair("dirigido", idEntidad));
formParams.add(new BasicNameValuePair("ley_email", "S"));
formParams.add(new BasicNameValuePair("detalle", request.getInformation() + "\n\n" + request.getContext() + "\n\n" + ApplicationProperties.getProperty("request.signature")));
- formParams.add(new BasicNameValuePair("remLen1", "" + (1998 - request.getInformation().length() - request.getContext().length())));
- formParams.add(new BasicNameValuePair("nombre", "Fundación Ciudadano Inteligente"));
- formParams.add(new BasicNameValuePair("ap_paterno", "N/A"));
- formParams.add(new BasicNameValuePair("ap_materno", "N/A"));
+ formParams.add(new BasicNameValuePair("remLen1", "" + (1996 - request.getInformation().length() - request.getContext().length() - ApplicationProperties.getProperty("request.signature").length())));
+ formParams.add(new BasicNameValuePair("nombre", "Felipe"));
+ formParams.add(new BasicNameValuePair("ap_paterno", "Heusser"));
+ formParams.add(new BasicNameValuePair("ap_materno", "Ferres"));
formParams.add(new BasicNameValuePair("rut", ""));
formParams.add(new BasicNameValuePair("rut_dv", ""));
formParams.add(new BasicNameValuePair("pasaporte", ""));
formParams.add(new BasicNameValuePair("nacionalidad", "320"));
formParams.add(new BasicNameValuePair("tipo_zona", "U"));
formParams.add(new BasicNameValuePair("educacion", "0"));
formParams.add(new BasicNameValuePair("edad", "0"));
formParams.add(new BasicNameValuePair("ocupacion", "0"));
- formParams.add(new BasicNameValuePair("sexo", ""));
- formParams.add(new BasicNameValuePair("rb_organizacion", "N"));
- formParams.add(new BasicNameValuePair("razon_social", ""));
+ formParams.add(new BasicNameValuePair("sexo", "M"));
+ formParams.add(new BasicNameValuePair("rb_organizacion", "S"));
+ formParams.add(new BasicNameValuePair("razon_social", "Fundación Ciudadano Inteligente"));
formParams.add(new BasicNameValuePair("rb_apoderado", "N"));
formParams.add(new BasicNameValuePair("nombre_apoderado", ""));
formParams.add(new BasicNameValuePair("residencia", "CHI"));
formParams.add(new BasicNameValuePair("direccion", "Holanda"));
formParams.add(new BasicNameValuePair("direccion_numero", "895"));
formParams.add(new BasicNameValuePair("direccion_villa", ""));
formParams.add(new BasicNameValuePair("fono_area", ""));
formParams.add(new BasicNameValuePair("fono", ""));
formParams.add(new BasicNameValuePair("comuna", "13123"));
formParams.add(new BasicNameValuePair("email", "[email protected]"));
formParams.add(new BasicNameValuePair("email_verif", "[email protected]"));
formParams.add(new BasicNameValuePair("bt_modificar", "Enviar Datos"));
post = new HttpPost(baseUrl);
post.addHeader("Referer", baseUrl);
post.setEntity(new UrlEncodedFormEntity(formParams, characterEncoding));
response = client.execute(post);
document = cleaner.clean(new InputStreamReader(response.getEntity().getContent(), characterEncoding));
for (TagNode node : document.getElementsByAttValue("class", "mark", true, true)) {
if (node.getChildTags()[0].toString().equalsIgnoreCase("ul")) {
matcher = pattern.matcher(node.getChildTags()[0].getText().toString().trim());
if (matcher.matches()) {
request.setRemoteIdentifier(matcher.group(1));
break;
}
}
}
if (request.getRemoteIdentifier() != null) {
request.setStatus(RequestStatus.PENDING);
request.setProcessDate(new Date());
return request;
} else {
throw new Exception();
}
} catch (Throwable ex) {
throw new RobotException();
}
}
@Override
public RequestStatus checkRequestStatus(Request request) throws RobotException {
if (characterEncoding == null) {
detectCharacterEncoding();
}
List<NameValuePair> formParams;
HttpPost post;
HttpResponse response;
TagNode document, statusCell;
String statusLabel;
try {
if (request.getRemoteIdentifier() == null || request.getRemoteIdentifier().length() == 0) {
throw new Exception();
}
formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("nsolicitud", request.getRemoteIdentifier()));
post = new HttpPost(baseUrl);
post.addHeader("Referer", baseUrl + "?accion=consulta");
post.addHeader("X-Requested-With", "XMLHttpRequest");
post.setEntity(new UrlEncodedFormEntity(formParams, characterEncoding));
response = client.execute(post);
document = cleaner.clean(new InputStreamReader(response.getEntity().getContent(), characterEncoding));
statusCell = document.getElementsByName("td", true)[5];
if (statusCell == null) {
throw new Exception();
}
statusLabel = statusCell.getText().toString().trim();
// TODO: we don't know the rest of the status strings
if (statusLabel.equals("Ingreso de Solicitud")) {
return RequestStatus.PENDING;
} else {
return null;
}
} catch (Throwable ex) {
throw new RobotException();
}
}
@Override
public Boolean checkInstitutionId() throws RobotException {
if (!loggedIn) {
login();
}
HttpGet get;
HttpResponse response;
TagNode document, selector;
try {
get = new HttpGet(baseUrl + "?accion=ingresa");
response = client.execute(get);
document = cleaner.clean(new InputStreamReader(response.getEntity().getContent(), characterEncoding));
selector = document.findElementByAttValue("name", "dirigido", true, true);
if (selector == null) {
throw new Exception();
}
for (TagNode option : selector.getElementsByName("option", true)) {
if (option.hasAttribute("value") && option.getAttributeByName("value").equals(idEntidad)) {
return true;
}
}
return false;
} catch (Throwable ex) {
throw new RobotException();
}
}
public void detectCharacterEncoding() {
HttpGet get;
HttpResponse response;
Header contentType;
Pattern pattern;
Matcher matcher;
try {
get = new HttpGet(baseUrl + "?accion=ingresa");
response = client.execute(get);
contentType = response.getFirstHeader("Content-Type");
EntityUtils.consume(response.getEntity());
if (contentType == null || contentType.getValue() == null) {
characterEncoding = "ISO-8859-1";
}
pattern = Pattern.compile(".*charset=(.+)");
matcher = pattern.matcher(contentType.getValue());
if (!matcher.matches()) {
characterEncoding = "ISO-8859-1";
}
characterEncoding = matcher.group(1);
} catch (Exception e) {
characterEncoding = "ISO-8859-1";
}
}
public String getCharacterEncoding() {
return characterEncoding;
}
public void setCharacterEncoding(String characterEncoding) {
this.characterEncoding = characterEncoding;
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
| false | true | public Request makeRequest(Request request) throws RobotException {
if (!loggedIn) {
login();
}
List<NameValuePair> formParams;
HttpPost post;
HttpResponse response;
TagNode document;
Pattern pattern = Pattern.compile("^Solicitud ingresada exitosamente, el número de su solicitud es: ([A-Z]{2}[0-9]{3}[A-Z][0-9]{7})$");
Matcher matcher;
try {
formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("user", userId));
formParams.add(new BasicNameValuePair("accion", "registrar"));
formParams.add(new BasicNameValuePair("tipo", "7"));
formParams.add(new BasicNameValuePair("dirigido", idEntidad));
formParams.add(new BasicNameValuePair("ley_email", "S"));
formParams.add(new BasicNameValuePair("detalle", request.getInformation() + "\n\n" + request.getContext() + "\n\n" + ApplicationProperties.getProperty("request.signature")));
formParams.add(new BasicNameValuePair("remLen1", "" + (1998 - request.getInformation().length() - request.getContext().length())));
formParams.add(new BasicNameValuePair("nombre", "Fundación Ciudadano Inteligente"));
formParams.add(new BasicNameValuePair("ap_paterno", "N/A"));
formParams.add(new BasicNameValuePair("ap_materno", "N/A"));
formParams.add(new BasicNameValuePair("rut", ""));
formParams.add(new BasicNameValuePair("rut_dv", ""));
formParams.add(new BasicNameValuePair("pasaporte", ""));
formParams.add(new BasicNameValuePair("nacionalidad", "320"));
formParams.add(new BasicNameValuePair("tipo_zona", "U"));
formParams.add(new BasicNameValuePair("educacion", "0"));
formParams.add(new BasicNameValuePair("edad", "0"));
formParams.add(new BasicNameValuePair("ocupacion", "0"));
formParams.add(new BasicNameValuePair("sexo", ""));
formParams.add(new BasicNameValuePair("rb_organizacion", "N"));
formParams.add(new BasicNameValuePair("razon_social", ""));
formParams.add(new BasicNameValuePair("rb_apoderado", "N"));
formParams.add(new BasicNameValuePair("nombre_apoderado", ""));
formParams.add(new BasicNameValuePair("residencia", "CHI"));
formParams.add(new BasicNameValuePair("direccion", "Holanda"));
formParams.add(new BasicNameValuePair("direccion_numero", "895"));
formParams.add(new BasicNameValuePair("direccion_villa", ""));
formParams.add(new BasicNameValuePair("fono_area", ""));
formParams.add(new BasicNameValuePair("fono", ""));
formParams.add(new BasicNameValuePair("comuna", "13123"));
formParams.add(new BasicNameValuePair("email", "[email protected]"));
formParams.add(new BasicNameValuePair("email_verif", "[email protected]"));
formParams.add(new BasicNameValuePair("bt_modificar", "Enviar Datos"));
post = new HttpPost(baseUrl);
post.addHeader("Referer", baseUrl);
post.setEntity(new UrlEncodedFormEntity(formParams, characterEncoding));
response = client.execute(post);
document = cleaner.clean(new InputStreamReader(response.getEntity().getContent(), characterEncoding));
for (TagNode node : document.getElementsByAttValue("class", "mark", true, true)) {
if (node.getChildTags()[0].toString().equalsIgnoreCase("ul")) {
matcher = pattern.matcher(node.getChildTags()[0].getText().toString().trim());
if (matcher.matches()) {
request.setRemoteIdentifier(matcher.group(1));
break;
}
}
}
if (request.getRemoteIdentifier() != null) {
request.setStatus(RequestStatus.PENDING);
request.setProcessDate(new Date());
return request;
} else {
throw new Exception();
}
} catch (Throwable ex) {
throw new RobotException();
}
}
| public Request makeRequest(Request request) throws RobotException {
if (!loggedIn) {
login();
}
List<NameValuePair> formParams;
HttpPost post;
HttpResponse response;
TagNode document;
Pattern pattern = Pattern.compile("^Solicitud ingresada exitosamente, el número de su solicitud es: ([A-Z]{2}[0-9]{3}[A-Z][0-9]{7})$");
Matcher matcher;
try {
formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("user", userId));
formParams.add(new BasicNameValuePair("accion", "registrar"));
formParams.add(new BasicNameValuePair("tipo", "7"));
formParams.add(new BasicNameValuePair("dirigido", idEntidad));
formParams.add(new BasicNameValuePair("ley_email", "S"));
formParams.add(new BasicNameValuePair("detalle", request.getInformation() + "\n\n" + request.getContext() + "\n\n" + ApplicationProperties.getProperty("request.signature")));
formParams.add(new BasicNameValuePair("remLen1", "" + (1996 - request.getInformation().length() - request.getContext().length() - ApplicationProperties.getProperty("request.signature").length())));
formParams.add(new BasicNameValuePair("nombre", "Felipe"));
formParams.add(new BasicNameValuePair("ap_paterno", "Heusser"));
formParams.add(new BasicNameValuePair("ap_materno", "Ferres"));
formParams.add(new BasicNameValuePair("rut", ""));
formParams.add(new BasicNameValuePair("rut_dv", ""));
formParams.add(new BasicNameValuePair("pasaporte", ""));
formParams.add(new BasicNameValuePair("nacionalidad", "320"));
formParams.add(new BasicNameValuePair("tipo_zona", "U"));
formParams.add(new BasicNameValuePair("educacion", "0"));
formParams.add(new BasicNameValuePair("edad", "0"));
formParams.add(new BasicNameValuePair("ocupacion", "0"));
formParams.add(new BasicNameValuePair("sexo", "M"));
formParams.add(new BasicNameValuePair("rb_organizacion", "S"));
formParams.add(new BasicNameValuePair("razon_social", "Fundación Ciudadano Inteligente"));
formParams.add(new BasicNameValuePair("rb_apoderado", "N"));
formParams.add(new BasicNameValuePair("nombre_apoderado", ""));
formParams.add(new BasicNameValuePair("residencia", "CHI"));
formParams.add(new BasicNameValuePair("direccion", "Holanda"));
formParams.add(new BasicNameValuePair("direccion_numero", "895"));
formParams.add(new BasicNameValuePair("direccion_villa", ""));
formParams.add(new BasicNameValuePair("fono_area", ""));
formParams.add(new BasicNameValuePair("fono", ""));
formParams.add(new BasicNameValuePair("comuna", "13123"));
formParams.add(new BasicNameValuePair("email", "[email protected]"));
formParams.add(new BasicNameValuePair("email_verif", "[email protected]"));
formParams.add(new BasicNameValuePair("bt_modificar", "Enviar Datos"));
post = new HttpPost(baseUrl);
post.addHeader("Referer", baseUrl);
post.setEntity(new UrlEncodedFormEntity(formParams, characterEncoding));
response = client.execute(post);
document = cleaner.clean(new InputStreamReader(response.getEntity().getContent(), characterEncoding));
for (TagNode node : document.getElementsByAttValue("class", "mark", true, true)) {
if (node.getChildTags()[0].toString().equalsIgnoreCase("ul")) {
matcher = pattern.matcher(node.getChildTags()[0].getText().toString().trim());
if (matcher.matches()) {
request.setRemoteIdentifier(matcher.group(1));
break;
}
}
}
if (request.getRemoteIdentifier() != null) {
request.setStatus(RequestStatus.PENDING);
request.setProcessDate(new Date());
return request;
} else {
throw new Exception();
}
} catch (Throwable ex) {
throw new RobotException();
}
}
|
diff --git a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceFileBuffer.java b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceFileBuffer.java
index 2cb6b11e4..4c651f651 100644
--- a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceFileBuffer.java
+++ b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceFileBuffer.java
@@ -1,544 +1,545 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.internal.filebuffers;
import java.net.URI;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileInfo;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceRuleFactory;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.filebuffers.IFileBufferStatusCodes;
import org.eclipse.jface.text.IDocumentExtension4;
public abstract class ResourceFileBuffer extends AbstractFileBuffer {
/**
* Runnable encapsulating an element state change. This runnable ensures
* that a element change failed message is sent out to the element state
* listeners in case an exception occurred.
*/
private class SafeFileChange implements Runnable {
/**
* Creates a new safe runnable for the given file.
*/
public SafeFileChange() {
}
/**
* Execute the change.
* Subclass responsibility.
*
* @exception Exception in case of error
*/
protected void execute() throws Exception {
}
/**
* Does everything necessary prior to execution.
*/
public void preRun() {
fManager.fireStateChanging(ResourceFileBuffer.this);
}
/*
* @see java.lang.Runnable#run()
*/
public void run() {
if (isDisconnected()) {
fManager.fireStateChangeFailed(ResourceFileBuffer.this);
return;
}
try {
execute();
} catch (Exception x) {
FileBuffersPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, "Exception when synchronizing", x)); //$NON-NLS-1$
fManager.fireStateChangeFailed(ResourceFileBuffer.this);
}
}
}
/**
* Synchronizes the document with external resource changes.
*/
private class FileSynchronizer implements IResourceChangeListener {
/** A flag indicating whether this synchronizer is installed or not. */
private boolean fIsInstalled= false;
/**
* Creates a new file synchronizer. Is not yet installed on a file.
*/
public FileSynchronizer() {
}
/**
* Installs the synchronizer on the file.
*/
public void install() {
fFile.getWorkspace().addResourceChangeListener(this);
fIsInstalled= true;
}
/**
* Uninstalls the synchronizer from the file.
*/
public void uninstall() {
fFile.getWorkspace().removeResourceChangeListener(this);
fIsInstalled= false;
}
/*
* @see IResourceChangeListener#resourceChanged(IResourceChangeEvent)
*/
public void resourceChanged(IResourceChangeEvent e) {
IResourceDelta delta= e.getDelta();
if (delta != null)
delta= delta.findMember(fFile.getFullPath());
if (delta != null && fIsInstalled) {
SafeFileChange fileChange= null;
+ final int flags= delta.getFlags();
switch (delta.getKind()) {
case IResourceDelta.CHANGED:
- if ((IResourceDelta.ENCODING & delta.getFlags()) != 0) {
+ if ((IResourceDelta.ENCODING & flags) != 0) {
if (!isDisconnected() && !fCanBeSaved && isSynchronized()) {
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileContentChanged(false);
}
};
}
}
- if (fileChange == null && (IResourceDelta.CONTENT & delta.getFlags()) != 0) {
- if (!isDisconnected() && !fCanBeSaved && !isSynchronized()) {
+ if (fileChange == null && (IResourceDelta.CONTENT & flags) != 0) {
+ if (!isDisconnected() && !fCanBeSaved && (!isSynchronized() || (IResourceDelta.REPLACED & flags) != 0)) {
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileContentChanged(false);
}
};
}
}
break;
case IResourceDelta.REMOVED:
- if ((IResourceDelta.MOVED_TO & delta.getFlags()) != 0) {
+ if ((IResourceDelta.MOVED_TO & flags) != 0) {
final IPath path= delta.getMovedToPath();
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileMoved(path);
}
};
} else {
if (!isDisconnected() && !fCanBeSaved) {
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileDeleted();
}
};
}
}
break;
}
if (fileChange != null) {
fileChange.preRun();
fManager.execute(fileChange, isSynchronizationContextRequested());
}
}
}
}
/** The location */
protected IPath fLocation;
/** The element for which the info is stored */
protected IFile fFile;
/** How often the element has been connected */
protected int fReferenceCount;
/** Can the element be saved */
protected boolean fCanBeSaved= false;
/** Has element state been validated */
protected boolean fIsStateValidated= false;
/** The status of this element */
protected IStatus fStatus;
/** The file synchronizer. */
protected FileSynchronizer fFileSynchronizer;
/** The modification stamp at which this buffer synchronized with the underlying file. */
protected long fSynchronizationStamp= IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
/** How often the synchronization context has been requested */
protected int fSynchronizationContextCount;
/** The text file buffer manager */
protected ResourceTextFileBufferManager fManager;
public ResourceFileBuffer(ResourceTextFileBufferManager manager) {
super();
fManager= manager;
}
abstract protected void addFileBufferContentListeners();
abstract protected void removeFileBufferContentListeners();
abstract protected void initializeFileBufferContent(IProgressMonitor monitor) throws CoreException;
abstract protected void commitFileBufferContent(IProgressMonitor monitor, boolean overwrite) throws CoreException;
abstract protected void handleFileContentChanged(boolean revert) throws CoreException;
public void create(IPath location, IProgressMonitor monitor) throws CoreException {
monitor= Progress.getMonitor(monitor);
monitor.beginTask(FileBuffersMessages.ResourceFileBuffer_task_creatingFileBuffer, 2);
try {
IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
IFile file= workspaceRoot.getFile(location);
if (file == null)
throw new CoreException(new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, FileBuffersMessages.ResourceFileBuffer_error_fileDoesNotExist, null));
URI uri= file.getLocationURI();
if (uri == null)
throw new CoreException(new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, IStatus.OK, FileBuffersMessages.ResourceFileBuffer_error_fileDoesNotExist, null));
fLocation= location;
fFile= file;
fFileStore= EFS.getStore(uri);
fFileSynchronizer= new FileSynchronizer();
SubProgressMonitor subMonitor= new SubProgressMonitor(monitor, 1);
initializeFileBufferContent(subMonitor);
subMonitor.done();
fSynchronizationStamp= fFile.getModificationStamp();
addFileBufferContentListeners();
} finally {
monitor.done();
}
}
public void connect() {
++fReferenceCount;
if (fReferenceCount == 1)
connected();
}
/**
* Called when this file buffer has been connected. This is the case when
* there is exactly one connection.
* <p>
* Clients may extend this method.
*/
protected void connected() {
fFileSynchronizer.install();
}
public void disconnect() throws CoreException {
--fReferenceCount;
if (fReferenceCount <= 0)
disconnected();
}
/**
* Called when this file buffer has been disconnected. This is the case when
* the number of connections drops below <code>1</code>.
* <p>
* Clients may extend this method.
*/
protected void disconnected() {
if (fFileSynchronizer != null) {
fFileSynchronizer.uninstall();
fFileSynchronizer= null;
}
removeFileBufferContentListeners();
}
/*
* @see org.eclipse.core.internal.filebuffers.AbstractFileBuffer#isDisconnected()
* @since 3.1
*/
public boolean isDisconnected() {
return fFileSynchronizer == null;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#getLocation()
*/
public IPath getLocation() {
return fLocation;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#computeCommitRule()
*/
public ISchedulingRule computeCommitRule() {
IResourceRuleFactory factory= ResourcesPlugin.getWorkspace().getRuleFactory();
return factory.modifyRule(fFile);
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#commit(org.eclipse.core.runtime.IProgressMonitor, boolean)
*/
public void commit(IProgressMonitor monitor, boolean overwrite) throws CoreException {
if (!isDisconnected() && fCanBeSaved) {
fManager.fireStateChanging(this);
try {
commitFileBufferContent(monitor, overwrite);
} catch (CoreException x) {
fManager.fireStateChangeFailed(this);
throw x;
} catch (RuntimeException x) {
fManager.fireStateChangeFailed(this);
throw x;
}
fCanBeSaved= false;
fManager.fireDirtyStateChanged(this, fCanBeSaved);
}
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#revert(org.eclipse.core.runtime.IProgressMonitor)
*/
public void revert(IProgressMonitor monitor) throws CoreException {
if (isDisconnected())
return;
if (!fFile.isSynchronized(IResource.DEPTH_INFINITE)) {
fCanBeSaved= false;
refreshFile(monitor);
return;
}
try {
fManager.fireStateChanging(this);
handleFileContentChanged(true);
} catch (RuntimeException x) {
fManager.fireStateChangeFailed(this);
throw x;
}
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#isDirty()
*/
public boolean isDirty() {
return fCanBeSaved;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#setDirty(boolean)
*/
public void setDirty(boolean isDirty) {
fCanBeSaved= isDirty;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#isShared()
*/
public boolean isShared() {
return fReferenceCount > 1;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#computeValidateStateRule()
*/
public ISchedulingRule computeValidateStateRule() {
IResourceRuleFactory factory= ResourcesPlugin.getWorkspace().getRuleFactory();
return factory.validateEditRule(new IResource[] { fFile });
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#validateState(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object)
*/
public void validateState(IProgressMonitor monitor, Object computationContext) throws CoreException {
if (!isDisconnected() && !fIsStateValidated) {
fStatus= null;
fManager.fireStateChanging(this);
try {
if (fFile.isReadOnly()) {
IWorkspace workspace= fFile.getWorkspace();
fStatus= workspace.validateEdit(new IFile[] { fFile }, computationContext);
if (fStatus.isOK())
handleFileContentChanged(false);
}
if (isDerived(fFile)) {
IStatus status= new Status(IStatus.WARNING, FileBuffersPlugin.PLUGIN_ID, IFileBufferStatusCodes.DERIVED_FILE, FileBuffersMessages.ResourceFileBuffer_warning_fileIsDerived, null);
if (fStatus == null || fStatus.isOK())
fStatus= status;
else
fStatus= new MultiStatus(FileBuffersPlugin.PLUGIN_ID, IFileBufferStatusCodes.STATE_VALIDATION_FAILED, new IStatus[] {fStatus, status}, FileBuffersMessages.ResourceFileBuffer_stateValidationFailed, null);
}
} catch (RuntimeException x) {
fManager.fireStateChangeFailed(this);
throw x;
}
fIsStateValidated= fStatus == null || fStatus.getSeverity() != IStatus.CANCEL;
fManager.fireStateValidationChanged(this, fIsStateValidated);
}
}
/*
*
* @see IResource#isDerived()
* @since 3.3
*/
private boolean isDerived(IResource resource) {
while (resource != null) {
if (resource.isDerived())
return true;
resource= resource.getParent();
}
return false;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#isStateValidated()
*/
public boolean isStateValidated() {
return fIsStateValidated;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#resetStateValidation()
*/
public void resetStateValidation() {
if (fIsStateValidated) {
fIsStateValidated= false;
fManager.fireStateValidationChanged(this, fIsStateValidated);
}
}
/**
* Sends out the notification that the file serving as document input has been moved.
*
* @param newLocation the path of the new location of the file
*/
protected void handleFileMoved(IPath newLocation) {
fManager.fireUnderlyingFileMoved(this, newLocation);
}
/**
* Sends out the notification that the file serving as document input has been deleted.
*/
protected void handleFileDeleted() {
fManager.fireUnderlyingFileDeleted(this);
}
/**
* Refreshes the given file.
*
* @param monitor the progress monitor
*/
protected void refreshFile(IProgressMonitor monitor) {
try {
fFile.refreshLocal(IResource.DEPTH_INFINITE, monitor);
} catch (OperationCanceledException x) {
} catch (CoreException x) {
handleCoreException(x);
}
}
/**
* Defines the standard procedure to handle <code>CoreExceptions</code>. Exceptions
* are written to the plug-in log.
*
* @param exception the exception to be logged
*/
protected void handleCoreException(CoreException exception) {
ILog log= FileBuffersPlugin.getDefault().getLog();
log.log(exception.getStatus());
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#isSynchronized()
*/
public boolean isSynchronized() {
if (fSynchronizationStamp == fFile.getModificationStamp() && fFile.isSynchronized(IResource.DEPTH_ZERO))
return true;
fSynchronizationStamp= IDocumentExtension4.UNKNOWN_MODIFICATION_STAMP;
return false;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#requestSynchronizationContext()
*/
public void requestSynchronizationContext() {
++ fSynchronizationContextCount;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#releaseSynchronizationContext()
*/
public void releaseSynchronizationContext() {
-- fSynchronizationContextCount;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#isSynchronizationContextRequested()
*/
public boolean isSynchronizationContextRequested() {
return fSynchronizationContextCount > 0;
}
/*
* @see org.eclipse.core.filebuffers.IFileBuffer#isCommitable()
*/
public boolean isCommitable() {
IFileInfo info= fFileStore.fetchInfo();
return info.exists() && !info.getAttribute(EFS.ATTRIBUTE_READ_ONLY);
}
/*
* @see org.eclipse.core.filebuffers.IStateValidationSupport#validationStateChanged(boolean, org.eclipse.core.runtime.IStatus)
*/
public void validationStateChanged(boolean validationState, IStatus status) {
fIsStateValidated= validationState;
fStatus= status;
}
}
| false | true | public void resourceChanged(IResourceChangeEvent e) {
IResourceDelta delta= e.getDelta();
if (delta != null)
delta= delta.findMember(fFile.getFullPath());
if (delta != null && fIsInstalled) {
SafeFileChange fileChange= null;
switch (delta.getKind()) {
case IResourceDelta.CHANGED:
if ((IResourceDelta.ENCODING & delta.getFlags()) != 0) {
if (!isDisconnected() && !fCanBeSaved && isSynchronized()) {
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileContentChanged(false);
}
};
}
}
if (fileChange == null && (IResourceDelta.CONTENT & delta.getFlags()) != 0) {
if (!isDisconnected() && !fCanBeSaved && !isSynchronized()) {
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileContentChanged(false);
}
};
}
}
break;
case IResourceDelta.REMOVED:
if ((IResourceDelta.MOVED_TO & delta.getFlags()) != 0) {
final IPath path= delta.getMovedToPath();
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileMoved(path);
}
};
} else {
if (!isDisconnected() && !fCanBeSaved) {
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileDeleted();
}
};
}
}
break;
}
if (fileChange != null) {
fileChange.preRun();
fManager.execute(fileChange, isSynchronizationContextRequested());
}
}
}
| public void resourceChanged(IResourceChangeEvent e) {
IResourceDelta delta= e.getDelta();
if (delta != null)
delta= delta.findMember(fFile.getFullPath());
if (delta != null && fIsInstalled) {
SafeFileChange fileChange= null;
final int flags= delta.getFlags();
switch (delta.getKind()) {
case IResourceDelta.CHANGED:
if ((IResourceDelta.ENCODING & flags) != 0) {
if (!isDisconnected() && !fCanBeSaved && isSynchronized()) {
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileContentChanged(false);
}
};
}
}
if (fileChange == null && (IResourceDelta.CONTENT & flags) != 0) {
if (!isDisconnected() && !fCanBeSaved && (!isSynchronized() || (IResourceDelta.REPLACED & flags) != 0)) {
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileContentChanged(false);
}
};
}
}
break;
case IResourceDelta.REMOVED:
if ((IResourceDelta.MOVED_TO & flags) != 0) {
final IPath path= delta.getMovedToPath();
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileMoved(path);
}
};
} else {
if (!isDisconnected() && !fCanBeSaved) {
fileChange= new SafeFileChange() {
protected void execute() throws Exception {
handleFileDeleted();
}
};
}
}
break;
}
if (fileChange != null) {
fileChange.preRun();
fManager.execute(fileChange, isSynchronizationContextRequested());
}
}
}
|
diff --git a/android/src/org/coolreader/crengine/BookInfo.java b/android/src/org/coolreader/crengine/BookInfo.java
index ec7a4185..6a88ff58 100644
--- a/android/src/org/coolreader/crengine/BookInfo.java
+++ b/android/src/org/coolreader/crengine/BookInfo.java
@@ -1,289 +1,289 @@
package org.coolreader.crengine;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import android.util.Log;
public class BookInfo {
private FileInfo fileInfo;
private Bookmark lastPosition;
private ArrayList<Bookmark> bookmarks = new ArrayList<Bookmark>();
synchronized public void setShortcutBookmark(int shortcut, Bookmark bookmark)
{
bookmark.setShortcut(shortcut);
bookmark.setModified(true);
for ( int i=0; i<bookmarks.size(); i++ ) {
Bookmark bm = bookmarks.get(i);
if ( bm.getType()==Bookmark.TYPE_POSITION && bm.getShortcut()==shortcut ) {
bookmark.setId(bm.getId());
bookmarks.set(i, bookmark);
return;
}
}
bookmarks.add(bookmark);
}
synchronized public Bookmark findShortcutBookmark( int shortcut )
{
for ( Bookmark bm : bookmarks )
if ( bm.getType()==Bookmark.TYPE_POSITION && bm.getShortcut()==shortcut )
return bm;
return null;
}
public void updateAccess()
{
// TODO:
}
public BookInfo( FileInfo fileInfo )
{
this.fileInfo = fileInfo; //new FileInfo(fileInfo);
}
public Bookmark getLastPosition()
{
return lastPosition;
}
public void setLastPosition( Bookmark position )
{
synchronized (this) {
if ( lastPosition!=null ) {
if (position.getStartPos()!=null && position.getStartPos().equals(lastPosition.getStartPos()))
return; // not changed
position.setId(lastPosition.getId());
}
lastPosition = position;
lastPosition.setModified(true);
fileInfo.lastAccessTime = lastPosition.getTimeStamp();
fileInfo.setModified(true);
}
}
public FileInfo getFileInfo()
{
return fileInfo;
}
synchronized public void addBookmark( Bookmark bm )
{
bookmarks.add(bm);
}
synchronized public int getBookmarkCount()
{
return bookmarks.size();
}
synchronized public Bookmark getBookmark( int index )
{
return bookmarks.get(index);
}
synchronized public Bookmark findBookmark(Bookmark bm)
{
if ( bm==null )
return null;
int index = findBookmarkIndex(bm);
if (index < 0)
return null;
return bookmarks.get(index);
}
private int findBookmarkIndex(Bookmark bm)
{
if ( bm==null )
return -1;
int index = -1;
for ( int i=0; i<bookmarks.size(); i++ ) {
Bookmark item = bookmarks.get(i);
if (bm.getType() == Bookmark.TYPE_LAST_POSITION && item.getType() == Bookmark.TYPE_LAST_POSITION) {
index = i;
break;
}
if ( bm.getShortcut()>0 && item.getShortcut()==bm.getShortcut() ) {
index = i;
break;
}
if ( bm.getStartPos()!=null && bm.getStartPos().equals(item.getStartPos())) {
if (bm.getType() == Bookmark.TYPE_POSITION) {
index = i;
break;
}
if (bm.getEndPos()!=null && bm.getEndPos().equals(item.getEndPos())) {
if (item.getId() != null && bm.getId() != null && !bm.getId().equals(item.getId()))
continue; // another bookmark with same pos
index = i;
break;
}
}
}
return index;
}
synchronized public Bookmark syncBookmark(Bookmark bm)
{
if ( bm==null )
return null;
int index = findBookmarkIndex(bm);
if ( index<0 ) {
addBookmark(bm);
return bm;
}
Bookmark item = bookmarks.get(index);
if (item.getTimeStamp() >= bm.getTimeStamp())
return null;
item.setType(bm.getType());
item.setTimeStamp(bm.getTimeStamp());
item.setPosText(bm.getPosText());
item.setCommentText(bm.getCommentText());
if (item.isModified())
return item;
return null;
}
synchronized public Bookmark updateBookmark(Bookmark bm)
{
if ( bm==null )
return null;
int index = findBookmarkIndex(bm);
if ( index<0 ) {
Log.e("cr3", "cannot find bookmark " + bm);
return null;
}
Bookmark item = bookmarks.get(index);
item.setTimeStamp(bm.getTimeStamp());
item.setPosText(bm.getPosText());
item.setCommentText(bm.getCommentText());
if (!item.isModified())
return null;
return item;
}
synchronized public Bookmark removeBookmark(Bookmark bm)
{
if ( bm==null )
return null;
int index = findBookmarkIndex(bm);
if ( index<0 ) {
Log.e("cr3", "cannot find bookmark " + bm);
return null;
}
return bookmarks.remove(index);
}
synchronized public void sortBookmarks() {
Collections.sort(bookmarks, new Comparator<Bookmark>() {
@Override
public int compare(Bookmark bm1, Bookmark bm2) {
if ( bm1.getPercent() < bm2.getPercent() )
return -1;
if ( bm1.getPercent() > bm2.getPercent() )
return 1;
return 0;
}
});
}
synchronized public String getBookmarksExportText() {
StringBuilder buf = new StringBuilder();
File pathname = new File(fileInfo.getPathName());
buf.append("# file name: " + pathname.getName() + "\n");
buf.append("# file path: " + pathname.getParent() + "\n");
buf.append("# book title: " + fileInfo.title + "\n");
buf.append("# author: " + fileInfo.authors + "\n");
buf.append("\n");
for ( Bookmark bm : bookmarks ) {
if ( bm.getType()!=Bookmark.TYPE_COMMENT && bm.getType()!=Bookmark.TYPE_CORRECTION )
continue;
int percent = bm.getPercent();
String ps = String.valueOf(percent%100);
if ( ps.length()<2 )
ps = "0" + ps;
ps = String.valueOf(percent/100) + "." + ps + "%";
buf.append("## " + ps + " - " + (bm.getType()!=Bookmark.TYPE_COMMENT ? "comment" : "correction") + "\n");
if ( bm.getTitleText()!=null )
buf.append("## " + bm.getTitleText() + "\n");
if ( bm.getPosText()!=null )
buf.append("<< " + bm.getPosText() + "\n");
if ( bm.getCommentText()!=null )
buf.append(">> " + bm.getCommentText() + "\n");
buf.append("\n");
}
return buf.toString();
}
synchronized public boolean exportBookmarks( String fileName ) {
Log.i("cr3", "Exporting bookmarks to file " + fileName);
try {
FileOutputStream stream = new FileOutputStream(new File(fileName));
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
writer.write(0xfeff);
writer.write("# Cool Reader 3 - exported bookmarks\r\n");
File pathname = new File(fileInfo.getPathName());
writer.write("# file name: " + pathname.getName() + "\r\n");
writer.write("# file path: " + pathname.getParent() + "\r\n");
writer.write("# book title: " + fileInfo.title + "\r\n");
writer.write("# author: " + fileInfo.authors + "\r\n");
writer.write("# series: " + fileInfo.series + "\r\n");
writer.write("\r\n");
for ( Bookmark bm : bookmarks ) {
if ( bm.getType()!=Bookmark.TYPE_COMMENT && bm.getType()!=Bookmark.TYPE_CORRECTION )
continue;
int percent = bm.getPercent();
String ps = String.valueOf(percent%100);
if ( ps.length()<2 )
ps = "0" + ps;
ps = String.valueOf(percent/100) + "." + ps + "%";
- writer.write("## " + ps + " - " + (bm.getType()!=Bookmark.TYPE_COMMENT ? "comment" : "correction") + "\r\n");
+ writer.write("## " + ps + " - " + (bm.getType()==Bookmark.TYPE_COMMENT ? "comment" : "correction") + "\r\n");
if ( bm.getTitleText()!=null )
writer.write("## " + bm.getTitleText() + "\r\n");
if ( bm.getPosText()!=null )
writer.write("<< " + bm.getPosText() + "\r\n");
if ( bm.getCommentText()!=null )
writer.write(">> " + bm.getCommentText() + "\r\n");
writer.write("\r\n");
}
writer.close();
return true;
} catch ( IOException e ) {
Log.e("cr3", "Cannot write bookmark file " + fileName);
return false;
}
}
synchronized public Bookmark removeBookmark( int index )
{
return bookmarks.remove(index);
}
synchronized void setBookmarks(ArrayList<Bookmark> list)
{
if ( list.size()>0 ) {
if ( list.get(0).getType()==0 ) {
lastPosition = list.remove(0);
}
}
if ( list.size()>0 ) {
bookmarks = list;
}
}
@Override
public String toString() {
return "BookInfo [fileInfo=" + fileInfo + ", lastPosition="
+ lastPosition + "]";
}
}
| true | true | synchronized public boolean exportBookmarks( String fileName ) {
Log.i("cr3", "Exporting bookmarks to file " + fileName);
try {
FileOutputStream stream = new FileOutputStream(new File(fileName));
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
writer.write(0xfeff);
writer.write("# Cool Reader 3 - exported bookmarks\r\n");
File pathname = new File(fileInfo.getPathName());
writer.write("# file name: " + pathname.getName() + "\r\n");
writer.write("# file path: " + pathname.getParent() + "\r\n");
writer.write("# book title: " + fileInfo.title + "\r\n");
writer.write("# author: " + fileInfo.authors + "\r\n");
writer.write("# series: " + fileInfo.series + "\r\n");
writer.write("\r\n");
for ( Bookmark bm : bookmarks ) {
if ( bm.getType()!=Bookmark.TYPE_COMMENT && bm.getType()!=Bookmark.TYPE_CORRECTION )
continue;
int percent = bm.getPercent();
String ps = String.valueOf(percent%100);
if ( ps.length()<2 )
ps = "0" + ps;
ps = String.valueOf(percent/100) + "." + ps + "%";
writer.write("## " + ps + " - " + (bm.getType()!=Bookmark.TYPE_COMMENT ? "comment" : "correction") + "\r\n");
if ( bm.getTitleText()!=null )
writer.write("## " + bm.getTitleText() + "\r\n");
if ( bm.getPosText()!=null )
writer.write("<< " + bm.getPosText() + "\r\n");
if ( bm.getCommentText()!=null )
writer.write(">> " + bm.getCommentText() + "\r\n");
writer.write("\r\n");
}
writer.close();
return true;
} catch ( IOException e ) {
Log.e("cr3", "Cannot write bookmark file " + fileName);
return false;
}
}
| synchronized public boolean exportBookmarks( String fileName ) {
Log.i("cr3", "Exporting bookmarks to file " + fileName);
try {
FileOutputStream stream = new FileOutputStream(new File(fileName));
OutputStreamWriter writer = new OutputStreamWriter(stream, "UTF-8");
writer.write(0xfeff);
writer.write("# Cool Reader 3 - exported bookmarks\r\n");
File pathname = new File(fileInfo.getPathName());
writer.write("# file name: " + pathname.getName() + "\r\n");
writer.write("# file path: " + pathname.getParent() + "\r\n");
writer.write("# book title: " + fileInfo.title + "\r\n");
writer.write("# author: " + fileInfo.authors + "\r\n");
writer.write("# series: " + fileInfo.series + "\r\n");
writer.write("\r\n");
for ( Bookmark bm : bookmarks ) {
if ( bm.getType()!=Bookmark.TYPE_COMMENT && bm.getType()!=Bookmark.TYPE_CORRECTION )
continue;
int percent = bm.getPercent();
String ps = String.valueOf(percent%100);
if ( ps.length()<2 )
ps = "0" + ps;
ps = String.valueOf(percent/100) + "." + ps + "%";
writer.write("## " + ps + " - " + (bm.getType()==Bookmark.TYPE_COMMENT ? "comment" : "correction") + "\r\n");
if ( bm.getTitleText()!=null )
writer.write("## " + bm.getTitleText() + "\r\n");
if ( bm.getPosText()!=null )
writer.write("<< " + bm.getPosText() + "\r\n");
if ( bm.getCommentText()!=null )
writer.write(">> " + bm.getCommentText() + "\r\n");
writer.write("\r\n");
}
writer.close();
return true;
} catch ( IOException e ) {
Log.e("cr3", "Cannot write bookmark file " + fileName);
return false;
}
}
|
diff --git a/src/java/com/eviware/soapui/security/check/MaliciousAttachmentSecurityCheck.java b/src/java/com/eviware/soapui/security/check/MaliciousAttachmentSecurityCheck.java
index 2b71da518..10f4e8c8b 100644
--- a/src/java/com/eviware/soapui/security/check/MaliciousAttachmentSecurityCheck.java
+++ b/src/java/com/eviware/soapui/security/check/MaliciousAttachmentSecurityCheck.java
@@ -1,295 +1,295 @@
/*
* soapUI, copyright (C) 2004-2011 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI 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 at gnu.org.
*/
package com.eviware.soapui.security.check;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.config.MaliciousAttachmentConfig;
import com.eviware.soapui.config.MaliciousAttachmentElementConfig;
import com.eviware.soapui.config.MaliciousAttachmentSecurityCheckConfig;
import com.eviware.soapui.config.SecurityCheckConfig;
import com.eviware.soapui.impl.wsdl.WsdlRequest;
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStepResult;
import com.eviware.soapui.model.ModelItem;
import com.eviware.soapui.model.iface.Attachment;
import com.eviware.soapui.model.testsuite.TestCaseRunner;
import com.eviware.soapui.model.testsuite.TestStep;
import com.eviware.soapui.security.SecurityTestRunContext;
import com.eviware.soapui.security.SecurityTestRunner;
import com.eviware.soapui.security.tools.RandomFile;
import com.eviware.soapui.security.ui.MaliciousAttachmentAdvancedSettingsPanel;
import com.eviware.soapui.security.ui.MaliciousAttachmentMutationsPanel;
import com.eviware.soapui.support.UISupport;
public class MaliciousAttachmentSecurityCheck extends AbstractSecurityCheck
{
public static final String TYPE = "MaliciousAttachmentSecurityCheck";
public static final String NAME = "Malicious Attachment";
private MaliciousAttachmentSecurityCheckConfig config;
private MaliciousAttachmentAdvancedSettingsPanel advancedSettingsPanel;
private MaliciousAttachmentMutationsPanel mutationsPanel;
private int currentIndex = 0;
public MaliciousAttachmentSecurityCheck( SecurityCheckConfig newConfig, ModelItem parent, String icon,
TestStep testStep )
{
super( testStep, newConfig, parent, icon );
if( newConfig.getConfig() == null || !( newConfig.getConfig() instanceof MaliciousAttachmentSecurityCheckConfig ) )
{
initConfig();
}
else
{
config = ( ( MaliciousAttachmentSecurityCheckConfig )newConfig.getConfig() );
}
getExecutionStrategy().setImmutable( true );
}
/**
* Default malicious attachment configuration
*/
protected void initConfig()
{
getConfig().setConfig( MaliciousAttachmentSecurityCheckConfig.Factory.newInstance() );
config = ( MaliciousAttachmentSecurityCheckConfig )getConfig().getConfig();
}
@Override
public void updateSecurityConfig( SecurityCheckConfig config )
{
super.updateSecurityConfig( config );
if( this.config != null )
{
this.config = ( MaliciousAttachmentSecurityCheckConfig )getConfig().getConfig();
}
if( advancedSettingsPanel != null )
{
advancedSettingsPanel.setConfig( ( MaliciousAttachmentSecurityCheckConfig )getConfig().getConfig() );
}
if( mutationsPanel != null )
{
mutationsPanel.updateConfig( ( MaliciousAttachmentSecurityCheckConfig )getConfig().getConfig() );
}
}
public MaliciousAttachmentSecurityCheckConfig getMaliciousAttachmentSecurityCheckConfig()
{
return config;
}
/*
* Set attachments
*/
private void updateRequestContent( TestStep testStep, SecurityTestRunContext context )
{
setRequestTimeout( testStep, config.getRequestTimeout() );
// add attachments
for( MaliciousAttachmentElementConfig element : config.getElementList() )
{
// remove all attachments
if( element.getRemove() )
{
removeAttachment( testStep, element.getKey() );
}
else
{
// first, remove original attachments
removeAttachment( testStep, element.getKey() );
// then, add specified ones
addAttachments( testStep, element.getGenerateAttachmentList(), true );
addAttachments( testStep, element.getReplaceAttachmentList(), false );
}
}
}
private void addAttachments( TestStep testStep, List<MaliciousAttachmentConfig> list, boolean generated )
{
for( MaliciousAttachmentConfig element : list )
{
File file = new File( element.getFilename() );
if( element.getEnabled() )
{
try
{
if( !file.exists() )
{
if( generated )
{
file = new RandomFile( element.getSize(), "attachment", element.getContentType() ).next();
}
else
{
UISupport.showErrorMessage( "Missing file: " + file.getName() );
return;
}
}
addAttachment( testStep, file, element.getContentType(), generated );
}
catch( IOException e )
{
- UISupport.showErrorMessage( e );
+ SoapUI.logError( e );
}
}
}
}
@Override
protected void execute( SecurityTestRunner securityTestRunner, TestStep testStep, SecurityTestRunContext context )
{
try
{
updateRequestContent( testStep, context );
WsdlTestRequestStepResult message = ( WsdlTestRequestStepResult )testStep.run(
( TestCaseRunner )securityTestRunner, context );
message.setRequestContent( "", false );
}
catch( Exception e )
{
SoapUI.logError( e, "[MaliciousAttachmentSecurityScan]Property value is not valid xml!" );
reportSecurityCheckException( "Property value is not XML or XPath is wrong!" );
}
}
@Override
public String getType()
{
return TYPE;
}
private Attachment addAttachment( TestStep testStep, File file, String contentType, boolean generated )
throws IOException
{
WsdlRequest request = ( WsdlRequest )getRequest( testStep );
request.setInlineFilesEnabled( false );
Attachment attach = request.attachFile( file, false );
attach.setContentType( contentType );
if( generated )
{
file.deleteOnExit();
}
return attach;
}
private void removeAttachment( TestStep testStep, String id )
{
WsdlRequest request = ( WsdlRequest )getRequest( testStep );
List<Attachment> toRemove = new ArrayList<Attachment>();
for( Attachment attachment : request.getAttachments() )
{
if( attachment.getId().equals( id ) )
{
toRemove.add( attachment );
}
}
for( Attachment remove : toRemove )
{
request.removeAttachment( remove );
}
}
private void setRequestTimeout( TestStep testStep, int timeout )
{
WsdlRequest request = ( WsdlRequest )getRequest( testStep );
request.setTimeout( String.valueOf( timeout ) );
}
@Override
public JComponent getComponent()
{
if( mutationsPanel == null )
mutationsPanel = new MaliciousAttachmentMutationsPanel( config, getTestStep(),
( WsdlRequest )getRequest( getTestStep() ) );
return mutationsPanel.getPanel();
}
@Override
protected boolean hasNext( TestStep testStep, SecurityTestRunContext context )
{
boolean hasNext = currentIndex++ < 1;
if( !hasNext )
{
currentIndex = 0;
}
return hasNext;
}
@Override
public String getConfigDescription()
{
return "Configures malicious attachment security scan";
}
@Override
public String getConfigName()
{
return "Malicious Attachment Security Scan";
}
@Override
public String getHelpURL()
{
return "http://www.soapui.org";
}
@Override
public JComponent getAdvancedSettingsPanel()
{
if( advancedSettingsPanel == null )
advancedSettingsPanel = new MaliciousAttachmentAdvancedSettingsPanel( config );
return advancedSettingsPanel.getPanel();
}
@Override
public void copyConfig( SecurityCheckConfig config )
{
super.copyConfig( config );
if( advancedSettingsPanel != null )
{
advancedSettingsPanel.setConfig( ( MaliciousAttachmentSecurityCheckConfig )getConfig().getConfig() );
}
if( mutationsPanel != null )
{
mutationsPanel.updateConfig( ( MaliciousAttachmentSecurityCheckConfig )getConfig().getConfig() );
}
}
}
| true | true | private void addAttachments( TestStep testStep, List<MaliciousAttachmentConfig> list, boolean generated )
{
for( MaliciousAttachmentConfig element : list )
{
File file = new File( element.getFilename() );
if( element.getEnabled() )
{
try
{
if( !file.exists() )
{
if( generated )
{
file = new RandomFile( element.getSize(), "attachment", element.getContentType() ).next();
}
else
{
UISupport.showErrorMessage( "Missing file: " + file.getName() );
return;
}
}
addAttachment( testStep, file, element.getContentType(), generated );
}
catch( IOException e )
{
UISupport.showErrorMessage( e );
}
}
}
}
| private void addAttachments( TestStep testStep, List<MaliciousAttachmentConfig> list, boolean generated )
{
for( MaliciousAttachmentConfig element : list )
{
File file = new File( element.getFilename() );
if( element.getEnabled() )
{
try
{
if( !file.exists() )
{
if( generated )
{
file = new RandomFile( element.getSize(), "attachment", element.getContentType() ).next();
}
else
{
UISupport.showErrorMessage( "Missing file: " + file.getName() );
return;
}
}
addAttachment( testStep, file, element.getContentType(), generated );
}
catch( IOException e )
{
SoapUI.logError( e );
}
}
}
}
|
diff --git a/hibernate/hibernate-datasource/src/main/java/org/obiba/magma/datasource/hibernate/HibernateVariableValueSourceFactory.java b/hibernate/hibernate-datasource/src/main/java/org/obiba/magma/datasource/hibernate/HibernateVariableValueSourceFactory.java
index 8781c7eb..062d6249 100644
--- a/hibernate/hibernate-datasource/src/main/java/org/obiba/magma/datasource/hibernate/HibernateVariableValueSourceFactory.java
+++ b/hibernate/hibernate-datasource/src/main/java/org/obiba/magma/datasource/hibernate/HibernateVariableValueSourceFactory.java
@@ -1,206 +1,209 @@
package org.obiba.magma.datasource.hibernate;
import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import org.hibernate.FetchMode;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.obiba.core.service.impl.hibernate.AssociationCriteria;
import org.obiba.core.service.impl.hibernate.AssociationCriteria.Operation;
import org.obiba.magma.Value;
import org.obiba.magma.ValueSet;
import org.obiba.magma.ValueType;
import org.obiba.magma.Variable;
import org.obiba.magma.VariableEntity;
import org.obiba.magma.VariableValueSource;
import org.obiba.magma.VariableValueSourceFactory;
import org.obiba.magma.VectorSource;
import org.obiba.magma.datasource.hibernate.HibernateValueTable.HibernateValueSet;
import org.obiba.magma.datasource.hibernate.converter.VariableConverter;
import org.obiba.magma.datasource.hibernate.domain.ValueSetValue;
import org.obiba.magma.datasource.hibernate.domain.VariableState;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
class HibernateVariableValueSourceFactory implements VariableValueSourceFactory {
private final HibernateValueTable valueTable;
HibernateVariableValueSourceFactory(HibernateValueTable valueTable) {
super();
if(valueTable == null) throw new IllegalArgumentException("valueTable cannot be null");
this.valueTable = valueTable;
}
@Override
public Set<VariableValueSource> createSources() {
Set<VariableValueSource> sources = new LinkedHashSet<VariableValueSource>();
AssociationCriteria criteria = AssociationCriteria.create(VariableState.class, getCurrentSession()).add("valueTable", Operation.eq, valueTable.getValueTableState());
for(Object obj : criteria.getCriteria().setFetchMode("categories", FetchMode.JOIN).list()) {
VariableState state = (VariableState) obj;
sources.add(new HibernateVariableValueSource(state, true));
}
return sources;
}
VariableValueSource createSource(VariableState variableState) {
return new HibernateVariableValueSource(variableState, true);
}
private Session getCurrentSession() {
return valueTable.getDatasource().getSessionFactory().getCurrentSession();
}
class HibernateVariableValueSource implements VariableValueSource, VectorSource {
private final Serializable variableId;
private final String name;
private Variable variable;
public HibernateVariableValueSource(VariableState state, boolean unmarshall) {
if(state == null) throw new IllegalArgumentException("state cannot be null");
if(state.getId() == null) throw new IllegalArgumentException("state must be persisted");
this.variableId = state.getId();
this.name = state.getName();
if(unmarshall) {
unmarshall(state);
}
}
public Serializable getVariableId() {
return variableId;
}
@Override
public synchronized Variable getVariable() {
if(variable == null) {
VariableState state = (VariableState) getCurrentSession().createCriteria(VariableState.class).add(Restrictions.idEq(this.variableId)).setFetchMode("categories", FetchMode.JOIN).uniqueResult();
unmarshall(state);
}
return variable;
}
@Override
public Value getValue(ValueSet valueSet) {
HibernateValueSet hibernateValueSet = (HibernateValueSet) valueSet;
ValueSetValue vsv = hibernateValueSet.getValueSetState().getValueMap().get(name);
if(vsv != null) return vsv.getValue();
return (getVariable().isRepeatable() ? getValueType().nullSequence() : getValueType().nullValue());
}
@Override
public VectorSource asVectorSource() {
return this;
}
@Override
public Iterable<Value> getValues(SortedSet<VariableEntity> entities) {
+ if(entities.size() == 0) {
+ return ImmutableList.of();
+ }
final Query valuesQuery;
valuesQuery = getCurrentSession().getNamedQuery("valuesWithEntities");
valuesQuery.setParameter("entityType", valueTable.getEntityType())//
.setParameterList("identifiers", ImmutableList.copyOf(Iterables.transform(entities, new Function<VariableEntity, String>() {
@Override
public String apply(VariableEntity from) {
return from.getIdentifier();
}
})));
valuesQuery//
.setParameter("valueTableId", valueTable.getValueTableState().getId())//
.setParameter("variableId", valueTable.getVariableId(getVariable()));
return new Iterable<Value>() {
@Override
public Iterator<Value> iterator() {
return new Iterator<Value>() {
private final ScrollableResults results;
private boolean hasNext;
{
results = valuesQuery.scroll(ScrollMode.FORWARD_ONLY);
hasNext = results.next();
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public Value next() {
if(hasNext == false) {
throw new NoSuchElementException();
}
Value value = (Value) results.get(0);
hasNext = results.next();
if(hasNext == false) {
results.close();
}
return value != null ? value : (getVariable().isRepeatable() ? getValueType().nullSequence() : getValueType().nullValue());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
@Override
public ValueType getValueType() {
return getVariable().getValueType();
}
/**
* Initialises the {@code variable} attribute from the provided state
* @param state
*/
private void unmarshall(VariableState state) {
variable = VariableConverter.getInstance().unmarshal(state, null);
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null) {
return false;
}
if(obj instanceof HibernateVariableValueSource == false) {
return super.equals(obj);
}
HibernateVariableValueSource rhs = (HibernateVariableValueSource) obj;
return this.name.equals(rhs.name);
}
@Override
public int hashCode() {
return this.name.hashCode();
}
}
}
| true | true | public Iterable<Value> getValues(SortedSet<VariableEntity> entities) {
final Query valuesQuery;
valuesQuery = getCurrentSession().getNamedQuery("valuesWithEntities");
valuesQuery.setParameter("entityType", valueTable.getEntityType())//
.setParameterList("identifiers", ImmutableList.copyOf(Iterables.transform(entities, new Function<VariableEntity, String>() {
@Override
public String apply(VariableEntity from) {
return from.getIdentifier();
}
})));
valuesQuery//
.setParameter("valueTableId", valueTable.getValueTableState().getId())//
.setParameter("variableId", valueTable.getVariableId(getVariable()));
return new Iterable<Value>() {
@Override
public Iterator<Value> iterator() {
return new Iterator<Value>() {
private final ScrollableResults results;
private boolean hasNext;
{
results = valuesQuery.scroll(ScrollMode.FORWARD_ONLY);
hasNext = results.next();
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public Value next() {
if(hasNext == false) {
throw new NoSuchElementException();
}
Value value = (Value) results.get(0);
hasNext = results.next();
if(hasNext == false) {
results.close();
}
return value != null ? value : (getVariable().isRepeatable() ? getValueType().nullSequence() : getValueType().nullValue());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
| public Iterable<Value> getValues(SortedSet<VariableEntity> entities) {
if(entities.size() == 0) {
return ImmutableList.of();
}
final Query valuesQuery;
valuesQuery = getCurrentSession().getNamedQuery("valuesWithEntities");
valuesQuery.setParameter("entityType", valueTable.getEntityType())//
.setParameterList("identifiers", ImmutableList.copyOf(Iterables.transform(entities, new Function<VariableEntity, String>() {
@Override
public String apply(VariableEntity from) {
return from.getIdentifier();
}
})));
valuesQuery//
.setParameter("valueTableId", valueTable.getValueTableState().getId())//
.setParameter("variableId", valueTable.getVariableId(getVariable()));
return new Iterable<Value>() {
@Override
public Iterator<Value> iterator() {
return new Iterator<Value>() {
private final ScrollableResults results;
private boolean hasNext;
{
results = valuesQuery.scroll(ScrollMode.FORWARD_ONLY);
hasNext = results.next();
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public Value next() {
if(hasNext == false) {
throw new NoSuchElementException();
}
Value value = (Value) results.get(0);
hasNext = results.next();
if(hasNext == false) {
results.close();
}
return value != null ? value : (getVariable().isRepeatable() ? getValueType().nullSequence() : getValueType().nullValue());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
|
diff --git a/contents/developer/open/java/search.java b/contents/developer/open/java/search.java
index a2d293d..93ae34b 100755
--- a/contents/developer/open/java/search.java
+++ b/contents/developer/open/java/search.java
@@ -1,195 +1,196 @@
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.jackrabbit.webdav.client.methods.SearchMethod;
import org.apache.jackrabbit.webdav.property.DavProperty;
import org.apache.jackrabbit.webdav.property.DavPropertyName;
import org.apache.jackrabbit.webdav.property.DavPropertyNameIterator;
import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
import org.apache.jackrabbit.webdav.property.DavPropertySet;
import org.apache.jackrabbit.webdav.xml.Namespace;
import org.apache.jackrabbit.webdav.MultiStatus;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
public class demo_search {
public static void main(String[] args) {
HostConfiguration hostConfig = new HostConfiguration();
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
int maxHostConnections = 20;
params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
connectionManager.setParams(params);
HttpClient client = new HttpClient(connectionManager);
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
client.getState().setCredentials(AuthScope.ANY, creds);
client.setHostConfiguration(hostConfig);
// select, ���صĶ�����Եõ�display(����), subjects(��ǩ), iscollection(�Ƿ�Ŀ¼)��������
String select =
"<D:select>" +
"<D:prop xmlns:ns1=\"http://ns.everydo.com/basic\" xmlns:ns0=\"DAV:\">"+
"<ns0:displayname />"+
"<ns1:subjects />"+
"<ns0:iscollection />"+
"<ns0:getlastmodified />"+
"</D:prop>"+
"</D:select>";
// from, ȷ�������ķ�Χ��infinity��ʾ�����ļ��������е��ļ����У�, 0 ��ʾֻ���������ļ����µ��ļ����У�
String from =
"<D:from>"+
"<D:scope>"+
+ "<D:href>/</D:href>"+
"<D:depth>infinity</D:depth>"+
"</D:scope>"+
"</D:from>";
// where, ���� getlastmodified, ���ڽ����賿��С�ڽ���24�������'�´�����'��'�ĵ�' �ļ��ϼ�
String lessDay = get_custom_time_string(0, 0, 0);
String greaterDay = get_custom_time_string(23, 59, 59);
String where =
"<D:where>"+
"<D:lte caseless=\"no\">"+
"<D:prop xmlns=\"DAV:\">"+
"<getlastmodified />"+
"</D:prop>"+
"<D:literal>" + greaterDay + "</D:literal>"+
"</D:lte>"+
"<D:gte caseless=\"no\">"+
"<D:prop xmlns=\"DAV:\">"+
"<getlastmodified />"+
"</D:prop>"+
"<D:literal>" + lessDay + "</D:literal>"+
"</D:gte>"+
"</D:where>";
// orderby, ���ձ�������
String orderby =
"<D:orderby>"+
"<D:order>"+
"<D:prop xmlns:ns0=\"DAV:\">"+
"<ns0:displayname />"+
"</D:prop>"+
"<D:descending />"+
"</D:order>"+
"</D:orderby>";
// ֻ����20�����
String limit =
"<D:limit>"+
"<D:nresults>20</D:nresults>"+
"</D:limit>";
String query = select + from + where + orderby + limit;
SearchMethod searchMethod=null;
try {
// ֻ���ص�20������������ݼ�
searchMethod = new SearchMethod("http://localhost:8089/files?start=20",query,"D:basicsearch");
client.executeMethod(searchMethod);
Namespace edoNamespace = Namespace.getNamespace("http://ns.everydo.com/basic");
if (searchMethod.getStatusCode() != 207){
System.out.println("����ִ��ʧ�ܣ���������ǣ�" + searchMethod.getStatusCode());
return;
}
MultiStatusResponse[] responses = null;
try{
MultiStatus resp = searchMethod.getResponseBodyAsMultiStatus();
responses = resp.getResponses();
} catch (DavException e){
System.out.println(e.getMessage());
}
for (int i=0; i<responses.length; i++) {
MultiStatusResponse content = responses[i];
String docHref = content.getHref();
System.out.println("source url: " + URLDecoder.decode(docHref, "utf-8"));
/*
* ��ӡ���е����Ժ�ֵ
*/
// �õ��������Ե����ֿռ�
// DavPropertySet properys = content.getProperties(200);
// DavPropertyNameSet nameSet = content.getPropertyNames(200);
// DavPropertyNameIterator nameSetIter = nameSet.iterator();
//
// // �����ӡ���Ժ�ֵ
// while (nameSetIter.hasNext()){
// DavProperty propery = properys.get(nameSetIter.next());
// System.out.print(propery.getName());
// if (propery.getValue() == null){
// System.out.println(": null");
// continue;
// }
// System.out.println(": " + propery.getValue().toString());
// }
/*
* �ֱ��ӡ�ض������Ժ�ֵ
*/
DavPropertySet properys = content.getProperties(200);
//�Ƿ�ΪĿ¼
Boolean isFile = properys.get("iscollection").getValue().equals("0");
System.out.println("IsFile: " + isFile.toString());
// ��ӡ�ļ������ļ��е�����
String sourceName = properys.get("displayname").getValue().toString();
System.out.println("display name: " + sourceName);
if (isFile){
// ��ӡ�ļ��ı�ǩ�� subjects ������webdav�����ԣ��������Զ�������ԣ�����Ҫ�����ǵ������ռ�ȥѰ��
DavProperty subjects = properys.get("subjects", edoNamespace);
// ֻ�д��ϱ�ǩ���ļ����ܻ�ñ�ǩ
if (subjects == null || subjects.getValue() == null){
System.out.println("subjects: null");
}else{
System.out.println("subjects: " + subjects.getValue().toString());
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* �õ����Ƶ�MGTʱ��
*/
@SuppressWarnings("static-access")
private static String get_custom_time_string(int hour, int minute, int second) {
final SimpleDateFormat sdf =
new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(calendar.YEAR),
calendar.get(calendar.MONTH),
calendar.get(calendar.DAY_OF_MONTH),
hour,
minute,
second);
return sdf.format(calendar.getTime());
}
}
| true | true | public static void main(String[] args) {
HostConfiguration hostConfig = new HostConfiguration();
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
int maxHostConnections = 20;
params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
connectionManager.setParams(params);
HttpClient client = new HttpClient(connectionManager);
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
client.getState().setCredentials(AuthScope.ANY, creds);
client.setHostConfiguration(hostConfig);
// select, ���صĶ�����Եõ�display(����), subjects(��ǩ), iscollection(�Ƿ�Ŀ¼)��������
String select =
"<D:select>" +
"<D:prop xmlns:ns1=\"http://ns.everydo.com/basic\" xmlns:ns0=\"DAV:\">"+
"<ns0:displayname />"+
"<ns1:subjects />"+
"<ns0:iscollection />"+
"<ns0:getlastmodified />"+
"</D:prop>"+
"</D:select>";
// from, ȷ�������ķ�Χ��infinity��ʾ�����ļ��������е��ļ����У�, 0 ��ʾֻ���������ļ����µ��ļ����У�
String from =
"<D:from>"+
"<D:scope>"+
"<D:depth>infinity</D:depth>"+
"</D:scope>"+
"</D:from>";
// where, ���� getlastmodified, ���ڽ����賿��С�ڽ���24�������'�´�����'��'�ĵ�' �ļ��ϼ�
String lessDay = get_custom_time_string(0, 0, 0);
String greaterDay = get_custom_time_string(23, 59, 59);
String where =
"<D:where>"+
"<D:lte caseless=\"no\">"+
"<D:prop xmlns=\"DAV:\">"+
"<getlastmodified />"+
"</D:prop>"+
"<D:literal>" + greaterDay + "</D:literal>"+
"</D:lte>"+
"<D:gte caseless=\"no\">"+
"<D:prop xmlns=\"DAV:\">"+
"<getlastmodified />"+
"</D:prop>"+
"<D:literal>" + lessDay + "</D:literal>"+
"</D:gte>"+
"</D:where>";
// orderby, ���ձ�������
String orderby =
"<D:orderby>"+
"<D:order>"+
"<D:prop xmlns:ns0=\"DAV:\">"+
"<ns0:displayname />"+
"</D:prop>"+
"<D:descending />"+
"</D:order>"+
"</D:orderby>";
// ֻ����20�����
String limit =
"<D:limit>"+
"<D:nresults>20</D:nresults>"+
"</D:limit>";
String query = select + from + where + orderby + limit;
SearchMethod searchMethod=null;
try {
// ֻ���ص�20������������ݼ�
searchMethod = new SearchMethod("http://localhost:8089/files?start=20",query,"D:basicsearch");
client.executeMethod(searchMethod);
Namespace edoNamespace = Namespace.getNamespace("http://ns.everydo.com/basic");
if (searchMethod.getStatusCode() != 207){
System.out.println("����ִ��ʧ�ܣ���������ǣ�" + searchMethod.getStatusCode());
return;
}
MultiStatusResponse[] responses = null;
try{
MultiStatus resp = searchMethod.getResponseBodyAsMultiStatus();
responses = resp.getResponses();
} catch (DavException e){
System.out.println(e.getMessage());
}
for (int i=0; i<responses.length; i++) {
MultiStatusResponse content = responses[i];
String docHref = content.getHref();
System.out.println("source url: " + URLDecoder.decode(docHref, "utf-8"));
/*
* ��ӡ���е����Ժ�ֵ
*/
// �õ��������Ե����ֿռ�
// DavPropertySet properys = content.getProperties(200);
// DavPropertyNameSet nameSet = content.getPropertyNames(200);
// DavPropertyNameIterator nameSetIter = nameSet.iterator();
//
// // �����ӡ���Ժ�ֵ
// while (nameSetIter.hasNext()){
// DavProperty propery = properys.get(nameSetIter.next());
// System.out.print(propery.getName());
// if (propery.getValue() == null){
// System.out.println(": null");
// continue;
// }
// System.out.println(": " + propery.getValue().toString());
// }
/*
* �ֱ��ӡ�ض������Ժ�ֵ
*/
DavPropertySet properys = content.getProperties(200);
//�Ƿ�ΪĿ¼
Boolean isFile = properys.get("iscollection").getValue().equals("0");
System.out.println("IsFile: " + isFile.toString());
// ��ӡ�ļ������ļ��е�����
String sourceName = properys.get("displayname").getValue().toString();
System.out.println("display name: " + sourceName);
if (isFile){
// ��ӡ�ļ��ı�ǩ�� subjects ������webdav�����ԣ��������Զ�������ԣ�����Ҫ�����ǵ������ռ�ȥѰ��
DavProperty subjects = properys.get("subjects", edoNamespace);
// ֻ�д��ϱ�ǩ���ļ����ܻ�ñ�ǩ
if (subjects == null || subjects.getValue() == null){
System.out.println("subjects: null");
}else{
System.out.println("subjects: " + subjects.getValue().toString());
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
| public static void main(String[] args) {
HostConfiguration hostConfig = new HostConfiguration();
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
int maxHostConnections = 20;
params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
connectionManager.setParams(params);
HttpClient client = new HttpClient(connectionManager);
Credentials creds = new UsernamePasswordCredentials("admin", "admin");
client.getState().setCredentials(AuthScope.ANY, creds);
client.setHostConfiguration(hostConfig);
// select, ���صĶ�����Եõ�display(����), subjects(��ǩ), iscollection(�Ƿ�Ŀ¼)��������
String select =
"<D:select>" +
"<D:prop xmlns:ns1=\"http://ns.everydo.com/basic\" xmlns:ns0=\"DAV:\">"+
"<ns0:displayname />"+
"<ns1:subjects />"+
"<ns0:iscollection />"+
"<ns0:getlastmodified />"+
"</D:prop>"+
"</D:select>";
// from, ȷ�������ķ�Χ��infinity��ʾ�����ļ��������е��ļ����У�, 0 ��ʾֻ���������ļ����µ��ļ����У�
String from =
"<D:from>"+
"<D:scope>"+
"<D:href>/</D:href>"+
"<D:depth>infinity</D:depth>"+
"</D:scope>"+
"</D:from>";
// where, ���� getlastmodified, ���ڽ����賿��С�ڽ���24�������'�´�����'��'�ĵ�' �ļ��ϼ�
String lessDay = get_custom_time_string(0, 0, 0);
String greaterDay = get_custom_time_string(23, 59, 59);
String where =
"<D:where>"+
"<D:lte caseless=\"no\">"+
"<D:prop xmlns=\"DAV:\">"+
"<getlastmodified />"+
"</D:prop>"+
"<D:literal>" + greaterDay + "</D:literal>"+
"</D:lte>"+
"<D:gte caseless=\"no\">"+
"<D:prop xmlns=\"DAV:\">"+
"<getlastmodified />"+
"</D:prop>"+
"<D:literal>" + lessDay + "</D:literal>"+
"</D:gte>"+
"</D:where>";
// orderby, ���ձ�������
String orderby =
"<D:orderby>"+
"<D:order>"+
"<D:prop xmlns:ns0=\"DAV:\">"+
"<ns0:displayname />"+
"</D:prop>"+
"<D:descending />"+
"</D:order>"+
"</D:orderby>";
// ֻ����20�����
String limit =
"<D:limit>"+
"<D:nresults>20</D:nresults>"+
"</D:limit>";
String query = select + from + where + orderby + limit;
SearchMethod searchMethod=null;
try {
// ֻ���ص�20������������ݼ�
searchMethod = new SearchMethod("http://localhost:8089/files?start=20",query,"D:basicsearch");
client.executeMethod(searchMethod);
Namespace edoNamespace = Namespace.getNamespace("http://ns.everydo.com/basic");
if (searchMethod.getStatusCode() != 207){
System.out.println("����ִ��ʧ�ܣ���������ǣ�" + searchMethod.getStatusCode());
return;
}
MultiStatusResponse[] responses = null;
try{
MultiStatus resp = searchMethod.getResponseBodyAsMultiStatus();
responses = resp.getResponses();
} catch (DavException e){
System.out.println(e.getMessage());
}
for (int i=0; i<responses.length; i++) {
MultiStatusResponse content = responses[i];
String docHref = content.getHref();
System.out.println("source url: " + URLDecoder.decode(docHref, "utf-8"));
/*
* ��ӡ���е����Ժ�ֵ
*/
// �õ��������Ե����ֿռ�
// DavPropertySet properys = content.getProperties(200);
// DavPropertyNameSet nameSet = content.getPropertyNames(200);
// DavPropertyNameIterator nameSetIter = nameSet.iterator();
//
// // �����ӡ���Ժ�ֵ
// while (nameSetIter.hasNext()){
// DavProperty propery = properys.get(nameSetIter.next());
// System.out.print(propery.getName());
// if (propery.getValue() == null){
// System.out.println(": null");
// continue;
// }
// System.out.println(": " + propery.getValue().toString());
// }
/*
* �ֱ��ӡ�ض������Ժ�ֵ
*/
DavPropertySet properys = content.getProperties(200);
//�Ƿ�ΪĿ¼
Boolean isFile = properys.get("iscollection").getValue().equals("0");
System.out.println("IsFile: " + isFile.toString());
// ��ӡ�ļ������ļ��е�����
String sourceName = properys.get("displayname").getValue().toString();
System.out.println("display name: " + sourceName);
if (isFile){
// ��ӡ�ļ��ı�ǩ�� subjects ������webdav�����ԣ��������Զ�������ԣ�����Ҫ�����ǵ������ռ�ȥѰ��
DavProperty subjects = properys.get("subjects", edoNamespace);
// ֻ�д��ϱ�ǩ���ļ����ܻ�ñ�ǩ
if (subjects == null || subjects.getValue() == null){
System.out.println("subjects: null");
}else{
System.out.println("subjects: " + subjects.getValue().toString());
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/Project2/test/PrintTableTest.java b/Project2/test/PrintTableTest.java
index a83ed02..ebc789b 100644
--- a/Project2/test/PrintTableTest.java
+++ b/Project2/test/PrintTableTest.java
@@ -1,44 +1,44 @@
import junit.framework.Assert;
import junit.framework.TestCase;
import main.TicTacToe;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.io.PrintStream;
/**
* Created with IntelliJ IDEA.
* User: fannar
* Date: 11/23/12
* Time: 16:20
* To change this template use File | Settings | File Templates.
*/
public class PrintTableTest extends TestCase
{
TicTacToe capture;
protected void setUp() throws Exception
{
super.setUp();
capture = new TicTacToe();
}
public final void testPrintTableTest()
{
PrintStream originalOut = System.out;
OutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
System.setOut(ps);
String separator = System.getProperty("line.separator");
capture.printTable();
assertEquals("["+ capture.arr[0][0] + "]"+ "" + "["+ capture.arr[0][1] + "]"+"" + "["+capture.arr[0][2] +"]"+ "\n" +
"["+ capture.arr[1][0] + "]"+ "" + "["+ capture.arr[1][1] + "]"+"" + "["+capture.arr[1][2] +"]"+ "\n" +
"["+ capture.arr[2][0] + "]"+ "" + "["+ capture.arr[2][1] + "]"+"" + "["+capture.arr[2][2] +"]" +separator, os.toString());
- System.setOut(originalOut);
+ System.setOut(originalOut); //test
}
}
| true | true | public final void testPrintTableTest()
{
PrintStream originalOut = System.out;
OutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
System.setOut(ps);
String separator = System.getProperty("line.separator");
capture.printTable();
assertEquals("["+ capture.arr[0][0] + "]"+ "" + "["+ capture.arr[0][1] + "]"+"" + "["+capture.arr[0][2] +"]"+ "\n" +
"["+ capture.arr[1][0] + "]"+ "" + "["+ capture.arr[1][1] + "]"+"" + "["+capture.arr[1][2] +"]"+ "\n" +
"["+ capture.arr[2][0] + "]"+ "" + "["+ capture.arr[2][1] + "]"+"" + "["+capture.arr[2][2] +"]" +separator, os.toString());
System.setOut(originalOut);
}
| public final void testPrintTableTest()
{
PrintStream originalOut = System.out;
OutputStream os = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(os);
System.setOut(ps);
String separator = System.getProperty("line.separator");
capture.printTable();
assertEquals("["+ capture.arr[0][0] + "]"+ "" + "["+ capture.arr[0][1] + "]"+"" + "["+capture.arr[0][2] +"]"+ "\n" +
"["+ capture.arr[1][0] + "]"+ "" + "["+ capture.arr[1][1] + "]"+"" + "["+capture.arr[1][2] +"]"+ "\n" +
"["+ capture.arr[2][0] + "]"+ "" + "["+ capture.arr[2][1] + "]"+"" + "["+capture.arr[2][2] +"]" +separator, os.toString());
System.setOut(originalOut); //test
}
|
diff --git a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java
index 518908af..b91e5fd5 100644
--- a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java
+++ b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/bean/UserSessionBean.java
@@ -1,305 +1,310 @@
package gov.nih.nci.evs.browser.bean;
import gov.nih.nci.evs.browser.utils.MailUtils;
import gov.nih.nci.evs.browser.utils.SearchUtils;
import gov.nih.nci.evs.browser.utils.UserInputException;
import gov.nih.nci.evs.browser.utils.Utils;
import gov.nih.nci.evs.browser.properties.NCItBrowserProperties;
import static gov.nih.nci.evs.browser.common.Constants.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.LexGrid.concepts.Concept;
/**
* <!-- LICENSE_TEXT_START -->
* Copyright 2008,2009 NGIT. This software was developed in conjunction with the National Cancer Institute,
* and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. 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.
* 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment:
* "This product includes software developed by NGIT and the National Cancer Institute."
* If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself,
* wherever such third-party acknowledgments normally appear.
* 3. The names "The National Cancer Institute", "NCI" and "NGIT" must not be used to endorse or promote products derived from this software.
* 4. This license does not authorize the incorporation of this software into any third party proprietary programs. This license does not authorize
* the recipient to use any trademarks owned by either NCI or NGIT
* 5. 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 NATIONAL CANCER INSTITUTE,
* NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* <!-- LICENSE_TEXT_END -->
*/
/**
* @author EVS Team
* @version 1.0
*
* Modification history
* Initial implementation [email protected]
*
*/
public class UserSessionBean extends Object {
private static String contains_warning_msg = "(WARNING: Only a subset of results may appear due to current limits in the terminology server (see Known Issues on the Help page).)";
private String selectedQuickLink = null;
private List quickLinkList = null;
public void setSelectedQuickLink(String selectedQuickLink) {
this.selectedQuickLink = selectedQuickLink;
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
request.getSession().setAttribute("selectedQuickLink",
selectedQuickLink);
}
public String getSelectedQuickLink() {
return this.selectedQuickLink;
}
public void quickLinkChanged(ValueChangeEvent event) {
if (event.getNewValue() == null)
return;
String newValue = (String) event.getNewValue();
System.out.println("quickLinkChanged; " + newValue);
setSelectedQuickLink(newValue);
HttpServletResponse response = (HttpServletResponse) FacesContext
.getCurrentInstance().getExternalContext().getResponse();
String targetURL = null;//"http://nciterms.nci.nih.gov/";
if (selectedQuickLink.compareTo("NCI Terminology Browser") == 0) {
targetURL = "http://nciterms.nci.nih.gov/";
}
try {
response.sendRedirect(response.encodeRedirectURL(targetURL));
} catch (Exception ex) {
ex.printStackTrace();
// send error message
}
}
public List getQuickLinkList() {
quickLinkList = new ArrayList();
quickLinkList.add(new SelectItem("Quick Links"));
quickLinkList.add(new SelectItem("NCI Terminology Browser"));
quickLinkList.add(new SelectItem("NCI MetaThesaurus"));
quickLinkList.add(new SelectItem("EVS Home"));
quickLinkList.add(new SelectItem("NCI Terminology Resources"));
return quickLinkList;
}
public String searchAction() {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
request.getSession().setAttribute("contains_warning_msg", "");
String matchText = (String) request.getParameter("matchText");
//[#19965] Error message is not displayed when Search Criteria is not provided
if (matchText == null || matchText.length() == 0) {
String message = "Please enter a search string.";
request.getSession().setAttribute("message", message);
return "message";
}
matchText = matchText.trim();
request.getSession().setAttribute("matchText", matchText);
String matchAlgorithm = (String) request.getParameter("algorithm");
+ if (matchAlgorithm == null || matchAlgorithm.length() == 0) {
+ String message = "Warning: Search algorithm parameter is not set.";
+ request.getSession().setAttribute("message", message);
+ return "message";
+ }
setSelectedAlgorithm(matchAlgorithm);
String scheme = CODING_SCHEME_NAME;
String version = null;
String max_str = null;
int maxToReturn = -1;//1000;
try {
max_str = NCItBrowserProperties
.getProperty(NCItBrowserProperties.MAXIMUM_RETURN);
maxToReturn = Integer.parseInt(max_str);
} catch (Exception ex) {
// Do nothing
}
request.getSession().setAttribute("vocabulary", scheme);
Utils.StopWatch stopWatch = new Utils.StopWatch();
Vector<org.LexGrid.concepts.Concept> v = new SearchUtils()
.searchByName(scheme, version, matchText, matchAlgorithm,
maxToReturn);
if (NCItBrowserProperties.debugOn) {
System.out.println("scheme: " + scheme);
System.out.println("version: " + version);
System.out.println("keyword(s): " + matchText);
System.out.println("algorithm: " + matchAlgorithm);
try {
System.out.println("sort.by.score: " + NCItBrowserProperties.
getProperty(NCItBrowserProperties.SORT_BY_SCORE));
} catch (Exception e) {
}
System.out.println(stopWatch.getResult());
}
if (v != null && v.size() > 1) {
request.getSession().setAttribute("search_results", v);
String match_size = Integer.toString(v.size());
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.getSession().setAttribute("new_search", Boolean.TRUE);
if (matchText.length() < 4
&& matchAlgorithm.compareTo("contains") == 0) {
request.getSession().setAttribute("contains_warning_msg",
contains_warning_msg);
} else if (matchText.length() == 1
&& matchAlgorithm.compareTo("startsWith") == 0) {
request.getSession().setAttribute("contains_warning_msg",
contains_warning_msg);
}
return "search_results";
}
else if (v != null && v.size() == 1) {
request.getSession().setAttribute("singleton", "true");
request.getSession().setAttribute("dictionary", CODING_SCHEME_NAME);
Concept c = (Concept) v.elementAt(0);
request.getSession().setAttribute("code", c.getId());
return "concept_details";
}
String message = "No match found.";
request.getSession().setAttribute("message", message);
return "message";
}
private String selectedResultsPerPage = null;
private List resultsPerPageList = null;
public List getResultsPerPageList() {
resultsPerPageList = new ArrayList();
resultsPerPageList.add(new SelectItem("10"));
resultsPerPageList.add(new SelectItem("25"));
resultsPerPageList.add(new SelectItem("50"));
resultsPerPageList.add(new SelectItem("75"));
resultsPerPageList.add(new SelectItem("100"));
resultsPerPageList.add(new SelectItem("250"));
resultsPerPageList.add(new SelectItem("500"));
selectedResultsPerPage = ((SelectItem) resultsPerPageList.get(2))
.getLabel(); // default to 50
return resultsPerPageList;
}
public void setSelectedResultsPerPage(String selectedResultsPerPage) {
if (selectedResultsPerPage == null)
return;
this.selectedResultsPerPage = selectedResultsPerPage;
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
request.getSession().setAttribute("selectedResultsPerPage",
selectedResultsPerPage);
}
public String getSelectedResultsPerPage() {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
String s = (String) request.getSession().getAttribute(
"selectedResultsPerPage");
if (s != null) {
this.selectedResultsPerPage = s;
} else {
this.selectedResultsPerPage = "50";
request.getSession().setAttribute("selectedResultsPerPage", "50");
}
return this.selectedResultsPerPage;
}
public void resultsPerPageChanged(ValueChangeEvent event) {
if (event.getNewValue() == null) {
return;
}
String newValue = (String) event.getNewValue();
setSelectedResultsPerPage(newValue);
}
public String linkAction() {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
return "";
}
private String selectedAlgorithm = null;
private List algorithmList = null;
public List getAlgorithmList() {
algorithmList = new ArrayList();
algorithmList.add(new SelectItem("exactMatch", "exactMatch"));
algorithmList.add(new SelectItem("startsWith", "Begins With"));
algorithmList.add(new SelectItem("contains", "Contains"));
selectedAlgorithm = ((SelectItem) algorithmList.get(0)).getLabel();
return algorithmList;
}
public void algorithmChanged(ValueChangeEvent event) {
if (event.getNewValue() == null)
return;
String newValue = (String) event.getNewValue();
//System.out.println("algorithmChanged; " + newValue);
setSelectedAlgorithm(newValue);
}
public void setSelectedAlgorithm(String selectedAlgorithm) {
this.selectedAlgorithm = selectedAlgorithm;
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
request.getSession().setAttribute("selectedAlgorithm",
selectedAlgorithm);
}
public String getSelectedAlgorithm() {
return this.selectedAlgorithm;
}
public String contactUs() throws Exception {
String msg = "Your message was successfully sent.";
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
try {
String subject = request.getParameter("subject");
String message = request.getParameter("message");
String from = request.getParameter("emailaddress");
String recipients[] = MailUtils.getRecipients();
MailUtils.postMail(from, recipients, subject, message);
} catch (UserInputException e) {
msg = e.getMessage();
request.setAttribute("errorMsg", Utils.toHtml(msg));
request.setAttribute("errorType", "user");
return "error";
} catch (Exception e) {
msg = "System Error: Your message was not sent.\n";
msg += " (If possible, please contact NCI systems team.)\n";
msg += "\n";
msg += e.getMessage();
request.setAttribute("errorMsg", Utils.toHtml(msg));
request.setAttribute("errorType", "system");
e.printStackTrace();
return "error";
}
request.getSession().setAttribute("message", Utils.toHtml(msg));
return "message";
}
}
| true | true | public String searchAction() {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
request.getSession().setAttribute("contains_warning_msg", "");
String matchText = (String) request.getParameter("matchText");
//[#19965] Error message is not displayed when Search Criteria is not provided
if (matchText == null || matchText.length() == 0) {
String message = "Please enter a search string.";
request.getSession().setAttribute("message", message);
return "message";
}
matchText = matchText.trim();
request.getSession().setAttribute("matchText", matchText);
String matchAlgorithm = (String) request.getParameter("algorithm");
setSelectedAlgorithm(matchAlgorithm);
String scheme = CODING_SCHEME_NAME;
String version = null;
String max_str = null;
int maxToReturn = -1;//1000;
try {
max_str = NCItBrowserProperties
.getProperty(NCItBrowserProperties.MAXIMUM_RETURN);
maxToReturn = Integer.parseInt(max_str);
} catch (Exception ex) {
// Do nothing
}
request.getSession().setAttribute("vocabulary", scheme);
Utils.StopWatch stopWatch = new Utils.StopWatch();
Vector<org.LexGrid.concepts.Concept> v = new SearchUtils()
.searchByName(scheme, version, matchText, matchAlgorithm,
maxToReturn);
if (NCItBrowserProperties.debugOn) {
System.out.println("scheme: " + scheme);
System.out.println("version: " + version);
System.out.println("keyword(s): " + matchText);
System.out.println("algorithm: " + matchAlgorithm);
try {
System.out.println("sort.by.score: " + NCItBrowserProperties.
getProperty(NCItBrowserProperties.SORT_BY_SCORE));
} catch (Exception e) {
}
System.out.println(stopWatch.getResult());
}
if (v != null && v.size() > 1) {
request.getSession().setAttribute("search_results", v);
String match_size = Integer.toString(v.size());
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.getSession().setAttribute("new_search", Boolean.TRUE);
if (matchText.length() < 4
&& matchAlgorithm.compareTo("contains") == 0) {
request.getSession().setAttribute("contains_warning_msg",
contains_warning_msg);
} else if (matchText.length() == 1
&& matchAlgorithm.compareTo("startsWith") == 0) {
request.getSession().setAttribute("contains_warning_msg",
contains_warning_msg);
}
return "search_results";
}
else if (v != null && v.size() == 1) {
request.getSession().setAttribute("singleton", "true");
request.getSession().setAttribute("dictionary", CODING_SCHEME_NAME);
Concept c = (Concept) v.elementAt(0);
request.getSession().setAttribute("code", c.getId());
return "concept_details";
}
String message = "No match found.";
request.getSession().setAttribute("message", message);
return "message";
}
| public String searchAction() {
HttpServletRequest request = (HttpServletRequest) FacesContext
.getCurrentInstance().getExternalContext().getRequest();
request.getSession().setAttribute("contains_warning_msg", "");
String matchText = (String) request.getParameter("matchText");
//[#19965] Error message is not displayed when Search Criteria is not provided
if (matchText == null || matchText.length() == 0) {
String message = "Please enter a search string.";
request.getSession().setAttribute("message", message);
return "message";
}
matchText = matchText.trim();
request.getSession().setAttribute("matchText", matchText);
String matchAlgorithm = (String) request.getParameter("algorithm");
if (matchAlgorithm == null || matchAlgorithm.length() == 0) {
String message = "Warning: Search algorithm parameter is not set.";
request.getSession().setAttribute("message", message);
return "message";
}
setSelectedAlgorithm(matchAlgorithm);
String scheme = CODING_SCHEME_NAME;
String version = null;
String max_str = null;
int maxToReturn = -1;//1000;
try {
max_str = NCItBrowserProperties
.getProperty(NCItBrowserProperties.MAXIMUM_RETURN);
maxToReturn = Integer.parseInt(max_str);
} catch (Exception ex) {
// Do nothing
}
request.getSession().setAttribute("vocabulary", scheme);
Utils.StopWatch stopWatch = new Utils.StopWatch();
Vector<org.LexGrid.concepts.Concept> v = new SearchUtils()
.searchByName(scheme, version, matchText, matchAlgorithm,
maxToReturn);
if (NCItBrowserProperties.debugOn) {
System.out.println("scheme: " + scheme);
System.out.println("version: " + version);
System.out.println("keyword(s): " + matchText);
System.out.println("algorithm: " + matchAlgorithm);
try {
System.out.println("sort.by.score: " + NCItBrowserProperties.
getProperty(NCItBrowserProperties.SORT_BY_SCORE));
} catch (Exception e) {
}
System.out.println(stopWatch.getResult());
}
if (v != null && v.size() > 1) {
request.getSession().setAttribute("search_results", v);
String match_size = Integer.toString(v.size());
request.getSession().setAttribute("match_size", match_size);
request.getSession().setAttribute("page_string", "1");
request.getSession().setAttribute("new_search", Boolean.TRUE);
if (matchText.length() < 4
&& matchAlgorithm.compareTo("contains") == 0) {
request.getSession().setAttribute("contains_warning_msg",
contains_warning_msg);
} else if (matchText.length() == 1
&& matchAlgorithm.compareTo("startsWith") == 0) {
request.getSession().setAttribute("contains_warning_msg",
contains_warning_msg);
}
return "search_results";
}
else if (v != null && v.size() == 1) {
request.getSession().setAttribute("singleton", "true");
request.getSession().setAttribute("dictionary", CODING_SCHEME_NAME);
Concept c = (Concept) v.elementAt(0);
request.getSession().setAttribute("code", c.getId());
return "concept_details";
}
String message = "No match found.";
request.getSession().setAttribute("message", message);
return "message";
}
|
diff --git a/src/test/java/org/neo4j/index/lucene/TestRecovery.java b/src/test/java/org/neo4j/index/lucene/TestRecovery.java
index 6faf93c..8973742 100644
--- a/src/test/java/org/neo4j/index/lucene/TestRecovery.java
+++ b/src/test/java/org/neo4j/index/lucene/TestRecovery.java
@@ -1,206 +1,207 @@
/*
* Copyright (c) 2002-2009 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.index.lucene;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.junit.Test;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;
import org.neo4j.index.IndexService;
import org.neo4j.index.Neo4jTestCase;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import org.neo4j.kernel.impl.transaction.XidImpl;
/**
* Don't extend Neo4jTestCase since these tests restarts the db in the tests.
*/
public class TestRecovery
{
private String getDbPath()
{
return "target/var/recovery";
}
private GraphDatabaseService newGraphDbService()
{
String path = getDbPath();
Neo4jTestCase.deleteFileOrDirectory( new File( path ) );
return new EmbeddedGraphDatabase( path );
}
@Test
public void testRecovery() throws Exception
{
final GraphDatabaseService graphDb = newGraphDbService();
final IndexService index = new LuceneIndexService( graphDb );
graphDb.beginTx();
Node node = graphDb.createNode();
Random random = new Random();
Thread stopper = new Thread()
{
@Override public void run()
{
sleepNice( 1000 );
index.shutdown();
graphDb.shutdown();
}
};
try
{
stopper.start();
for ( int i = 0; i < 500; i++ )
{
index.index( node, "" + random.nextInt(), random.nextInt() );
sleepNice( 10 );
}
}
catch ( Exception e )
{
// Ok
}
sleepNice( 1000 );
final GraphDatabaseService newGraphDb =
new EmbeddedGraphDatabase( getDbPath() );
final IndexService newIndexService = new LuceneIndexService( newGraphDb );
sleepNice( 1000 );
newIndexService.shutdown();
newGraphDb.shutdown();
}
private static void sleepNice( long time )
{
try
{
Thread.sleep( time );
}
catch ( InterruptedException e )
{
// Ok
}
}
@Test
public void testReCommit() throws Exception
{
GraphDatabaseService graphDb = newGraphDbService();
IndexService idx = new LuceneIndexService( graphDb );
Transaction tx = graphDb.beginTx();
assertEquals( null, idx.getSingleNode( "test", "1" ) );
Node refNode = graphDb.getReferenceNode();
tx.finish();
idx.shutdown();
Map<Object,Object> params = new HashMap<Object,Object>();
String luceneDir = getDbPath() + "/lucene";
params.put( "dir", luceneDir );
+ params.put( "store_dir", getDbPath() );
LuceneDataSource xaDs = new LuceneDataSource( params );
LuceneXaConnection xaC = (LuceneXaConnection) xaDs.getXaConnection();
XAResource xaR = xaC.getXaResource();
Xid xid = new XidImpl( new byte[1], new byte[1] );
xaR.start( xid, XAResource.TMNOFLAGS );
xaC.index( refNode, "test", "1" );
xaR.end( xid, XAResource.TMSUCCESS );
xaR.prepare( xid );
xaR.commit( xid, false );
copyLogicalLog( luceneDir + "/lucene.log.active",
luceneDir + "/lucene.log.active.bak" );
copyLogicalLog( luceneDir + "/lucene.log.1",
luceneDir + "/lucene.log.1.bak" );
// test recovery re-commit
idx = new LuceneIndexService( graphDb );
tx = graphDb.beginTx();
assertEquals( refNode, idx.getSingleNode( "test", "1" ) );
tx.finish();
idx.shutdown();
assertTrue( new File( luceneDir + "/lucene.log.active" ).delete() );
// test recovery again on same log and only still only get 1 node
copyLogicalLog( luceneDir + "/lucene.log.active.bak",
luceneDir + "/lucene.log.active" );
copyLogicalLog( luceneDir + "/lucene.log.1.bak",
luceneDir + "/lucene.log.1" );
idx = new LuceneIndexService( graphDb );
tx = graphDb.beginTx();
assertEquals( refNode, idx.getSingleNode( "test", "1" ) );
tx.finish();
idx.shutdown();
graphDb.shutdown();
}
private void copyLogicalLog( String name, String copy ) throws IOException
{
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
assertTrue( new File( name ).exists() );
FileChannel source = new RandomAccessFile( name, "r" ).getChannel();
assertTrue( !new File( copy ).exists() );
FileChannel dest = new RandomAccessFile( copy, "rw" ).getChannel();
int read = -1;
do
{
read = source.read( buffer );
buffer.flip();
dest.write( buffer );
buffer.clear();
}
while ( read == 1024 );
source.close();
dest.close();
}
@Test
public void testRecoveryFulltextIndex()
{
GraphDatabaseService graphDb = new EmbeddedGraphDatabase(
"target/graphdb" );
LuceneFulltextIndexService idx = new LuceneFulltextIndexService(
graphDb );
Transaction tx = graphDb.beginTx();
try
{
Node node = graphDb.createNode();
idx.index( node, "test", "value" );
tx.success();
}
finally
{
// no tx commit
}
idx.shutdown();
graphDb.shutdown();
graphDb = new EmbeddedGraphDatabase( "target/graphdb" );
graphDb.shutdown();
}
}
| true | true | public void testReCommit() throws Exception
{
GraphDatabaseService graphDb = newGraphDbService();
IndexService idx = new LuceneIndexService( graphDb );
Transaction tx = graphDb.beginTx();
assertEquals( null, idx.getSingleNode( "test", "1" ) );
Node refNode = graphDb.getReferenceNode();
tx.finish();
idx.shutdown();
Map<Object,Object> params = new HashMap<Object,Object>();
String luceneDir = getDbPath() + "/lucene";
params.put( "dir", luceneDir );
LuceneDataSource xaDs = new LuceneDataSource( params );
LuceneXaConnection xaC = (LuceneXaConnection) xaDs.getXaConnection();
XAResource xaR = xaC.getXaResource();
Xid xid = new XidImpl( new byte[1], new byte[1] );
xaR.start( xid, XAResource.TMNOFLAGS );
xaC.index( refNode, "test", "1" );
xaR.end( xid, XAResource.TMSUCCESS );
xaR.prepare( xid );
xaR.commit( xid, false );
copyLogicalLog( luceneDir + "/lucene.log.active",
luceneDir + "/lucene.log.active.bak" );
copyLogicalLog( luceneDir + "/lucene.log.1",
luceneDir + "/lucene.log.1.bak" );
// test recovery re-commit
idx = new LuceneIndexService( graphDb );
tx = graphDb.beginTx();
assertEquals( refNode, idx.getSingleNode( "test", "1" ) );
tx.finish();
idx.shutdown();
assertTrue( new File( luceneDir + "/lucene.log.active" ).delete() );
// test recovery again on same log and only still only get 1 node
copyLogicalLog( luceneDir + "/lucene.log.active.bak",
luceneDir + "/lucene.log.active" );
copyLogicalLog( luceneDir + "/lucene.log.1.bak",
luceneDir + "/lucene.log.1" );
idx = new LuceneIndexService( graphDb );
tx = graphDb.beginTx();
assertEquals( refNode, idx.getSingleNode( "test", "1" ) );
tx.finish();
idx.shutdown();
graphDb.shutdown();
}
| public void testReCommit() throws Exception
{
GraphDatabaseService graphDb = newGraphDbService();
IndexService idx = new LuceneIndexService( graphDb );
Transaction tx = graphDb.beginTx();
assertEquals( null, idx.getSingleNode( "test", "1" ) );
Node refNode = graphDb.getReferenceNode();
tx.finish();
idx.shutdown();
Map<Object,Object> params = new HashMap<Object,Object>();
String luceneDir = getDbPath() + "/lucene";
params.put( "dir", luceneDir );
params.put( "store_dir", getDbPath() );
LuceneDataSource xaDs = new LuceneDataSource( params );
LuceneXaConnection xaC = (LuceneXaConnection) xaDs.getXaConnection();
XAResource xaR = xaC.getXaResource();
Xid xid = new XidImpl( new byte[1], new byte[1] );
xaR.start( xid, XAResource.TMNOFLAGS );
xaC.index( refNode, "test", "1" );
xaR.end( xid, XAResource.TMSUCCESS );
xaR.prepare( xid );
xaR.commit( xid, false );
copyLogicalLog( luceneDir + "/lucene.log.active",
luceneDir + "/lucene.log.active.bak" );
copyLogicalLog( luceneDir + "/lucene.log.1",
luceneDir + "/lucene.log.1.bak" );
// test recovery re-commit
idx = new LuceneIndexService( graphDb );
tx = graphDb.beginTx();
assertEquals( refNode, idx.getSingleNode( "test", "1" ) );
tx.finish();
idx.shutdown();
assertTrue( new File( luceneDir + "/lucene.log.active" ).delete() );
// test recovery again on same log and only still only get 1 node
copyLogicalLog( luceneDir + "/lucene.log.active.bak",
luceneDir + "/lucene.log.active" );
copyLogicalLog( luceneDir + "/lucene.log.1.bak",
luceneDir + "/lucene.log.1" );
idx = new LuceneIndexService( graphDb );
tx = graphDb.beginTx();
assertEquals( refNode, idx.getSingleNode( "test", "1" ) );
tx.finish();
idx.shutdown();
graphDb.shutdown();
}
|
diff --git a/android-service-sample/src/com/pannous/vaservice/sample/VoiceActionsService.java b/android-service-sample/src/com/pannous/vaservice/sample/VoiceActionsService.java
index 08de2bf..3645b19 100644
--- a/android-service-sample/src/com/pannous/vaservice/sample/VoiceActionsService.java
+++ b/android-service-sample/src/com/pannous/vaservice/sample/VoiceActionsService.java
@@ -1,144 +1,145 @@
package com.pannous.vaservice.sample;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Handler;
import android.util.Log;
/**
* @author Peter Karich
*/
public class VoiceActionsService extends Handler {
protected int timeout = 5000;
public String text;
public List<String> imageUrls = new ArrayList<String>();
public VoiceActionsService(int timeout) {
this.timeout = timeout;
}
public String getText() {
return text;
}
public String getImageUrl() {
if (imageUrls.isEmpty())
return "";
return imageUrls.get(0);
}
public void runJeannie(String input, String location, String lang,
String hashedId) {
if (location == null)
location = "";
try {
input = URLEncoder.encode(input, "UTF-8");
} catch (Exception ex) {
}
int timeZoneInMinutes = TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 1000 / 60;
- // TODO add client features: show-urls, reminder, ...
+ // TODO add ping https://weannie.pannous.com/ping
+ // TODO add more client features: open-url, reminder, ...
// see API Documentation & demo at https://weannie.pannous.com/demo/
String voiceActionsUrl = "https://weannie.pannous.com/api?input=" + input
+ "&clientFeatures=say,show-images"
//
+ "&locale=" + lang
//
+ "&timeZone=" + timeZoneInMinutes
//
+ "&location=" + location
// TODO use your production key here!
+ "&login=test-user";
imageUrls.clear();
String resultStr = "";
try {
log(voiceActionsUrl);
URLConnection conn = new URL(voiceActionsUrl).openConnection();
conn.setDoOutput(true);
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
conn.setRequestProperty("Set-Cookie", "id=" + hashedId
+ ";Domain=.pannous.com;Path=/;Secure");
resultStr = Helper.streamToString(conn.getInputStream(), "UTF-8");
} catch (Exception ex) {
err(ex);
text = "Problem " + ex.getMessage();
return;
}
try {
if (resultStr == null || resultStr.length() == 0) {
text = "VoiceActions returned empty response!?";
return;
}
JSONArray outputJson = new JSONObject(resultStr)
.getJSONArray("output");
if (outputJson.length() == 0) {
text = "Sorry, nothing found";
return;
}
JSONObject firstHandler = outputJson.getJSONObject(0);
- if (firstHandler.has("errorMessage")) {
+ if (firstHandler.has("errorMessage") && firstHandler.getString("errorMessage").length() > 0) {
throw new RuntimeException("Server side error: "
+ firstHandler.getString("errorMessage"));
}
JSONObject actions = firstHandler.getJSONObject("actions");
if (actions.has("say")) {
Object obj = actions.get("say");
if (obj instanceof JSONObject) {
JSONObject sObj = (JSONObject) obj;
text = sObj.getString("text");
JSONArray arr = sObj.getJSONArray("moreText");
for (int i = 0; i < arr.length(); i++) {
text += " " + arr.getString(i);
}
} else {
text = obj.toString();
}
}
if (actions.has("show")
&& actions.getJSONObject("show").has("images")) {
JSONArray arr = actions.getJSONObject("show").getJSONArray(
"images");
for (int i = 0; i < arr.length(); i++) {
imageUrls.add(arr.getString(i));
}
}
log("text:" + text);
// log("result:"+result);
} catch (Exception ex) {
err(ex);
text = "Problem while parsing json " + ex.getMessage();
return;
}
}
public void log(String str) {
Log.i("VoiceActions", str);
}
public void err(Exception exc) {
Log.e("VoiceActions", "Problem", exc);
}
public void err(String str) {
Log.e("VoiceActions", str);
}
}
| false | true | public void runJeannie(String input, String location, String lang,
String hashedId) {
if (location == null)
location = "";
try {
input = URLEncoder.encode(input, "UTF-8");
} catch (Exception ex) {
}
int timeZoneInMinutes = TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 1000 / 60;
// TODO add client features: show-urls, reminder, ...
// see API Documentation & demo at https://weannie.pannous.com/demo/
String voiceActionsUrl = "https://weannie.pannous.com/api?input=" + input
+ "&clientFeatures=say,show-images"
//
+ "&locale=" + lang
//
+ "&timeZone=" + timeZoneInMinutes
//
+ "&location=" + location
// TODO use your production key here!
+ "&login=test-user";
imageUrls.clear();
String resultStr = "";
try {
log(voiceActionsUrl);
URLConnection conn = new URL(voiceActionsUrl).openConnection();
conn.setDoOutput(true);
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
conn.setRequestProperty("Set-Cookie", "id=" + hashedId
+ ";Domain=.pannous.com;Path=/;Secure");
resultStr = Helper.streamToString(conn.getInputStream(), "UTF-8");
} catch (Exception ex) {
err(ex);
text = "Problem " + ex.getMessage();
return;
}
try {
if (resultStr == null || resultStr.length() == 0) {
text = "VoiceActions returned empty response!?";
return;
}
JSONArray outputJson = new JSONObject(resultStr)
.getJSONArray("output");
if (outputJson.length() == 0) {
text = "Sorry, nothing found";
return;
}
JSONObject firstHandler = outputJson.getJSONObject(0);
if (firstHandler.has("errorMessage")) {
throw new RuntimeException("Server side error: "
+ firstHandler.getString("errorMessage"));
}
JSONObject actions = firstHandler.getJSONObject("actions");
if (actions.has("say")) {
Object obj = actions.get("say");
if (obj instanceof JSONObject) {
JSONObject sObj = (JSONObject) obj;
text = sObj.getString("text");
JSONArray arr = sObj.getJSONArray("moreText");
for (int i = 0; i < arr.length(); i++) {
text += " " + arr.getString(i);
}
} else {
text = obj.toString();
}
}
if (actions.has("show")
&& actions.getJSONObject("show").has("images")) {
JSONArray arr = actions.getJSONObject("show").getJSONArray(
"images");
for (int i = 0; i < arr.length(); i++) {
imageUrls.add(arr.getString(i));
}
}
log("text:" + text);
// log("result:"+result);
} catch (Exception ex) {
err(ex);
text = "Problem while parsing json " + ex.getMessage();
return;
}
}
| public void runJeannie(String input, String location, String lang,
String hashedId) {
if (location == null)
location = "";
try {
input = URLEncoder.encode(input, "UTF-8");
} catch (Exception ex) {
}
int timeZoneInMinutes = TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 1000 / 60;
// TODO add ping https://weannie.pannous.com/ping
// TODO add more client features: open-url, reminder, ...
// see API Documentation & demo at https://weannie.pannous.com/demo/
String voiceActionsUrl = "https://weannie.pannous.com/api?input=" + input
+ "&clientFeatures=say,show-images"
//
+ "&locale=" + lang
//
+ "&timeZone=" + timeZoneInMinutes
//
+ "&location=" + location
// TODO use your production key here!
+ "&login=test-user";
imageUrls.clear();
String resultStr = "";
try {
log(voiceActionsUrl);
URLConnection conn = new URL(voiceActionsUrl).openConnection();
conn.setDoOutput(true);
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
conn.setRequestProperty("Set-Cookie", "id=" + hashedId
+ ";Domain=.pannous.com;Path=/;Secure");
resultStr = Helper.streamToString(conn.getInputStream(), "UTF-8");
} catch (Exception ex) {
err(ex);
text = "Problem " + ex.getMessage();
return;
}
try {
if (resultStr == null || resultStr.length() == 0) {
text = "VoiceActions returned empty response!?";
return;
}
JSONArray outputJson = new JSONObject(resultStr)
.getJSONArray("output");
if (outputJson.length() == 0) {
text = "Sorry, nothing found";
return;
}
JSONObject firstHandler = outputJson.getJSONObject(0);
if (firstHandler.has("errorMessage") && firstHandler.getString("errorMessage").length() > 0) {
throw new RuntimeException("Server side error: "
+ firstHandler.getString("errorMessage"));
}
JSONObject actions = firstHandler.getJSONObject("actions");
if (actions.has("say")) {
Object obj = actions.get("say");
if (obj instanceof JSONObject) {
JSONObject sObj = (JSONObject) obj;
text = sObj.getString("text");
JSONArray arr = sObj.getJSONArray("moreText");
for (int i = 0; i < arr.length(); i++) {
text += " " + arr.getString(i);
}
} else {
text = obj.toString();
}
}
if (actions.has("show")
&& actions.getJSONObject("show").has("images")) {
JSONArray arr = actions.getJSONObject("show").getJSONArray(
"images");
for (int i = 0; i < arr.length(); i++) {
imageUrls.add(arr.getString(i));
}
}
log("text:" + text);
// log("result:"+result);
} catch (Exception ex) {
err(ex);
text = "Problem while parsing json " + ex.getMessage();
return;
}
}
|
diff --git a/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/RequestProcessor.java b/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/RequestProcessor.java
index b32e119ad..8b6c153da 100644
--- a/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/RequestProcessor.java
+++ b/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/RequestProcessor.java
@@ -1,583 +1,583 @@
package com.octo.android.robospice.request;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import roboguice.util.temp.Ln;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import com.octo.android.robospice.SpiceService;
import com.octo.android.robospice.exception.NetworkException;
import com.octo.android.robospice.exception.NoNetworkException;
import com.octo.android.robospice.exception.RequestCancelledException;
import com.octo.android.robospice.networkstate.NetworkStateChecker;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.ICacheManager;
import com.octo.android.robospice.persistence.exception.CacheCreationException;
import com.octo.android.robospice.persistence.exception.CacheLoadingException;
import com.octo.android.robospice.persistence.exception.CacheSavingException;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.priority.PriorityRunnable;
import com.octo.android.robospice.request.listener.RequestCancellationListener;
import com.octo.android.robospice.request.listener.RequestListener;
import com.octo.android.robospice.request.listener.RequestProgress;
import com.octo.android.robospice.request.listener.RequestProgressListener;
import com.octo.android.robospice.request.listener.RequestStatus;
import com.octo.android.robospice.request.listener.SpiceServiceServiceListener;
/**
* Delegate class of the {@link SpiceService}, easier to test than an Android
* {@link Service}.
* @author jva
*/
public class RequestProcessor {
// ============================================================================================
// ATTRIBUTES
// ============================================================================================
private final Map<CachedSpiceRequest<?>, Set<RequestListener<?>>> mapRequestToRequestListener = Collections.synchronizedMap(new LinkedHashMap<CachedSpiceRequest<?>, Set<RequestListener<?>>>());
/**
* Thanks Olivier Croiser from Zenika for his excellent <a href=
* "http://blog.zenika.com/index.php?post/2012/04/11/Introduction-programmation-concurrente-Java-2sur2. "
* >blog article</a>.
*/
private ExecutorService executorService = null;
private final ICacheManager cacheManager;
private final Handler handlerResponse;
private final Context applicationContext;
private boolean failOnCacheError;
private final Set<SpiceServiceServiceListener> spiceServiceListenerSet;
private final RequestProcessorListener requestProcessorListener;
private final NetworkStateChecker networkStateChecker;
// ============================================================================================
// CONSTRUCTOR
// ============================================================================================
/**
* Build a request processor using a custom. This feature has been
* implemented follwing a feature request from Riccardo Ciovati.
* @param context
* the context on which {@link SpiceRequest} will provide their
* results.
* @param cacheManager
* the {@link CacheManager} that will be used to retrieve
* requests' result and store them.
* @param executorService
* a custom {@link ExecutorService} that will be used to execute
* {@link SpiceRequest} .
* @param requestProcessorListener
* a listener of the {@link RequestProcessor}, it will be
* notified when no more requests are left, typically allowing
* the {@link SpiceService} to stop itself.
*/
public RequestProcessor(final Context context, final ICacheManager cacheManager, final ExecutorService executorService, final RequestProcessorListener requestProcessorListener,
final NetworkStateChecker networkStateChecker) {
this.applicationContext = context;
this.cacheManager = cacheManager;
this.requestProcessorListener = requestProcessorListener;
this.networkStateChecker = networkStateChecker;
handlerResponse = new Handler(Looper.getMainLooper());
spiceServiceListenerSet = Collections.synchronizedSet(new HashSet<SpiceServiceServiceListener>());
this.executorService = executorService;
this.networkStateChecker.checkPermissions(context);
}
// ============================================================================================
// PUBLIC
// ============================================================================================
public void addRequest(final CachedSpiceRequest<?> request, final Set<RequestListener<?>> listRequestListener) {
Ln.d("Adding request to queue " + hashCode() + ": " + request + " size is " + mapRequestToRequestListener.size());
if (request.isCancelled()) {
synchronized (mapRequestToRequestListener) {
for (final CachedSpiceRequest<?> cachedSpiceRequest : mapRequestToRequestListener.keySet()) {
if (cachedSpiceRequest.equals(request)) {
cachedSpiceRequest.cancel();
return;
}
}
}
}
boolean aggregated = false;
if (listRequestListener != null) {
Set<RequestListener<?>> listRequestListenerForThisRequest = mapRequestToRequestListener.get(request);
if (listRequestListenerForThisRequest == null) {
if (request.isProcessable()) {
Ln.d("Adding entry for type %s and cacheKey %s.", request.getResultType(), request.getRequestCacheKey());
listRequestListenerForThisRequest = new HashSet<RequestListener<?>>();
this.mapRequestToRequestListener.put(request, listRequestListenerForThisRequest);
}
} else {
Ln.d("Request for type %s and cacheKey %s already exists.", request.getResultType(), request.getRequestCacheKey());
aggregated = true;
}
if (listRequestListenerForThisRequest != null) {
listRequestListenerForThisRequest.addAll(listRequestListener);
}
if (request.isProcessable()) {
notifyListenersOfRequestProgress(request, listRequestListener, request.getProgress());
}
}
if (aggregated) {
return;
}
final RequestCancellationListener requestCancellationListener = new RequestCancellationListener() {
@Override
public void onRequestCancelled() {
mapRequestToRequestListener.remove(request);
notifyListenersOfRequestCancellation(request, listRequestListener);
}
};
request.setRequestCancellationListener(requestCancellationListener);
if (request.isCancelled()) {
mapRequestToRequestListener.remove(request);
notifyListenersOfRequestCancellation(request, listRequestListener);
return;
} else if (!request.isProcessable()) {
notifyOfRequestProcessed(request);
return;
} else {
planRequestExecution(request);
}
}
private static String getTimeString(long millis) {
return String.format("%02d ms", millis);
}
private void printRequestProcessingDuration(long startTime, CachedSpiceRequest<?> request) {
Ln.d("It tooks %s to process request %s.", getTimeString(System.currentTimeMillis() - startTime), request.toString());
}
protected <T> void processRequest(final CachedSpiceRequest<T> request) {
final long startTime = System.currentTimeMillis();
Ln.d("Processing request : " + request);
T result = null;
// add a progress listener to the request to be notified of
// progress during load data from network
final RequestProgressListener requestProgressListener = new RequestProgressListener() {
@Override
public void onRequestProgressUpdate(final RequestProgress progress) {
final Set<RequestListener<?>> listeners = mapRequestToRequestListener.get(request);
notifyListenersOfRequestProgress(request, listeners, progress);
}
};
request.setRequestProgressListener(requestProgressListener);
if (request.getRequestCacheKey() != null && request.getCacheDuration() != DurationInMillis.ALWAYS_EXPIRED) {
// First, search data in cache
try {
Ln.d("Loading request from cache : " + request);
request.setStatus(RequestStatus.READING_FROM_CACHE);
result = loadDataFromCache(request.getResultType(), request.getRequestCacheKey(), request.getCacheDuration());
// if something is found in cache, fire result and finish
// request
if (result != null) {
Ln.d("Request loaded from cache : " + request + " result=" + result);
notifyListenersOfRequestSuccess(request, result);
printRequestProcessingDuration(startTime, request);
return;
} else if (request.isAcceptingDirtyCache()) {
// as a fallback, some request may accept whatever is in the
// cache but still
// want an update from network.
result = loadDataFromCache(request.getResultType(), request.getRequestCacheKey(), DurationInMillis.ALWAYS_RETURNED);
if (result != null) {
notifyListenersOfRequestSuccessButDontCompleteRequest(request, result);
}
}
} catch (final SpiceException e) {
Ln.d(e, "Cache file could not be read.");
if (failOnCacheError) {
handleRetry(request, e);
printRequestProcessingDuration(startTime, request);
return;
}
cacheManager.removeDataFromCache(request.getResultType(), request.getRequestCacheKey());
Ln.d(e, "Cache file deleted.");
}
}
// if result is not in cache, load data from network
Ln.d("Cache content not available or expired or disabled");
if (!isNetworkAvailable(applicationContext) && !request.isOffline()) {
Ln.e("Network is down.");
handleRetry(request, new NoNetworkException());
printRequestProcessingDuration(startTime, request);
return;
}
// network is ok, load data from network
try {
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
Ln.d("Calling netwok request.");
request.setStatus(RequestStatus.LOADING_FROM_NETWORK);
result = request.loadDataFromNetwork();
Ln.d("Network request call ended.");
} catch (final Exception e) {
if (!request.isCancelled()) {
Ln.e(e, "An exception occured during request network execution :" + e.getMessage());
handleRetry(request, new NetworkException("Exception occured during invocation of web service.", e));
} else {
Ln.e("An exception occured during request network execution but request was cancelled, so listeners are not called.");
}
printRequestProcessingDuration(startTime, request);
return;
}
if (result != null && request.getRequestCacheKey() != null) {
// request worked and result is not null, save
// it to cache
try {
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
Ln.d("Start caching content...");
request.setStatus(RequestStatus.WRITING_TO_CACHE);
result = saveDataToCacheAndReturnData(result, request.getRequestCacheKey());
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
notifyListenersOfRequestSuccess(request, result);
printRequestProcessingDuration(startTime, request);
return;
} catch (final SpiceException e) {
- Ln.d("An exception occured during service execution :" + e.getMessage(), e);
+ Ln.d("An exception occured during service execution :" + e.getMessage());
if (failOnCacheError) {
handleRetry(request, e);
printRequestProcessingDuration(startTime, request);
return;
} else {
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
// result can't be saved to
// cache but we reached that
// point after a success of load
// data from
// network
notifyListenersOfRequestSuccess(request, result);
}
cacheManager.removeDataFromCache(request.getResultType(), request.getRequestCacheKey());
Ln.d(e, "Cache file deleted.");
}
} else {
// result can't be saved to cache but we reached
// that point after a success of load data from
// network
notifyListenersOfRequestSuccess(request, result);
printRequestProcessingDuration(startTime, request);
return;
}
}
private void planRequestExecution(final CachedSpiceRequest<?> request) {
Future<?> future = executorService.submit(new PriorityRunnable() {
@Override
public void run() {
try {
processRequest(request);
} catch (final Throwable t) {
Ln.d(t, "An unexpected error occured when processsing request %s", request.toString());
} finally {
request.setRequestCancellationListener(null);
}
}
@Override
public int getPriority() {
return request.getPriority();
}
});
request.setFuture(future);
}
private void handleRetry(final CachedSpiceRequest<?> request, final SpiceException e) {
if (request.getRetryPolicy() != null) {
request.getRetryPolicy().retry(e);
if (request.getRetryPolicy().getRetryCount() > 0) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(request.getRetryPolicy().getDelayBeforeRetry());
planRequestExecution(request);
} catch (InterruptedException e) {
Ln.e(e, "Retry attempt failed for request " + request);
}
}
}).start();
return;
}
}
notifyListenersOfRequestFailure(request, e);
}
private void post(final Runnable r, final Object token) {
handlerResponse.postAtTime(r, token, SystemClock.uptimeMillis());
}
private <T> void notifyListenersOfRequestProgress(final CachedSpiceRequest<?> request, final Set<RequestListener<?>> listeners, final RequestStatus status) {
notifyListenersOfRequestProgress(request, listeners, new RequestProgress(status));
}
private <T> void notifyListenersOfRequestProgress(final CachedSpiceRequest<?> request, final Set<RequestListener<?>> listeners, final RequestProgress progress) {
Ln.d("Sending progress %s", progress.getStatus());
post(new ProgressRunnable(listeners, progress), request.getRequestCacheKey());
checkAllRequestComplete();
}
private void checkAllRequestComplete() {
if (mapRequestToRequestListener.isEmpty()) {
requestProcessorListener.allRequestComplete();
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> void notifyListenersOfRequestSuccessButDontCompleteRequest(final CachedSpiceRequest<T> request, final T result) {
final Set<RequestListener<?>> listeners = mapRequestToRequestListener.get(request);
post(new ResultRunnable(listeners, result), request.getRequestCacheKey());
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> void notifyListenersOfRequestSuccess(final CachedSpiceRequest<T> request, final T result) {
final Set<RequestListener<?>> listeners = mapRequestToRequestListener.get(request);
notifyListenersOfRequestProgress(request, listeners, RequestStatus.COMPLETE);
post(new ResultRunnable(listeners, result), request.getRequestCacheKey());
notifyOfRequestProcessed(request);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private <T> void notifyListenersOfRequestFailure(final CachedSpiceRequest<T> request, final SpiceException e) {
final Set<RequestListener<?>> listeners = mapRequestToRequestListener.get(request);
notifyListenersOfRequestProgress(request, listeners, RequestStatus.COMPLETE);
post(new ResultRunnable(listeners, e), request.getRequestCacheKey());
notifyOfRequestProcessed(request);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void notifyListenersOfRequestCancellation(final CachedSpiceRequest<?> request, final Set<RequestListener<?>> listeners) {
Ln.d("Not calling network request : " + request + " as it is cancelled. ");
notifyListenersOfRequestProgress(request, listeners, RequestStatus.COMPLETE);
post(new ResultRunnable(listeners, new RequestCancelledException("Request has been cancelled explicitely.")), request.getRequestCacheKey());
notifyOfRequestProcessed(request);
}
/**
* Disable request listeners notifications for a specific request.<br/>
* All listeners associated to this request won't be called when request
* will finish.<br/>
* @param request
* Request on which you want to disable listeners
* @param listRequestListener
* the collection of listeners associated to request not to be
* notified
*/
public void dontNotifyRequestListenersForRequest(final CachedSpiceRequest<?> request, final Collection<RequestListener<?>> listRequestListener) {
handlerResponse.removeCallbacksAndMessages(request.getRequestCacheKey());
final Set<RequestListener<?>> setRequestListener = mapRequestToRequestListener.get(request);
if (setRequestListener != null && listRequestListener != null) {
Ln.d("Removing listeners of request : " + request.toString() + " : " + setRequestListener.size());
setRequestListener.removeAll(listRequestListener);
}
}
/**
* @return true if network is available.
*/
public boolean isNetworkAvailable(final Context context) {
return networkStateChecker.isNetworkAvailable(context);
}
public void checkPermissions(final Context context) {
networkStateChecker.checkPermissions(context);
}
public static boolean hasNetworkPermission(final Context context) {
return context.getPackageManager().checkPermission("android.permission.INTERNET", context.getPackageName()) == PackageManager.PERMISSION_GRANTED;
}
public boolean removeDataFromCache(final Class<?> clazz, final Object cacheKey) {
return cacheManager.removeDataFromCache(clazz, cacheKey);
}
public void removeAllDataFromCache(final Class<?> clazz) {
cacheManager.removeAllDataFromCache(clazz);
}
public void removeAllDataFromCache() {
cacheManager.removeAllDataFromCache();
}
public boolean isFailOnCacheError() {
return failOnCacheError;
}
public void setFailOnCacheError(final boolean failOnCacheError) {
this.failOnCacheError = failOnCacheError;
}
// ============================================================================================
// PRIVATE
// ============================================================================================
private <T> T loadDataFromCache(final Class<T> clazz, final Object cacheKey, final long maxTimeInCacheBeforeExpiry) throws CacheLoadingException, CacheCreationException {
return cacheManager.loadDataFromCache(clazz, cacheKey, maxTimeInCacheBeforeExpiry);
}
private <T> T saveDataToCacheAndReturnData(final T data, final Object cacheKey) throws CacheSavingException, CacheCreationException {
return cacheManager.saveDataToCacheAndReturnData(data, cacheKey);
}
private static class ProgressRunnable implements Runnable {
private final RequestProgress progress;
private final Set<RequestListener<?>> listeners;
public ProgressRunnable(final Set<RequestListener<?>> listeners, final RequestProgress progress) {
this.progress = progress;
this.listeners = listeners;
}
@Override
public void run() {
if (listeners == null) {
return;
}
Ln.v("Notifying " + listeners.size() + " listeners of progress " + progress);
for (final RequestListener<?> listener : listeners) {
if (listener != null && listener instanceof RequestProgressListener) {
Ln.v("Notifying %s", listener.getClass().getSimpleName());
((RequestProgressListener) listener).onRequestProgressUpdate(progress);
}
}
}
}
private static class ResultRunnable<T> implements Runnable {
private SpiceException spiceException;
private T result;
private final Set<RequestListener<?>> listeners;
public ResultRunnable(final Set<RequestListener<?>> listeners, final T result) {
this.result = result;
this.listeners = listeners;
}
public ResultRunnable(final Set<RequestListener<?>> listeners, final SpiceException spiceException) {
this.spiceException = spiceException;
this.listeners = listeners;
}
@Override
public void run() {
if (listeners == null) {
return;
}
final String resultMsg = spiceException == null ? "success" : "failure";
Ln.v("Notifying " + listeners.size() + " listeners of request " + resultMsg);
for (final RequestListener<?> listener : listeners) {
if (listener != null) {
@SuppressWarnings("unchecked")
final RequestListener<T> listenerOfT = (RequestListener<T>) listener;
Ln.v("Notifying %s", listener.getClass().getSimpleName());
if (spiceException == null) {
listenerOfT.onRequestSuccess(result);
} else {
listener.onRequestFailure(spiceException);
}
}
}
}
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('[');
stringBuilder.append(getClass().getName());
stringBuilder.append(" : ");
stringBuilder.append(" request count= ");
stringBuilder.append(mapRequestToRequestListener.keySet().size());
stringBuilder.append(", listeners per requests = [");
for (final Map.Entry<CachedSpiceRequest<?>, Set<RequestListener<?>>> entry : mapRequestToRequestListener.entrySet()) {
stringBuilder.append(entry.getKey().getClass().getName());
stringBuilder.append(":");
stringBuilder.append(entry.getKey());
stringBuilder.append(" --> ");
if (entry.getValue() == null) {
stringBuilder.append(entry.getValue());
} else {
stringBuilder.append(entry.getValue().size());
}
}
stringBuilder.append(']');
stringBuilder.append(']');
return stringBuilder.toString();
}
public void addSpiceServiceListener(final SpiceServiceServiceListener spiceServiceServiceListener) {
this.spiceServiceListenerSet.add(spiceServiceServiceListener);
}
public void removeSpiceServiceListener(final SpiceServiceServiceListener spiceServiceServiceListener) {
this.spiceServiceListenerSet.add(spiceServiceServiceListener);
}
protected void notifyOfRequestProcessed(final CachedSpiceRequest<?> request) {
Ln.v("Removing %s size is %d", request, mapRequestToRequestListener.size());
mapRequestToRequestListener.remove(request);
checkAllRequestComplete();
synchronized (spiceServiceListenerSet) {
for (final SpiceServiceServiceListener spiceServiceServiceListener : spiceServiceListenerSet) {
spiceServiceServiceListener.onRequestProcessed(request);
}
}
}
public int getPendingRequestCount() {
return mapRequestToRequestListener.keySet().size();
}
}
| true | true | protected <T> void processRequest(final CachedSpiceRequest<T> request) {
final long startTime = System.currentTimeMillis();
Ln.d("Processing request : " + request);
T result = null;
// add a progress listener to the request to be notified of
// progress during load data from network
final RequestProgressListener requestProgressListener = new RequestProgressListener() {
@Override
public void onRequestProgressUpdate(final RequestProgress progress) {
final Set<RequestListener<?>> listeners = mapRequestToRequestListener.get(request);
notifyListenersOfRequestProgress(request, listeners, progress);
}
};
request.setRequestProgressListener(requestProgressListener);
if (request.getRequestCacheKey() != null && request.getCacheDuration() != DurationInMillis.ALWAYS_EXPIRED) {
// First, search data in cache
try {
Ln.d("Loading request from cache : " + request);
request.setStatus(RequestStatus.READING_FROM_CACHE);
result = loadDataFromCache(request.getResultType(), request.getRequestCacheKey(), request.getCacheDuration());
// if something is found in cache, fire result and finish
// request
if (result != null) {
Ln.d("Request loaded from cache : " + request + " result=" + result);
notifyListenersOfRequestSuccess(request, result);
printRequestProcessingDuration(startTime, request);
return;
} else if (request.isAcceptingDirtyCache()) {
// as a fallback, some request may accept whatever is in the
// cache but still
// want an update from network.
result = loadDataFromCache(request.getResultType(), request.getRequestCacheKey(), DurationInMillis.ALWAYS_RETURNED);
if (result != null) {
notifyListenersOfRequestSuccessButDontCompleteRequest(request, result);
}
}
} catch (final SpiceException e) {
Ln.d(e, "Cache file could not be read.");
if (failOnCacheError) {
handleRetry(request, e);
printRequestProcessingDuration(startTime, request);
return;
}
cacheManager.removeDataFromCache(request.getResultType(), request.getRequestCacheKey());
Ln.d(e, "Cache file deleted.");
}
}
// if result is not in cache, load data from network
Ln.d("Cache content not available or expired or disabled");
if (!isNetworkAvailable(applicationContext) && !request.isOffline()) {
Ln.e("Network is down.");
handleRetry(request, new NoNetworkException());
printRequestProcessingDuration(startTime, request);
return;
}
// network is ok, load data from network
try {
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
Ln.d("Calling netwok request.");
request.setStatus(RequestStatus.LOADING_FROM_NETWORK);
result = request.loadDataFromNetwork();
Ln.d("Network request call ended.");
} catch (final Exception e) {
if (!request.isCancelled()) {
Ln.e(e, "An exception occured during request network execution :" + e.getMessage());
handleRetry(request, new NetworkException("Exception occured during invocation of web service.", e));
} else {
Ln.e("An exception occured during request network execution but request was cancelled, so listeners are not called.");
}
printRequestProcessingDuration(startTime, request);
return;
}
if (result != null && request.getRequestCacheKey() != null) {
// request worked and result is not null, save
// it to cache
try {
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
Ln.d("Start caching content...");
request.setStatus(RequestStatus.WRITING_TO_CACHE);
result = saveDataToCacheAndReturnData(result, request.getRequestCacheKey());
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
notifyListenersOfRequestSuccess(request, result);
printRequestProcessingDuration(startTime, request);
return;
} catch (final SpiceException e) {
Ln.d("An exception occured during service execution :" + e.getMessage(), e);
if (failOnCacheError) {
handleRetry(request, e);
printRequestProcessingDuration(startTime, request);
return;
} else {
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
// result can't be saved to
// cache but we reached that
// point after a success of load
// data from
// network
notifyListenersOfRequestSuccess(request, result);
}
cacheManager.removeDataFromCache(request.getResultType(), request.getRequestCacheKey());
Ln.d(e, "Cache file deleted.");
}
} else {
// result can't be saved to cache but we reached
// that point after a success of load data from
// network
notifyListenersOfRequestSuccess(request, result);
printRequestProcessingDuration(startTime, request);
return;
}
}
| protected <T> void processRequest(final CachedSpiceRequest<T> request) {
final long startTime = System.currentTimeMillis();
Ln.d("Processing request : " + request);
T result = null;
// add a progress listener to the request to be notified of
// progress during load data from network
final RequestProgressListener requestProgressListener = new RequestProgressListener() {
@Override
public void onRequestProgressUpdate(final RequestProgress progress) {
final Set<RequestListener<?>> listeners = mapRequestToRequestListener.get(request);
notifyListenersOfRequestProgress(request, listeners, progress);
}
};
request.setRequestProgressListener(requestProgressListener);
if (request.getRequestCacheKey() != null && request.getCacheDuration() != DurationInMillis.ALWAYS_EXPIRED) {
// First, search data in cache
try {
Ln.d("Loading request from cache : " + request);
request.setStatus(RequestStatus.READING_FROM_CACHE);
result = loadDataFromCache(request.getResultType(), request.getRequestCacheKey(), request.getCacheDuration());
// if something is found in cache, fire result and finish
// request
if (result != null) {
Ln.d("Request loaded from cache : " + request + " result=" + result);
notifyListenersOfRequestSuccess(request, result);
printRequestProcessingDuration(startTime, request);
return;
} else if (request.isAcceptingDirtyCache()) {
// as a fallback, some request may accept whatever is in the
// cache but still
// want an update from network.
result = loadDataFromCache(request.getResultType(), request.getRequestCacheKey(), DurationInMillis.ALWAYS_RETURNED);
if (result != null) {
notifyListenersOfRequestSuccessButDontCompleteRequest(request, result);
}
}
} catch (final SpiceException e) {
Ln.d(e, "Cache file could not be read.");
if (failOnCacheError) {
handleRetry(request, e);
printRequestProcessingDuration(startTime, request);
return;
}
cacheManager.removeDataFromCache(request.getResultType(), request.getRequestCacheKey());
Ln.d(e, "Cache file deleted.");
}
}
// if result is not in cache, load data from network
Ln.d("Cache content not available or expired or disabled");
if (!isNetworkAvailable(applicationContext) && !request.isOffline()) {
Ln.e("Network is down.");
handleRetry(request, new NoNetworkException());
printRequestProcessingDuration(startTime, request);
return;
}
// network is ok, load data from network
try {
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
Ln.d("Calling netwok request.");
request.setStatus(RequestStatus.LOADING_FROM_NETWORK);
result = request.loadDataFromNetwork();
Ln.d("Network request call ended.");
} catch (final Exception e) {
if (!request.isCancelled()) {
Ln.e(e, "An exception occured during request network execution :" + e.getMessage());
handleRetry(request, new NetworkException("Exception occured during invocation of web service.", e));
} else {
Ln.e("An exception occured during request network execution but request was cancelled, so listeners are not called.");
}
printRequestProcessingDuration(startTime, request);
return;
}
if (result != null && request.getRequestCacheKey() != null) {
// request worked and result is not null, save
// it to cache
try {
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
Ln.d("Start caching content...");
request.setStatus(RequestStatus.WRITING_TO_CACHE);
result = saveDataToCacheAndReturnData(result, request.getRequestCacheKey());
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
notifyListenersOfRequestSuccess(request, result);
printRequestProcessingDuration(startTime, request);
return;
} catch (final SpiceException e) {
Ln.d("An exception occured during service execution :" + e.getMessage());
if (failOnCacheError) {
handleRetry(request, e);
printRequestProcessingDuration(startTime, request);
return;
} else {
if (request.isCancelled()) {
printRequestProcessingDuration(startTime, request);
return;
}
// result can't be saved to
// cache but we reached that
// point after a success of load
// data from
// network
notifyListenersOfRequestSuccess(request, result);
}
cacheManager.removeDataFromCache(request.getResultType(), request.getRequestCacheKey());
Ln.d(e, "Cache file deleted.");
}
} else {
// result can't be saved to cache but we reached
// that point after a success of load data from
// network
notifyListenersOfRequestSuccess(request, result);
printRequestProcessingDuration(startTime, request);
return;
}
}
|
diff --git a/src/com/android/music/MediaPlaybackService.java b/src/com/android/music/MediaPlaybackService.java
index a035eaa..2977a3f 100644
--- a/src/com/android/music/MediaPlaybackService.java
+++ b/src/com/android/music/MediaPlaybackService.java
@@ -1,2525 +1,2525 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.music;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.preference.PreferenceManager;
import android.media.audiofx.AudioEffect;
import android.media.AudioManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.os.PowerManager.WakeLock;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AudioColumns;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;
import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.util.Random;
import java.util.Vector;
import android.provider.Settings;
/**
* Provides "background" audio playback capabilities, allowing the
* user to switch between activities without stopping playback.
*/
public class MediaPlaybackService extends Service implements
SensorEventListener, Shaker.Callback {
/** used to specify whether enqueue() should start playing
* the new list of files right away, next or once all the currently
* queued files have been played
*/
public static final int NOW = 1;
public static final int NEXT = 2;
public static final int LAST = 3;
public static final int PLAYBACKSERVICE_STATUS = 1;
public static final int SHUFFLE_NONE = 0;
public static final int SHUFFLE_NORMAL = 1;
public static final int SHUFFLE_AUTO = 2;
public static final int REPEAT_NONE = 0;
public static final int REPEAT_CURRENT = 1;
public static final int REPEAT_ALL = 2;
public static final String PLAYSTATE_CHANGED = "com.android.music.playstatechanged";
public static final String META_CHANGED = "com.android.music.metachanged";
public static final String QUEUE_CHANGED = "com.android.music.queuechanged";
public static final String REPEATMODE_CHANGED = "com.android.music.repeatmodechanged";
public static final String SHUFFLEMODE_CHANGED = "com.android.music.shufflemodechanged";
public static final String ALARM_ALERT_ACTION = "com.android.deskclock.ALARM_ALERT";
public static final String ALARM_DONE_ACTION = "com.android.deskclock.ALARM_DONE";
public static final String ALARM_SNOOZE_ACTION = "com.android.deskclock.ALARM_SNOOZE";
public static final String SERVICECMD = "com.android.music.musicservicecommand";
public static final String CMDNAME = "command";
public static final String CMDTOGGLEPAUSE = "togglepause";
public static final String CMDSTOP = "stop";
public static final String CMDPAUSE = "pause";
public static final String CMDPREVIOUS = "previous";
public static final String CMDNEXT = "next";
public static final String CMDCYCLEREPEAT = "cyclerepeat";
public static final String CMDTOGGLESHUFFLE = "toggleshuffle";
public static final String TOGGLEPAUSE_ACTION = "com.android.music.musicservicecommand.togglepause";
public static final String PAUSE_ACTION = "com.android.music.musicservicecommand.pause";
public static final String PREVIOUS_ACTION = "com.android.music.musicservicecommand.previous";
public static final String NEXT_ACTION = "com.android.music.musicservicecommand.next";
public static final String CYCLEREPEAT_ACTION = "com.android.music.musicservicecommand.cyclerepeat";
public static final String TOGGLESHUFFLE_ACTION = "com.android.music.musicservicecommand.toggleshuffle";
private static final String PLAYSTATUS_REQUEST = "com.android.music.playstatusrequest";
private static final String PLAYSTATUS_RESPONSE = "com.android.music.playstatusresponse";
private static final int MAX_HISTORY_SIZE = 100;
private static final float VOLUME_FULL = 1.0f;
private static final float VOLUME_MUTE = 0.1f;
private static final int FADE_UP_DURATION = 300; // ms
private static final int FADE_DOWN_DURATION = 150; // ms
private static final int FADE_STEP_DURATION = 10; // ms
// TODO: make this logarithmic somehow.
private static final float VOLUME_DOWN = (VOLUME_FULL - VOLUME_MUTE) * FADE_STEP_DURATION / FADE_DOWN_DURATION;
private static final float VOLUME_UP = (VOLUME_FULL - VOLUME_MUTE) * FADE_STEP_DURATION / FADE_UP_DURATION;
private MultiPlayer mPlayer;
private String mFileToPlay;
private int mShuffleMode = SHUFFLE_NONE;
private int mRepeatMode = REPEAT_NONE;
private int mMediaMountedCount = 0;
private long [] mAutoShuffleList = null;
private long [] mPlayList = null;
private int mPlayListLen = 0;
private Vector<Integer> mHistory = new Vector<Integer>(MAX_HISTORY_SIZE);
private Cursor mCursor;
private int mPlayPos = -1;
private static final String LOGTAG = "MediaPlaybackService";
private final Shuffler mRand = new Shuffler();
private int mOpenFailedCounter = 0;
String[] mCursorCols = new String[] {
"audio._id AS _id", // index must match IDCOLIDX below
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM_ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.ALBUM_ARTIST_ID,
MediaStore.Audio.Media.IS_PODCAST, // index must match PODCASTCOLIDX below
MediaStore.Audio.Media.BOOKMARK // index must match BOOKMARKCOLIDX below
};
private final static int IDCOLIDX = 0;
private final static int PODCASTCOLIDX = 10;
private final static int BOOKMARKCOLIDX = 11;
private BroadcastReceiver mUnmountReceiver = null;
private BroadcastReceiver mA2dpReceiver = null;
private WakeLock mWakeLock;
private int mServiceStartId = -1;
private boolean mServiceInUse = false;
private boolean mIsSupposedToBePlaying = false;
private boolean mQuietMode = false;
private AudioManager mAudioManager;
private boolean mQueueIsSaveable = true;
// used to track what type of audio focus loss caused the playback to pause
private boolean mPausedByTransientLossOfFocus = false;
// Flip action
public static int ROLL_LOVER = -25;
public static int ROLL_UPER = 25;
public static int PITCH_LOVER = -160;
public static int PITCH_UPER = 160;
// Sensitivity
public static int FLIP_SENS = 0;
public static double SHAKE_SENS = 0d;
public static Shaker shaker;
public static String shake_actions_db;
private IMediaPlaybackService mService = null;
// Flip
private SensorManager sensorMan = null;
private float PITCH;
private float ROLL;
private boolean IsWorked = false;
private boolean mPausedByIncomingAlarm = false;
// used to track current volume
private float mCurrentVolume = 1.0f;
private SharedPreferences mPreferences;
// We use this to distinguish between different cards when saving/restoring playlists.
// This will have to change if we want to support multiple simultaneous cards.
private int mCardId;
private MediaAppWidgetProvider4x1 mAppWidgetProvider4x1 = MediaAppWidgetProvider4x1.getInstance();
private MediaAppWidgetProvider4x2 mAppWidgetProvider4x2 = MediaAppWidgetProvider4x2.getInstance();
// interval after which we stop the service when idle
private static final int IDLE_DELAY = 60000;
private boolean mStartPlayback = false;
private class MediaplayerHandler extends Handler {
private static final int MESSAGE_TRACK_ENDED = 1;
private static final int MESSAGE_RELEASE_WAKELOCK = 2;
private static final int MESSAGE_SERVER_DIED = 3;
private static final int MESSAGE_FOCUSCHANGE = 4;
private static final int MESSAGE_FADE = 7;
private static final int MESSAGE_STOP = 8;
private static final int MESSAGE_PAUSE = 9;
private static final int MESSAGE_NEXT = 10;
private static final int MESSAGE_PREV = 11;
// seek to position stored in targetpos
private static final int MESSAGE_SEEK = 12;
// seek to position stored in targetqueuepos
private static final int MESSAGE_SET_QUEUEPOS = 13;
// used to store target volume when fading
private float mTargetVolume = mCurrentVolume;
// used to store target pos when fade-seeking
private long mTargetPos = 0;
// used to store target queue pos when fade-seeking
private int mTargetQueuePos = 0;
@Override
public void handleMessage(Message msg) {
MusicUtils.debugLog("mMediaplayerHandler.handleMessage " + msg.what);
Message andThen = null;
if (msg.obj instanceof Message) {
andThen = (Message) msg.obj;
}
boolean sendQueuedMessage = true;
switch (msg.what) {
case MESSAGE_PAUSE:
pause();
break;
case MESSAGE_STOP:
stop();
break;
case MESSAGE_NEXT:
next(true);
break;
case MESSAGE_PREV:
prev();
break;
case MESSAGE_SEEK:
seek(mTargetPos);
break;
case MESSAGE_SET_QUEUEPOS:
setQueuePosition(mTargetQueuePos);
break;
case MESSAGE_FADE:
final float targetVolume = mTargetVolume;
float currentVolume = mCurrentVolume;
float newVolume;
if (targetVolume > currentVolume) {
newVolume = currentVolume + VOLUME_UP;
if (newVolume > targetVolume)
newVolume = targetVolume;
}
else { // targetVolume <= currentVolume;
newVolume = currentVolume - VOLUME_DOWN;
if (newVolume < targetVolume)
newVolume = targetVolume;
}
mCurrentVolume = newVolume;
mPlayer.setVolume(newVolume);
if (newVolume != targetVolume) {
sendMessageDelayed(obtainMessage(MESSAGE_FADE, msg.obj), 10);
sendQueuedMessage = false;
}
break;
case MESSAGE_SERVER_DIED:
if (mIsSupposedToBePlaying) {
next(true);
} else {
// the server died when we were idle, so just
// reopen the same song (it will start again
// from the beginning though when the user
// restarts)
openCurrent();
}
break;
case MESSAGE_TRACK_ENDED:
if (mRepeatMode == REPEAT_CURRENT) {
seek(0);
play();
} else {
next(false);
}
break;
case MESSAGE_RELEASE_WAKELOCK:
mWakeLock.release();
break;
case MESSAGE_FOCUSCHANGE:
// This code is here so we can better synchronize it with the code that
// handles fade-in
switch (msg.arg1) {
case AudioManager.AUDIOFOCUS_LOSS:
Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS");
if(isPlaying()) {
mPausedByTransientLossOfFocus = false;
}
fadeDownAndPause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
fadeDown();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT");
if (isPlaying()) {
int focusLossAttenuation = getFocusLossAttenuation();
if (focusLossAttenuation >= 0) {
//Convert from decibels to volume level
float duckVolume = (float) Math.pow(10.0, -focusLossAttenuation / 20.0);
Log.v(LOGTAG, "New attentuated volume: " + duckVolume);
mPlayer.setVolume(duckVolume);
} else {
mPausedByTransientLossOfFocus = true;
pause(); // don't move pause out because we have ducking
}
}
break;
case AudioManager.AUDIOFOCUS_GAIN:
Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_GAIN");
if(isPlaying() || mPausedByTransientLossOfFocus) {
TelephonyManager telephonyManager =
(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
while (telephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
try{
Thread.sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
mPausedByTransientLossOfFocus = false;
play(); // also queues a fade-in
} else {
fadeUp();
}
break;
default:
Log.e(LOGTAG, "Unknown audio focus change code");
}
break;
default:
break;
}
if (sendQueuedMessage && andThen != null) {
sendMessage(andThen);
}
}
}
private MediaplayerHandler mMediaplayerHandler = new MediaplayerHandler();
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
MusicUtils.debugLog("mIntentReceiver.onReceive " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
fadeDownAndNext();
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
fadeDownAndPrev();
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
fadeDownAndPause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
fadeDownAndPause();
mPausedByTransientLossOfFocus = false;
} else if (CMDSTOP.equals(cmd)) {
fadeDownAndStop();
mPausedByTransientLossOfFocus = false;
// seek(0);
} else if (CMDCYCLEREPEAT.equals(cmd) || CYCLEREPEAT_ACTION.equals(action)) {
cycleRepeat();
} else if (CMDTOGGLESHUFFLE.equals(cmd) || TOGGLESHUFFLE_ACTION.equals(action)) {
toggleShuffle();
} else if (MediaAppWidgetProvider4x1.CMDAPPWIDGETUPDATE.equals(cmd)) {
// Someone asked us to refresh a set of specific widgets, probably
// because they were just added.
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
mAppWidgetProvider4x1.performUpdate(MediaPlaybackService.this, appWidgetIds);
} else if (MediaAppWidgetProvider4x2.CMDAPPWIDGETUPDATE.equals(cmd)) {
// Someone asked us to refresh a set of specific widgets, probably
// because they were just added.
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
mAppWidgetProvider4x2.performUpdate(MediaPlaybackService.this, appWidgetIds);
} else if (ALARM_ALERT_ACTION.equals(action)) {
if (isPlaying()) {
mPausedByIncomingAlarm = true;
pause();
}
} else if (ALARM_DONE_ACTION.equals(action)) {
if (mPausedByIncomingAlarm) {
play();
}
}
}
};
private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_FOCUSCHANGE, focusChange, 0).sendToTarget();
}
};
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
if (getFocusLossAttenuation() < 0) {
/* the audio focus handler will do the right thing in that case */
return;
}
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
Log.v(LOGTAG, "PhoneState: received CALL_STATE_RINGING");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.v(LOGTAG, "PhoneState: received CALL_STATE_OFFHOOK");
break;
default:
return;
}
if (isPlaying()) {
mPausedByTransientLossOfFocus = true;
pause();
}
}
};
public MediaPlaybackService() {
}
@Override
public void onCreate() {
super.onCreate();
SharedPreferences mPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
Double shakeChange = new Double(mPrefs.getInt(
MusicSettingsActivity.SHAKE_SENSITIVITY,
(int) (MusicSettingsActivity.DEFAULT_SHAKE_SENS)));
SHAKE_SENS = shakeChange;
if (SHAKE_SENS == 0) {
new Shaker(this, 1.25, 500, this);
} else {
new Shaker(this, SHAKE_SENS + .25d, 500, this);
}
// Flip action
sensorMan = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorMan.registerListener(this,
sensorMan.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_UI);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(),
MediaButtonIntentReceiver.class.getName()));
mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
mCardId = MusicUtils.getCardId(this);
registerExternalStorageListener();
registerA2dpServiceListener();
// Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
mPlayer = new MultiPlayer();
mPlayer.setHandler(mMediaplayerHandler);
reloadQueue();
IntentFilter commandFilter = new IntentFilter();
commandFilter.addAction(SERVICECMD);
commandFilter.addAction(TOGGLEPAUSE_ACTION);
commandFilter.addAction(PAUSE_ACTION);
commandFilter.addAction(NEXT_ACTION);
commandFilter.addAction(PREVIOUS_ACTION);
commandFilter.addAction(CYCLEREPEAT_ACTION);
commandFilter.addAction(TOGGLESHUFFLE_ACTION);
commandFilter.addAction(PLAYSTATUS_REQUEST);
commandFilter.addAction(ALARM_ALERT_ACTION);
commandFilter.addAction(ALARM_DONE_ACTION);
commandFilter.addAction(ALARM_SNOOZE_ACTION);
registerReceiver(mIntentReceiver, commandFilter);
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
mWakeLock.setReferenceCounted(false);
// If the service was idle, but got killed before it stopped itself, the
// system will relaunch it. Make sure it gets stopped again in that case.
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
}
@Override
public void onDestroy() {
sensorMan.unregisterListener(this);
// Check that we're not being destroyed while something is still playing.
if (isPlaying()) {
Log.e(LOGTAG, "Service being destroyed while still playing.");
}
// release all MediaPlayer resources, including the native player and wakelocks
Intent i = new Intent(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION);
i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
sendBroadcast(i);
mPlayer.release();
mPlayer = null;
mAudioManager.abandonAudioFocus(mAudioFocusListener);
TelephonyManager telephonyManager =
(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
// make sure there aren't any other messages coming
mDelayedStopHandler.removeCallbacksAndMessages(null);
mMediaplayerHandler.removeCallbacksAndMessages(null);
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
unregisterReceiver(mIntentReceiver);
unregisterReceiver(mA2dpReceiver);
if (mUnmountReceiver != null) {
unregisterReceiver(mUnmountReceiver);
mUnmountReceiver = null;
}
mWakeLock.release();
super.onDestroy();
}
private int getFocusLossAttenuation() {
SharedPreferences prefs = getSharedPreferences(
MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
if (!prefs.getBoolean(MusicSettingsActivity.KEY_ENABLE_FOCUS_LOSS_DUCKING, false)) {
return -1;
}
return Integer.valueOf(prefs.getString(
MusicSettingsActivity.KEY_DUCK_ATTENUATION_DB,
MusicSettingsActivity.DEFAULT_DUCK_ATTENUATION_DB));
}
private final char hexdigits [] = new char [] {
'0', '1', '2', '3',
'4', '5', '6', '7',
'8', '9', 'a', 'b',
'c', 'd', 'e', 'f'
};
private void saveQueue(boolean full) {
if (!mQueueIsSaveable) {
return;
}
Editor ed = mPreferences.edit();
//long start = System.currentTimeMillis();
if (full) {
StringBuilder q = new StringBuilder();
// The current playlist is saved as a list of "reverse hexadecimal"
// numbers, which we can generate faster than normal decimal or
// hexadecimal numbers, which in turn allows us to save the playlist
// more often without worrying too much about performance.
// (saving the full state takes about 40 ms under no-load conditions
// on the phone)
int len = mPlayListLen;
for (int i = 0; i < len; i++) {
long n = mPlayList[i];
if (n < 0) {
continue;
} else if (n == 0) {
q.append("0;");
} else {
while (n != 0) {
int digit = (int)(n & 0xf);
n >>>= 4;
q.append(hexdigits[digit]);
}
q.append(";");
}
}
//Log.i("@@@@ service", "created queue string in " + (System.currentTimeMillis() - start) + " ms");
ed.putString("queue", q.toString());
ed.putInt("cardid", mCardId);
if (mShuffleMode != SHUFFLE_NONE) {
// In shuffle mode we need to save the history too
len = mHistory.size();
q.setLength(0);
for (int i = 0; i < len; i++) {
int n = mHistory.get(i);
if (n == 0) {
q.append("0;");
} else {
while (n != 0) {
int digit = (n & 0xf);
n >>>= 4;
q.append(hexdigits[digit]);
}
q.append(";");
}
}
ed.putString("history", q.toString());
}
}
ed.putInt("curpos", mPlayPos);
if (mPlayer.isInitialized()) {
ed.putLong("seekpos", mPlayer.position());
}
ed.putInt("repeatmode", mRepeatMode);
ed.putInt("shufflemode", mShuffleMode);
SharedPreferencesCompat.apply(ed);
//Log.i("@@@@ service", "saved state in " + (System.currentTimeMillis() - start) + " ms");
}
private void reloadQueue() {
String q = null;
int id = mCardId;
if (mPreferences.contains("cardid")) {
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
int qlen = q != null ? q.length() : 0;
if (qlen > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus playlist data
plen = 0;
break;
}
shift += 4;
}
}
mPlayListLen = plen;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= mPlayListLen) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor crsr = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (crsr == null || crsr.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
crsr = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (crsr != null) {
crsr.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrent();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
Log.d(LOGTAG, "restored queue, currently at position "
+ position() + "/" + duration()
+ " (requested " + seekpos + ")");
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode != SHUFFLE_NONE) {
// in shuffle mode we need to restore the history too
q = mPreferences.getString("history", "");
qlen = q != null ? q.length() : 0;
if (qlen > 1) {
plen = 0;
n = 0;
shift = 0;
mHistory.clear();
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
if (n >= mPlayListLen) {
// bogus history data
mHistory.clear();
break;
}
mHistory.add(n);
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus history data
mHistory.clear();
break;
}
shift += 4;
}
}
}
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
if (intent != null) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
MusicUtils.debugLog("onStartCommand " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
fadeDownAndNext();
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
if (position() < 2000) {
fadeDownAndPrev();
} else {
fadeDownAndSeek(0);
}
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
fadeDownAndPause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
fadeDownAndPause();
mPausedByTransientLossOfFocus = false;
} else if (CMDSTOP.equals(cmd)) {
fadeDownAndStop();
mPausedByTransientLossOfFocus = false;
} else if (CMDCYCLEREPEAT.equals(cmd) || CYCLEREPEAT_ACTION.equals(action)) {
cycleRepeat();
} else if (CMDTOGGLESHUFFLE.equals(cmd) || TOGGLESHUFFLE_ACTION.equals(action)) {
toggleShuffle();
} else if (PLAYSTATUS_REQUEST.equals(action)) {
notifyChange(PLAYSTATUS_RESPONSE);
}
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return START_STICKY;
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mPausedByTransientLossOfFocus) {
// something is currently playing, or will be playing once
// an in-progress action requesting audio focus ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(MediaplayerHandler.MESSAGE_TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse
|| mMediaplayerHandler.hasMessages(MediaplayerHandler.MESSAGE_TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mQueueIsSaveable = false;
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = MusicUtils.getCardId(MediaPlaybackService.this);
reloadQueue();
mQueueIsSaveable = true;
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
public void registerA2dpServiceListener() {
mA2dpReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(PLAYSTATUS_REQUEST)) {
notifyChange(PLAYSTATUS_RESPONSE);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(PLAYSTATUS_REQUEST);
registerReceiver(mA2dpReceiver, iFilter);
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album_artist" - String: the name of the album artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Long.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album_artist", getAlbumartistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
i.putExtra("playing", isPlaying());
i.putExtra("songid", getAudioId());
i.putExtra("albumid", getAlbumId());
i.putExtra("duration", duration());
i.putExtra("position", position());
if (mPlayList != null)
i.putExtra("ListSize", Long.valueOf(mPlayList.length));
else
i.putExtra("ListSize", Long.valueOf(mPlayListLen));
sendStickyBroadcast(i);
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider4x1.notifyChange(this, what);
mAppWidgetProvider4x2.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
long [] newlist = new long[size * 2];
int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(long [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
if (mPlayListLen == 0) {
mCursor.close();
mCursor = null;
notifyChange(META_CHANGED);
}
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(long [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(long [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
long oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrent();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
long tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
long tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public long [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
long [] list = new long[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private void openCurrent() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
String id = String.valueOf(mPlayList[mPlayPos]);
mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (mCursor != null) {
mCursor.moveToFirst();
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id);
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
}
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
*/
public void open(String path) {
synchronized (this) {
if (path == null) {
return;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getLong(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
if (! mPlayer.isInitialized()) {
stop(true);
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
// beware: this ends up being recursive because next() calls open() again.
next(false);
}
if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) {
// need to make sure we only shows this once
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
Log.d(LOGTAG, "Failed to open file for playback");
}
} else {
mOpenFailedCounter = 0;
}
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
TelephonyManager telephonyManager =
(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
return;
}
mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(),
MediaButtonIntentReceiver.class.getName()));
telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
long duration = mPlayer.duration();
if (mRepeatMode != REPEAT_CURRENT && duration > 2000 &&
mPlayer.position() >= duration - 2000) {
next(true);
}
mPlayer.start();
// make sure we fade in, in case a previous fadein was stopped because
// of another focus loss
fadeUp();
if (Settings.System.getInt(getContentResolver(), Settings.System.EXPANDED_VIEW_WIDGET, 0) == 0) {
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.statusbar);
views.setImageViewBitmap(R.id.icon, MusicUtils.getArtwork(
getBaseContext(), getAudioId(), getAlbumId(), true));
SharedPreferences preferences = getSharedPreferences(
MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
mPreferences.getBoolean(MusicSettingsActivity.KEY_TICK, false);
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_SONG_TEXT, true)) {
views.setViewVisibility(R.id.trackname, View.VISIBLE);
} else {
views.setViewVisibility(R.id.trackname, View.INVISIBLE);
}
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_ARTIST_TEXT, true)) {
views.setViewVisibility(R.id.artist, View.VISIBLE);
} else {
views.setViewVisibility(R.id.artist, View.GONE);
}
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_ALBUM_ART, true)) {
views.setViewVisibility(R.id.icon, View.VISIBLE);
views.setViewVisibility(R.id.status_icon, View.GONE);
} else {
views.setViewVisibility(R.id.icon, View.GONE);
views.setViewVisibility(R.id.status_icon, View.VISIBLE);
views.setImageViewResource(R.id.status_icon,
R.drawable.stat_notify_musicplayer);
}
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_NONYA, false)) {
views.setViewVisibility(R.id.icon, View.GONE);
views.setViewVisibility(R.id.status_icon, View.GONE);
}
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artist, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artist, getString(R.string.notification_artist_album, artist, album));
}
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
if (preferences.getBoolean(MusicSettingsActivity.KEY_TICK, true)) {
status.tickerText = getTrackName() + " by " + getArtistName();
}
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
startForeground(PLAYBACKSERVICE_STATUS, status);
}
if (!mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = true;
notifyChange(PLAYSTATE_CHANGED);
}
mPausedByIncomingAlarm = false;
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
} else {
stopForeground(false);
}
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
fadeDown();
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
private void fade(float newVolume, Message andThen) {
mMediaplayerHandler.removeMessages(MediaplayerHandler.MESSAGE_FADE);
mMediaplayerHandler.mTargetVolume = newVolume;
mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_FADE, andThen).sendToTarget();
}
private void fade(float newVolume) {
fade(newVolume, null);
}
public void fadeUp() {
fade(VOLUME_FULL);
}
public void fadeDown() {
fade(VOLUME_MUTE);
}
public void fadeDownAndStop() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_STOP));
}
public void fadeDownAndPause() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_PAUSE));
}
public void fadeDownAndNext() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_NEXT));
}
public void fadeDownAndPrev() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_PREV));
}
public void fadeDownAndSeek(long pos) {
mMediaplayerHandler.mTargetPos = pos;
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_SEEK));
}
public void fadeDownAndSetQueuePosition(int pos) {
mMediaplayerHandler.mTargetQueuePos = pos;
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_SET_QUEUEPOS));
}
/** Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (position() > 2000) {
seek(0);
} else {
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
fadeUp();
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
}
play();
notifyChange(META_CHANGED);
}
}
public void next(boolean force) {
synchronized (this) {
if (mPlayListLen <= 0) {
Log.d(LOGTAG, "No play queue");
return;
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(mPlayPos);
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
mPlayPos = cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
mPlayPos++;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
return;
} else if (mRepeatMode == REPEAT_ALL || force) {
mPlayPos = 0;
}
} else {
mPlayPos++;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public void cycleRepeat() {
if (mRepeatMode == REPEAT_NONE) {
setRepeatMode(REPEAT_ALL);
} else if (mRepeatMode == REPEAT_ALL) {
setRepeatMode(REPEAT_CURRENT);
if (mShuffleMode != SHUFFLE_NONE) {
setShuffleMode(SHUFFLE_NONE);
}
} else {
setRepeatMode(REPEAT_NONE);
}
}
public void toggleShuffle() {
if (mShuffleMode == SHUFFLE_NONE) {
setShuffleMode(SHUFFLE_NORMAL);
if (mRepeatMode == REPEAT_CURRENT) {
setRepeatMode(REPEAT_ALL);
}
} else if (mShuffleMode == SHUFFLE_NORMAL || mShuffleMode == SHUFFLE_AUTO) {
setShuffleMode(SHUFFLE_NONE);
} else {
Log.e("MediaPlaybackService", "Invalid shuffle mode: " + mShuffleMode);
}
}
private void gotoIdleState() {
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
stopForeground(true);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int lookback = mHistory.size();
int idx = -1;
while(true) {
idx = mRand.nextInt(mAutoShuffleList.length);
if (!wasRecentlyUsed(idx, lookback)) {
break;
}
lookback /= 2;
}
mHistory.add(idx);
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.remove(0);
}
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = mAutoShuffleList[idx];
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// check that the specified idx is not in the history (but only look at at
// most lookbacksize entries in the history)
private boolean wasRecentlyUsed(int idx, int lookbacksize) {
// early exit to prevent infinite loops in case idx == mPlayPos
if (lookbacksize == 0) {
return false;
}
int histsize = mHistory.size();
if (histsize < lookbacksize) {
Log.d(LOGTAG, "lookback too big");
lookbacksize = histsize;
}
int maxidx = histsize - 1;
for (int i = 0; i < lookbacksize; i++) {
long entry = mHistory.get(maxidx - i);
if (entry == idx) {
return true;
}
}
return false;
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private static class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
long [] list = new long[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getLong(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrent();
if (wasPlaying) {
play();
}
}
notifyChange(META_CHANGED);
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(long id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
notifyChange(SHUFFLEMODE_CHANGED);
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
notifyChange(REPEATMODE_CHANGED);
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public long getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrent();
play();
notifyChange(META_CHANGED);
if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
}
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public long getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumartistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ARTIST));
}
}
public long getAlbumartistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public long getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
long result = mPlayer.seek(pos);
fadeUp();
return result;
}
return -1;
}
/**
* Sets the audio session ID.
*
* @param sessionId: the audio session ID.
*/
public void setAudioSessionId(int sessionId) {
synchronized (this) {
mPlayer.setAudioSessionId(sessionId);
}
}
/**
* Returns the audio session ID.
*/
public int getAudioSessionId() {
synchronized (this) {
return mPlayer.getAudioSessionId();
}
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private MediaPlayer mMediaPlayer = new MediaPlayer();
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSource(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setOnPreparedListener(null);
if (path.startsWith("content://")) {
mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
mMediaPlayer.setDataSource(path);
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
sendBroadcast(i);
mIsInitialized = true;
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
MusicUtils.debugLog(new Exception("MultiPlayer.start called"));
mMediaPlayer.start();
}
public void stop() {
mMediaPlayer.reset();
mIsInitialized = false;
}
/**
* You CANNOT use this player anymore after calling release()
*/
public void release() {
stop();
mMediaPlayer.release();
}
public void pause() {
mMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(MediaplayerHandler.MESSAGE_TRACK_ENDED);
mHandler.sendEmptyMessage(MediaplayerHandler.MESSAGE_RELEASE_WAKELOCK);
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MediaplayerHandler.MESSAGE_SERVER_DIED), 2000);
return true;
default:
Log.d("MultiPlayer", "Error: " + what + "," + extra);
break;
}
return false;
}
};
public long duration() {
return mMediaPlayer.getDuration();
}
public long position() {
return mMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mMediaPlayer.setVolume(vol, vol);
mCurrentVolume = vol;
}
public void setAudioSessionId(int sessionId) {
mMediaPlayer.setAudioSessionId(sessionId);
}
public int getAudioSessionId() {
return mMediaPlayer.getAudioSessionId();
}
}
/*
* By making this a static class with a WeakReference to the Service, we
* ensure that the Service can be GCd even when the system process still
* has a remote reference to the stub.
*/
static class ServiceStub extends IMediaPlaybackService.Stub {
WeakReference<MediaPlaybackService> mService;
ServiceStub(MediaPlaybackService service) {
mService = new WeakReference<MediaPlaybackService>(service);
}
public void openFile(String path)
{
mService.get().open(path);
}
public void open(long [] list, int position) {
mService.get().open(list, position);
}
public int getQueuePosition() {
return mService.get().getQueuePosition();
}
public void setQueuePosition(int index) {
mService.get().fadeDownAndSetQueuePosition(index);
}
public boolean isPlaying() {
return mService.get().isPlaying();
}
public void stop() {
mService.get().fadeDownAndStop();
}
public void pause() {
mService.get().fadeDownAndPause();
}
public void play() {
mService.get().play();
}
public void prev() {
mService.get().fadeDownAndPrev();
}
public void next() {
mService.get().fadeDownAndNext();
}
public void cycleRepeat() {
mService.get().cycleRepeat();
}
public void toggleShuffle() {
mService.get().toggleShuffle();
}
public String getTrackName() {
return mService.get().getTrackName();
}
public String getAlbumName() {
return mService.get().getAlbumName();
}
public long getAlbumId() {
return mService.get().getAlbumId();
}
public String getArtistName() {
return mService.get().getArtistName();
}
public long getArtistId() {
return mService.get().getArtistId();
}
public String getAlbumartistName() {
return mService.get().getAlbumartistName();
}
public long getAlbumartistId() {
return mService.get().getAlbumartistId();
}
public void enqueue(long [] list , int action) {
mService.get().enqueue(list, action);
}
public long [] getQueue() {
return mService.get().getQueue();
}
public void moveQueueItem(int from, int to) {
mService.get().moveQueueItem(from, to);
}
public String getPath() {
return mService.get().getPath();
}
public long getAudioId() {
return mService.get().getAudioId();
}
public long position() {
return mService.get().position();
}
public long duration() {
return mService.get().duration();
}
public long seek(long pos) {
// try to avoid jumping of seekbar, not always successful
// but there's no way to fade and return the correct position immediately
long currentPos = mService.get().position();
mService.get().fadeDownAndSeek(pos);
return currentPos;
}
public void setShuffleMode(int shufflemode) {
mService.get().setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return mService.get().getShuffleMode();
}
public int removeTracks(int first, int last) {
return mService.get().removeTracks(first, last);
}
public int removeTrack(long id) {
return mService.get().removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
mService.get().setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return mService.get().getRepeatMode();
}
public int getMediaMountedCount() {
return mService.get().getMediaMountedCount();
}
public int getAudioSessionId() {
return mService.get().getAudioSessionId();
}
}
@Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
writer.println("" + mPlayListLen + " items in queue, currently at index " + mPlayPos);
writer.println("Currently loaded:");
writer.println(getArtistName());
writer.println(getAlbumartistName());
writer.println(getAlbumName());
writer.println(getTrackName());
writer.println(getPath());
writer.println("playing: " + mIsSupposedToBePlaying);
writer.println("actual: " + mPlayer.mMediaPlayer.isPlaying());
writer.println("shuffle mode: " + mShuffleMode);
MusicUtils.debugDump(writer);
}
private final IBinder mBinder = new ServiceStub(this);
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
SharedPreferences preferences = getSharedPreferences(
MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
mPreferences.getBoolean(MusicSettingsActivity.KEY_FLIP, false);
SharedPreferences mPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
int flipChange = new Integer(mPrefs.getInt(
MusicSettingsActivity.FLIP_SENSITIVITY,
MusicSettingsActivity.DEFAULT_FLIP_SENS));
FLIP_SENS = flipChange;
float vals[] = event.values;
PITCH = vals[1];// Pitch
ROLL = vals[2];// Roll
int nPITCH_UPER = PITCH_UPER;
int nPITCH_LOVER = PITCH_LOVER;
int nROLL_UPER = ROLL_UPER;
int nROLL_LOVER = ROLL_LOVER;
if (FLIP_SENS != 0) {
nPITCH_UPER = PITCH_UPER - FLIP_SENS;
nPITCH_LOVER = PITCH_LOVER + FLIP_SENS;
nROLL_UPER = ROLL_UPER + FLIP_SENS;
nROLL_LOVER = ROLL_LOVER - FLIP_SENS;
}
if (preferences.getBoolean(MusicSettingsActivity.KEY_FLIP, false)) {
if (PITCH > nPITCH_UPER || PITCH < nPITCH_LOVER) {
if (ROLL < nROLL_UPER && ROLL > nROLL_LOVER) {
if (isPlaying()) {
pause();
IsWorked = true;
}
} else if (PITCH > nPITCH_UPER || PITCH < nPITCH_LOVER) {
if (IsWorked) {
if (!isPlaying()) {
play();
IsWorked = false;
}
}
}
}
}
}
public static void setSensivity(int sensivity) {
FLIP_SENS = sensivity - 0;
}
private void doPauseResume() {
if (isPlaying()) {
pause();
} else {
play();
}
}
private void doNext() {
next(true);
}
private void doPrev() {
if (position() < 2000) {
prev();
} else {
seek(0);
play();
}
}
@Override
public void shakingStarted() {
SharedPreferences preferences = getSharedPreferences(
MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
shake_actions_db = preferences.getString("shake_actions_db", "1");
if (shake_actions_db.equals("1")) {
doPauseResume();
}
shake_actions_db = preferences.getString("shake_actions_db", "2");
if (shake_actions_db.equals("2")) {
doNext();
}
shake_actions_db = preferences.getString("shake_actions_db", "3");
if (shake_actions_db.equals("3")) {
doPrev();
}
shake_actions_db = preferences.getString("shake_actions_db", "4");
if (shake_actions_db.equals("4")) {
Cursor cursor;
cursor = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { BaseColumns._ID }, AudioColumns.IS_MUSIC
+ "=1", null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor != null) {
MusicUtils.shuffleAll(this, cursor);
cursor.close();
}
}
shake_actions_db = preferences.getString("shake_actions_db", "5");
if (shake_actions_db.equals("5")) {
int shuffle = getShuffleMode();
if (shuffle == SHUFFLE_AUTO) {
setShuffleMode(SHUFFLE_NONE);
} else {
setShuffleMode(SHUFFLE_AUTO);
}
- shake_actions_db = preferences.getString("shake_actions_db", "0");
- if (shake_actions_db.equals("0")) {
- // Nothing - this needs to stay last
- }
+ }
+ shake_actions_db = preferences.getString("shake_actions_db", "0");
+ if (shake_actions_db.equals("0")) {
+ // Nothing - this needs to stay last
}
}
@Override
public void shakingStopped() {
}
}
| true | true | private void reloadQueue() {
String q = null;
int id = mCardId;
if (mPreferences.contains("cardid")) {
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
int qlen = q != null ? q.length() : 0;
if (qlen > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus playlist data
plen = 0;
break;
}
shift += 4;
}
}
mPlayListLen = plen;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= mPlayListLen) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor crsr = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (crsr == null || crsr.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
crsr = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (crsr != null) {
crsr.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrent();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
Log.d(LOGTAG, "restored queue, currently at position "
+ position() + "/" + duration()
+ " (requested " + seekpos + ")");
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode != SHUFFLE_NONE) {
// in shuffle mode we need to restore the history too
q = mPreferences.getString("history", "");
qlen = q != null ? q.length() : 0;
if (qlen > 1) {
plen = 0;
n = 0;
shift = 0;
mHistory.clear();
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
if (n >= mPlayListLen) {
// bogus history data
mHistory.clear();
break;
}
mHistory.add(n);
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus history data
mHistory.clear();
break;
}
shift += 4;
}
}
}
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
if (intent != null) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
MusicUtils.debugLog("onStartCommand " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
fadeDownAndNext();
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
if (position() < 2000) {
fadeDownAndPrev();
} else {
fadeDownAndSeek(0);
}
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
fadeDownAndPause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
fadeDownAndPause();
mPausedByTransientLossOfFocus = false;
} else if (CMDSTOP.equals(cmd)) {
fadeDownAndStop();
mPausedByTransientLossOfFocus = false;
} else if (CMDCYCLEREPEAT.equals(cmd) || CYCLEREPEAT_ACTION.equals(action)) {
cycleRepeat();
} else if (CMDTOGGLESHUFFLE.equals(cmd) || TOGGLESHUFFLE_ACTION.equals(action)) {
toggleShuffle();
} else if (PLAYSTATUS_REQUEST.equals(action)) {
notifyChange(PLAYSTATUS_RESPONSE);
}
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return START_STICKY;
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mPausedByTransientLossOfFocus) {
// something is currently playing, or will be playing once
// an in-progress action requesting audio focus ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(MediaplayerHandler.MESSAGE_TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse
|| mMediaplayerHandler.hasMessages(MediaplayerHandler.MESSAGE_TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mQueueIsSaveable = false;
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = MusicUtils.getCardId(MediaPlaybackService.this);
reloadQueue();
mQueueIsSaveable = true;
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
public void registerA2dpServiceListener() {
mA2dpReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(PLAYSTATUS_REQUEST)) {
notifyChange(PLAYSTATUS_RESPONSE);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(PLAYSTATUS_REQUEST);
registerReceiver(mA2dpReceiver, iFilter);
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album_artist" - String: the name of the album artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Long.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album_artist", getAlbumartistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
i.putExtra("playing", isPlaying());
i.putExtra("songid", getAudioId());
i.putExtra("albumid", getAlbumId());
i.putExtra("duration", duration());
i.putExtra("position", position());
if (mPlayList != null)
i.putExtra("ListSize", Long.valueOf(mPlayList.length));
else
i.putExtra("ListSize", Long.valueOf(mPlayListLen));
sendStickyBroadcast(i);
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider4x1.notifyChange(this, what);
mAppWidgetProvider4x2.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
long [] newlist = new long[size * 2];
int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(long [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
if (mPlayListLen == 0) {
mCursor.close();
mCursor = null;
notifyChange(META_CHANGED);
}
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(long [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(long [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
long oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrent();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
long tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
long tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public long [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
long [] list = new long[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private void openCurrent() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
String id = String.valueOf(mPlayList[mPlayPos]);
mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (mCursor != null) {
mCursor.moveToFirst();
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id);
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
}
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
*/
public void open(String path) {
synchronized (this) {
if (path == null) {
return;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getLong(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
if (! mPlayer.isInitialized()) {
stop(true);
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
// beware: this ends up being recursive because next() calls open() again.
next(false);
}
if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) {
// need to make sure we only shows this once
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
Log.d(LOGTAG, "Failed to open file for playback");
}
} else {
mOpenFailedCounter = 0;
}
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
TelephonyManager telephonyManager =
(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
return;
}
mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(),
MediaButtonIntentReceiver.class.getName()));
telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
long duration = mPlayer.duration();
if (mRepeatMode != REPEAT_CURRENT && duration > 2000 &&
mPlayer.position() >= duration - 2000) {
next(true);
}
mPlayer.start();
// make sure we fade in, in case a previous fadein was stopped because
// of another focus loss
fadeUp();
if (Settings.System.getInt(getContentResolver(), Settings.System.EXPANDED_VIEW_WIDGET, 0) == 0) {
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.statusbar);
views.setImageViewBitmap(R.id.icon, MusicUtils.getArtwork(
getBaseContext(), getAudioId(), getAlbumId(), true));
SharedPreferences preferences = getSharedPreferences(
MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
mPreferences.getBoolean(MusicSettingsActivity.KEY_TICK, false);
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_SONG_TEXT, true)) {
views.setViewVisibility(R.id.trackname, View.VISIBLE);
} else {
views.setViewVisibility(R.id.trackname, View.INVISIBLE);
}
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_ARTIST_TEXT, true)) {
views.setViewVisibility(R.id.artist, View.VISIBLE);
} else {
views.setViewVisibility(R.id.artist, View.GONE);
}
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_ALBUM_ART, true)) {
views.setViewVisibility(R.id.icon, View.VISIBLE);
views.setViewVisibility(R.id.status_icon, View.GONE);
} else {
views.setViewVisibility(R.id.icon, View.GONE);
views.setViewVisibility(R.id.status_icon, View.VISIBLE);
views.setImageViewResource(R.id.status_icon,
R.drawable.stat_notify_musicplayer);
}
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_NONYA, false)) {
views.setViewVisibility(R.id.icon, View.GONE);
views.setViewVisibility(R.id.status_icon, View.GONE);
}
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artist, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artist, getString(R.string.notification_artist_album, artist, album));
}
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
if (preferences.getBoolean(MusicSettingsActivity.KEY_TICK, true)) {
status.tickerText = getTrackName() + " by " + getArtistName();
}
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
startForeground(PLAYBACKSERVICE_STATUS, status);
}
if (!mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = true;
notifyChange(PLAYSTATE_CHANGED);
}
mPausedByIncomingAlarm = false;
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
} else {
stopForeground(false);
}
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
fadeDown();
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
private void fade(float newVolume, Message andThen) {
mMediaplayerHandler.removeMessages(MediaplayerHandler.MESSAGE_FADE);
mMediaplayerHandler.mTargetVolume = newVolume;
mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_FADE, andThen).sendToTarget();
}
private void fade(float newVolume) {
fade(newVolume, null);
}
public void fadeUp() {
fade(VOLUME_FULL);
}
public void fadeDown() {
fade(VOLUME_MUTE);
}
public void fadeDownAndStop() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_STOP));
}
public void fadeDownAndPause() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_PAUSE));
}
public void fadeDownAndNext() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_NEXT));
}
public void fadeDownAndPrev() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_PREV));
}
public void fadeDownAndSeek(long pos) {
mMediaplayerHandler.mTargetPos = pos;
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_SEEK));
}
public void fadeDownAndSetQueuePosition(int pos) {
mMediaplayerHandler.mTargetQueuePos = pos;
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_SET_QUEUEPOS));
}
/** Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (position() > 2000) {
seek(0);
} else {
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
fadeUp();
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
}
play();
notifyChange(META_CHANGED);
}
}
public void next(boolean force) {
synchronized (this) {
if (mPlayListLen <= 0) {
Log.d(LOGTAG, "No play queue");
return;
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(mPlayPos);
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
mPlayPos = cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
mPlayPos++;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
return;
} else if (mRepeatMode == REPEAT_ALL || force) {
mPlayPos = 0;
}
} else {
mPlayPos++;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public void cycleRepeat() {
if (mRepeatMode == REPEAT_NONE) {
setRepeatMode(REPEAT_ALL);
} else if (mRepeatMode == REPEAT_ALL) {
setRepeatMode(REPEAT_CURRENT);
if (mShuffleMode != SHUFFLE_NONE) {
setShuffleMode(SHUFFLE_NONE);
}
} else {
setRepeatMode(REPEAT_NONE);
}
}
public void toggleShuffle() {
if (mShuffleMode == SHUFFLE_NONE) {
setShuffleMode(SHUFFLE_NORMAL);
if (mRepeatMode == REPEAT_CURRENT) {
setRepeatMode(REPEAT_ALL);
}
} else if (mShuffleMode == SHUFFLE_NORMAL || mShuffleMode == SHUFFLE_AUTO) {
setShuffleMode(SHUFFLE_NONE);
} else {
Log.e("MediaPlaybackService", "Invalid shuffle mode: " + mShuffleMode);
}
}
private void gotoIdleState() {
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
stopForeground(true);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int lookback = mHistory.size();
int idx = -1;
while(true) {
idx = mRand.nextInt(mAutoShuffleList.length);
if (!wasRecentlyUsed(idx, lookback)) {
break;
}
lookback /= 2;
}
mHistory.add(idx);
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.remove(0);
}
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = mAutoShuffleList[idx];
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// check that the specified idx is not in the history (but only look at at
// most lookbacksize entries in the history)
private boolean wasRecentlyUsed(int idx, int lookbacksize) {
// early exit to prevent infinite loops in case idx == mPlayPos
if (lookbacksize == 0) {
return false;
}
int histsize = mHistory.size();
if (histsize < lookbacksize) {
Log.d(LOGTAG, "lookback too big");
lookbacksize = histsize;
}
int maxidx = histsize - 1;
for (int i = 0; i < lookbacksize; i++) {
long entry = mHistory.get(maxidx - i);
if (entry == idx) {
return true;
}
}
return false;
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private static class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
long [] list = new long[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getLong(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrent();
if (wasPlaying) {
play();
}
}
notifyChange(META_CHANGED);
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(long id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
notifyChange(SHUFFLEMODE_CHANGED);
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
notifyChange(REPEATMODE_CHANGED);
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public long getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrent();
play();
notifyChange(META_CHANGED);
if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
}
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public long getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumartistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ARTIST));
}
}
public long getAlbumartistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public long getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
long result = mPlayer.seek(pos);
fadeUp();
return result;
}
return -1;
}
/**
* Sets the audio session ID.
*
* @param sessionId: the audio session ID.
*/
public void setAudioSessionId(int sessionId) {
synchronized (this) {
mPlayer.setAudioSessionId(sessionId);
}
}
/**
* Returns the audio session ID.
*/
public int getAudioSessionId() {
synchronized (this) {
return mPlayer.getAudioSessionId();
}
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private MediaPlayer mMediaPlayer = new MediaPlayer();
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSource(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setOnPreparedListener(null);
if (path.startsWith("content://")) {
mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
mMediaPlayer.setDataSource(path);
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
sendBroadcast(i);
mIsInitialized = true;
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
MusicUtils.debugLog(new Exception("MultiPlayer.start called"));
mMediaPlayer.start();
}
public void stop() {
mMediaPlayer.reset();
mIsInitialized = false;
}
/**
* You CANNOT use this player anymore after calling release()
*/
public void release() {
stop();
mMediaPlayer.release();
}
public void pause() {
mMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(MediaplayerHandler.MESSAGE_TRACK_ENDED);
mHandler.sendEmptyMessage(MediaplayerHandler.MESSAGE_RELEASE_WAKELOCK);
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MediaplayerHandler.MESSAGE_SERVER_DIED), 2000);
return true;
default:
Log.d("MultiPlayer", "Error: " + what + "," + extra);
break;
}
return false;
}
};
public long duration() {
return mMediaPlayer.getDuration();
}
public long position() {
return mMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mMediaPlayer.setVolume(vol, vol);
mCurrentVolume = vol;
}
public void setAudioSessionId(int sessionId) {
mMediaPlayer.setAudioSessionId(sessionId);
}
public int getAudioSessionId() {
return mMediaPlayer.getAudioSessionId();
}
}
/*
* By making this a static class with a WeakReference to the Service, we
* ensure that the Service can be GCd even when the system process still
* has a remote reference to the stub.
*/
static class ServiceStub extends IMediaPlaybackService.Stub {
WeakReference<MediaPlaybackService> mService;
ServiceStub(MediaPlaybackService service) {
mService = new WeakReference<MediaPlaybackService>(service);
}
public void openFile(String path)
{
mService.get().open(path);
}
public void open(long [] list, int position) {
mService.get().open(list, position);
}
public int getQueuePosition() {
return mService.get().getQueuePosition();
}
public void setQueuePosition(int index) {
mService.get().fadeDownAndSetQueuePosition(index);
}
public boolean isPlaying() {
return mService.get().isPlaying();
}
public void stop() {
mService.get().fadeDownAndStop();
}
public void pause() {
mService.get().fadeDownAndPause();
}
public void play() {
mService.get().play();
}
public void prev() {
mService.get().fadeDownAndPrev();
}
public void next() {
mService.get().fadeDownAndNext();
}
public void cycleRepeat() {
mService.get().cycleRepeat();
}
public void toggleShuffle() {
mService.get().toggleShuffle();
}
public String getTrackName() {
return mService.get().getTrackName();
}
public String getAlbumName() {
return mService.get().getAlbumName();
}
public long getAlbumId() {
return mService.get().getAlbumId();
}
public String getArtistName() {
return mService.get().getArtistName();
}
public long getArtistId() {
return mService.get().getArtistId();
}
public String getAlbumartistName() {
return mService.get().getAlbumartistName();
}
public long getAlbumartistId() {
return mService.get().getAlbumartistId();
}
public void enqueue(long [] list , int action) {
mService.get().enqueue(list, action);
}
public long [] getQueue() {
return mService.get().getQueue();
}
public void moveQueueItem(int from, int to) {
mService.get().moveQueueItem(from, to);
}
public String getPath() {
return mService.get().getPath();
}
public long getAudioId() {
return mService.get().getAudioId();
}
public long position() {
return mService.get().position();
}
public long duration() {
return mService.get().duration();
}
public long seek(long pos) {
// try to avoid jumping of seekbar, not always successful
// but there's no way to fade and return the correct position immediately
long currentPos = mService.get().position();
mService.get().fadeDownAndSeek(pos);
return currentPos;
}
public void setShuffleMode(int shufflemode) {
mService.get().setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return mService.get().getShuffleMode();
}
public int removeTracks(int first, int last) {
return mService.get().removeTracks(first, last);
}
public int removeTrack(long id) {
return mService.get().removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
mService.get().setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return mService.get().getRepeatMode();
}
public int getMediaMountedCount() {
return mService.get().getMediaMountedCount();
}
public int getAudioSessionId() {
return mService.get().getAudioSessionId();
}
}
@Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
writer.println("" + mPlayListLen + " items in queue, currently at index " + mPlayPos);
writer.println("Currently loaded:");
writer.println(getArtistName());
writer.println(getAlbumartistName());
writer.println(getAlbumName());
writer.println(getTrackName());
writer.println(getPath());
writer.println("playing: " + mIsSupposedToBePlaying);
writer.println("actual: " + mPlayer.mMediaPlayer.isPlaying());
writer.println("shuffle mode: " + mShuffleMode);
MusicUtils.debugDump(writer);
}
private final IBinder mBinder = new ServiceStub(this);
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
SharedPreferences preferences = getSharedPreferences(
MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
mPreferences.getBoolean(MusicSettingsActivity.KEY_FLIP, false);
SharedPreferences mPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
int flipChange = new Integer(mPrefs.getInt(
MusicSettingsActivity.FLIP_SENSITIVITY,
MusicSettingsActivity.DEFAULT_FLIP_SENS));
FLIP_SENS = flipChange;
float vals[] = event.values;
PITCH = vals[1];// Pitch
ROLL = vals[2];// Roll
int nPITCH_UPER = PITCH_UPER;
int nPITCH_LOVER = PITCH_LOVER;
int nROLL_UPER = ROLL_UPER;
int nROLL_LOVER = ROLL_LOVER;
if (FLIP_SENS != 0) {
nPITCH_UPER = PITCH_UPER - FLIP_SENS;
nPITCH_LOVER = PITCH_LOVER + FLIP_SENS;
nROLL_UPER = ROLL_UPER + FLIP_SENS;
nROLL_LOVER = ROLL_LOVER - FLIP_SENS;
}
if (preferences.getBoolean(MusicSettingsActivity.KEY_FLIP, false)) {
if (PITCH > nPITCH_UPER || PITCH < nPITCH_LOVER) {
if (ROLL < nROLL_UPER && ROLL > nROLL_LOVER) {
if (isPlaying()) {
pause();
IsWorked = true;
}
} else if (PITCH > nPITCH_UPER || PITCH < nPITCH_LOVER) {
if (IsWorked) {
if (!isPlaying()) {
play();
IsWorked = false;
}
}
}
}
}
}
public static void setSensivity(int sensivity) {
FLIP_SENS = sensivity - 0;
}
private void doPauseResume() {
if (isPlaying()) {
pause();
} else {
play();
}
}
private void doNext() {
next(true);
}
private void doPrev() {
if (position() < 2000) {
prev();
} else {
seek(0);
play();
}
}
@Override
public void shakingStarted() {
SharedPreferences preferences = getSharedPreferences(
MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
shake_actions_db = preferences.getString("shake_actions_db", "1");
if (shake_actions_db.equals("1")) {
doPauseResume();
}
shake_actions_db = preferences.getString("shake_actions_db", "2");
if (shake_actions_db.equals("2")) {
doNext();
}
shake_actions_db = preferences.getString("shake_actions_db", "3");
if (shake_actions_db.equals("3")) {
doPrev();
}
shake_actions_db = preferences.getString("shake_actions_db", "4");
if (shake_actions_db.equals("4")) {
Cursor cursor;
cursor = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { BaseColumns._ID }, AudioColumns.IS_MUSIC
+ "=1", null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor != null) {
MusicUtils.shuffleAll(this, cursor);
cursor.close();
}
}
shake_actions_db = preferences.getString("shake_actions_db", "5");
if (shake_actions_db.equals("5")) {
int shuffle = getShuffleMode();
if (shuffle == SHUFFLE_AUTO) {
setShuffleMode(SHUFFLE_NONE);
} else {
setShuffleMode(SHUFFLE_AUTO);
}
shake_actions_db = preferences.getString("shake_actions_db", "0");
if (shake_actions_db.equals("0")) {
// Nothing - this needs to stay last
}
}
}
@Override
public void shakingStopped() {
}
}
| private void reloadQueue() {
String q = null;
int id = mCardId;
if (mPreferences.contains("cardid")) {
id = mPreferences.getInt("cardid", ~mCardId);
}
if (id == mCardId) {
// Only restore the saved playlist if the card is still
// the same one as when the playlist was saved
q = mPreferences.getString("queue", "");
}
int qlen = q != null ? q.length() : 0;
if (qlen > 1) {
//Log.i("@@@@ service", "loaded queue: " + q);
int plen = 0;
int n = 0;
int shift = 0;
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
ensurePlayListCapacity(plen + 1);
mPlayList[plen] = n;
plen++;
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus playlist data
plen = 0;
break;
}
shift += 4;
}
}
mPlayListLen = plen;
int pos = mPreferences.getInt("curpos", 0);
if (pos < 0 || pos >= mPlayListLen) {
// The saved playlist is bogus, discard it
mPlayListLen = 0;
return;
}
mPlayPos = pos;
// When reloadQueue is called in response to a card-insertion,
// we might not be able to query the media provider right away.
// To deal with this, try querying for the current file, and if
// that fails, wait a while and try again. If that too fails,
// assume there is a problem and don't restore the state.
Cursor crsr = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null);
if (crsr == null || crsr.getCount() == 0) {
// wait a bit and try again
SystemClock.sleep(3000);
crsr = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null);
}
if (crsr != null) {
crsr.close();
}
// Make sure we don't auto-skip to the next song, since that
// also starts playback. What could happen in that case is:
// - music is paused
// - go to UMS and delete some files, including the currently playing one
// - come back from UMS
// (time passes)
// - music app is killed for some reason (out of memory)
// - music service is restarted, service restores state, doesn't find
// the "current" file, goes to the next and: playback starts on its
// own, potentially at some random inconvenient time.
mOpenFailedCounter = 20;
mQuietMode = true;
openCurrent();
mQuietMode = false;
if (!mPlayer.isInitialized()) {
// couldn't restore the saved state
mPlayListLen = 0;
return;
}
long seekpos = mPreferences.getLong("seekpos", 0);
seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0);
Log.d(LOGTAG, "restored queue, currently at position "
+ position() + "/" + duration()
+ " (requested " + seekpos + ")");
int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE);
if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) {
repmode = REPEAT_NONE;
}
mRepeatMode = repmode;
int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE);
if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) {
shufmode = SHUFFLE_NONE;
}
if (shufmode != SHUFFLE_NONE) {
// in shuffle mode we need to restore the history too
q = mPreferences.getString("history", "");
qlen = q != null ? q.length() : 0;
if (qlen > 1) {
plen = 0;
n = 0;
shift = 0;
mHistory.clear();
for (int i = 0; i < qlen; i++) {
char c = q.charAt(i);
if (c == ';') {
if (n >= mPlayListLen) {
// bogus history data
mHistory.clear();
break;
}
mHistory.add(n);
n = 0;
shift = 0;
} else {
if (c >= '0' && c <= '9') {
n += ((c - '0') << shift);
} else if (c >= 'a' && c <= 'f') {
n += ((10 + c - 'a') << shift);
} else {
// bogus history data
mHistory.clear();
break;
}
shift += 4;
}
}
}
}
if (shufmode == SHUFFLE_AUTO) {
if (! makeAutoShuffleList()) {
shufmode = SHUFFLE_NONE;
}
}
mShuffleMode = shufmode;
}
}
@Override
public IBinder onBind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
return mBinder;
}
@Override
public void onRebind(Intent intent) {
mDelayedStopHandler.removeCallbacksAndMessages(null);
mServiceInUse = true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mServiceStartId = startId;
mDelayedStopHandler.removeCallbacksAndMessages(null);
if (intent != null) {
String action = intent.getAction();
String cmd = intent.getStringExtra("command");
MusicUtils.debugLog("onStartCommand " + action + " / " + cmd);
if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
fadeDownAndNext();
} else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
if (position() < 2000) {
fadeDownAndPrev();
} else {
fadeDownAndSeek(0);
}
} else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
if (isPlaying()) {
fadeDownAndPause();
mPausedByTransientLossOfFocus = false;
} else {
play();
}
} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
fadeDownAndPause();
mPausedByTransientLossOfFocus = false;
} else if (CMDSTOP.equals(cmd)) {
fadeDownAndStop();
mPausedByTransientLossOfFocus = false;
} else if (CMDCYCLEREPEAT.equals(cmd) || CYCLEREPEAT_ACTION.equals(action)) {
cycleRepeat();
} else if (CMDTOGGLESHUFFLE.equals(cmd) || TOGGLESHUFFLE_ACTION.equals(action)) {
toggleShuffle();
} else if (PLAYSTATUS_REQUEST.equals(action)) {
notifyChange(PLAYSTATUS_RESPONSE);
}
}
// make sure the service will shut down on its own if it was
// just started but not bound to and nothing is playing
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return START_STICKY;
}
@Override
public boolean onUnbind(Intent intent) {
mServiceInUse = false;
// Take a snapshot of the current playlist
saveQueue(true);
if (isPlaying() || mPausedByTransientLossOfFocus) {
// something is currently playing, or will be playing once
// an in-progress action requesting audio focus ends, so don't stop the service now.
return true;
}
// If there is a playlist but playback is paused, then wait a while
// before stopping the service, so that pause/resume isn't slow.
// Also delay stopping the service if we're transitioning between tracks.
if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(MediaplayerHandler.MESSAGE_TRACK_ENDED)) {
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
return true;
}
// No active playlist, OK to stop the service right now
stopSelf(mServiceStartId);
return true;
}
private Handler mDelayedStopHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Check again to make sure nothing is playing right now
if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse
|| mMediaplayerHandler.hasMessages(MediaplayerHandler.MESSAGE_TRACK_ENDED)) {
return;
}
// save the queue again, because it might have changed
// since the user exited the music app (because of
// party-shuffle or because the play-position changed)
saveQueue(true);
stopSelf(mServiceStartId);
}
};
/**
* Called when we receive a ACTION_MEDIA_EJECT notification.
*
* @param storagePath path to mount point for the removed media
*/
public void closeExternalStorageFiles(String storagePath) {
// stop playback and clean up if the SD card is going to be unmounted.
stop(true);
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
/**
* Registers an intent to listen for ACTION_MEDIA_EJECT notifications.
* The intent will call closeExternalStorageFiles() if the external media
* is going to be ejected, so applications can clean up any files they have open.
*/
public void registerExternalStorageListener() {
if (mUnmountReceiver == null) {
mUnmountReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
saveQueue(true);
mQueueIsSaveable = false;
closeExternalStorageFiles(intent.getData().getPath());
} else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
mMediaMountedCount++;
mCardId = MusicUtils.getCardId(MediaPlaybackService.this);
reloadQueue();
mQueueIsSaveable = true;
notifyChange(QUEUE_CHANGED);
notifyChange(META_CHANGED);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
iFilter.addDataScheme("file");
registerReceiver(mUnmountReceiver, iFilter);
}
}
public void registerA2dpServiceListener() {
mA2dpReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(PLAYSTATUS_REQUEST)) {
notifyChange(PLAYSTATUS_RESPONSE);
}
}
};
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(PLAYSTATUS_REQUEST);
registerReceiver(mA2dpReceiver, iFilter);
}
/**
* Notify the change-receivers that something has changed.
* The intent that is sent contains the following data
* for the currently playing track:
* "id" - Integer: the database row ID
* "artist" - String: the name of the artist
* "album_artist" - String: the name of the album artist
* "album" - String: the name of the album
* "track" - String: the name of the track
* The intent has an action that is one of
* "com.android.music.metachanged"
* "com.android.music.queuechanged",
* "com.android.music.playbackcomplete"
* "com.android.music.playstatechanged"
* respectively indicating that a new track has
* started playing, that the playback queue has
* changed, that playback has stopped because
* the last file in the list has been played,
* or that the play-state changed (paused/resumed).
*/
private void notifyChange(String what) {
Intent i = new Intent(what);
i.putExtra("id", Long.valueOf(getAudioId()));
i.putExtra("artist", getArtistName());
i.putExtra("album_artist", getAlbumartistName());
i.putExtra("album",getAlbumName());
i.putExtra("track", getTrackName());
i.putExtra("playing", isPlaying());
i.putExtra("songid", getAudioId());
i.putExtra("albumid", getAlbumId());
i.putExtra("duration", duration());
i.putExtra("position", position());
if (mPlayList != null)
i.putExtra("ListSize", Long.valueOf(mPlayList.length));
else
i.putExtra("ListSize", Long.valueOf(mPlayListLen));
sendStickyBroadcast(i);
if (what.equals(QUEUE_CHANGED)) {
saveQueue(true);
} else {
saveQueue(false);
}
// Share this notification directly with our widgets
mAppWidgetProvider4x1.notifyChange(this, what);
mAppWidgetProvider4x2.notifyChange(this, what);
}
private void ensurePlayListCapacity(int size) {
if (mPlayList == null || size > mPlayList.length) {
// reallocate at 2x requested size so we don't
// need to grow and copy the array for every
// insert
long [] newlist = new long[size * 2];
int len = mPlayList != null ? mPlayList.length : mPlayListLen;
for (int i = 0; i < len; i++) {
newlist[i] = mPlayList[i];
}
mPlayList = newlist;
}
// FIXME: shrink the array when the needed size is much smaller
// than the allocated size
}
// insert the list of songs at the specified position in the playlist
private void addToPlayList(long [] list, int position) {
int addlen = list.length;
if (position < 0) { // overwrite
mPlayListLen = 0;
position = 0;
}
ensurePlayListCapacity(mPlayListLen + addlen);
if (position > mPlayListLen) {
position = mPlayListLen;
}
// move part of list after insertion point
int tailsize = mPlayListLen - position;
for (int i = tailsize ; i > 0 ; i--) {
mPlayList[position + i] = mPlayList[position + i - addlen];
}
// copy list into playlist
for (int i = 0; i < addlen; i++) {
mPlayList[position + i] = list[i];
}
mPlayListLen += addlen;
if (mPlayListLen == 0) {
mCursor.close();
mCursor = null;
notifyChange(META_CHANGED);
}
}
/**
* Appends a list of tracks to the current playlist.
* If nothing is playing currently, playback will be started at
* the first track.
* If the action is NOW, playback will switch to the first of
* the new tracks immediately.
* @param list The list of tracks to append.
* @param action NOW, NEXT or LAST
*/
public void enqueue(long [] list, int action) {
synchronized(this) {
if (action == NEXT && mPlayPos + 1 < mPlayListLen) {
addToPlayList(list, mPlayPos + 1);
notifyChange(QUEUE_CHANGED);
} else {
// action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen
addToPlayList(list, Integer.MAX_VALUE);
notifyChange(QUEUE_CHANGED);
if (action == NOW) {
mPlayPos = mPlayListLen - list.length;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
}
}
if (mPlayPos < 0) {
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
}
/**
* Replaces the current playlist with a new list,
* and prepares for starting playback at the specified
* position in the list, or a random position if the
* specified position is 0.
* @param list The new list of tracks.
*/
public void open(long [] list, int position) {
synchronized (this) {
if (mShuffleMode == SHUFFLE_AUTO) {
mShuffleMode = SHUFFLE_NORMAL;
}
long oldId = getAudioId();
int listlength = list.length;
boolean newlist = true;
if (mPlayListLen == listlength) {
// possible fast path: list might be the same
newlist = false;
for (int i = 0; i < listlength; i++) {
if (list[i] != mPlayList[i]) {
newlist = true;
break;
}
}
}
if (newlist) {
addToPlayList(list, -1);
notifyChange(QUEUE_CHANGED);
}
if (position >= 0) {
mPlayPos = position;
} else {
mPlayPos = mRand.nextInt(mPlayListLen);
}
mHistory.clear();
saveBookmarkIfNeeded();
openCurrent();
if (oldId != getAudioId()) {
notifyChange(META_CHANGED);
}
}
}
/**
* Moves the item at index1 to index2.
* @param index1
* @param index2
*/
public void moveQueueItem(int index1, int index2) {
synchronized (this) {
if (index1 >= mPlayListLen) {
index1 = mPlayListLen - 1;
}
if (index2 >= mPlayListLen) {
index2 = mPlayListLen - 1;
}
if (index1 < index2) {
long tmp = mPlayList[index1];
for (int i = index1; i < index2; i++) {
mPlayList[i] = mPlayList[i+1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index1 && mPlayPos <= index2) {
mPlayPos--;
}
} else if (index2 < index1) {
long tmp = mPlayList[index1];
for (int i = index1; i > index2; i--) {
mPlayList[i] = mPlayList[i-1];
}
mPlayList[index2] = tmp;
if (mPlayPos == index1) {
mPlayPos = index2;
} else if (mPlayPos >= index2 && mPlayPos <= index1) {
mPlayPos++;
}
}
notifyChange(QUEUE_CHANGED);
}
}
/**
* Returns the current play list
* @return An array of integers containing the IDs of the tracks in the play list
*/
public long [] getQueue() {
synchronized (this) {
int len = mPlayListLen;
long [] list = new long[len];
for (int i = 0; i < len; i++) {
list[i] = mPlayList[i];
}
return list;
}
}
private void openCurrent() {
synchronized (this) {
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (mPlayListLen == 0) {
return;
}
stop(false);
String id = String.valueOf(mPlayList[mPlayPos]);
mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
mCursorCols, "_id=" + id , null, null);
if (mCursor != null) {
mCursor.moveToFirst();
open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id);
// go to bookmark if needed
if (isPodcast()) {
long bookmark = getBookmark();
// Start playing a little bit before the bookmark,
// so it's easier to get back in to the narrative.
seek(bookmark - 5000);
}
}
}
}
/**
* Opens the specified file and readies it for playback.
*
* @param path The full path of the file to be opened.
*/
public void open(String path) {
synchronized (this) {
if (path == null) {
return;
}
// if mCursor is null, try to associate path with a database cursor
if (mCursor == null) {
ContentResolver resolver = getContentResolver();
Uri uri;
String where;
String selectionArgs[];
if (path.startsWith("content://media/")) {
uri = Uri.parse(path);
where = null;
selectionArgs = null;
} else {
uri = MediaStore.Audio.Media.getContentUriForPath(path);
where = MediaStore.Audio.Media.DATA + "=?";
selectionArgs = new String[] { path };
}
try {
mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null);
if (mCursor != null) {
if (mCursor.getCount() == 0) {
mCursor.close();
mCursor = null;
} else {
mCursor.moveToNext();
ensurePlayListCapacity(1);
mPlayListLen = 1;
mPlayList[0] = mCursor.getLong(IDCOLIDX);
mPlayPos = 0;
}
}
} catch (UnsupportedOperationException ex) {
}
}
mFileToPlay = path;
mPlayer.setDataSource(mFileToPlay);
if (! mPlayer.isInitialized()) {
stop(true);
if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) {
// beware: this ends up being recursive because next() calls open() again.
next(false);
}
if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) {
// need to make sure we only shows this once
mOpenFailedCounter = 0;
if (!mQuietMode) {
Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show();
}
Log.d(LOGTAG, "Failed to open file for playback");
}
} else {
mOpenFailedCounter = 0;
}
}
}
/**
* Starts playback of a previously opened file.
*/
public void play() {
TelephonyManager telephonyManager =
(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
return;
}
mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(),
MediaButtonIntentReceiver.class.getName()));
telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
if (mPlayer.isInitialized()) {
// if we are at the end of the song, go to the next song first
long duration = mPlayer.duration();
if (mRepeatMode != REPEAT_CURRENT && duration > 2000 &&
mPlayer.position() >= duration - 2000) {
next(true);
}
mPlayer.start();
// make sure we fade in, in case a previous fadein was stopped because
// of another focus loss
fadeUp();
if (Settings.System.getInt(getContentResolver(), Settings.System.EXPANDED_VIEW_WIDGET, 0) == 0) {
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.statusbar);
views.setImageViewBitmap(R.id.icon, MusicUtils.getArtwork(
getBaseContext(), getAudioId(), getAlbumId(), true));
SharedPreferences preferences = getSharedPreferences(
MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
mPreferences.getBoolean(MusicSettingsActivity.KEY_TICK, false);
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_SONG_TEXT, true)) {
views.setViewVisibility(R.id.trackname, View.VISIBLE);
} else {
views.setViewVisibility(R.id.trackname, View.INVISIBLE);
}
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_ARTIST_TEXT, true)) {
views.setViewVisibility(R.id.artist, View.VISIBLE);
} else {
views.setViewVisibility(R.id.artist, View.GONE);
}
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_ALBUM_ART, true)) {
views.setViewVisibility(R.id.icon, View.VISIBLE);
views.setViewVisibility(R.id.status_icon, View.GONE);
} else {
views.setViewVisibility(R.id.icon, View.GONE);
views.setViewVisibility(R.id.status_icon, View.VISIBLE);
views.setImageViewResource(R.id.status_icon,
R.drawable.stat_notify_musicplayer);
}
if (preferences.getBoolean(
MusicSettingsActivity.KEY_ENABLE_STATUS_NONYA, false)) {
views.setViewVisibility(R.id.icon, View.GONE);
views.setViewVisibility(R.id.status_icon, View.GONE);
}
if (getAudioId() < 0) {
// streaming
views.setTextViewText(R.id.trackname, getPath());
views.setTextViewText(R.id.artist, null);
} else {
String artist = getArtistName();
views.setTextViewText(R.id.trackname, getTrackName());
if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) {
artist = getString(R.string.unknown_artist_name);
}
String album = getAlbumName();
if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) {
album = getString(R.string.unknown_album_name);
}
views.setTextViewText(R.id.artist, getString(R.string.notification_artist_album, artist, album));
}
Notification status = new Notification();
status.contentView = views;
status.flags |= Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.stat_notify_musicplayer;
if (preferences.getBoolean(MusicSettingsActivity.KEY_TICK, true)) {
status.tickerText = getTrackName() + " by " + getArtistName();
}
status.contentIntent = PendingIntent.getActivity(this, 0,
new Intent("com.android.music.PLAYBACK_VIEWER")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
startForeground(PLAYBACKSERVICE_STATUS, status);
}
if (!mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = true;
notifyChange(PLAYSTATE_CHANGED);
}
mPausedByIncomingAlarm = false;
} else if (mPlayListLen <= 0) {
// This is mostly so that if you press 'play' on a bluetooth headset
// without every having played anything before, it will still play
// something.
setShuffleMode(SHUFFLE_AUTO);
}
}
private void stop(boolean remove_status_icon) {
if (mPlayer.isInitialized()) {
mPlayer.stop();
}
mFileToPlay = null;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
if (remove_status_icon) {
gotoIdleState();
} else {
stopForeground(false);
}
if (remove_status_icon) {
mIsSupposedToBePlaying = false;
}
}
/**
* Stops playback.
*/
public void stop() {
stop(true);
}
/**
* Pauses playback (call play() to resume)
*/
public void pause() {
synchronized(this) {
fadeDown();
if (isPlaying()) {
mPlayer.pause();
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
saveBookmarkIfNeeded();
}
}
}
private void fade(float newVolume, Message andThen) {
mMediaplayerHandler.removeMessages(MediaplayerHandler.MESSAGE_FADE);
mMediaplayerHandler.mTargetVolume = newVolume;
mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_FADE, andThen).sendToTarget();
}
private void fade(float newVolume) {
fade(newVolume, null);
}
public void fadeUp() {
fade(VOLUME_FULL);
}
public void fadeDown() {
fade(VOLUME_MUTE);
}
public void fadeDownAndStop() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_STOP));
}
public void fadeDownAndPause() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_PAUSE));
}
public void fadeDownAndNext() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_NEXT));
}
public void fadeDownAndPrev() {
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_PREV));
}
public void fadeDownAndSeek(long pos) {
mMediaplayerHandler.mTargetPos = pos;
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_SEEK));
}
public void fadeDownAndSetQueuePosition(int pos) {
mMediaplayerHandler.mTargetQueuePos = pos;
fade(VOLUME_MUTE, mMediaplayerHandler.obtainMessage(MediaplayerHandler.MESSAGE_SET_QUEUEPOS));
}
/** Returns whether something is currently playing
*
* @return true if something is playing (or will be playing shortly, in case
* we're currently transitioning between tracks), false if not.
*/
public boolean isPlaying() {
return mIsSupposedToBePlaying;
}
/*
Desired behavior for prev/next/shuffle:
- NEXT will move to the next track in the list when not shuffling, and to
a track randomly picked from the not-yet-played tracks when shuffling.
If all tracks have already been played, pick from the full set, but
avoid picking the previously played track if possible.
- when shuffling, PREV will go to the previously played track. Hitting PREV
again will go to the track played before that, etc. When the start of the
history has been reached, PREV is a no-op.
When not shuffling, PREV will go to the sequentially previous track (the
difference with the shuffle-case is mainly that when not shuffling, the
user can back up to tracks that are not in the history).
Example:
When playing an album with 10 tracks from the start, and enabling shuffle
while playing track 5, the remaining tracks (6-10) will be shuffled, e.g.
the final play order might be 1-2-3-4-5-8-10-6-9-7.
When hitting 'prev' 8 times while playing track 7 in this example, the
user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next',
a random track will be picked again. If at any time user disables shuffling
the next/previous track will be picked in sequential order again.
*/
public void prev() {
synchronized (this) {
if (position() > 2000) {
seek(0);
} else {
if (mShuffleMode == SHUFFLE_NORMAL) {
// go to previously-played track and remove it from the history
int histsize = mHistory.size();
if (histsize == 0) {
// prev is a no-op
fadeUp();
return;
}
Integer pos = mHistory.remove(histsize - 1);
mPlayPos = pos.intValue();
} else {
if (mPlayPos > 0) {
mPlayPos--;
} else {
mPlayPos = mPlayListLen - 1;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
}
play();
notifyChange(META_CHANGED);
}
}
public void next(boolean force) {
synchronized (this) {
if (mPlayListLen <= 0) {
Log.d(LOGTAG, "No play queue");
return;
}
if (mShuffleMode == SHUFFLE_NORMAL) {
// Pick random next track from the not-yet-played ones
// TODO: make it work right after adding/removing items in the queue.
// Store the current file in the history, but keep the history at a
// reasonable size
if (mPlayPos >= 0) {
mHistory.add(mPlayPos);
}
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.removeElementAt(0);
}
int numTracks = mPlayListLen;
int[] tracks = new int[numTracks];
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
int numHistory = mHistory.size();
int numUnplayed = numTracks;
for (int i=0;i < numHistory; i++) {
int idx = mHistory.get(i).intValue();
if (idx < numTracks && tracks[idx] >= 0) {
numUnplayed--;
tracks[idx] = -1;
}
}
// 'numUnplayed' now indicates how many tracks have not yet
// been played, and 'tracks' contains the indices of those
// tracks.
if (numUnplayed <=0) {
// everything's already been played
if (mRepeatMode == REPEAT_ALL || force) {
//pick from full set
numUnplayed = numTracks;
for (int i=0;i < numTracks; i++) {
tracks[i] = i;
}
} else {
// all done
gotoIdleState();
if (mIsSupposedToBePlaying) {
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
}
return;
}
}
int skip = mRand.nextInt(numUnplayed);
int cnt = -1;
while (true) {
while (tracks[++cnt] < 0)
;
skip--;
if (skip < 0) {
break;
}
}
mPlayPos = cnt;
} else if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
mPlayPos++;
} else {
if (mPlayPos >= mPlayListLen - 1) {
// we're at the end of the list
if (mRepeatMode == REPEAT_NONE && !force) {
// all done
gotoIdleState();
mIsSupposedToBePlaying = false;
notifyChange(PLAYSTATE_CHANGED);
return;
} else if (mRepeatMode == REPEAT_ALL || force) {
mPlayPos = 0;
}
} else {
mPlayPos++;
}
}
saveBookmarkIfNeeded();
stop(false);
openCurrent();
play();
notifyChange(META_CHANGED);
}
}
public void cycleRepeat() {
if (mRepeatMode == REPEAT_NONE) {
setRepeatMode(REPEAT_ALL);
} else if (mRepeatMode == REPEAT_ALL) {
setRepeatMode(REPEAT_CURRENT);
if (mShuffleMode != SHUFFLE_NONE) {
setShuffleMode(SHUFFLE_NONE);
}
} else {
setRepeatMode(REPEAT_NONE);
}
}
public void toggleShuffle() {
if (mShuffleMode == SHUFFLE_NONE) {
setShuffleMode(SHUFFLE_NORMAL);
if (mRepeatMode == REPEAT_CURRENT) {
setRepeatMode(REPEAT_ALL);
}
} else if (mShuffleMode == SHUFFLE_NORMAL || mShuffleMode == SHUFFLE_AUTO) {
setShuffleMode(SHUFFLE_NONE);
} else {
Log.e("MediaPlaybackService", "Invalid shuffle mode: " + mShuffleMode);
}
}
private void gotoIdleState() {
mDelayedStopHandler.removeCallbacksAndMessages(null);
Message msg = mDelayedStopHandler.obtainMessage();
mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
stopForeground(true);
}
private void saveBookmarkIfNeeded() {
try {
if (isPodcast()) {
long pos = position();
long bookmark = getBookmark();
long duration = duration();
if ((pos < bookmark && (pos + 10000) > bookmark) ||
(pos > bookmark && (pos - 10000) < bookmark)) {
// The existing bookmark is close to the current
// position, so don't update it.
return;
}
if (pos < 15000 || (pos + 10000) > duration) {
// if we're near the start or end, clear the bookmark
pos = 0;
}
// write 'pos' to the bookmark field
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.BOOKMARK, pos);
Uri uri = ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX));
getContentResolver().update(uri, values, null, null);
}
} catch (SQLiteException ex) {
}
}
// Make sure there are at least 5 items after the currently playing item
// and no more than 10 items before.
private void doAutoShuffleUpdate() {
boolean notify = false;
// remove old entries
if (mPlayPos > 10) {
removeTracks(0, mPlayPos - 9);
notify = true;
}
// add new entries if needed
int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos));
for (int i = 0; i < to_add; i++) {
// pick something at random from the list
int lookback = mHistory.size();
int idx = -1;
while(true) {
idx = mRand.nextInt(mAutoShuffleList.length);
if (!wasRecentlyUsed(idx, lookback)) {
break;
}
lookback /= 2;
}
mHistory.add(idx);
if (mHistory.size() > MAX_HISTORY_SIZE) {
mHistory.remove(0);
}
ensurePlayListCapacity(mPlayListLen + 1);
mPlayList[mPlayListLen++] = mAutoShuffleList[idx];
notify = true;
}
if (notify) {
notifyChange(QUEUE_CHANGED);
}
}
// check that the specified idx is not in the history (but only look at at
// most lookbacksize entries in the history)
private boolean wasRecentlyUsed(int idx, int lookbacksize) {
// early exit to prevent infinite loops in case idx == mPlayPos
if (lookbacksize == 0) {
return false;
}
int histsize = mHistory.size();
if (histsize < lookbacksize) {
Log.d(LOGTAG, "lookback too big");
lookbacksize = histsize;
}
int maxidx = histsize - 1;
for (int i = 0; i < lookbacksize; i++) {
long entry = mHistory.get(maxidx - i);
if (entry == idx) {
return true;
}
}
return false;
}
// A simple variation of Random that makes sure that the
// value it returns is not equal to the value it returned
// previously, unless the interval is 1.
private static class Shuffler {
private int mPrevious;
private Random mRandom = new Random();
public int nextInt(int interval) {
int ret;
do {
ret = mRandom.nextInt(interval);
} while (ret == mPrevious && interval > 1);
mPrevious = ret;
return ret;
}
};
private boolean makeAutoShuffleList() {
ContentResolver res = getContentResolver();
Cursor c = null;
try {
c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
null, null);
if (c == null || c.getCount() == 0) {
return false;
}
int len = c.getCount();
long [] list = new long[len];
for (int i = 0; i < len; i++) {
c.moveToNext();
list[i] = c.getLong(0);
}
mAutoShuffleList = list;
return true;
} catch (RuntimeException ex) {
} finally {
if (c != null) {
c.close();
}
}
return false;
}
/**
* Removes the range of tracks specified from the play list. If a file within the range is
* the file currently being played, playback will move to the next file after the
* range.
* @param first The first file to be removed
* @param last The last file to be removed
* @return the number of tracks deleted
*/
public int removeTracks(int first, int last) {
int numremoved = removeTracksInternal(first, last);
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
private int removeTracksInternal(int first, int last) {
synchronized (this) {
if (last < first) return 0;
if (first < 0) first = 0;
if (last >= mPlayListLen) last = mPlayListLen - 1;
boolean gotonext = false;
if (first <= mPlayPos && mPlayPos <= last) {
mPlayPos = first;
gotonext = true;
} else if (mPlayPos > last) {
mPlayPos -= (last - first + 1);
}
int num = mPlayListLen - last - 1;
for (int i = 0; i < num; i++) {
mPlayList[first + i] = mPlayList[last + 1 + i];
}
mPlayListLen -= last - first + 1;
if (gotonext) {
if (mPlayListLen == 0) {
stop(true);
mPlayPos = -1;
if (mCursor != null) {
mCursor.close();
mCursor = null;
}
} else {
if (mPlayPos >= mPlayListLen) {
mPlayPos = 0;
}
boolean wasPlaying = isPlaying();
stop(false);
openCurrent();
if (wasPlaying) {
play();
}
}
notifyChange(META_CHANGED);
}
return last - first + 1;
}
}
/**
* Removes all instances of the track with the given id
* from the playlist.
* @param id The id to be removed
* @return how many instances of the track were removed
*/
public int removeTrack(long id) {
int numremoved = 0;
synchronized (this) {
for (int i = 0; i < mPlayListLen; i++) {
if (mPlayList[i] == id) {
numremoved += removeTracksInternal(i, i);
i--;
}
}
}
if (numremoved > 0) {
notifyChange(QUEUE_CHANGED);
}
return numremoved;
}
public void setShuffleMode(int shufflemode) {
synchronized(this) {
if (mShuffleMode == shufflemode && mPlayListLen > 0) {
return;
}
mShuffleMode = shufflemode;
notifyChange(SHUFFLEMODE_CHANGED);
if (mShuffleMode == SHUFFLE_AUTO) {
if (makeAutoShuffleList()) {
mPlayListLen = 0;
doAutoShuffleUpdate();
mPlayPos = 0;
openCurrent();
play();
notifyChange(META_CHANGED);
return;
} else {
// failed to build a list of files to shuffle
mShuffleMode = SHUFFLE_NONE;
}
}
saveQueue(false);
}
}
public int getShuffleMode() {
return mShuffleMode;
}
public void setRepeatMode(int repeatmode) {
synchronized(this) {
mRepeatMode = repeatmode;
notifyChange(REPEATMODE_CHANGED);
saveQueue(false);
}
}
public int getRepeatMode() {
return mRepeatMode;
}
public int getMediaMountedCount() {
return mMediaMountedCount;
}
/**
* Returns the path of the currently playing file, or null if
* no file is currently playing.
*/
public String getPath() {
return mFileToPlay;
}
/**
* Returns the rowid of the currently playing file, or -1 if
* no file is currently playing.
*/
public long getAudioId() {
synchronized (this) {
if (mPlayPos >= 0 && mPlayer.isInitialized()) {
return mPlayList[mPlayPos];
}
}
return -1;
}
/**
* Returns the position in the queue
* @return the position in the queue
*/
public int getQueuePosition() {
synchronized(this) {
return mPlayPos;
}
}
/**
* Starts playing the track at the given position in the queue.
* @param pos The position in the queue of the track that will be played.
*/
public void setQueuePosition(int pos) {
synchronized(this) {
stop(false);
mPlayPos = pos;
openCurrent();
play();
notifyChange(META_CHANGED);
if (mShuffleMode == SHUFFLE_AUTO) {
doAutoShuffleUpdate();
}
}
}
public String getArtistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
}
}
public long getArtistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID));
}
}
public String getAlbumartistName() {
synchronized(this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ARTIST));
}
}
public long getAlbumartistId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ARTIST_ID));
}
}
public String getAlbumName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
}
}
public long getAlbumId() {
synchronized (this) {
if (mCursor == null) {
return -1;
}
return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
public String getTrackName() {
synchronized (this) {
if (mCursor == null) {
return null;
}
return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
}
}
private boolean isPodcast() {
synchronized (this) {
if (mCursor == null) {
return false;
}
return (mCursor.getInt(PODCASTCOLIDX) > 0);
}
}
private long getBookmark() {
synchronized (this) {
if (mCursor == null) {
return 0;
}
return mCursor.getLong(BOOKMARKCOLIDX);
}
}
/**
* Returns the duration of the file in milliseconds.
* Currently this method returns -1 for the duration of MIDI files.
*/
public long duration() {
if (mPlayer.isInitialized()) {
return mPlayer.duration();
}
return -1;
}
/**
* Returns the current playback position in milliseconds
*/
public long position() {
if (mPlayer.isInitialized()) {
return mPlayer.position();
}
return -1;
}
/**
* Seeks to the position specified.
*
* @param pos The position to seek to, in milliseconds
*/
public long seek(long pos) {
if (mPlayer.isInitialized()) {
if (pos < 0) pos = 0;
if (pos > mPlayer.duration()) pos = mPlayer.duration();
long result = mPlayer.seek(pos);
fadeUp();
return result;
}
return -1;
}
/**
* Sets the audio session ID.
*
* @param sessionId: the audio session ID.
*/
public void setAudioSessionId(int sessionId) {
synchronized (this) {
mPlayer.setAudioSessionId(sessionId);
}
}
/**
* Returns the audio session ID.
*/
public int getAudioSessionId() {
synchronized (this) {
return mPlayer.getAudioSessionId();
}
}
/**
* Provides a unified interface for dealing with midi files and
* other media files.
*/
private class MultiPlayer {
private MediaPlayer mMediaPlayer = new MediaPlayer();
private Handler mHandler;
private boolean mIsInitialized = false;
public MultiPlayer() {
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
}
public void setDataSource(String path) {
try {
mMediaPlayer.reset();
mMediaPlayer.setOnPreparedListener(null);
if (path.startsWith("content://")) {
mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path));
} else {
mMediaPlayer.setDataSource(path);
}
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.prepare();
} catch (IOException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
} catch (IllegalArgumentException ex) {
// TODO: notify the user why the file couldn't be opened
mIsInitialized = false;
return;
}
mMediaPlayer.setOnCompletionListener(listener);
mMediaPlayer.setOnErrorListener(errorListener);
Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId());
i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
sendBroadcast(i);
mIsInitialized = true;
}
public boolean isInitialized() {
return mIsInitialized;
}
public void start() {
MusicUtils.debugLog(new Exception("MultiPlayer.start called"));
mMediaPlayer.start();
}
public void stop() {
mMediaPlayer.reset();
mIsInitialized = false;
}
/**
* You CANNOT use this player anymore after calling release()
*/
public void release() {
stop();
mMediaPlayer.release();
}
public void pause() {
mMediaPlayer.pause();
}
public void setHandler(Handler handler) {
mHandler = handler;
}
MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Acquire a temporary wakelock, since when we return from
// this callback the MediaPlayer will release its wakelock
// and allow the device to go to sleep.
// This temporary wakelock is released when the RELEASE_WAKELOCK
// message is processed, but just in case, put a timeout on it.
mWakeLock.acquire(30000);
mHandler.sendEmptyMessage(MediaplayerHandler.MESSAGE_TRACK_ENDED);
mHandler.sendEmptyMessage(MediaplayerHandler.MESSAGE_RELEASE_WAKELOCK);
}
};
MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
mIsInitialized = false;
mMediaPlayer.release();
// Creating a new MediaPlayer and settings its wakemode does not
// require the media service, so it's OK to do this now, while the
// service is still being restarted
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MediaplayerHandler.MESSAGE_SERVER_DIED), 2000);
return true;
default:
Log.d("MultiPlayer", "Error: " + what + "," + extra);
break;
}
return false;
}
};
public long duration() {
return mMediaPlayer.getDuration();
}
public long position() {
return mMediaPlayer.getCurrentPosition();
}
public long seek(long whereto) {
mMediaPlayer.seekTo((int) whereto);
return whereto;
}
public void setVolume(float vol) {
mMediaPlayer.setVolume(vol, vol);
mCurrentVolume = vol;
}
public void setAudioSessionId(int sessionId) {
mMediaPlayer.setAudioSessionId(sessionId);
}
public int getAudioSessionId() {
return mMediaPlayer.getAudioSessionId();
}
}
/*
* By making this a static class with a WeakReference to the Service, we
* ensure that the Service can be GCd even when the system process still
* has a remote reference to the stub.
*/
static class ServiceStub extends IMediaPlaybackService.Stub {
WeakReference<MediaPlaybackService> mService;
ServiceStub(MediaPlaybackService service) {
mService = new WeakReference<MediaPlaybackService>(service);
}
public void openFile(String path)
{
mService.get().open(path);
}
public void open(long [] list, int position) {
mService.get().open(list, position);
}
public int getQueuePosition() {
return mService.get().getQueuePosition();
}
public void setQueuePosition(int index) {
mService.get().fadeDownAndSetQueuePosition(index);
}
public boolean isPlaying() {
return mService.get().isPlaying();
}
public void stop() {
mService.get().fadeDownAndStop();
}
public void pause() {
mService.get().fadeDownAndPause();
}
public void play() {
mService.get().play();
}
public void prev() {
mService.get().fadeDownAndPrev();
}
public void next() {
mService.get().fadeDownAndNext();
}
public void cycleRepeat() {
mService.get().cycleRepeat();
}
public void toggleShuffle() {
mService.get().toggleShuffle();
}
public String getTrackName() {
return mService.get().getTrackName();
}
public String getAlbumName() {
return mService.get().getAlbumName();
}
public long getAlbumId() {
return mService.get().getAlbumId();
}
public String getArtistName() {
return mService.get().getArtistName();
}
public long getArtistId() {
return mService.get().getArtistId();
}
public String getAlbumartistName() {
return mService.get().getAlbumartistName();
}
public long getAlbumartistId() {
return mService.get().getAlbumartistId();
}
public void enqueue(long [] list , int action) {
mService.get().enqueue(list, action);
}
public long [] getQueue() {
return mService.get().getQueue();
}
public void moveQueueItem(int from, int to) {
mService.get().moveQueueItem(from, to);
}
public String getPath() {
return mService.get().getPath();
}
public long getAudioId() {
return mService.get().getAudioId();
}
public long position() {
return mService.get().position();
}
public long duration() {
return mService.get().duration();
}
public long seek(long pos) {
// try to avoid jumping of seekbar, not always successful
// but there's no way to fade and return the correct position immediately
long currentPos = mService.get().position();
mService.get().fadeDownAndSeek(pos);
return currentPos;
}
public void setShuffleMode(int shufflemode) {
mService.get().setShuffleMode(shufflemode);
}
public int getShuffleMode() {
return mService.get().getShuffleMode();
}
public int removeTracks(int first, int last) {
return mService.get().removeTracks(first, last);
}
public int removeTrack(long id) {
return mService.get().removeTrack(id);
}
public void setRepeatMode(int repeatmode) {
mService.get().setRepeatMode(repeatmode);
}
public int getRepeatMode() {
return mService.get().getRepeatMode();
}
public int getMediaMountedCount() {
return mService.get().getMediaMountedCount();
}
public int getAudioSessionId() {
return mService.get().getAudioSessionId();
}
}
@Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
writer.println("" + mPlayListLen + " items in queue, currently at index " + mPlayPos);
writer.println("Currently loaded:");
writer.println(getArtistName());
writer.println(getAlbumartistName());
writer.println(getAlbumName());
writer.println(getTrackName());
writer.println(getPath());
writer.println("playing: " + mIsSupposedToBePlaying);
writer.println("actual: " + mPlayer.mMediaPlayer.isPlaying());
writer.println("shuffle mode: " + mShuffleMode);
MusicUtils.debugDump(writer);
}
private final IBinder mBinder = new ServiceStub(this);
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
SharedPreferences preferences = getSharedPreferences(
MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
mPreferences.getBoolean(MusicSettingsActivity.KEY_FLIP, false);
SharedPreferences mPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
int flipChange = new Integer(mPrefs.getInt(
MusicSettingsActivity.FLIP_SENSITIVITY,
MusicSettingsActivity.DEFAULT_FLIP_SENS));
FLIP_SENS = flipChange;
float vals[] = event.values;
PITCH = vals[1];// Pitch
ROLL = vals[2];// Roll
int nPITCH_UPER = PITCH_UPER;
int nPITCH_LOVER = PITCH_LOVER;
int nROLL_UPER = ROLL_UPER;
int nROLL_LOVER = ROLL_LOVER;
if (FLIP_SENS != 0) {
nPITCH_UPER = PITCH_UPER - FLIP_SENS;
nPITCH_LOVER = PITCH_LOVER + FLIP_SENS;
nROLL_UPER = ROLL_UPER + FLIP_SENS;
nROLL_LOVER = ROLL_LOVER - FLIP_SENS;
}
if (preferences.getBoolean(MusicSettingsActivity.KEY_FLIP, false)) {
if (PITCH > nPITCH_UPER || PITCH < nPITCH_LOVER) {
if (ROLL < nROLL_UPER && ROLL > nROLL_LOVER) {
if (isPlaying()) {
pause();
IsWorked = true;
}
} else if (PITCH > nPITCH_UPER || PITCH < nPITCH_LOVER) {
if (IsWorked) {
if (!isPlaying()) {
play();
IsWorked = false;
}
}
}
}
}
}
public static void setSensivity(int sensivity) {
FLIP_SENS = sensivity - 0;
}
private void doPauseResume() {
if (isPlaying()) {
pause();
} else {
play();
}
}
private void doNext() {
next(true);
}
private void doPrev() {
if (position() < 2000) {
prev();
} else {
seek(0);
play();
}
}
@Override
public void shakingStarted() {
SharedPreferences preferences = getSharedPreferences(
MusicSettingsActivity.PREFERENCES_FILE, MODE_PRIVATE);
shake_actions_db = preferences.getString("shake_actions_db", "1");
if (shake_actions_db.equals("1")) {
doPauseResume();
}
shake_actions_db = preferences.getString("shake_actions_db", "2");
if (shake_actions_db.equals("2")) {
doNext();
}
shake_actions_db = preferences.getString("shake_actions_db", "3");
if (shake_actions_db.equals("3")) {
doPrev();
}
shake_actions_db = preferences.getString("shake_actions_db", "4");
if (shake_actions_db.equals("4")) {
Cursor cursor;
cursor = MusicUtils.query(this,
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { BaseColumns._ID }, AudioColumns.IS_MUSIC
+ "=1", null,
MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor != null) {
MusicUtils.shuffleAll(this, cursor);
cursor.close();
}
}
shake_actions_db = preferences.getString("shake_actions_db", "5");
if (shake_actions_db.equals("5")) {
int shuffle = getShuffleMode();
if (shuffle == SHUFFLE_AUTO) {
setShuffleMode(SHUFFLE_NONE);
} else {
setShuffleMode(SHUFFLE_AUTO);
}
}
shake_actions_db = preferences.getString("shake_actions_db", "0");
if (shake_actions_db.equals("0")) {
// Nothing - this needs to stay last
}
}
@Override
public void shakingStopped() {
}
}
|
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/packets/hierarchical/election/BullyAlive.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/packets/hierarchical/election/BullyAlive.java
index 0ed0634c..7b81ed5d 100644
--- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/packets/hierarchical/election/BullyAlive.java
+++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/packets/hierarchical/election/BullyAlive.java
@@ -1,43 +1,43 @@
/*******************************************************************************
* Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management
* Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau.
*
* 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 de.tuilmenau.ics.fog.packets.hierarchical.election;
import de.tuilmenau.ics.fog.facade.Name;
import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID;
/**
* PACKET: It is used to signal that a peer is still alive.
* The packet has to be send as broadcast.
*/
public class BullyAlive extends SignalingMessageBully
{
private static final long serialVersionUID = 4870662765189881992L;
/**
* Constructor
*
* @param pSenderName the name of the message sender
*/
- public BullyAlive(Name pSenderName) //TODO: ev. sollte hier auch die Prio. �bermittelt werden, so dass man nicht immer erst auf das BullyElect warten muss
+ public BullyAlive(Name pSenderName)
{
super(pSenderName, HRMID.createBroadcast());
}
/**
* Returns a describing string
*
* @return the describing string
*/
@Override
public String toString()
{
return getClass().getSimpleName() + "(Sender=" + getSenderName() + ", Receiver=" + getReceiverName() + ")";
}
}
| true | true | public BullyAlive(Name pSenderName) //TODO: ev. sollte hier auch die Prio. �bermittelt werden, so dass man nicht immer erst auf das BullyElect warten muss
{
super(pSenderName, HRMID.createBroadcast());
}
| public BullyAlive(Name pSenderName)
{
super(pSenderName, HRMID.createBroadcast());
}
|
diff --git a/src/main/java/net/krinsoft/privileges/commands/InfoCommand.java b/src/main/java/net/krinsoft/privileges/commands/InfoCommand.java
index 5e7f43e..3ab464d 100644
--- a/src/main/java/net/krinsoft/privileges/commands/InfoCommand.java
+++ b/src/main/java/net/krinsoft/privileges/commands/InfoCommand.java
@@ -1,65 +1,65 @@
package net.krinsoft.privileges.commands;
import net.krinsoft.privileges.Privileges;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
/**
* @author krinsdeath
*/
public class InfoCommand extends PrivilegesCommand {
public InfoCommand(Privileges plugin) {
super(plugin);
setName("Privileges: Info");
setCommandUsage("/priv info [PLAYER]");
setArgRange(0, 1);
addKey("privileges info");
addKey("priv info");
addKey("pinfo");
addKey("pi");
setPermission("privileges.info", "Allows the user to check information about themselves or others.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
List<String> lines = new ArrayList<String>();
CommandSender target = sender;
if (args.size() == 1) {
target = plugin.getServer().getPlayer(args.get(0));
if (target == null) {
if (sender instanceof ConsoleCommandSender) {
sender.sendMessage(ChatColor.RED + "Target must exist from Console.");
return;
}
target = sender;
}
} else {
if (sender instanceof ConsoleCommandSender) {
sender.sendMessage(ChatColor.RED + "Target must exist from Console.");
return;
}
}
- if (target.equals(sender) && !sender.hasPermission("privileges.info.other")) {
+ if (!target.equals(sender) && !sender.hasPermission("privileges.info.other")) {
sender.sendMessage(ChatColor.RED + "You cannot view other peoples' information.");
return;
}
lines.add("=== User Info: " + ChatColor.BLUE + target.getName() + ChatColor.WHITE + " ===");
lines.add("Is " + ChatColor.AQUA + target.getName() + ChatColor.WHITE + " an op? " + ChatColor.GREEN + (target.isOp() ? "Yes." : "No."));
if (!target.getName().equals(((Player)target).getDisplayName())) {
lines.add(ChatColor.AQUA + target.getName() + ChatColor.WHITE + " is currently known as '" + ChatColor.AQUA + ((Player)target).getDisplayName() + ChatColor.WHITE + "'");
}
lines.add(ChatColor.AQUA + target.getName() + ChatColor.WHITE + "'s group is: " + ChatColor.GREEN + plugin.getGroupManager().getGroup((OfflinePlayer)target).getName());
lines.add(ChatColor.AQUA + target.getName() + ChatColor.WHITE + "'s current world is: " + ChatColor.GREEN + ((Player)target).getWorld().getName() + ChatColor.WHITE + ".");
for (String line : lines) {
sender.sendMessage(line);
}
}
}
| true | true | public void runCommand(CommandSender sender, List<String> args) {
List<String> lines = new ArrayList<String>();
CommandSender target = sender;
if (args.size() == 1) {
target = plugin.getServer().getPlayer(args.get(0));
if (target == null) {
if (sender instanceof ConsoleCommandSender) {
sender.sendMessage(ChatColor.RED + "Target must exist from Console.");
return;
}
target = sender;
}
} else {
if (sender instanceof ConsoleCommandSender) {
sender.sendMessage(ChatColor.RED + "Target must exist from Console.");
return;
}
}
if (target.equals(sender) && !sender.hasPermission("privileges.info.other")) {
sender.sendMessage(ChatColor.RED + "You cannot view other peoples' information.");
return;
}
lines.add("=== User Info: " + ChatColor.BLUE + target.getName() + ChatColor.WHITE + " ===");
lines.add("Is " + ChatColor.AQUA + target.getName() + ChatColor.WHITE + " an op? " + ChatColor.GREEN + (target.isOp() ? "Yes." : "No."));
if (!target.getName().equals(((Player)target).getDisplayName())) {
lines.add(ChatColor.AQUA + target.getName() + ChatColor.WHITE + " is currently known as '" + ChatColor.AQUA + ((Player)target).getDisplayName() + ChatColor.WHITE + "'");
}
lines.add(ChatColor.AQUA + target.getName() + ChatColor.WHITE + "'s group is: " + ChatColor.GREEN + plugin.getGroupManager().getGroup((OfflinePlayer)target).getName());
lines.add(ChatColor.AQUA + target.getName() + ChatColor.WHITE + "'s current world is: " + ChatColor.GREEN + ((Player)target).getWorld().getName() + ChatColor.WHITE + ".");
for (String line : lines) {
sender.sendMessage(line);
}
}
| public void runCommand(CommandSender sender, List<String> args) {
List<String> lines = new ArrayList<String>();
CommandSender target = sender;
if (args.size() == 1) {
target = plugin.getServer().getPlayer(args.get(0));
if (target == null) {
if (sender instanceof ConsoleCommandSender) {
sender.sendMessage(ChatColor.RED + "Target must exist from Console.");
return;
}
target = sender;
}
} else {
if (sender instanceof ConsoleCommandSender) {
sender.sendMessage(ChatColor.RED + "Target must exist from Console.");
return;
}
}
if (!target.equals(sender) && !sender.hasPermission("privileges.info.other")) {
sender.sendMessage(ChatColor.RED + "You cannot view other peoples' information.");
return;
}
lines.add("=== User Info: " + ChatColor.BLUE + target.getName() + ChatColor.WHITE + " ===");
lines.add("Is " + ChatColor.AQUA + target.getName() + ChatColor.WHITE + " an op? " + ChatColor.GREEN + (target.isOp() ? "Yes." : "No."));
if (!target.getName().equals(((Player)target).getDisplayName())) {
lines.add(ChatColor.AQUA + target.getName() + ChatColor.WHITE + " is currently known as '" + ChatColor.AQUA + ((Player)target).getDisplayName() + ChatColor.WHITE + "'");
}
lines.add(ChatColor.AQUA + target.getName() + ChatColor.WHITE + "'s group is: " + ChatColor.GREEN + plugin.getGroupManager().getGroup((OfflinePlayer)target).getName());
lines.add(ChatColor.AQUA + target.getName() + ChatColor.WHITE + "'s current world is: " + ChatColor.GREEN + ((Player)target).getWorld().getName() + ChatColor.WHITE + ".");
for (String line : lines) {
sender.sendMessage(line);
}
}
|
diff --git a/src/nl/b3p/viewer/config/services/WMSService.java b/src/nl/b3p/viewer/config/services/WMSService.java
index d8bf6a4f6..dafbaeb4e 100644
--- a/src/nl/b3p/viewer/config/services/WMSService.java
+++ b/src/nl/b3p/viewer/config/services/WMSService.java
@@ -1,188 +1,190 @@
/*
* Copyright (C) 2011 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.viewer.config.services;
import java.net.URL;
import java.util.*;
import javax.persistence.*;
import nl.b3p.web.WaitPageStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.ServiceInfo;
import org.geotools.data.ows.LayerDescription;
import org.geotools.data.wfs.WFSDataStoreFactory;
import org.geotools.data.wms.*;
import org.geotools.data.wms.request.DescribeLayerRequest;
import org.geotools.data.wms.response.DescribeLayerResponse;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Matthijs Laan
*/
@Entity
@DiscriminatorValue(WMSService.PROTOCOL)
public class WMSService extends GeoService {
private static final Log log = LogFactory.getLog(WMSService.class);
public static final String PROTOCOL = "wms";
public static final String PARAM_OVERRIDE_URL = "overrideUrl";
private Boolean overrideUrl;
public Boolean getOverrideUrl() {
return overrideUrl;
}
public void setOverrideUrl(Boolean overrideUrl) {
this.overrideUrl = overrideUrl;
}
@Override
public WMSService loadFromUrl(String url, Map params, WaitPageStatus status) throws Exception {
try {
status.setCurrentAction("Ophalen informatie...");
// XXX username / password by overriding HTTPClient?
WebMapServer gtwms = new WebMapServer(new URL(url));
WMSService wms = new WMSService();
ServiceInfo si = gtwms.getInfo();
wms.setName(si.getTitle());
wms.setOverrideUrl(Boolean.TRUE.equals(params.get(PARAM_OVERRIDE_URL)));
if(wms.getOverrideUrl()) {
wms.setUrl(url);
} else {
wms.setUrl(si.getSource().toString());
}
wms.getKeywords().addAll(si.getKeywords());
status.setProgress(30);
status.setCurrentAction("Inladen layers...");
status.setProgress(50);
org.geotools.data.ows.Layer rl = gtwms.getCapabilities().getLayer();
wms.setTopLayer(new Layer(rl, wms));
status.setProgress(60);
status.setCurrentAction("Gerelateerde WFS bronnen opzoeken...");
StringBuffer layers = new StringBuffer();
try {
getAllNonVirtualLayers(layers, wms.getTopLayer());
DescribeLayerRequest dlreq = gtwms.createDescribeLayerRequest();
dlreq.setLayers(layers.toString());
log.debug("Issuing DescribeLayer request for WMS " + url + " with layers=" + layers);
DescribeLayerResponse dlr = gtwms.issueRequest(dlreq);
Map<String,List<LayerDescription>> layerDescByWfs = new HashMap<String,List<LayerDescription>>();
for(LayerDescription ld: dlr.getLayerDescs()) {
log.debug(String.format("DescribeLayer response, name=%s, wfs=%s, typeNames=%s",
ld.getName(),
ld.getWfs(),
Arrays.toString(ld.getQueries())
));
if(ld.getWfs() != null && ld.getQueries() != null && ld.getQueries().length != 0) {
if(ld.getQueries().length != 1) {
log.debug("Cannot handle multiple typeNames for this layer, only using the first");
}
List<LayerDescription> lds = layerDescByWfs.get(ld.getWfs().toString());
if(lds == null) {
lds = new ArrayList<LayerDescription>();
layerDescByWfs.put(ld.getWfs().toString(), lds);
}
lds.add(ld);
}
}
status.setProgress(70);
String action = "Gerelateerde WFS bron inladen";
String[] wfses = (String[])layerDescByWfs.keySet().toArray(new String[] {});
for(int i = 0; i < wfses.length; i++) {
String wfsUrl = wfses[i];
String thisAction = action + (wfses.length > 1 ? " (" + (i+1) + " van " + wfses.length + ")" : "");
status.setCurrentAction(thisAction + ": GetCapabilities...");
Map p = new HashMap();
p.put(WFSDataStoreFactory.URL.key, wfsUrl);
// XXX use same password for WMS, maybe only if URLs have same hostname?
try {
WFSFeatureSource wfsFs = new WFSFeatureSource(p);
wfsFs.loadFeatureTypes();
boolean used = false;
for(LayerDescription ld: layerDescByWfs.get(wfsUrl)) {
Layer l = wms.getLayer(ld.getName());
if(l != null) {
SimpleFeatureType sft = wfsFs.getFeatureType(ld.getQueries()[0]);
- l.setFeatureType(sft);
- log.debug("Feature type for layer " + l.getName() + " set to feature type " + sft.getTypeName());
- used = true;
+ if(sft != null) {
+ l.setFeatureType(sft);
+ log.debug("Feature type for layer " + l.getName() + " set to feature type " + sft.getTypeName());
+ used = true;
+ }
}
}
if(used) {
log.debug("Type from WFSFeatureSource with url " + wfsUrl + " used by layer of WMS, persisting after finding unique name");
wfsFs.setName(FeatureSource.findUniqueName(wms.getName()));
log.debug("Unique name found for WFSFeatureSource: " + wfsFs.getName());
Stripersist.getEntityManager().persist(wfsFs);
} else {
log.debug("No type from WFSFeatureSource with url " + wfsUrl + " used, not persisting!");
}
} catch(Exception e) {
log.error("Error loading WFS from url " + wfsUrl, e);
}
}
} catch(Exception e) {
log.warn("DescribeLayer request failed for layers " + layers + " on service " + url, e);
}
return wms;
} finally {
status.setProgress(100);
status.setCurrentAction("Service ingeladen");
status.setFinished(true);
}
}
private void getAllNonVirtualLayers(StringBuffer sb, Layer l) {
if(!l.isVirtual()) {
if(sb.length() > 0) {
sb.append(",");
}
sb.append(l.getName());
}
for(Layer child: l.getChildren()) {
getAllNonVirtualLayers(sb, child);
}
}
@Override
public String toString() {
return String.format("WMS service \"%s\" at %s", getName(), getUrl());
}
}
| true | true | public WMSService loadFromUrl(String url, Map params, WaitPageStatus status) throws Exception {
try {
status.setCurrentAction("Ophalen informatie...");
// XXX username / password by overriding HTTPClient?
WebMapServer gtwms = new WebMapServer(new URL(url));
WMSService wms = new WMSService();
ServiceInfo si = gtwms.getInfo();
wms.setName(si.getTitle());
wms.setOverrideUrl(Boolean.TRUE.equals(params.get(PARAM_OVERRIDE_URL)));
if(wms.getOverrideUrl()) {
wms.setUrl(url);
} else {
wms.setUrl(si.getSource().toString());
}
wms.getKeywords().addAll(si.getKeywords());
status.setProgress(30);
status.setCurrentAction("Inladen layers...");
status.setProgress(50);
org.geotools.data.ows.Layer rl = gtwms.getCapabilities().getLayer();
wms.setTopLayer(new Layer(rl, wms));
status.setProgress(60);
status.setCurrentAction("Gerelateerde WFS bronnen opzoeken...");
StringBuffer layers = new StringBuffer();
try {
getAllNonVirtualLayers(layers, wms.getTopLayer());
DescribeLayerRequest dlreq = gtwms.createDescribeLayerRequest();
dlreq.setLayers(layers.toString());
log.debug("Issuing DescribeLayer request for WMS " + url + " with layers=" + layers);
DescribeLayerResponse dlr = gtwms.issueRequest(dlreq);
Map<String,List<LayerDescription>> layerDescByWfs = new HashMap<String,List<LayerDescription>>();
for(LayerDescription ld: dlr.getLayerDescs()) {
log.debug(String.format("DescribeLayer response, name=%s, wfs=%s, typeNames=%s",
ld.getName(),
ld.getWfs(),
Arrays.toString(ld.getQueries())
));
if(ld.getWfs() != null && ld.getQueries() != null && ld.getQueries().length != 0) {
if(ld.getQueries().length != 1) {
log.debug("Cannot handle multiple typeNames for this layer, only using the first");
}
List<LayerDescription> lds = layerDescByWfs.get(ld.getWfs().toString());
if(lds == null) {
lds = new ArrayList<LayerDescription>();
layerDescByWfs.put(ld.getWfs().toString(), lds);
}
lds.add(ld);
}
}
status.setProgress(70);
String action = "Gerelateerde WFS bron inladen";
String[] wfses = (String[])layerDescByWfs.keySet().toArray(new String[] {});
for(int i = 0; i < wfses.length; i++) {
String wfsUrl = wfses[i];
String thisAction = action + (wfses.length > 1 ? " (" + (i+1) + " van " + wfses.length + ")" : "");
status.setCurrentAction(thisAction + ": GetCapabilities...");
Map p = new HashMap();
p.put(WFSDataStoreFactory.URL.key, wfsUrl);
// XXX use same password for WMS, maybe only if URLs have same hostname?
try {
WFSFeatureSource wfsFs = new WFSFeatureSource(p);
wfsFs.loadFeatureTypes();
boolean used = false;
for(LayerDescription ld: layerDescByWfs.get(wfsUrl)) {
Layer l = wms.getLayer(ld.getName());
if(l != null) {
SimpleFeatureType sft = wfsFs.getFeatureType(ld.getQueries()[0]);
l.setFeatureType(sft);
log.debug("Feature type for layer " + l.getName() + " set to feature type " + sft.getTypeName());
used = true;
}
}
if(used) {
log.debug("Type from WFSFeatureSource with url " + wfsUrl + " used by layer of WMS, persisting after finding unique name");
wfsFs.setName(FeatureSource.findUniqueName(wms.getName()));
log.debug("Unique name found for WFSFeatureSource: " + wfsFs.getName());
Stripersist.getEntityManager().persist(wfsFs);
} else {
log.debug("No type from WFSFeatureSource with url " + wfsUrl + " used, not persisting!");
}
} catch(Exception e) {
log.error("Error loading WFS from url " + wfsUrl, e);
}
}
} catch(Exception e) {
log.warn("DescribeLayer request failed for layers " + layers + " on service " + url, e);
}
return wms;
} finally {
status.setProgress(100);
status.setCurrentAction("Service ingeladen");
status.setFinished(true);
}
}
| public WMSService loadFromUrl(String url, Map params, WaitPageStatus status) throws Exception {
try {
status.setCurrentAction("Ophalen informatie...");
// XXX username / password by overriding HTTPClient?
WebMapServer gtwms = new WebMapServer(new URL(url));
WMSService wms = new WMSService();
ServiceInfo si = gtwms.getInfo();
wms.setName(si.getTitle());
wms.setOverrideUrl(Boolean.TRUE.equals(params.get(PARAM_OVERRIDE_URL)));
if(wms.getOverrideUrl()) {
wms.setUrl(url);
} else {
wms.setUrl(si.getSource().toString());
}
wms.getKeywords().addAll(si.getKeywords());
status.setProgress(30);
status.setCurrentAction("Inladen layers...");
status.setProgress(50);
org.geotools.data.ows.Layer rl = gtwms.getCapabilities().getLayer();
wms.setTopLayer(new Layer(rl, wms));
status.setProgress(60);
status.setCurrentAction("Gerelateerde WFS bronnen opzoeken...");
StringBuffer layers = new StringBuffer();
try {
getAllNonVirtualLayers(layers, wms.getTopLayer());
DescribeLayerRequest dlreq = gtwms.createDescribeLayerRequest();
dlreq.setLayers(layers.toString());
log.debug("Issuing DescribeLayer request for WMS " + url + " with layers=" + layers);
DescribeLayerResponse dlr = gtwms.issueRequest(dlreq);
Map<String,List<LayerDescription>> layerDescByWfs = new HashMap<String,List<LayerDescription>>();
for(LayerDescription ld: dlr.getLayerDescs()) {
log.debug(String.format("DescribeLayer response, name=%s, wfs=%s, typeNames=%s",
ld.getName(),
ld.getWfs(),
Arrays.toString(ld.getQueries())
));
if(ld.getWfs() != null && ld.getQueries() != null && ld.getQueries().length != 0) {
if(ld.getQueries().length != 1) {
log.debug("Cannot handle multiple typeNames for this layer, only using the first");
}
List<LayerDescription> lds = layerDescByWfs.get(ld.getWfs().toString());
if(lds == null) {
lds = new ArrayList<LayerDescription>();
layerDescByWfs.put(ld.getWfs().toString(), lds);
}
lds.add(ld);
}
}
status.setProgress(70);
String action = "Gerelateerde WFS bron inladen";
String[] wfses = (String[])layerDescByWfs.keySet().toArray(new String[] {});
for(int i = 0; i < wfses.length; i++) {
String wfsUrl = wfses[i];
String thisAction = action + (wfses.length > 1 ? " (" + (i+1) + " van " + wfses.length + ")" : "");
status.setCurrentAction(thisAction + ": GetCapabilities...");
Map p = new HashMap();
p.put(WFSDataStoreFactory.URL.key, wfsUrl);
// XXX use same password for WMS, maybe only if URLs have same hostname?
try {
WFSFeatureSource wfsFs = new WFSFeatureSource(p);
wfsFs.loadFeatureTypes();
boolean used = false;
for(LayerDescription ld: layerDescByWfs.get(wfsUrl)) {
Layer l = wms.getLayer(ld.getName());
if(l != null) {
SimpleFeatureType sft = wfsFs.getFeatureType(ld.getQueries()[0]);
if(sft != null) {
l.setFeatureType(sft);
log.debug("Feature type for layer " + l.getName() + " set to feature type " + sft.getTypeName());
used = true;
}
}
}
if(used) {
log.debug("Type from WFSFeatureSource with url " + wfsUrl + " used by layer of WMS, persisting after finding unique name");
wfsFs.setName(FeatureSource.findUniqueName(wms.getName()));
log.debug("Unique name found for WFSFeatureSource: " + wfsFs.getName());
Stripersist.getEntityManager().persist(wfsFs);
} else {
log.debug("No type from WFSFeatureSource with url " + wfsUrl + " used, not persisting!");
}
} catch(Exception e) {
log.error("Error loading WFS from url " + wfsUrl, e);
}
}
} catch(Exception e) {
log.warn("DescribeLayer request failed for layers " + layers + " on service " + url, e);
}
return wms;
} finally {
status.setProgress(100);
status.setCurrentAction("Service ingeladen");
status.setFinished(true);
}
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/contraction/ContractionHierarchy.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/contraction/ContractionHierarchy.java
index 0645848cc..900d52fe1 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/contraction/ContractionHierarchy.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/contraction/ContractionHierarchy.java
@@ -1,897 +1,897 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.contraction;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.opentripplanner.common.pqueue.BinHeap;
import org.opentripplanner.routing.algorithm.Dijkstra;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.core.TraverseModeSet;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.edgetype.OutEdge;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.location.StreetLocation;
import org.opentripplanner.routing.spt.BasicShortestPathTree;
import org.opentripplanner.routing.spt.GraphPath;
import org.opentripplanner.routing.util.NullExtraEdges;
import org.opentripplanner.routing.vertextype.StreetVertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implements roughly the algorithm described in
* "Contraction Hierarchies: Faster and Simpler Hierarchical Routing in Road Networks"
* http://algo2.iti.kit.edu/1087.php
*
* Some code initially based on Brandon Martin-Anderson's implementation in Graphserver.
*
*/
public class ContractionHierarchy implements Serializable {
/* contraction parameters */
private static final int HOP_LIMIT_SIMULATE = 5; //10;
private static final int HOP_LIMIT_CONTRACT = 5; //Integer.MAX_VALUE;
private static final int NODE_LIMIT_SIMULATE = 500;
private static final int NODE_LIMIT_CONTRACT = 500; //Integer.MAX_VALUE;
private static final Logger _log = LoggerFactory.getLogger(ContractionHierarchy.class);
private static final long serialVersionUID = 20111118L;
public Graph graph;
// _contractable_ core vertices -- we maintain both a queue and a set to allow
// fast set membership checking.
public Set<Vertex> corev, chv;
private double contractionFactor;
private transient RoutingRequest fwdOptions, backOptions;
private transient TraverseMode mode;
private transient ThreadPoolExecutor threadPool;
/**
* Returns the set of shortcuts around a vertex, as well as the size of the space searched.
*
* @param u - the node around which to find shortcuts
* @param hopLimit - maximum length of witness search paths, in number of edges traversed
* @param simulate - If true, use different hop and vertex visit limits, and do not remove any edges.
* This is used for establishing the node order rather than actually contracting.
*
* @return - the necessary shortcuts and the search space of the witness search.
*/
public WitnessSearchResult getShortcuts(Vertex u, boolean simulate) {
/* Compute the cost from each vertex with an incoming edge to the target */
State su = new State(u, backOptions); // search backward
int searchSpace = 0;
ArrayList<State> vs = new ArrayList<State>();
for (Edge e : u.getIncoming()) {
if (! corev.contains(e.getFromVertex()))
continue;
State sv = e.traverse(su);
if (sv == null)
continue;
vs.add(sv);
}
/* Compute the cost to each vertex with an outgoing edge from the target */
su = new State(u, fwdOptions); // search forward
double maxWWeight = 0;
ArrayList<State> ws = new ArrayList<State>();
//System.out.println("vertex " + u);
for (Edge e : u.getOutgoing()) {
if (! corev.contains(e.getToVertex()))
continue;
State sw = e.traverse(su);
if (sw == null)
continue;
ws.add(sw);
if (sw.exceedsWeightLimit(maxWWeight))
maxWWeight = sw.getWeight();
}
/* figure out which shortcuts are needed */
List<PotentialShortcut> shortcuts = new ArrayList<PotentialShortcut>();
ArrayList<Callable<WitnessSearchResult>> tasks =
new ArrayList<Callable<WitnessSearchResult>>(vs.size());
int nodeLimit = simulate ? NODE_LIMIT_SIMULATE : NODE_LIMIT_CONTRACT;
int hopLimit = simulate ? HOP_LIMIT_SIMULATE : HOP_LIMIT_CONTRACT;
for (State v : vs) {
//allow about a second of inefficiency in routes in the name of planning
//efficiency (+ 1)
double weightLimit = v.getWeight() + maxWWeight + 1;
WitnessSearch task = new WitnessSearch(u, hopLimit, nodeLimit,
weightLimit, ws, v);
tasks.add(task);
}
if (threadPool == null) {
createThreadPool();
}
try {
for (Future<WitnessSearchResult> future : threadPool.invokeAll(tasks)) {
WitnessSearchResult wsresult = future.get();
BasicShortestPathTree spt = wsresult.spt;
// if (!simulate && spt != null) {
// /* while we're here, remove some non-optimal edges */
// ArrayList<Edge> toRemove = new ArrayList<Edge>();
// // starting from each v
// State sv0 = new State(wsresult.vertex, fwdOptions);
// for (Edge e : wsresult.vertex.getOutgoing()) {
// State sSpt = spt.getState(e.getToVertex());
// if (sSpt == null) {
// continue;
// }
// State sv1 = e.traverse(sv0);
// if (sv1 == null) {
// toRemove.add(e);
// continue;
// }
// if (sSpt.getWeight() < sv1.getWeight()) {
// // the path found by Dijkstra from u to e.tov is better
// // than the path through e. Therefore e can be deleted.
// toRemove.add(e);
// }
// }
//
// Vertex uv = wsresult.vertex;
// for (Edge e : toRemove) {
// // concurrent modification argh
// //e.detach();
//// uv.removeOutgoing(e);
//// e.getToVertex().removeIncoming(e);
// }
// }
searchSpace += wsresult.searchSpace;
shortcuts.addAll(wsresult.shortcuts);
}
} catch (Exception e1) {
throw new RuntimeException(e1);
}
return new WitnessSearchResult(shortcuts, null, null, searchSpace);
}
private class WitnessSearch implements Callable<WitnessSearchResult> {
private Vertex u;
private double weightLimit;
private int hopLimit;
private List<State> ws;
private State v;
private int nodeLimit;
public WitnessSearch(Vertex u, int hopLimit, int nodeLimit,
double weightLimit, List<State> ws, State v) {
this.u = u;
this.hopLimit = hopLimit;
this.nodeLimit = nodeLimit;
this.weightLimit = weightLimit;
this.ws = ws;
this.v = v;
}
public WitnessSearchResult call() {
return searchWitnesses(u, hopLimit, nodeLimit, weightLimit, ws, v);
}
}
private WitnessSearchResult searchWitnesses(Vertex u, int hopLimit,
int nodeLimit, double weightLimit, List<State> ws, State v) {
Dijkstra dijkstra = new Dijkstra(v.getVertex(), fwdOptions, u, hopLimit);
dijkstra.setTargets(ws);
dijkstra.setRouteOn(corev);
BasicShortestPathTree spt = dijkstra.getShortestPathTree(weightLimit, nodeLimit);
ArrayList<PotentialShortcut> shortcuts = new ArrayList<PotentialShortcut>();
// FOR EACH W
for (State w : ws) {
if (v.getVertex() == w.getVertex()) {
continue;
}
double weightThroughU = v.getWeight() + w.getWeight();
State pathAroundU = spt.getState(w.getVertex());
// if the path around the vertex is longer than the path through,
// add the path through to the shortcuts
if (pathAroundU == null || pathAroundU.exceedsWeightLimit(weightThroughU + .01)) {
int timeThroughU = (int) (w.getAbsTimeDeltaSec() + v.getAbsTimeDeltaSec());
double walkDistance = v.getWalkDistance() + w.getWalkDistance();
// this is implicitly modifying edgelists while searches are happening.
// must use threadsafe list modifications in Shortcut, or no multithreafding.
shortcuts.add(new PotentialShortcut(v.getBackEdge(), w.getBackEdge(),
timeThroughU, weightThroughU, walkDistance));
}
}
return new WitnessSearchResult(shortcuts, spt, v.getVertex(), spt.getVertexCount());
}
public class PotentialShortcut {
Edge e1, e2;
int time;
double weight, walk;
PotentialShortcut (Edge e1, Edge e2, int time, double weight, double walk) {
this.e1=e1;
this.e2=e2;
this.time = time;
this.weight = weight;
this.walk = walk;
}
public void make () {
new Shortcut(e1, e2, time, weight, walk, mode);
}
}
/**
* Returns the importance of a vertex from the edge difference, number of deleted neighbors, and
* search space size ("EDS").
*/
private int getImportance(Vertex v, WitnessSearchResult shortcutsAndSearchSpace,
int deletedNeighbors) {
int degree_in = v.getDegreeIn();
int degree_out = v.getDegreeOut();
int edge_difference = shortcutsAndSearchSpace.shortcuts.size() - (degree_in + degree_out);
int searchSpace = shortcutsAndSearchSpace.searchSpace;
return edge_difference * 190 + deletedNeighbors * 120 + searchSpace;
}
/**
* Initialize the priority queue for contracting, by computing the initial importance of every
* node. Also initializes the set of nodes to be contracted.
*
* @return
*/
BinHeap<Vertex> initPriorityQueue(Graph g) {
BinHeap<Vertex> pq = new BinHeap<Vertex>(g.getVertices().size());
corev = new HashSet<Vertex>();
chv = new HashSet<Vertex>();
for (Vertex v : g.getVertices()) {
if (v instanceof StreetVertex)
corev.add(v);
}
for (Vertex v : corev) {
// if (v.getDegreeIn() > 7 || v.getDegreeOut() > 7)
// continue;
WitnessSearchResult shortcuts = getShortcuts(v, true);
int imp = getImportance(v, shortcuts, 0);
pq.insert(v, imp);
}
return pq;
}
/**
* Create a contraction hierarchy from a graph.
*
* @param orig
* @param options
* @param contractionFactor
* A fraction from 0 to 1 of (the contractable portion of) the graph to contract
*/
public ContractionHierarchy(Graph graph, RoutingRequest options, double contractionFactor) {
this.graph = graph;
fwdOptions = options;
fwdOptions.setMaxWalkDistance(Double.MAX_VALUE);
fwdOptions.setArriveBy(false);
backOptions = fwdOptions.clone();
backOptions.setArriveBy(true);
this.contractionFactor = contractionFactor;
// TODO LG Check this
TraverseModeSet modes = this.fwdOptions.getModes();
this.mode = modes.getCar() ? TraverseMode.CAR
: modes.getBicycle() ? TraverseMode.BICYCLE : TraverseMode.WALK;
build();
}
/**
* Does the work of construting the CH.
*
*/
void build() {
createThreadPool();
long start = System.currentTimeMillis();
HashMap<Vertex, Integer> deletedNeighbors = new HashMap<Vertex, Integer>();
_log.debug("Preparing contraction hierarchy -- this may take quite a while");
_log.debug("Initializing priority queue");
// initialize a priority queue containing only contractable vertices
BinHeap<Vertex> pq = initPriorityQueue(graph);
_log.debug("Contracting");
long lastNotified = System.currentTimeMillis();
int i = 0;
int totalContractableVertices = pq.size(); // == corev.size()
int nContractableEdges = countContractableEdges(graph);
boolean edgesRemoved = false;
while (!pq.empty()) {
// stop contracting once a core is reached
if (i > Math.ceil(totalContractableVertices * contractionFactor)) {
break;
}
i += 1;
/*
* "Keeping the cost of contraction up-to-date in the priority queue is quite costly. The
* contraction of a node in a search tree of the local search can affect the cost of contraction. So
* after the contraction of a node w, it would be necessary to recalculate the priority of each node
* that has w in their local search spaces. Most local search spaces are small but there are
* exceptions.
* If there is an edge with a large edge weight, e.g. a long-distance ferry connection, the search
* space can grow arbitrarily and with it the number of nodes that trigger a change in the cost of
* contraction. A simplified example can be found in Figure 6.
* In our implementation we will omit exakt updates for the sake of performance, update only
* the neighbors of the contracted node and eventually use lazy updates to cope with drastic
* increases of search space sizes." Geisberger (2008)
*/
// if (potentialLazyUpdates > 30 && lazyUpdates > 28) {
// rebuildPriorityQueue(hopLimit, deletedNeighbors);
// potentialLazyUpdates = 0;
// lazyUpdates = 0;
// }
Vertex vertex = pq.extract_min();
_log.trace("contracting vertex " + vertex);
WitnessSearchResult shortcutsAndSearchSpace;
// make sure priority of current vertex
if (pq.empty()) {
shortcutsAndSearchSpace = getShortcuts(vertex, false);
} else {
// resort the priority queue as necessary (lazy updates)
while (true) {
shortcutsAndSearchSpace = getShortcuts(vertex, true);
int deleted = 0;
if (deletedNeighbors.containsKey(vertex)) {
deleted = deletedNeighbors.get(vertex);
}
double new_prio = getImportance(vertex, shortcutsAndSearchSpace, deleted);
Double new_min = pq.peek_min_key();
if (new_prio <= new_min) {
break;
} else {
pq.insert(vertex, new_prio);
vertex = pq.extract_min();
}
}
shortcutsAndSearchSpace = getShortcuts(vertex, false);
}
long now = System.currentTimeMillis();
if (now - lastNotified > 5000) {
_log.debug("contracted: " + i + " / " + totalContractableVertices
+ " (" + i / (double)totalContractableVertices
+ ") total time "
+ (now - start) / 1000.0 + "sec, average degree "
+ nContractableEdges / (corev.size() + 0.00001));
lastNotified = now;
}
// move edges from main graph to up and down graphs
// vertices that are still in the graph are, by definition, of higher importance than
// the one currently being plucked from the graph. Edges that go out are upward edges.
// Edges that are coming in are downward edges.
HashSet<Vertex> neighbors = new HashSet<Vertex>();
// outgoing, therefore upward
for (Edge de : vertex.getOutgoing()) {
Vertex toVertex = de.getToVertex();
neighbors.add(toVertex);
nContractableEdges--;
}
// incoming, therefore downward
for (Edge de : vertex.getIncoming()) {
Vertex fromVertex = de.getFromVertex();
neighbors.add(fromVertex);
nContractableEdges--;
}
/* update neighbors' priority and deleted neighbors */
for (Vertex n : neighbors) {
if (n == null) {
_log.warn("a neighbor vertex of {} was null", vertex);
continue;
}
int deleted = 0;
if (deletedNeighbors.containsKey(n)) {
deleted = deletedNeighbors.get(n);
}
deleted += 1;
deletedNeighbors.put(n, deleted);
//update priority queue
WitnessSearchResult nwsr = getShortcuts(n, true);
double new_prio = getImportance(n, nwsr, deleted);
pq.rekey(n, new_prio);
}
// need to explicitly add shortcuts to graph - they not added as they are found
// to void concurrency problems.
for (PotentialShortcut ps : shortcutsAndSearchSpace.shortcuts) {
ps.make();
nContractableEdges += 1;
}
/* effectively move vertex out of core */
// if this was done before searching
// this should replace the taboo vertex in Dijkstra.
if (corev.remove(vertex)) {
chv.add(vertex);
} else {
_log.warn("attempt to move vertex out of core when it was not still in core.");
}
if (corev.size() == 0) {
continue;
}
// float averageDegree = nEdges / nVertices;
// int oldHopLimit = hopLimit;
// if (averageDegree > 10) {
// if (edgesRemoved) {
// hopLimit = 5;
// } else {
// hopLimit = 3;
// int removed = removeNonoptimalEdges(5);
// nEdges -= removed;
// edgesRemoved = true;
// }
// } else {
// if (averageDegree > 3.3 && hopLimit == 1) {
// hopLimit = 2;
// }
// }
//
// // after a hop limit upgrade, rebuild the priority queue
// if (oldHopLimit != hopLimit) {
// pq = rebuildPriorityQueue(hopLimit, deletedNeighbors);
// }
}
threadPool.shutdownNow();
threadPool = null;
}
private void createThreadPool() {
int nThreads = Runtime.getRuntime().availableProcessors();
//nThreads = 1; // temp fix for concurrent modification by shortcuts
_log.debug("number of threads: " + nThreads);
ArrayBlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<Runnable>(1000);
threadPool = new ThreadPoolExecutor(nThreads, nThreads, 10, TimeUnit.SECONDS, taskQueue);
}
private BinHeap<Vertex> rebuildPriorityQueue(int hopLimit,
HashMap<Vertex, Integer> deletedNeighbors) {
_log.debug(" rebuild priority queue, hoplimit is now {}", hopLimit);
BinHeap<Vertex> newpq = new BinHeap<Vertex>(corev.size());
for (Vertex v : corev) {
if (! (v instanceof StreetVertex))
continue;
WitnessSearchResult wsresult = getShortcuts(v, true);
Integer deleted = deletedNeighbors.get(v);
if (deleted == null) {
deleted = 0;
}
int imp = getImportance(v, wsresult, deleted);
newpq.insert(v, imp);
}
return newpq;
}
private int removeNonoptimalEdges(int hopLimit) {
_log.debug("removing non-optimal edges, hopLimit is {}", hopLimit);
int removed = 0;
for (Vertex u : corev) {
State su = new State(u, fwdOptions);
Dijkstra dijkstra = new Dijkstra(u, fwdOptions, null, hopLimit);
dijkstra.setRouteOn(corev);
BasicShortestPathTree spt = dijkstra.getShortestPathTree(Double.POSITIVE_INFINITY,
Integer.MAX_VALUE);
ArrayList<Edge> toRemove = new ArrayList<Edge>();
for (Edge e : u.getOutgoing()) {
State svSpt = spt.getState(e.getToVertex());
State sv = e.traverse(su);
if (sv == null) {
//it is safe to remove edges that are not traversable anyway
toRemove.add(e);
continue;
}
if (svSpt != null && sv.getBackState().getVertex() != u
&& svSpt.getWeight() <= sv.getWeight() + .01) {
toRemove.add(e);
}
}
for (Edge e : toRemove) {
e.detach(); // TODO: is this really the right action to take?
}
removed += toRemove.size();
}
return removed;
}
private int countContractableEdges(Graph g) {
int total = 0;
for (Vertex v : g.getVertices()) {
if (v instanceof StreetVertex)
total += v.getDegreeOut();
}
return total;
}
/**
* Bidirectional Dijkstra's algorithm with some twists: For forward searches, The search from
* the target stops when it hits the uncontracted core of the graph and the search from the
* source continues across the (time-dependent) core.
*
*/
public GraphPath getShortestPath(Vertex origin, Vertex target, long time,
RoutingRequest opt) {
if (origin == null || target == null) {
return null;
}
RoutingRequest upOptions = opt.clone();
RoutingRequest downOptions = opt.clone();
//TODO: verify set to/from are correct (AMB)
upOptions.setArriveBy(false);
upOptions.dateTime = time;
upOptions.setRoutingContext(graph, origin, target);
downOptions.setArriveBy(true);
downOptions.dateTime = time;
- upOptions.setRoutingContext(graph, target, origin);
+ downOptions.setRoutingContext(graph, target, origin);
/** max walk distance cannot be less than distances to nearest transit stops */
double minWalkDistance =
origin.getDistanceToNearestTransitStop() + target.getDistanceToNearestTransitStop();
upOptions.setMaxWalkDistance(Math.max(upOptions.getMaxWalkDistance(), minWalkDistance));
downOptions.setMaxWalkDistance(Math.max(downOptions.getMaxWalkDistance(), minWalkDistance));
final boolean VERBOSE = false;
// DEBUG no walk limit
//options.maxWalkDistance = Double.MAX_VALUE;
final int INITIAL_SIZE = 1000;
if (VERBOSE)
_log.debug("origin {} target {}", origin, target);
Map<Vertex, ArrayList<Edge>> extraEdges = getExtraEdges(origin, target);
BasicShortestPathTree upspt = new BasicShortestPathTree(upOptions);
BasicShortestPathTree downspt = new BasicShortestPathTree(downOptions);
BinHeap<State> upqueue = new BinHeap<State>(INITIAL_SIZE);
BinHeap<State> downqueue = new BinHeap<State>(INITIAL_SIZE);
// These sets are used not only to avoid revisiting nodes, but to find meetings
HashSet<Vertex> upclosed = new HashSet<Vertex>(INITIAL_SIZE);
HashSet<Vertex> downclosed = new HashSet<Vertex>(INITIAL_SIZE);
State upInit = new State(origin, upOptions);
upspt.add(upInit);
upqueue.insert(upInit, upInit.getWeight());
/* FIXME: insert extra bike walking targets */
State downInit = new State(target, downOptions);
downspt.add(downInit);
downqueue.insert(downInit, downInit.getWeight());
Vertex meeting = null;
double bestMeetingCost = Double.POSITIVE_INFINITY;
boolean done_up = false;
boolean done_down = false;
while (!(done_up && done_down)) {
// up and down steps could be a single method with parameters changed
// if ( ! done_up) treeStep(queue, options, thisClosed, thatClosed, thisSpt, thatSpt, bestMeeting);
/* one step on the up tree */
if (!done_up) {
if (upqueue.empty()) {
done_up = true;
continue;
}
State up_su = upqueue.extract_min(); // get the lowest-weightSum
// if ( ! upspt.visit(up_su))
// continue;
if (up_su.exceedsWeightLimit(bestMeetingCost)) {
if (VERBOSE)
_log.debug("pruning on up tree (best meeting cost)");
done_up = true;
continue;
}
Vertex u = up_su.getVertex();
upclosed.add(u); // should basic spt maintain a closed list?
if (VERBOSE)
_log.debug(" extract up {}", u);
if (downclosed.contains(u) && downspt.getState(u).getWalkDistance() + up_su.getWalkDistance() <= up_su.getOptions().getMaxWalkDistance()) {
double thisMeetingCost = up_su.getWeight() + downspt.getState(u).getWeight();
if (VERBOSE)
_log.debug(" meeting at {}", u);
if (thisMeetingCost < bestMeetingCost) {
bestMeetingCost = thisMeetingCost;
meeting = u;
}
continue;
}
if (opt.isArriveBy() && !(u instanceof StreetVertex)) {
// up path can only explore until core vertices on reverse paths
continue;
}
Collection<Edge> outgoing = u.getOutgoing();
if (VERBOSE)
_log.debug(" {} edges in core", outgoing.size());
if (extraEdges.containsKey(u)) {
List<Edge> newOutgoing = new ArrayList<Edge>();
newOutgoing.addAll(extraEdges.get(u));
if (VERBOSE)
_log.debug(" {} edges in extra", newOutgoing.size());
newOutgoing.addAll(outgoing);
outgoing = newOutgoing;
}
for (Edge edge : outgoing) {
if (VERBOSE)
_log.debug(" edge up {}", edge);
if (edge instanceof OutEdge) {
continue;
}
State up_sv = edge.traverse(up_su);
// When an edge leads nowhere (as indicated by returning NULL), the iteration is
// over.
if (up_sv == null) {
continue;
}
Vertex v = up_sv.getVertex();
if (upclosed.contains(v)) {
continue;
}
if (up_sv.exceedsWeightLimit(opt.maxWeight)) {
//too expensive to get here
continue;
}
if (!opt.isArriveBy() && up_sv.getTime() > opt.worstTime) {
continue;
}
if (upspt.add(up_sv)) {
double weight = up_sv.getWeight();
if (weight < bestMeetingCost)
upqueue.insert(up_sv, weight);
}
}
}
/* one step on the down tree */
if (!done_down) {
if (downqueue.empty()) {
done_down = true;
continue;
}
State down_su = downqueue.extract_min(); // get the lowest-weightSum
if ( ! downspt.visit(down_su))
continue;
if (down_su.exceedsWeightLimit(bestMeetingCost)) {
done_down = true;
continue;
}
Vertex down_u = down_su.getVertex();
if (VERBOSE)
_log.debug(" extract down {}", down_u);
if (upclosed.contains(down_u) && upspt.getState(down_u).getWalkDistance() + down_su.getWalkDistance() <= down_su.getOptions().getMaxWalkDistance()) {
double thisMeetingCost = down_su.getWeight() + upspt.getState(down_u).getWeight();
if (VERBOSE)
_log.debug(" meeting at {}", down_u);
if (thisMeetingCost < bestMeetingCost) {
bestMeetingCost = thisMeetingCost;
meeting = down_u;
}
}
downclosed.add(down_u);
if (!opt.isArriveBy() && !(down_u instanceof StreetVertex)) {
// down path can only explore until core vertices on forward paths
continue;
}
Collection<Edge> incoming = down_u.getIncoming();
if (VERBOSE)
_log.debug(" {} edges in core", incoming.size());
if (extraEdges.containsKey(down_u)) {
List<Edge> newIncoming = new ArrayList<Edge>();
newIncoming.addAll(incoming);
newIncoming.addAll(extraEdges.get(down_u));
incoming = newIncoming;
}
if (VERBOSE)
_log.debug(" {} edges with overlay and extra", incoming.size());
for (Edge edge : incoming) {
if (VERBOSE)
_log.debug(" edge down {}", edge);
Vertex down_v = edge.getFromVertex();
if (downclosed.contains(down_v)) {
continue;
}
if (edge instanceof OutEdge) {
continue;
}
// traverse will be backward because ArriveBy was set in the initial down state
State down_sv = edge.traverse(down_su);
if (VERBOSE)
_log.debug(" result down {}", down_sv);
// When an edge leads nowhere (as indicated by returning NULL), the iteration is
// over.
if (down_sv == null) {
continue;
}
if (down_sv.exceedsWeightLimit(opt.maxWeight)) {
if (VERBOSE)
_log.debug(" down result too heavy {}", down_sv);
//too expensive to get here
continue;
}
if (opt.isArriveBy() && down_sv.getTime() < opt.worstTime) {
if (VERBOSE)
_log.debug(" down result exceeds worst time {} {}", opt.worstTime, down_sv);
continue;
}
if (downspt.add(down_sv)) {
double weight = down_sv.getWeight();
if (weight < bestMeetingCost)
downqueue.insert(down_sv, weight);
}
}
}
}
if (meeting == null) {
return null;
} else {
if (VERBOSE)
_log.debug("meeting point is {}", meeting);
}
/* Splice paths */
State upMeet = upspt.getState(meeting);
State downMeet = downspt.getState(meeting);
State r = opt.isArriveBy() ? downMeet : upMeet;
State s = opt.isArriveBy() ? upMeet : downMeet;
while (s.getBackEdge() != null) {
r = s.getBackEdge().traverse(r);
// traversals might exceed limits here, even if they didn't during search
if (r == null)
return null;
s = s.getBackState();
}
/* Unpack shortcuts */
s = r.reversedClone();
while (r.getBackEdge() != null) {
Edge e = r.getBackEdge();
if (e instanceof Shortcut)
s = ((Shortcut)e).unpackTraverse(s);
else
s = e.traverse(s);
// traversals might exceed limits and fail during unpacking, even if they didn't during search
if (s == null)
return null;
r = r.getBackState();
}
// no need to request optimization, we just unpacked the path backward
GraphPath ret = new GraphPath(s, false);
return ret;
}
private Map<Vertex, ArrayList<Edge>> getExtraEdges(Vertex origin, Vertex target) {
Map<Vertex, ArrayList<Edge>> extraEdges;
if (origin instanceof StreetLocation) {
extraEdges = new HashMap<Vertex, ArrayList<Edge>>();
Iterable<Edge> extra = ((StreetLocation)origin).getExtra();
for (Edge edge : extra) {
Vertex fromv = edge.getFromVertex();
ArrayList<Edge> edges = extraEdges.get(fromv);
if (edges == null) {
edges = new ArrayList<Edge>();
extraEdges.put(fromv, edges);
}
edges.add(edge);
}
} else {
extraEdges = new NullExtraEdges();
}
if (target instanceof StreetLocation) {
if (extraEdges instanceof NullExtraEdges) {
extraEdges = new HashMap<Vertex, ArrayList<Edge>>();
}
Iterable<Edge> extra = ((StreetLocation) target).getExtra();
for (Edge edge : extra) {
Vertex tov = edge.getToVertex();
ArrayList<Edge> edges = extraEdges.get(tov);
if (edges == null) {
edges = new ArrayList<Edge>();
extraEdges.put(tov, edges);
}
edges.add(edge);
}
}
return extraEdges;
}
}
| true | true | public GraphPath getShortestPath(Vertex origin, Vertex target, long time,
RoutingRequest opt) {
if (origin == null || target == null) {
return null;
}
RoutingRequest upOptions = opt.clone();
RoutingRequest downOptions = opt.clone();
//TODO: verify set to/from are correct (AMB)
upOptions.setArriveBy(false);
upOptions.dateTime = time;
upOptions.setRoutingContext(graph, origin, target);
downOptions.setArriveBy(true);
downOptions.dateTime = time;
upOptions.setRoutingContext(graph, target, origin);
/** max walk distance cannot be less than distances to nearest transit stops */
double minWalkDistance =
origin.getDistanceToNearestTransitStop() + target.getDistanceToNearestTransitStop();
upOptions.setMaxWalkDistance(Math.max(upOptions.getMaxWalkDistance(), minWalkDistance));
downOptions.setMaxWalkDistance(Math.max(downOptions.getMaxWalkDistance(), minWalkDistance));
final boolean VERBOSE = false;
// DEBUG no walk limit
//options.maxWalkDistance = Double.MAX_VALUE;
final int INITIAL_SIZE = 1000;
if (VERBOSE)
_log.debug("origin {} target {}", origin, target);
Map<Vertex, ArrayList<Edge>> extraEdges = getExtraEdges(origin, target);
BasicShortestPathTree upspt = new BasicShortestPathTree(upOptions);
BasicShortestPathTree downspt = new BasicShortestPathTree(downOptions);
BinHeap<State> upqueue = new BinHeap<State>(INITIAL_SIZE);
BinHeap<State> downqueue = new BinHeap<State>(INITIAL_SIZE);
// These sets are used not only to avoid revisiting nodes, but to find meetings
HashSet<Vertex> upclosed = new HashSet<Vertex>(INITIAL_SIZE);
HashSet<Vertex> downclosed = new HashSet<Vertex>(INITIAL_SIZE);
State upInit = new State(origin, upOptions);
upspt.add(upInit);
upqueue.insert(upInit, upInit.getWeight());
/* FIXME: insert extra bike walking targets */
State downInit = new State(target, downOptions);
downspt.add(downInit);
downqueue.insert(downInit, downInit.getWeight());
Vertex meeting = null;
double bestMeetingCost = Double.POSITIVE_INFINITY;
boolean done_up = false;
boolean done_down = false;
while (!(done_up && done_down)) {
// up and down steps could be a single method with parameters changed
// if ( ! done_up) treeStep(queue, options, thisClosed, thatClosed, thisSpt, thatSpt, bestMeeting);
/* one step on the up tree */
if (!done_up) {
if (upqueue.empty()) {
done_up = true;
continue;
}
State up_su = upqueue.extract_min(); // get the lowest-weightSum
// if ( ! upspt.visit(up_su))
// continue;
if (up_su.exceedsWeightLimit(bestMeetingCost)) {
if (VERBOSE)
_log.debug("pruning on up tree (best meeting cost)");
done_up = true;
continue;
}
Vertex u = up_su.getVertex();
upclosed.add(u); // should basic spt maintain a closed list?
if (VERBOSE)
_log.debug(" extract up {}", u);
if (downclosed.contains(u) && downspt.getState(u).getWalkDistance() + up_su.getWalkDistance() <= up_su.getOptions().getMaxWalkDistance()) {
double thisMeetingCost = up_su.getWeight() + downspt.getState(u).getWeight();
if (VERBOSE)
_log.debug(" meeting at {}", u);
if (thisMeetingCost < bestMeetingCost) {
bestMeetingCost = thisMeetingCost;
meeting = u;
}
continue;
}
if (opt.isArriveBy() && !(u instanceof StreetVertex)) {
// up path can only explore until core vertices on reverse paths
continue;
}
Collection<Edge> outgoing = u.getOutgoing();
if (VERBOSE)
_log.debug(" {} edges in core", outgoing.size());
if (extraEdges.containsKey(u)) {
List<Edge> newOutgoing = new ArrayList<Edge>();
newOutgoing.addAll(extraEdges.get(u));
if (VERBOSE)
_log.debug(" {} edges in extra", newOutgoing.size());
newOutgoing.addAll(outgoing);
outgoing = newOutgoing;
}
for (Edge edge : outgoing) {
if (VERBOSE)
_log.debug(" edge up {}", edge);
if (edge instanceof OutEdge) {
continue;
}
State up_sv = edge.traverse(up_su);
// When an edge leads nowhere (as indicated by returning NULL), the iteration is
// over.
if (up_sv == null) {
continue;
}
Vertex v = up_sv.getVertex();
if (upclosed.contains(v)) {
continue;
}
if (up_sv.exceedsWeightLimit(opt.maxWeight)) {
//too expensive to get here
continue;
}
if (!opt.isArriveBy() && up_sv.getTime() > opt.worstTime) {
continue;
}
if (upspt.add(up_sv)) {
double weight = up_sv.getWeight();
if (weight < bestMeetingCost)
upqueue.insert(up_sv, weight);
}
}
}
/* one step on the down tree */
if (!done_down) {
if (downqueue.empty()) {
done_down = true;
continue;
}
State down_su = downqueue.extract_min(); // get the lowest-weightSum
if ( ! downspt.visit(down_su))
continue;
if (down_su.exceedsWeightLimit(bestMeetingCost)) {
done_down = true;
continue;
}
Vertex down_u = down_su.getVertex();
if (VERBOSE)
_log.debug(" extract down {}", down_u);
if (upclosed.contains(down_u) && upspt.getState(down_u).getWalkDistance() + down_su.getWalkDistance() <= down_su.getOptions().getMaxWalkDistance()) {
double thisMeetingCost = down_su.getWeight() + upspt.getState(down_u).getWeight();
if (VERBOSE)
_log.debug(" meeting at {}", down_u);
if (thisMeetingCost < bestMeetingCost) {
bestMeetingCost = thisMeetingCost;
meeting = down_u;
}
}
downclosed.add(down_u);
if (!opt.isArriveBy() && !(down_u instanceof StreetVertex)) {
// down path can only explore until core vertices on forward paths
continue;
}
Collection<Edge> incoming = down_u.getIncoming();
if (VERBOSE)
_log.debug(" {} edges in core", incoming.size());
if (extraEdges.containsKey(down_u)) {
List<Edge> newIncoming = new ArrayList<Edge>();
newIncoming.addAll(incoming);
newIncoming.addAll(extraEdges.get(down_u));
incoming = newIncoming;
}
if (VERBOSE)
_log.debug(" {} edges with overlay and extra", incoming.size());
for (Edge edge : incoming) {
if (VERBOSE)
_log.debug(" edge down {}", edge);
Vertex down_v = edge.getFromVertex();
if (downclosed.contains(down_v)) {
continue;
}
if (edge instanceof OutEdge) {
continue;
}
// traverse will be backward because ArriveBy was set in the initial down state
State down_sv = edge.traverse(down_su);
if (VERBOSE)
_log.debug(" result down {}", down_sv);
// When an edge leads nowhere (as indicated by returning NULL), the iteration is
// over.
if (down_sv == null) {
continue;
}
if (down_sv.exceedsWeightLimit(opt.maxWeight)) {
if (VERBOSE)
_log.debug(" down result too heavy {}", down_sv);
//too expensive to get here
continue;
}
if (opt.isArriveBy() && down_sv.getTime() < opt.worstTime) {
if (VERBOSE)
_log.debug(" down result exceeds worst time {} {}", opt.worstTime, down_sv);
continue;
}
if (downspt.add(down_sv)) {
double weight = down_sv.getWeight();
if (weight < bestMeetingCost)
downqueue.insert(down_sv, weight);
}
}
}
}
if (meeting == null) {
return null;
} else {
if (VERBOSE)
_log.debug("meeting point is {}", meeting);
}
/* Splice paths */
State upMeet = upspt.getState(meeting);
State downMeet = downspt.getState(meeting);
State r = opt.isArriveBy() ? downMeet : upMeet;
State s = opt.isArriveBy() ? upMeet : downMeet;
while (s.getBackEdge() != null) {
r = s.getBackEdge().traverse(r);
// traversals might exceed limits here, even if they didn't during search
if (r == null)
return null;
s = s.getBackState();
}
/* Unpack shortcuts */
s = r.reversedClone();
while (r.getBackEdge() != null) {
Edge e = r.getBackEdge();
if (e instanceof Shortcut)
s = ((Shortcut)e).unpackTraverse(s);
else
s = e.traverse(s);
// traversals might exceed limits and fail during unpacking, even if they didn't during search
if (s == null)
return null;
r = r.getBackState();
}
// no need to request optimization, we just unpacked the path backward
GraphPath ret = new GraphPath(s, false);
return ret;
}
| public GraphPath getShortestPath(Vertex origin, Vertex target, long time,
RoutingRequest opt) {
if (origin == null || target == null) {
return null;
}
RoutingRequest upOptions = opt.clone();
RoutingRequest downOptions = opt.clone();
//TODO: verify set to/from are correct (AMB)
upOptions.setArriveBy(false);
upOptions.dateTime = time;
upOptions.setRoutingContext(graph, origin, target);
downOptions.setArriveBy(true);
downOptions.dateTime = time;
downOptions.setRoutingContext(graph, target, origin);
/** max walk distance cannot be less than distances to nearest transit stops */
double minWalkDistance =
origin.getDistanceToNearestTransitStop() + target.getDistanceToNearestTransitStop();
upOptions.setMaxWalkDistance(Math.max(upOptions.getMaxWalkDistance(), minWalkDistance));
downOptions.setMaxWalkDistance(Math.max(downOptions.getMaxWalkDistance(), minWalkDistance));
final boolean VERBOSE = false;
// DEBUG no walk limit
//options.maxWalkDistance = Double.MAX_VALUE;
final int INITIAL_SIZE = 1000;
if (VERBOSE)
_log.debug("origin {} target {}", origin, target);
Map<Vertex, ArrayList<Edge>> extraEdges = getExtraEdges(origin, target);
BasicShortestPathTree upspt = new BasicShortestPathTree(upOptions);
BasicShortestPathTree downspt = new BasicShortestPathTree(downOptions);
BinHeap<State> upqueue = new BinHeap<State>(INITIAL_SIZE);
BinHeap<State> downqueue = new BinHeap<State>(INITIAL_SIZE);
// These sets are used not only to avoid revisiting nodes, but to find meetings
HashSet<Vertex> upclosed = new HashSet<Vertex>(INITIAL_SIZE);
HashSet<Vertex> downclosed = new HashSet<Vertex>(INITIAL_SIZE);
State upInit = new State(origin, upOptions);
upspt.add(upInit);
upqueue.insert(upInit, upInit.getWeight());
/* FIXME: insert extra bike walking targets */
State downInit = new State(target, downOptions);
downspt.add(downInit);
downqueue.insert(downInit, downInit.getWeight());
Vertex meeting = null;
double bestMeetingCost = Double.POSITIVE_INFINITY;
boolean done_up = false;
boolean done_down = false;
while (!(done_up && done_down)) {
// up and down steps could be a single method with parameters changed
// if ( ! done_up) treeStep(queue, options, thisClosed, thatClosed, thisSpt, thatSpt, bestMeeting);
/* one step on the up tree */
if (!done_up) {
if (upqueue.empty()) {
done_up = true;
continue;
}
State up_su = upqueue.extract_min(); // get the lowest-weightSum
// if ( ! upspt.visit(up_su))
// continue;
if (up_su.exceedsWeightLimit(bestMeetingCost)) {
if (VERBOSE)
_log.debug("pruning on up tree (best meeting cost)");
done_up = true;
continue;
}
Vertex u = up_su.getVertex();
upclosed.add(u); // should basic spt maintain a closed list?
if (VERBOSE)
_log.debug(" extract up {}", u);
if (downclosed.contains(u) && downspt.getState(u).getWalkDistance() + up_su.getWalkDistance() <= up_su.getOptions().getMaxWalkDistance()) {
double thisMeetingCost = up_su.getWeight() + downspt.getState(u).getWeight();
if (VERBOSE)
_log.debug(" meeting at {}", u);
if (thisMeetingCost < bestMeetingCost) {
bestMeetingCost = thisMeetingCost;
meeting = u;
}
continue;
}
if (opt.isArriveBy() && !(u instanceof StreetVertex)) {
// up path can only explore until core vertices on reverse paths
continue;
}
Collection<Edge> outgoing = u.getOutgoing();
if (VERBOSE)
_log.debug(" {} edges in core", outgoing.size());
if (extraEdges.containsKey(u)) {
List<Edge> newOutgoing = new ArrayList<Edge>();
newOutgoing.addAll(extraEdges.get(u));
if (VERBOSE)
_log.debug(" {} edges in extra", newOutgoing.size());
newOutgoing.addAll(outgoing);
outgoing = newOutgoing;
}
for (Edge edge : outgoing) {
if (VERBOSE)
_log.debug(" edge up {}", edge);
if (edge instanceof OutEdge) {
continue;
}
State up_sv = edge.traverse(up_su);
// When an edge leads nowhere (as indicated by returning NULL), the iteration is
// over.
if (up_sv == null) {
continue;
}
Vertex v = up_sv.getVertex();
if (upclosed.contains(v)) {
continue;
}
if (up_sv.exceedsWeightLimit(opt.maxWeight)) {
//too expensive to get here
continue;
}
if (!opt.isArriveBy() && up_sv.getTime() > opt.worstTime) {
continue;
}
if (upspt.add(up_sv)) {
double weight = up_sv.getWeight();
if (weight < bestMeetingCost)
upqueue.insert(up_sv, weight);
}
}
}
/* one step on the down tree */
if (!done_down) {
if (downqueue.empty()) {
done_down = true;
continue;
}
State down_su = downqueue.extract_min(); // get the lowest-weightSum
if ( ! downspt.visit(down_su))
continue;
if (down_su.exceedsWeightLimit(bestMeetingCost)) {
done_down = true;
continue;
}
Vertex down_u = down_su.getVertex();
if (VERBOSE)
_log.debug(" extract down {}", down_u);
if (upclosed.contains(down_u) && upspt.getState(down_u).getWalkDistance() + down_su.getWalkDistance() <= down_su.getOptions().getMaxWalkDistance()) {
double thisMeetingCost = down_su.getWeight() + upspt.getState(down_u).getWeight();
if (VERBOSE)
_log.debug(" meeting at {}", down_u);
if (thisMeetingCost < bestMeetingCost) {
bestMeetingCost = thisMeetingCost;
meeting = down_u;
}
}
downclosed.add(down_u);
if (!opt.isArriveBy() && !(down_u instanceof StreetVertex)) {
// down path can only explore until core vertices on forward paths
continue;
}
Collection<Edge> incoming = down_u.getIncoming();
if (VERBOSE)
_log.debug(" {} edges in core", incoming.size());
if (extraEdges.containsKey(down_u)) {
List<Edge> newIncoming = new ArrayList<Edge>();
newIncoming.addAll(incoming);
newIncoming.addAll(extraEdges.get(down_u));
incoming = newIncoming;
}
if (VERBOSE)
_log.debug(" {} edges with overlay and extra", incoming.size());
for (Edge edge : incoming) {
if (VERBOSE)
_log.debug(" edge down {}", edge);
Vertex down_v = edge.getFromVertex();
if (downclosed.contains(down_v)) {
continue;
}
if (edge instanceof OutEdge) {
continue;
}
// traverse will be backward because ArriveBy was set in the initial down state
State down_sv = edge.traverse(down_su);
if (VERBOSE)
_log.debug(" result down {}", down_sv);
// When an edge leads nowhere (as indicated by returning NULL), the iteration is
// over.
if (down_sv == null) {
continue;
}
if (down_sv.exceedsWeightLimit(opt.maxWeight)) {
if (VERBOSE)
_log.debug(" down result too heavy {}", down_sv);
//too expensive to get here
continue;
}
if (opt.isArriveBy() && down_sv.getTime() < opt.worstTime) {
if (VERBOSE)
_log.debug(" down result exceeds worst time {} {}", opt.worstTime, down_sv);
continue;
}
if (downspt.add(down_sv)) {
double weight = down_sv.getWeight();
if (weight < bestMeetingCost)
downqueue.insert(down_sv, weight);
}
}
}
}
if (meeting == null) {
return null;
} else {
if (VERBOSE)
_log.debug("meeting point is {}", meeting);
}
/* Splice paths */
State upMeet = upspt.getState(meeting);
State downMeet = downspt.getState(meeting);
State r = opt.isArriveBy() ? downMeet : upMeet;
State s = opt.isArriveBy() ? upMeet : downMeet;
while (s.getBackEdge() != null) {
r = s.getBackEdge().traverse(r);
// traversals might exceed limits here, even if they didn't during search
if (r == null)
return null;
s = s.getBackState();
}
/* Unpack shortcuts */
s = r.reversedClone();
while (r.getBackEdge() != null) {
Edge e = r.getBackEdge();
if (e instanceof Shortcut)
s = ((Shortcut)e).unpackTraverse(s);
else
s = e.traverse(s);
// traversals might exceed limits and fail during unpacking, even if they didn't during search
if (s == null)
return null;
r = r.getBackState();
}
// no need to request optimization, we just unpacked the path backward
GraphPath ret = new GraphPath(s, false);
return ret;
}
|
diff --git a/src/org/openstreetmap/josm/data/osm/visitor/paint/MapPaintSettings.java b/src/org/openstreetmap/josm/data/osm/visitor/paint/MapPaintSettings.java
index c9d58a7b..187fb41d 100644
--- a/src/org/openstreetmap/josm/data/osm/visitor/paint/MapPaintSettings.java
+++ b/src/org/openstreetmap/josm/data/osm/visitor/paint/MapPaintSettings.java
@@ -1,183 +1,183 @@
// License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.data.osm.visitor.paint;
import java.awt.Color;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
import org.openstreetmap.josm.data.Preferences.PreferenceChangedListener;
public class MapPaintSettings implements PreferenceChangedListener {
public static final MapPaintSettings INSTANCE = new MapPaintSettings();
private boolean useRealWidth;
private boolean showDirectionArrow;
private boolean showRelevantDirectionsOnly;
private int defaultSegmentWidth;
private boolean showOrderNumber;
private boolean showHeadArrowOnly;
private int showNamesDistance;
private int useStrokesDistance;
private int showIconsDistance;
private int selectedNodeSize;
private int connectionNodeSize;
private int unselectedNodeSize;
private int taggedNodeSize;
private boolean fillSelectedNode;
private boolean fillUnselectedNode;
private boolean fillTaggedNode;
private boolean fillConnectionNode;
private Color selectedColor;
private Color highlightColor;
private Color inactiveColor;
private Color nodeColor;
private Color taggedColor;
private Color connectionColor;
private Color taggedConnectionColor;
private MapPaintSettings() {
load();
Main.pref.addPreferenceChangeListener(this);
}
private void load() {
showDirectionArrow = Main.pref.getBoolean("draw.segment.direction", true);
showRelevantDirectionsOnly = Main.pref.getBoolean("draw.segment.relevant_directions_only", true);
useRealWidth = Main.pref.getBoolean("mappaint.useRealWidth", false);
defaultSegmentWidth = Main.pref.getInteger("mappaint.segment.default-width", 2);
selectedColor = PaintColors.SELECTED.get();
highlightColor = PaintColors.HIGHLIGHT.get();
inactiveColor = PaintColors.INACTIVE.get();
nodeColor = PaintColors.NODE.get();
taggedColor = PaintColors.TAGGED.get();
connectionColor = PaintColors.CONNECTION.get();
if (taggedColor != nodeColor) {
taggedConnectionColor = taggedColor;
} else {
taggedConnectionColor = connectionColor;
}
showOrderNumber = Main.pref.getBoolean("draw.segment.order_number", false);
showHeadArrowOnly = Main.pref.getBoolean("draw.segment.head_only", false);
showNamesDistance = Main.pref.getInteger("mappaint.shownames", 10000000);
useStrokesDistance = Main.pref.getInteger("mappaint.strokes", 10000000);
showIconsDistance = Main.pref.getInteger("mappaint.showicons", 10000000);
selectedNodeSize = Main.pref.getInteger("mappaint.node.selected-size", 5);
unselectedNodeSize = Main.pref.getInteger("mappaint.node.unselected-size", 3);
- connectionNodeSize = Main.pref.getInteger("mappaint.node.onnection-size", 5);
+ connectionNodeSize = Main.pref.getInteger("mappaint.node.connection-size", 5);
taggedNodeSize = Main.pref.getInteger("mappaint.node.tagged-size", 3);
fillSelectedNode = Main.pref.getBoolean("mappaint.node.fill-selected", true);
fillUnselectedNode = Main.pref.getBoolean("mappaint.node.fill-unselected", false);
fillTaggedNode = Main.pref.getBoolean("mappaint.node.fill-tagged", true);
- fillConnectionNode = Main.pref.getBoolean("mappaint.node.fill-onnection", false);
+ fillConnectionNode = Main.pref.getBoolean("mappaint.node.fill-connection", false);
}
public void preferenceChanged(PreferenceChangeEvent e) {
load();
}
public boolean isUseRealWidth() {
return useRealWidth;
}
public boolean isShowDirectionArrow() {
return showDirectionArrow;
}
public boolean isShowRelevantDirectionsOnly() {
return showRelevantDirectionsOnly;
}
public int getDefaultSegmentWidth() {
return defaultSegmentWidth;
}
public Color getSelectedColor() {
return selectedColor;
}
public Color getHighlightColor() {
return highlightColor;
}
public Color getInactiveColor() {
return inactiveColor;
}
public Color getNodeColor() {
return nodeColor;
}
public Color getTaggedColor() {
return taggedColor;
}
public Color getConnectionColor() {
return connectionColor;
}
public Color getTaggedConnectionColor() {
return taggedConnectionColor;
}
public boolean isShowOrderNumber() {
return showOrderNumber;
}
public void setShowHeadArrowOnly(boolean showHeadArrowOnly) {
this.showHeadArrowOnly = showHeadArrowOnly;
}
public boolean isShowHeadArrowOnly() {
return showHeadArrowOnly;
}
public int getShowNamesDistance() {
return showNamesDistance;
}
public int getUseStrokesDistance() {
return useStrokesDistance;
}
public int getShowIconsDistance() {
return showIconsDistance;
}
public int getSelectedNodeSize() {
return selectedNodeSize;
}
public int getConnectionNodeSize() {
return connectionNodeSize;
}
public int getUnselectedNodeSize() {
return unselectedNodeSize;
}
public int getTaggedNodeSize() {
return taggedNodeSize;
}
public boolean isFillSelectedNode() {
return fillSelectedNode;
}
public boolean isFillUnselectedNode() {
return fillUnselectedNode;
}
public boolean isFillConnectionNode() {
return fillConnectionNode;
}
public boolean isFillTaggedNode() {
return fillTaggedNode;
}
}
| false | true | private void load() {
showDirectionArrow = Main.pref.getBoolean("draw.segment.direction", true);
showRelevantDirectionsOnly = Main.pref.getBoolean("draw.segment.relevant_directions_only", true);
useRealWidth = Main.pref.getBoolean("mappaint.useRealWidth", false);
defaultSegmentWidth = Main.pref.getInteger("mappaint.segment.default-width", 2);
selectedColor = PaintColors.SELECTED.get();
highlightColor = PaintColors.HIGHLIGHT.get();
inactiveColor = PaintColors.INACTIVE.get();
nodeColor = PaintColors.NODE.get();
taggedColor = PaintColors.TAGGED.get();
connectionColor = PaintColors.CONNECTION.get();
if (taggedColor != nodeColor) {
taggedConnectionColor = taggedColor;
} else {
taggedConnectionColor = connectionColor;
}
showOrderNumber = Main.pref.getBoolean("draw.segment.order_number", false);
showHeadArrowOnly = Main.pref.getBoolean("draw.segment.head_only", false);
showNamesDistance = Main.pref.getInteger("mappaint.shownames", 10000000);
useStrokesDistance = Main.pref.getInteger("mappaint.strokes", 10000000);
showIconsDistance = Main.pref.getInteger("mappaint.showicons", 10000000);
selectedNodeSize = Main.pref.getInteger("mappaint.node.selected-size", 5);
unselectedNodeSize = Main.pref.getInteger("mappaint.node.unselected-size", 3);
connectionNodeSize = Main.pref.getInteger("mappaint.node.onnection-size", 5);
taggedNodeSize = Main.pref.getInteger("mappaint.node.tagged-size", 3);
fillSelectedNode = Main.pref.getBoolean("mappaint.node.fill-selected", true);
fillUnselectedNode = Main.pref.getBoolean("mappaint.node.fill-unselected", false);
fillTaggedNode = Main.pref.getBoolean("mappaint.node.fill-tagged", true);
fillConnectionNode = Main.pref.getBoolean("mappaint.node.fill-onnection", false);
}
| private void load() {
showDirectionArrow = Main.pref.getBoolean("draw.segment.direction", true);
showRelevantDirectionsOnly = Main.pref.getBoolean("draw.segment.relevant_directions_only", true);
useRealWidth = Main.pref.getBoolean("mappaint.useRealWidth", false);
defaultSegmentWidth = Main.pref.getInteger("mappaint.segment.default-width", 2);
selectedColor = PaintColors.SELECTED.get();
highlightColor = PaintColors.HIGHLIGHT.get();
inactiveColor = PaintColors.INACTIVE.get();
nodeColor = PaintColors.NODE.get();
taggedColor = PaintColors.TAGGED.get();
connectionColor = PaintColors.CONNECTION.get();
if (taggedColor != nodeColor) {
taggedConnectionColor = taggedColor;
} else {
taggedConnectionColor = connectionColor;
}
showOrderNumber = Main.pref.getBoolean("draw.segment.order_number", false);
showHeadArrowOnly = Main.pref.getBoolean("draw.segment.head_only", false);
showNamesDistance = Main.pref.getInteger("mappaint.shownames", 10000000);
useStrokesDistance = Main.pref.getInteger("mappaint.strokes", 10000000);
showIconsDistance = Main.pref.getInteger("mappaint.showicons", 10000000);
selectedNodeSize = Main.pref.getInteger("mappaint.node.selected-size", 5);
unselectedNodeSize = Main.pref.getInteger("mappaint.node.unselected-size", 3);
connectionNodeSize = Main.pref.getInteger("mappaint.node.connection-size", 5);
taggedNodeSize = Main.pref.getInteger("mappaint.node.tagged-size", 3);
fillSelectedNode = Main.pref.getBoolean("mappaint.node.fill-selected", true);
fillUnselectedNode = Main.pref.getBoolean("mappaint.node.fill-unselected", false);
fillTaggedNode = Main.pref.getBoolean("mappaint.node.fill-tagged", true);
fillConnectionNode = Main.pref.getBoolean("mappaint.node.fill-connection", false);
}
|
diff --git a/src/ComputerPlayer.java b/src/ComputerPlayer.java
index 7a52672..e023336 100644
--- a/src/ComputerPlayer.java
+++ b/src/ComputerPlayer.java
@@ -1,75 +1,75 @@
import java.util.ArrayList;
public class ComputerPlayer extends Player {
public ComputerPlayer(String n, Intersection.Piece p) {
super(n, p);
// TODO Auto-generated constructor stub
}
public void promptMove(GoEngine g) {
int row = 0;
int col = 0;
boolean placed = false;
while(placed != true) {
int leftSpace = 0;
int rightSpace = 0;
int topSpace = 0;
int bottomSpace = 0;
for(int i = 0; i < 81; i++){
if(g.board.getContents(row, col) != Intersection.Piece.EMPTY
&& g.board.getContents(row, col) != piece) {
for(int j = row + 1; j <= 8; j++){
if(g.board.getContents(j, col) == Intersection.Piece.EMPTY) {
bottomSpace++;
} else {
break;
}
}
- for(int j = row - 1; j >= 0; j++){
+ for(int j = row - 1; j >= 0; j--){
if(g.board.getContents(j, col) == Intersection.Piece.EMPTY) {
topSpace++;
} else {
break;
}
}
for(int j = col + 1; j <= 8; j++){
if(g.board.getContents(row, j) == Intersection.Piece.EMPTY) {
rightSpace++;
} else {
break;
}
}
- for(int j = col - 1; j >= 0; j++){
+ for(int j = col - 1; j >= 0; j--){
if(g.board.getContents(j, col) == Intersection.Piece.EMPTY) {
leftSpace++;
} else {
break;
}
}
if(leftSpace >= rightSpace && leftSpace >= topSpace && leftSpace >= bottomSpace){
placed = g.board.placePiece(row, col - 1, piece);
} else if(rightSpace >= leftSpace && rightSpace >= topSpace && rightSpace >= bottomSpace){
placed = g.board.placePiece(row, col + 1, piece);
} else if(topSpace >= rightSpace && topSpace >= leftSpace && topSpace >= bottomSpace){
placed = g.board.placePiece(row - 1, col, piece);
} else if(bottomSpace >= rightSpace && bottomSpace >= topSpace && bottomSpace >= leftSpace){
placed = g.board.placePiece(row + 1, col, piece);
}
}
if(placed || (col == 8 && row == 8)){
break;
}
if(col >= 8){
col = 0;
row++;
} else {
col++;
}
}
}
}
}
| false | true | public void promptMove(GoEngine g) {
int row = 0;
int col = 0;
boolean placed = false;
while(placed != true) {
int leftSpace = 0;
int rightSpace = 0;
int topSpace = 0;
int bottomSpace = 0;
for(int i = 0; i < 81; i++){
if(g.board.getContents(row, col) != Intersection.Piece.EMPTY
&& g.board.getContents(row, col) != piece) {
for(int j = row + 1; j <= 8; j++){
if(g.board.getContents(j, col) == Intersection.Piece.EMPTY) {
bottomSpace++;
} else {
break;
}
}
for(int j = row - 1; j >= 0; j++){
if(g.board.getContents(j, col) == Intersection.Piece.EMPTY) {
topSpace++;
} else {
break;
}
}
for(int j = col + 1; j <= 8; j++){
if(g.board.getContents(row, j) == Intersection.Piece.EMPTY) {
rightSpace++;
} else {
break;
}
}
for(int j = col - 1; j >= 0; j++){
if(g.board.getContents(j, col) == Intersection.Piece.EMPTY) {
leftSpace++;
} else {
break;
}
}
if(leftSpace >= rightSpace && leftSpace >= topSpace && leftSpace >= bottomSpace){
placed = g.board.placePiece(row, col - 1, piece);
} else if(rightSpace >= leftSpace && rightSpace >= topSpace && rightSpace >= bottomSpace){
placed = g.board.placePiece(row, col + 1, piece);
} else if(topSpace >= rightSpace && topSpace >= leftSpace && topSpace >= bottomSpace){
placed = g.board.placePiece(row - 1, col, piece);
} else if(bottomSpace >= rightSpace && bottomSpace >= topSpace && bottomSpace >= leftSpace){
placed = g.board.placePiece(row + 1, col, piece);
}
}
if(placed || (col == 8 && row == 8)){
break;
}
if(col >= 8){
col = 0;
row++;
} else {
col++;
}
}
}
}
| public void promptMove(GoEngine g) {
int row = 0;
int col = 0;
boolean placed = false;
while(placed != true) {
int leftSpace = 0;
int rightSpace = 0;
int topSpace = 0;
int bottomSpace = 0;
for(int i = 0; i < 81; i++){
if(g.board.getContents(row, col) != Intersection.Piece.EMPTY
&& g.board.getContents(row, col) != piece) {
for(int j = row + 1; j <= 8; j++){
if(g.board.getContents(j, col) == Intersection.Piece.EMPTY) {
bottomSpace++;
} else {
break;
}
}
for(int j = row - 1; j >= 0; j--){
if(g.board.getContents(j, col) == Intersection.Piece.EMPTY) {
topSpace++;
} else {
break;
}
}
for(int j = col + 1; j <= 8; j++){
if(g.board.getContents(row, j) == Intersection.Piece.EMPTY) {
rightSpace++;
} else {
break;
}
}
for(int j = col - 1; j >= 0; j--){
if(g.board.getContents(j, col) == Intersection.Piece.EMPTY) {
leftSpace++;
} else {
break;
}
}
if(leftSpace >= rightSpace && leftSpace >= topSpace && leftSpace >= bottomSpace){
placed = g.board.placePiece(row, col - 1, piece);
} else if(rightSpace >= leftSpace && rightSpace >= topSpace && rightSpace >= bottomSpace){
placed = g.board.placePiece(row, col + 1, piece);
} else if(topSpace >= rightSpace && topSpace >= leftSpace && topSpace >= bottomSpace){
placed = g.board.placePiece(row - 1, col, piece);
} else if(bottomSpace >= rightSpace && bottomSpace >= topSpace && bottomSpace >= leftSpace){
placed = g.board.placePiece(row + 1, col, piece);
}
}
if(placed || (col == 8 && row == 8)){
break;
}
if(col >= 8){
col = 0;
row++;
} else {
col++;
}
}
}
}
|
diff --git a/client-android/src/org/pushtalk/android/service/TalkReceiver.java b/client-android/src/org/pushtalk/android/service/TalkReceiver.java
index 305a9b4..fd81b05 100644
--- a/client-android/src/org/pushtalk/android/service/TalkReceiver.java
+++ b/client-android/src/org/pushtalk/android/service/TalkReceiver.java
@@ -1,87 +1,87 @@
package org.pushtalk.android.service;
import org.json.JSONException;
import org.json.JSONObject;
import org.pushtalk.android.Config;
import org.pushtalk.android.Constants;
import org.pushtalk.android.activity.WebPageActivity;
import org.pushtalk.android.utils.AndroidUtil;
import org.pushtalk.android.utils.Logger;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import cn.jpush.android.api.JPushInterface;
public class TalkReceiver extends BroadcastReceiver {
private static final String TAG = "TalkReceiver";
private NotificationManager nm;
@Override
public void onReceive(Context context, Intent intent) {
if (null == nm) {
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
Bundle bundle = intent.getExtras();
Logger.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + AndroidUtil.printBundle(bundle));
if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
Logger.d(TAG, "接受到推送下来的自定义消息: " + message);
String title = bundle.getString(JPushInterface.EXTRA_TITLE);
String channel = null;
String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
try {
- JSONObject json = new JSONObject(extras);
- channel = json.optString(Constants.KEY_CHANNEL);
+ JSONObject extrasJson = new JSONObject(extras);
+ channel = extrasJson.optString(Constants.KEY_CHANNEL);
} catch (Exception e) {
Logger.w(TAG, "");
}
if (!Config.isBackground) {
Intent msgIntent = new Intent(WebPageActivity.MESSAGE_RECEIVED_ACTION);
msgIntent.putExtra(Constants.KEY_MESSAGE, message);
msgIntent.putExtra(Constants.KEY_TITLE, title);
if (null != channel) {
msgIntent.putExtra(Constants.KEY_CHANNEL, channel);
}
JSONObject all = new JSONObject();
try {
all.put(Constants.KEY_TITLE, title);
all.put(Constants.KEY_MESSAGE, message);
- all.put(Constants.KEY_EXTRAS, extras);
+ all.put(Constants.KEY_EXTRAS, new JSONObject(extras));
} catch (JSONException e) {
}
msgIntent.putExtra("all", all.toString());
context.sendBroadcast(msgIntent);
Logger.v(TAG, "sending msg to ui ");
}
if (Config.IS_TEST_MODE) {
NotificationHelper.showMessageNotification(context, nm, title, message, channel);
}
} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
Logger.d(TAG, "接受到推送下来的通知");
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
Logger.d(TAG, "用户点击打开了通知");
} else {
Logger.d(TAG, "Unhandled intent - " + intent.getAction());
}
}
}
| false | true | public void onReceive(Context context, Intent intent) {
if (null == nm) {
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
Bundle bundle = intent.getExtras();
Logger.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + AndroidUtil.printBundle(bundle));
if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
Logger.d(TAG, "接受到推送下来的自定义消息: " + message);
String title = bundle.getString(JPushInterface.EXTRA_TITLE);
String channel = null;
String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
try {
JSONObject json = new JSONObject(extras);
channel = json.optString(Constants.KEY_CHANNEL);
} catch (Exception e) {
Logger.w(TAG, "");
}
if (!Config.isBackground) {
Intent msgIntent = new Intent(WebPageActivity.MESSAGE_RECEIVED_ACTION);
msgIntent.putExtra(Constants.KEY_MESSAGE, message);
msgIntent.putExtra(Constants.KEY_TITLE, title);
if (null != channel) {
msgIntent.putExtra(Constants.KEY_CHANNEL, channel);
}
JSONObject all = new JSONObject();
try {
all.put(Constants.KEY_TITLE, title);
all.put(Constants.KEY_MESSAGE, message);
all.put(Constants.KEY_EXTRAS, extras);
} catch (JSONException e) {
}
msgIntent.putExtra("all", all.toString());
context.sendBroadcast(msgIntent);
Logger.v(TAG, "sending msg to ui ");
}
if (Config.IS_TEST_MODE) {
NotificationHelper.showMessageNotification(context, nm, title, message, channel);
}
} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
Logger.d(TAG, "接受到推送下来的通知");
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
Logger.d(TAG, "用户点击打开了通知");
} else {
Logger.d(TAG, "Unhandled intent - " + intent.getAction());
}
}
| public void onReceive(Context context, Intent intent) {
if (null == nm) {
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
Bundle bundle = intent.getExtras();
Logger.d(TAG, "onReceive - " + intent.getAction() + ", extras: " + AndroidUtil.printBundle(bundle));
if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
Logger.d(TAG, "接受到推送下来的自定义消息: " + message);
String title = bundle.getString(JPushInterface.EXTRA_TITLE);
String channel = null;
String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
try {
JSONObject extrasJson = new JSONObject(extras);
channel = extrasJson.optString(Constants.KEY_CHANNEL);
} catch (Exception e) {
Logger.w(TAG, "");
}
if (!Config.isBackground) {
Intent msgIntent = new Intent(WebPageActivity.MESSAGE_RECEIVED_ACTION);
msgIntent.putExtra(Constants.KEY_MESSAGE, message);
msgIntent.putExtra(Constants.KEY_TITLE, title);
if (null != channel) {
msgIntent.putExtra(Constants.KEY_CHANNEL, channel);
}
JSONObject all = new JSONObject();
try {
all.put(Constants.KEY_TITLE, title);
all.put(Constants.KEY_MESSAGE, message);
all.put(Constants.KEY_EXTRAS, new JSONObject(extras));
} catch (JSONException e) {
}
msgIntent.putExtra("all", all.toString());
context.sendBroadcast(msgIntent);
Logger.v(TAG, "sending msg to ui ");
}
if (Config.IS_TEST_MODE) {
NotificationHelper.showMessageNotification(context, nm, title, message, channel);
}
} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
Logger.d(TAG, "接受到推送下来的通知");
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
Logger.d(TAG, "用户点击打开了通知");
} else {
Logger.d(TAG, "Unhandled intent - " + intent.getAction());
}
}
|
diff --git a/apps/cbm/plugins/xml/ImportCbmData.java b/apps/cbm/plugins/xml/ImportCbmData.java
index f56da2e3b..041bbf063 100644
--- a/apps/cbm/plugins/xml/ImportCbmData.java
+++ b/apps/cbm/plugins/xml/ImportCbmData.java
@@ -1,560 +1,560 @@
package plugins.xml;
import gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.AnnotationAvailabilityProfile;
import gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.CbmNode;
import gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.CollectionProtocol;
import gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.ParticipantCollectionSummary;
import gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.SpecimenAvailabilitySummaryProfile;
import gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.SpecimenCollectionContact;
import gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.SpecimenCollectionSummary;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.molgenis.cbm.Address;
import org.molgenis.cbm.Annotation_Availability_Profile;
import org.molgenis.cbm.CbmXmlParser;
import org.molgenis.cbm.Collection_Protocol;
import org.molgenis.cbm.Institution;
import org.molgenis.cbm.Join_Collection_Protocol_To_Institution;
import org.molgenis.cbm.Join_Participant_Collection_Summary_To_Race;
import org.molgenis.cbm.Join_Participant_Collection_Summary_Todiagnosis;
import org.molgenis.cbm.Organization;
import org.molgenis.cbm.Participant_Collection_Summary;
import org.molgenis.cbm.Person;
import org.molgenis.cbm.Specimen_Availability_Summary_Profile;
import org.molgenis.cbm.Specimen_Collection_Contact;
import org.molgenis.cbm.Specimen_Collection_Summary;
import org.molgenis.framework.db.Database;
import org.molgenis.framework.db.QueryRule;
import org.molgenis.framework.db.QueryRule.Operator;
import org.molgenis.framework.server.MolgenisRequest;
import org.molgenis.framework.ui.PluginModel;
import org.molgenis.framework.ui.ScreenController;
import org.molgenis.util.Entity;
public class ImportCbmData extends PluginModel<Entity>
{
private File currentFile;
private static final long serialVersionUID = -6143910771849972946L;
public ImportCbmData(String name, ScreenController<?> parent)
{
super(name, parent);
}
@Override
public String getViewName()
{
return "plugins_xml_ImportCbmData";
}
@Override
public String getViewTemplate()
{
return "plugins/xml/ImportCbmData.ftl";
}
@Override
public void handleRequest(Database db, MolgenisRequest request) throws Exception
{
if (request.getString("__action").equals("upload"))
{
// get uploaded file and do checks
File file = request.getFile("uploadData");
if (file == null)
{
throw new Exception("No file selected.");
}
else if (!file.getName().endsWith(".xml"))
{
throw new Exception("File does not end with '.xml', other formats are not supported.");
}
// get uploaded file and do checks
File currentXsdfile = request.getFile("uploadSchema");
if (currentXsdfile == null)
{
throw new Exception("No file selected.");
}
else if (!currentXsdfile.getName().endsWith(".xsd"))
{
throw new Exception("File does not end with '.xml', other formats are not supported.");
}
// if no error, set file, and continue
this.setCurrentFile(file);
System.out.println("current file : " + this.getCurrentFile());
// Parsing a document with JAXP
CbmXmlParser cbmXmlParser = new CbmXmlParser();
CbmNode result = cbmXmlParser.load(currentFile, currentXsdfile);
Map<Integer, Participant_Collection_Summary> listOfParticipantSummary = new HashMap<Integer, Participant_Collection_Summary>();
Map<Integer, Collection_Protocol> listOfCollectionProtocol = new HashMap<Integer, Collection_Protocol>();
Map<String, Join_Participant_Collection_Summary_To_Race> listOfParticipantRaceLinkTable = new HashMap<String, Join_Participant_Collection_Summary_To_Race>();
Map<String, Join_Participant_Collection_Summary_Todiagnosis> listOfParticipantDiagnosisLinkTable = new HashMap<String, Join_Participant_Collection_Summary_Todiagnosis>();
Map<Integer, Institution> listOfInstitues = new HashMap<Integer, Institution>();
Map<Integer, Organization> listOfOrganizations = new HashMap<Integer, Organization>();
Map<String, Join_Collection_Protocol_To_Institution> listOfCollectionInstituteLinkTable = new HashMap<String, Join_Collection_Protocol_To_Institution>();
Map<Integer, Specimen_Availability_Summary_Profile> listOfCollectionConstrained = new HashMap<Integer, Specimen_Availability_Summary_Profile>();
Map<Integer, Annotation_Availability_Profile> listOfAnnotationProfile = new HashMap<Integer, Annotation_Availability_Profile>();
Map<Integer, Specimen_Collection_Contact> listOfContacts = new HashMap<Integer, Specimen_Collection_Contact>();
Map<Integer, Address> listOfAddress = new HashMap<Integer, Address>();
Map<Integer, Person> listOfPersons = new HashMap<Integer, Person>();
for (CollectionProtocol collectionProtocolFromJaxb : result.getProtocols().getCollectionProtocol())
{
if (!listOfCollectionProtocol.containsKey(collectionProtocolFromJaxb.getId()))
{
List<ParticipantCollectionSummary> participantCollectionSummaryList = collectionProtocolFromJaxb
.getEnrolls().getParticipantCollectionSummary();
for (ParticipantCollectionSummary participantSummary : participantCollectionSummaryList)
{
if (!listOfParticipantSummary.containsKey(participantSummary.getId()))
{
// Create molgenis object for it
Participant_Collection_Summary participantCollectionSummary = new Participant_Collection_Summary();
// Set participant count
participantCollectionSummary.setParticipant_Count(participantSummary.getParticipantCount());
participantCollectionSummary.setParticipant_Collection_Summary_ID(participantSummary
.getId());
// Ethnicity should go to Race table.
participantCollectionSummary.setEthnicity(participantSummary.getEthnicity());
// Set gender to participant
participantCollectionSummary.setGender(participantSummary.getGender());
// ############# Collect all the races from Jaxb
// Object
// and
// ###########
// ############# create Molgenis entities ##########
for (gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Race eachRace : participantSummary
.getIsClassifiedBy().getRace())
{
// Make linkTable for
// ParticipantCollectionSummary
// and
// Race, therefore should check the uniqueness
// of
// combination of both ids
StringBuilder uniqueLinktableKey = new StringBuilder();
uniqueLinktableKey.append(participantSummary.getId()).append(eachRace.getId());
if (!listOfParticipantRaceLinkTable.containsKey(uniqueLinktableKey.toString()
.toLowerCase().trim()))
{
org.molgenis.cbm.Race existingRace = db.find(
org.molgenis.cbm.Race.class,
new QueryRule(org.molgenis.cbm.Race.RACE_ID, Operator.EQUALS, eachRace
.getId())).get(0);
Join_Participant_Collection_Summary_To_Race linkTable = new Join_Participant_Collection_Summary_To_Race();
linkTable.setParticipant_Collection_Summary_ID(participantCollectionSummary);
linkTable.setRace_Id(existingRace);
listOfParticipantRaceLinkTable.put(uniqueLinktableKey.toString().toLowerCase()
.trim(), linkTable);
}
}
// Get the specimenCollection from the participant
// summary
List<Integer> listoFSpecimenID = new ArrayList<Integer>();
for (SpecimenCollectionSummary specimen : participantSummary.getProvides()
.getSpecimenCollectionSummary())
{
listoFSpecimenID.add(specimen.getId());
}
List<Specimen_Collection_Summary> collectionOfSpecimens = db.find(
Specimen_Collection_Summary.class, new QueryRule(
Specimen_Collection_Summary.SPECIMEN_COLLECTION_SUMMARY_ID, Operator.IN,
listoFSpecimenID));
participantCollectionSummary
.setIs_Collected_FromSpecimen_Collection_SummaryCollection(collectionOfSpecimens);
// Diagnosis
for (gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Diagnosis diagnosis : participantSummary
.getReceives().getDiagnosis())
{
StringBuilder uniqueIdentifer = new StringBuilder();
uniqueIdentifer.append(participantSummary.getId()).append(diagnosis.getId());
if (!listOfParticipantDiagnosisLinkTable.containsKey(uniqueIdentifer.toString().trim()
.toLowerCase()))
{
Join_Participant_Collection_Summary_Todiagnosis joinTableParticipantDiagnosis = new Join_Participant_Collection_Summary_Todiagnosis();
joinTableParticipantDiagnosis
.setParticipant_Collection_Summary_ID(participantCollectionSummary);
org.molgenis.cbm.Diagnosis diag = db.find(
org.molgenis.cbm.Diagnosis.class,
new QueryRule(org.molgenis.cbm.Diagnosis.DIAGNOSIS_ID, Operator.EQUALS,
diagnosis.getId())).get(0);
joinTableParticipantDiagnosis.setDiagnosis_Id(diag);
joinTableParticipantDiagnosis.setDiagnosis_Id_Diagnosis_ID(diag.getDiagnosis_ID());
joinTableParticipantDiagnosis
.setDiagnosis_Id_DiagnosisType(diag.getDiagnosisType());
listOfParticipantDiagnosisLinkTable.put(uniqueIdentifer.toString().trim()
.toLowerCase(), joinTableParticipantDiagnosis);
}
}
// Add this participantSummary to the list
// collection
listOfParticipantSummary.put(participantSummary.getId(), participantCollectionSummary);
}
}
// Collect information for collection_protocol
Collection_Protocol cp = new Collection_Protocol();
String collectionProtocolName = collectionProtocolFromJaxb.getName();
String collectionProtocolIdentifier = collectionProtocolFromJaxb.getIdentifier();
Integer collectionProtocolID = collectionProtocolFromJaxb.getId();
cp.setCollectionProtocolID(collectionProtocolID);
cp.setName(collectionProtocolName);
cp.setIdentifier(collectionProtocolIdentifier);
// TODO: The date format comes in XMLDateFormat, need to
// convert it
// cp.setDate_Last_Updated(collectionProtocolFromJaxb.getDateLastUpdated().toString());
//
// TODO: The date format comes in XMLDateFormat, need to
// convert it
// cp.setEnd_Date(collectionProtocolFromJaxb.getEndDate().toString());
// Collection information for institution and organization
for (gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Institution cbmInsititue : collectionProtocolFromJaxb
.getResidesAt().getInstitution())
{
Institution institue = null;
if (!listOfOrganizations.containsKey(cbmInsititue.getId()))
{
Organization organization = new Organization();
organization.setName(cbmInsititue.getName());
organization.setOrganization_ID(cbmInsititue.getId());
institue = new Institution();
- institue.setInstitution_ID(organization);
+ institue.setInstitution_ID(organization.getOrganization_ID());
institue.setHomepage_URL(cbmInsititue.getHomepageURL());
if (!listOfInstitues.containsKey(cbmInsititue.getId()))
{
listOfInstitues.put(cbmInsititue.getId(), institue);
}
listOfOrganizations.put(cbmInsititue.getId(), organization);
}
else
{
institue = listOfInstitues.get(cbmInsititue.getId());
}
StringBuilder builder = new StringBuilder();
if (!listOfCollectionInstituteLinkTable.containsKey(builder.append(collectionProtocolID)
.append(cbmInsititue.getId()).toString()))
{
Join_Collection_Protocol_To_Institution joinTable = new Join_Collection_Protocol_To_Institution();
joinTable.setInstitution_ID(institue);
joinTable.setCollection_Protocol_ID(cp);
listOfCollectionInstituteLinkTable.put(
builder.append(collectionProtocolID).append(cbmInsititue.getId()).toString(),
joinTable);
}
}
// Set the isconstrained entity
if (collectionProtocolFromJaxb.getIsConstrainedBy() != null)
{
SpecimenAvailabilitySummaryProfile profileJaxb = collectionProtocolFromJaxb
.getIsConstrainedBy();
Specimen_Availability_Summary_Profile specimenProfile = null;
if (!listOfCollectionConstrained.containsKey(profileJaxb.getId()))
{
specimenProfile = new Specimen_Availability_Summary_Profile();
specimenProfile.setIs_Collaboration_Required(profileJaxb.isIsCollaborationRequired());
specimenProfile.setIs_Available_To_Outside_Institution(profileJaxb
.isIsAvailableToOutsideInstitution());
specimenProfile.setIs_Available_To_Foreign_Investigators(profileJaxb
.isIsAvailableToForeignInvestigators());
specimenProfile.setIs_Available_To_Commercial_Organizations(profileJaxb
.isIsAvailableToCommercialOrganizations());
specimenProfile.setSpecimen_Availability_Summary_Profile_ID(profileJaxb.getId());
listOfCollectionConstrained.put(profileJaxb.getId(), specimenProfile);
}
else
{
specimenProfile = listOfCollectionConstrained.get(profileJaxb.getId());
}
cp.setIs_Constrained_By(specimenProfile);
}
if (collectionProtocolFromJaxb.getMakesAvailable() != null)
{
AnnotationAvailabilityProfile annotationProfileJaxb = collectionProtocolFromJaxb
.getMakesAvailable();
Annotation_Availability_Profile profile = null;
if (!listOfAnnotationProfile.containsKey(annotationProfileJaxb.getId()))
{
profile = new Annotation_Availability_Profile();
profile.setHas_Additional_Patient_Demographics(annotationProfileJaxb
.isHasAdditionalPatientDemographics());
profile.setHas_Exposure_History(annotationProfileJaxb.isHasExposureHistory());
profile.setHas_Family_History(annotationProfileJaxb.isHasFamilyHistory());
profile.setHas_Histopathologic_Information(annotationProfileJaxb
.isHasHistopathologicInformation());
profile.setHas_Lab_Data(annotationProfileJaxb.isHasLabData());
profile.setHas_Longitudinal_Specimens(annotationProfileJaxb.isHasLongitudinalSpecimens());
profile.setHas_Matched_Specimens(annotationProfileJaxb.isHasMatchedSpecimens());
profile.setHas_Outcome_Information(annotationProfileJaxb.isHasOutcomeInformation());
profile.setHas_Participants_Available_For_Followup(annotationProfileJaxb
.isHasParticipantsAvailableForFollowup());
profile.setHas_Treatment_Information(annotationProfileJaxb.isHasTreatmentInformation());
profile.setAnnotation_Availability_Profile_ID(annotationProfileJaxb.getId());
listOfAnnotationProfile.put(annotationProfileJaxb.getId(), profile);
}
else
{
profile = listOfAnnotationProfile.get(annotationProfileJaxb.getId());
}
cp.setMakes_Available(profile);
}
// Collect information on Specimen_collection_contact and
// Person
// and Address
if (collectionProtocolFromJaxb.getIsAssignedTo() != null)
{
SpecimenCollectionContact collectionContactJaxb = collectionProtocolFromJaxb.getIsAssignedTo();
Specimen_Collection_Contact contact = null;
if (!listOfContacts.containsKey(collectionContactJaxb.getId()))
{
Person person = new Person();
person.setFirst_Name(collectionContactJaxb.getFirstName());
person.setLast_Name(collectionContactJaxb.getLastName());
person.setFull_Name(collectionContactJaxb.getFullName());
person.setEmail_Address(collectionContactJaxb.getEmailAddress());
person.setMiddle_Name_Or_Initial(collectionContactJaxb.getMiddleNameOrInitial());
person.setPerson_ID(collectionContactJaxb.getId());
listOfPersons.put(collectionContactJaxb.getId(), person);
contact = new Specimen_Collection_Contact();
- contact.setSpecimen_Collection_Contact_ID(person);
+ contact.setSpecimen_Collection_Contact_ID(person.getPerson_ID());
contact.setPhone(collectionContactJaxb.getPhone());
gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Address addressJaxb = collectionContactJaxb
.getIsLocatedAt();
if (addressJaxb != null)
{
if (listOfAddress.containsKey(addressJaxb.getId()))
{
contact.setAddress_Id(listOfAddress.get(addressJaxb.getId()));
}
else
{
Address address = new Address();
address.setAddress_ID(addressJaxb.getId());
address.setCity(addressJaxb.getCity());
address.setCountry(addressJaxb.getCountry());
address.setDepartment_Or_Division(addressJaxb.getDepartmentOrDivision());
address.setEntity_Name(addressJaxb.getEntityName());
address.setEntity_Number(addressJaxb.getEntityNumber());
address.setFloor_Or_Premises(addressJaxb.getFloorOrPremises());
address.setPost_Office_Box(addressJaxb.getPostOfficeBox());
address.setState(addressJaxb.getState());
address.setStreet_Or_Thoroughfare_Extension_Name(addressJaxb
.getStreetOrThoroughfareExtensionName());
address.setStreet_Or_Thoroughfare_Name_And_Type(addressJaxb
.getStreetOrThoroughfareNameAndType());
address.setStreet_Or_Thoroughfare_Number(addressJaxb
.getStreetOrThoroughfareNumber());
address.setStreet_Or_Thoroughfare_Section_Name(addressJaxb
.getStreetOrThoroughfareSectionName());
address.setStreet_Post_Directional(addressJaxb.getStreetPostDirectional());
address.setStreet_Pre_Directional(addressJaxb.getStreetPreDirectional());
address.setZip_Code(addressJaxb.getZipCode());
listOfAddress.put(addressJaxb.getId(), address);
}
}
listOfContacts.put(collectionContactJaxb.getId(), contact);
}
else
{
contact = listOfContacts.get(collectionContactJaxb.getId());
}
cp.setIs_Assigned_To(contact);
}
listOfCollectionProtocol.put(collectionProtocolFromJaxb.getId(), cp);
}
}
db.add(new ArrayList<Person>(listOfPersons.values()));
db.add(new ArrayList<Address>(listOfAddress.values()));
db.add(new ArrayList<Specimen_Collection_Contact>(listOfContacts.values()));
db.add(new ArrayList<Annotation_Availability_Profile>(listOfAnnotationProfile.values()));
db.add(new ArrayList<Specimen_Availability_Summary_Profile>(listOfCollectionConstrained.values()));
db.add(new ArrayList<Organization>(listOfOrganizations.values()));
db.add(new ArrayList<Institution>(listOfInstitues.values()));
db.add(new ArrayList<Participant_Collection_Summary>(listOfParticipantSummary.values()));
db.add(new ArrayList<Collection_Protocol>(listOfCollectionProtocol.values()));
db.add(new ArrayList<Join_Participant_Collection_Summary_To_Race>(listOfParticipantRaceLinkTable.values()));
db.add(new ArrayList<Join_Participant_Collection_Summary_Todiagnosis>(listOfParticipantDiagnosisLinkTable
.values()));
}
}
private void setCurrentFile(File file)
{
this.currentFile = file;
}
private File getCurrentFile()
{
return this.currentFile;
}
@Override
public void reload(Database db)
{
}
@Override
public boolean isVisible()
{
// you can use this to hide this plugin, e.g. based on user rights.
// e.g.
// if(!this.getLogin().hasEditPermission(myEntity)) return false;
return true;
}
}
| false | true | public void handleRequest(Database db, MolgenisRequest request) throws Exception
{
if (request.getString("__action").equals("upload"))
{
// get uploaded file and do checks
File file = request.getFile("uploadData");
if (file == null)
{
throw new Exception("No file selected.");
}
else if (!file.getName().endsWith(".xml"))
{
throw new Exception("File does not end with '.xml', other formats are not supported.");
}
// get uploaded file and do checks
File currentXsdfile = request.getFile("uploadSchema");
if (currentXsdfile == null)
{
throw new Exception("No file selected.");
}
else if (!currentXsdfile.getName().endsWith(".xsd"))
{
throw new Exception("File does not end with '.xml', other formats are not supported.");
}
// if no error, set file, and continue
this.setCurrentFile(file);
System.out.println("current file : " + this.getCurrentFile());
// Parsing a document with JAXP
CbmXmlParser cbmXmlParser = new CbmXmlParser();
CbmNode result = cbmXmlParser.load(currentFile, currentXsdfile);
Map<Integer, Participant_Collection_Summary> listOfParticipantSummary = new HashMap<Integer, Participant_Collection_Summary>();
Map<Integer, Collection_Protocol> listOfCollectionProtocol = new HashMap<Integer, Collection_Protocol>();
Map<String, Join_Participant_Collection_Summary_To_Race> listOfParticipantRaceLinkTable = new HashMap<String, Join_Participant_Collection_Summary_To_Race>();
Map<String, Join_Participant_Collection_Summary_Todiagnosis> listOfParticipantDiagnosisLinkTable = new HashMap<String, Join_Participant_Collection_Summary_Todiagnosis>();
Map<Integer, Institution> listOfInstitues = new HashMap<Integer, Institution>();
Map<Integer, Organization> listOfOrganizations = new HashMap<Integer, Organization>();
Map<String, Join_Collection_Protocol_To_Institution> listOfCollectionInstituteLinkTable = new HashMap<String, Join_Collection_Protocol_To_Institution>();
Map<Integer, Specimen_Availability_Summary_Profile> listOfCollectionConstrained = new HashMap<Integer, Specimen_Availability_Summary_Profile>();
Map<Integer, Annotation_Availability_Profile> listOfAnnotationProfile = new HashMap<Integer, Annotation_Availability_Profile>();
Map<Integer, Specimen_Collection_Contact> listOfContacts = new HashMap<Integer, Specimen_Collection_Contact>();
Map<Integer, Address> listOfAddress = new HashMap<Integer, Address>();
Map<Integer, Person> listOfPersons = new HashMap<Integer, Person>();
for (CollectionProtocol collectionProtocolFromJaxb : result.getProtocols().getCollectionProtocol())
{
if (!listOfCollectionProtocol.containsKey(collectionProtocolFromJaxb.getId()))
{
List<ParticipantCollectionSummary> participantCollectionSummaryList = collectionProtocolFromJaxb
.getEnrolls().getParticipantCollectionSummary();
for (ParticipantCollectionSummary participantSummary : participantCollectionSummaryList)
{
if (!listOfParticipantSummary.containsKey(participantSummary.getId()))
{
// Create molgenis object for it
Participant_Collection_Summary participantCollectionSummary = new Participant_Collection_Summary();
// Set participant count
participantCollectionSummary.setParticipant_Count(participantSummary.getParticipantCount());
participantCollectionSummary.setParticipant_Collection_Summary_ID(participantSummary
.getId());
// Ethnicity should go to Race table.
participantCollectionSummary.setEthnicity(participantSummary.getEthnicity());
// Set gender to participant
participantCollectionSummary.setGender(participantSummary.getGender());
// ############# Collect all the races from Jaxb
// Object
// and
// ###########
// ############# create Molgenis entities ##########
for (gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Race eachRace : participantSummary
.getIsClassifiedBy().getRace())
{
// Make linkTable for
// ParticipantCollectionSummary
// and
// Race, therefore should check the uniqueness
// of
// combination of both ids
StringBuilder uniqueLinktableKey = new StringBuilder();
uniqueLinktableKey.append(participantSummary.getId()).append(eachRace.getId());
if (!listOfParticipantRaceLinkTable.containsKey(uniqueLinktableKey.toString()
.toLowerCase().trim()))
{
org.molgenis.cbm.Race existingRace = db.find(
org.molgenis.cbm.Race.class,
new QueryRule(org.molgenis.cbm.Race.RACE_ID, Operator.EQUALS, eachRace
.getId())).get(0);
Join_Participant_Collection_Summary_To_Race linkTable = new Join_Participant_Collection_Summary_To_Race();
linkTable.setParticipant_Collection_Summary_ID(participantCollectionSummary);
linkTable.setRace_Id(existingRace);
listOfParticipantRaceLinkTable.put(uniqueLinktableKey.toString().toLowerCase()
.trim(), linkTable);
}
}
// Get the specimenCollection from the participant
// summary
List<Integer> listoFSpecimenID = new ArrayList<Integer>();
for (SpecimenCollectionSummary specimen : participantSummary.getProvides()
.getSpecimenCollectionSummary())
{
listoFSpecimenID.add(specimen.getId());
}
List<Specimen_Collection_Summary> collectionOfSpecimens = db.find(
Specimen_Collection_Summary.class, new QueryRule(
Specimen_Collection_Summary.SPECIMEN_COLLECTION_SUMMARY_ID, Operator.IN,
listoFSpecimenID));
participantCollectionSummary
.setIs_Collected_FromSpecimen_Collection_SummaryCollection(collectionOfSpecimens);
// Diagnosis
for (gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Diagnosis diagnosis : participantSummary
.getReceives().getDiagnosis())
{
StringBuilder uniqueIdentifer = new StringBuilder();
uniqueIdentifer.append(participantSummary.getId()).append(diagnosis.getId());
if (!listOfParticipantDiagnosisLinkTable.containsKey(uniqueIdentifer.toString().trim()
.toLowerCase()))
{
Join_Participant_Collection_Summary_Todiagnosis joinTableParticipantDiagnosis = new Join_Participant_Collection_Summary_Todiagnosis();
joinTableParticipantDiagnosis
.setParticipant_Collection_Summary_ID(participantCollectionSummary);
org.molgenis.cbm.Diagnosis diag = db.find(
org.molgenis.cbm.Diagnosis.class,
new QueryRule(org.molgenis.cbm.Diagnosis.DIAGNOSIS_ID, Operator.EQUALS,
diagnosis.getId())).get(0);
joinTableParticipantDiagnosis.setDiagnosis_Id(diag);
joinTableParticipantDiagnosis.setDiagnosis_Id_Diagnosis_ID(diag.getDiagnosis_ID());
joinTableParticipantDiagnosis
.setDiagnosis_Id_DiagnosisType(diag.getDiagnosisType());
listOfParticipantDiagnosisLinkTable.put(uniqueIdentifer.toString().trim()
.toLowerCase(), joinTableParticipantDiagnosis);
}
}
// Add this participantSummary to the list
// collection
listOfParticipantSummary.put(participantSummary.getId(), participantCollectionSummary);
}
}
// Collect information for collection_protocol
Collection_Protocol cp = new Collection_Protocol();
String collectionProtocolName = collectionProtocolFromJaxb.getName();
String collectionProtocolIdentifier = collectionProtocolFromJaxb.getIdentifier();
Integer collectionProtocolID = collectionProtocolFromJaxb.getId();
cp.setCollectionProtocolID(collectionProtocolID);
cp.setName(collectionProtocolName);
cp.setIdentifier(collectionProtocolIdentifier);
// TODO: The date format comes in XMLDateFormat, need to
// convert it
// cp.setDate_Last_Updated(collectionProtocolFromJaxb.getDateLastUpdated().toString());
//
// TODO: The date format comes in XMLDateFormat, need to
// convert it
// cp.setEnd_Date(collectionProtocolFromJaxb.getEndDate().toString());
// Collection information for institution and organization
for (gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Institution cbmInsititue : collectionProtocolFromJaxb
.getResidesAt().getInstitution())
{
Institution institue = null;
if (!listOfOrganizations.containsKey(cbmInsititue.getId()))
{
Organization organization = new Organization();
organization.setName(cbmInsititue.getName());
organization.setOrganization_ID(cbmInsititue.getId());
institue = new Institution();
institue.setInstitution_ID(organization);
institue.setHomepage_URL(cbmInsititue.getHomepageURL());
if (!listOfInstitues.containsKey(cbmInsititue.getId()))
{
listOfInstitues.put(cbmInsititue.getId(), institue);
}
listOfOrganizations.put(cbmInsititue.getId(), organization);
}
else
{
institue = listOfInstitues.get(cbmInsititue.getId());
}
StringBuilder builder = new StringBuilder();
if (!listOfCollectionInstituteLinkTable.containsKey(builder.append(collectionProtocolID)
.append(cbmInsititue.getId()).toString()))
{
Join_Collection_Protocol_To_Institution joinTable = new Join_Collection_Protocol_To_Institution();
joinTable.setInstitution_ID(institue);
joinTable.setCollection_Protocol_ID(cp);
listOfCollectionInstituteLinkTable.put(
builder.append(collectionProtocolID).append(cbmInsititue.getId()).toString(),
joinTable);
}
}
// Set the isconstrained entity
if (collectionProtocolFromJaxb.getIsConstrainedBy() != null)
{
SpecimenAvailabilitySummaryProfile profileJaxb = collectionProtocolFromJaxb
.getIsConstrainedBy();
Specimen_Availability_Summary_Profile specimenProfile = null;
if (!listOfCollectionConstrained.containsKey(profileJaxb.getId()))
{
specimenProfile = new Specimen_Availability_Summary_Profile();
specimenProfile.setIs_Collaboration_Required(profileJaxb.isIsCollaborationRequired());
specimenProfile.setIs_Available_To_Outside_Institution(profileJaxb
.isIsAvailableToOutsideInstitution());
specimenProfile.setIs_Available_To_Foreign_Investigators(profileJaxb
.isIsAvailableToForeignInvestigators());
specimenProfile.setIs_Available_To_Commercial_Organizations(profileJaxb
.isIsAvailableToCommercialOrganizations());
specimenProfile.setSpecimen_Availability_Summary_Profile_ID(profileJaxb.getId());
listOfCollectionConstrained.put(profileJaxb.getId(), specimenProfile);
}
else
{
specimenProfile = listOfCollectionConstrained.get(profileJaxb.getId());
}
cp.setIs_Constrained_By(specimenProfile);
}
if (collectionProtocolFromJaxb.getMakesAvailable() != null)
{
AnnotationAvailabilityProfile annotationProfileJaxb = collectionProtocolFromJaxb
.getMakesAvailable();
Annotation_Availability_Profile profile = null;
if (!listOfAnnotationProfile.containsKey(annotationProfileJaxb.getId()))
{
profile = new Annotation_Availability_Profile();
profile.setHas_Additional_Patient_Demographics(annotationProfileJaxb
.isHasAdditionalPatientDemographics());
profile.setHas_Exposure_History(annotationProfileJaxb.isHasExposureHistory());
profile.setHas_Family_History(annotationProfileJaxb.isHasFamilyHistory());
profile.setHas_Histopathologic_Information(annotationProfileJaxb
.isHasHistopathologicInformation());
profile.setHas_Lab_Data(annotationProfileJaxb.isHasLabData());
profile.setHas_Longitudinal_Specimens(annotationProfileJaxb.isHasLongitudinalSpecimens());
profile.setHas_Matched_Specimens(annotationProfileJaxb.isHasMatchedSpecimens());
profile.setHas_Outcome_Information(annotationProfileJaxb.isHasOutcomeInformation());
profile.setHas_Participants_Available_For_Followup(annotationProfileJaxb
.isHasParticipantsAvailableForFollowup());
profile.setHas_Treatment_Information(annotationProfileJaxb.isHasTreatmentInformation());
profile.setAnnotation_Availability_Profile_ID(annotationProfileJaxb.getId());
listOfAnnotationProfile.put(annotationProfileJaxb.getId(), profile);
}
else
{
profile = listOfAnnotationProfile.get(annotationProfileJaxb.getId());
}
cp.setMakes_Available(profile);
}
// Collect information on Specimen_collection_contact and
// Person
// and Address
if (collectionProtocolFromJaxb.getIsAssignedTo() != null)
{
SpecimenCollectionContact collectionContactJaxb = collectionProtocolFromJaxb.getIsAssignedTo();
Specimen_Collection_Contact contact = null;
if (!listOfContacts.containsKey(collectionContactJaxb.getId()))
{
Person person = new Person();
person.setFirst_Name(collectionContactJaxb.getFirstName());
person.setLast_Name(collectionContactJaxb.getLastName());
person.setFull_Name(collectionContactJaxb.getFullName());
person.setEmail_Address(collectionContactJaxb.getEmailAddress());
person.setMiddle_Name_Or_Initial(collectionContactJaxb.getMiddleNameOrInitial());
person.setPerson_ID(collectionContactJaxb.getId());
listOfPersons.put(collectionContactJaxb.getId(), person);
contact = new Specimen_Collection_Contact();
contact.setSpecimen_Collection_Contact_ID(person);
contact.setPhone(collectionContactJaxb.getPhone());
gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Address addressJaxb = collectionContactJaxb
.getIsLocatedAt();
if (addressJaxb != null)
{
if (listOfAddress.containsKey(addressJaxb.getId()))
{
contact.setAddress_Id(listOfAddress.get(addressJaxb.getId()));
}
else
{
Address address = new Address();
address.setAddress_ID(addressJaxb.getId());
address.setCity(addressJaxb.getCity());
address.setCountry(addressJaxb.getCountry());
address.setDepartment_Or_Division(addressJaxb.getDepartmentOrDivision());
address.setEntity_Name(addressJaxb.getEntityName());
address.setEntity_Number(addressJaxb.getEntityNumber());
address.setFloor_Or_Premises(addressJaxb.getFloorOrPremises());
address.setPost_Office_Box(addressJaxb.getPostOfficeBox());
address.setState(addressJaxb.getState());
address.setStreet_Or_Thoroughfare_Extension_Name(addressJaxb
.getStreetOrThoroughfareExtensionName());
address.setStreet_Or_Thoroughfare_Name_And_Type(addressJaxb
.getStreetOrThoroughfareNameAndType());
address.setStreet_Or_Thoroughfare_Number(addressJaxb
.getStreetOrThoroughfareNumber());
address.setStreet_Or_Thoroughfare_Section_Name(addressJaxb
.getStreetOrThoroughfareSectionName());
address.setStreet_Post_Directional(addressJaxb.getStreetPostDirectional());
address.setStreet_Pre_Directional(addressJaxb.getStreetPreDirectional());
address.setZip_Code(addressJaxb.getZipCode());
listOfAddress.put(addressJaxb.getId(), address);
}
}
listOfContacts.put(collectionContactJaxb.getId(), contact);
}
else
{
contact = listOfContacts.get(collectionContactJaxb.getId());
}
cp.setIs_Assigned_To(contact);
}
listOfCollectionProtocol.put(collectionProtocolFromJaxb.getId(), cp);
}
}
db.add(new ArrayList<Person>(listOfPersons.values()));
db.add(new ArrayList<Address>(listOfAddress.values()));
db.add(new ArrayList<Specimen_Collection_Contact>(listOfContacts.values()));
db.add(new ArrayList<Annotation_Availability_Profile>(listOfAnnotationProfile.values()));
db.add(new ArrayList<Specimen_Availability_Summary_Profile>(listOfCollectionConstrained.values()));
db.add(new ArrayList<Organization>(listOfOrganizations.values()));
db.add(new ArrayList<Institution>(listOfInstitues.values()));
db.add(new ArrayList<Participant_Collection_Summary>(listOfParticipantSummary.values()));
db.add(new ArrayList<Collection_Protocol>(listOfCollectionProtocol.values()));
db.add(new ArrayList<Join_Participant_Collection_Summary_To_Race>(listOfParticipantRaceLinkTable.values()));
db.add(new ArrayList<Join_Participant_Collection_Summary_Todiagnosis>(listOfParticipantDiagnosisLinkTable
.values()));
}
}
| public void handleRequest(Database db, MolgenisRequest request) throws Exception
{
if (request.getString("__action").equals("upload"))
{
// get uploaded file and do checks
File file = request.getFile("uploadData");
if (file == null)
{
throw new Exception("No file selected.");
}
else if (!file.getName().endsWith(".xml"))
{
throw new Exception("File does not end with '.xml', other formats are not supported.");
}
// get uploaded file and do checks
File currentXsdfile = request.getFile("uploadSchema");
if (currentXsdfile == null)
{
throw new Exception("No file selected.");
}
else if (!currentXsdfile.getName().endsWith(".xsd"))
{
throw new Exception("File does not end with '.xml', other formats are not supported.");
}
// if no error, set file, and continue
this.setCurrentFile(file);
System.out.println("current file : " + this.getCurrentFile());
// Parsing a document with JAXP
CbmXmlParser cbmXmlParser = new CbmXmlParser();
CbmNode result = cbmXmlParser.load(currentFile, currentXsdfile);
Map<Integer, Participant_Collection_Summary> listOfParticipantSummary = new HashMap<Integer, Participant_Collection_Summary>();
Map<Integer, Collection_Protocol> listOfCollectionProtocol = new HashMap<Integer, Collection_Protocol>();
Map<String, Join_Participant_Collection_Summary_To_Race> listOfParticipantRaceLinkTable = new HashMap<String, Join_Participant_Collection_Summary_To_Race>();
Map<String, Join_Participant_Collection_Summary_Todiagnosis> listOfParticipantDiagnosisLinkTable = new HashMap<String, Join_Participant_Collection_Summary_Todiagnosis>();
Map<Integer, Institution> listOfInstitues = new HashMap<Integer, Institution>();
Map<Integer, Organization> listOfOrganizations = new HashMap<Integer, Organization>();
Map<String, Join_Collection_Protocol_To_Institution> listOfCollectionInstituteLinkTable = new HashMap<String, Join_Collection_Protocol_To_Institution>();
Map<Integer, Specimen_Availability_Summary_Profile> listOfCollectionConstrained = new HashMap<Integer, Specimen_Availability_Summary_Profile>();
Map<Integer, Annotation_Availability_Profile> listOfAnnotationProfile = new HashMap<Integer, Annotation_Availability_Profile>();
Map<Integer, Specimen_Collection_Contact> listOfContacts = new HashMap<Integer, Specimen_Collection_Contact>();
Map<Integer, Address> listOfAddress = new HashMap<Integer, Address>();
Map<Integer, Person> listOfPersons = new HashMap<Integer, Person>();
for (CollectionProtocol collectionProtocolFromJaxb : result.getProtocols().getCollectionProtocol())
{
if (!listOfCollectionProtocol.containsKey(collectionProtocolFromJaxb.getId()))
{
List<ParticipantCollectionSummary> participantCollectionSummaryList = collectionProtocolFromJaxb
.getEnrolls().getParticipantCollectionSummary();
for (ParticipantCollectionSummary participantSummary : participantCollectionSummaryList)
{
if (!listOfParticipantSummary.containsKey(participantSummary.getId()))
{
// Create molgenis object for it
Participant_Collection_Summary participantCollectionSummary = new Participant_Collection_Summary();
// Set participant count
participantCollectionSummary.setParticipant_Count(participantSummary.getParticipantCount());
participantCollectionSummary.setParticipant_Collection_Summary_ID(participantSummary
.getId());
// Ethnicity should go to Race table.
participantCollectionSummary.setEthnicity(participantSummary.getEthnicity());
// Set gender to participant
participantCollectionSummary.setGender(participantSummary.getGender());
// ############# Collect all the races from Jaxb
// Object
// and
// ###########
// ############# create Molgenis entities ##########
for (gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Race eachRace : participantSummary
.getIsClassifiedBy().getRace())
{
// Make linkTable for
// ParticipantCollectionSummary
// and
// Race, therefore should check the uniqueness
// of
// combination of both ids
StringBuilder uniqueLinktableKey = new StringBuilder();
uniqueLinktableKey.append(participantSummary.getId()).append(eachRace.getId());
if (!listOfParticipantRaceLinkTable.containsKey(uniqueLinktableKey.toString()
.toLowerCase().trim()))
{
org.molgenis.cbm.Race existingRace = db.find(
org.molgenis.cbm.Race.class,
new QueryRule(org.molgenis.cbm.Race.RACE_ID, Operator.EQUALS, eachRace
.getId())).get(0);
Join_Participant_Collection_Summary_To_Race linkTable = new Join_Participant_Collection_Summary_To_Race();
linkTable.setParticipant_Collection_Summary_ID(participantCollectionSummary);
linkTable.setRace_Id(existingRace);
listOfParticipantRaceLinkTable.put(uniqueLinktableKey.toString().toLowerCase()
.trim(), linkTable);
}
}
// Get the specimenCollection from the participant
// summary
List<Integer> listoFSpecimenID = new ArrayList<Integer>();
for (SpecimenCollectionSummary specimen : participantSummary.getProvides()
.getSpecimenCollectionSummary())
{
listoFSpecimenID.add(specimen.getId());
}
List<Specimen_Collection_Summary> collectionOfSpecimens = db.find(
Specimen_Collection_Summary.class, new QueryRule(
Specimen_Collection_Summary.SPECIMEN_COLLECTION_SUMMARY_ID, Operator.IN,
listoFSpecimenID));
participantCollectionSummary
.setIs_Collected_FromSpecimen_Collection_SummaryCollection(collectionOfSpecimens);
// Diagnosis
for (gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Diagnosis diagnosis : participantSummary
.getReceives().getDiagnosis())
{
StringBuilder uniqueIdentifer = new StringBuilder();
uniqueIdentifer.append(participantSummary.getId()).append(diagnosis.getId());
if (!listOfParticipantDiagnosisLinkTable.containsKey(uniqueIdentifer.toString().trim()
.toLowerCase()))
{
Join_Participant_Collection_Summary_Todiagnosis joinTableParticipantDiagnosis = new Join_Participant_Collection_Summary_Todiagnosis();
joinTableParticipantDiagnosis
.setParticipant_Collection_Summary_ID(participantCollectionSummary);
org.molgenis.cbm.Diagnosis diag = db.find(
org.molgenis.cbm.Diagnosis.class,
new QueryRule(org.molgenis.cbm.Diagnosis.DIAGNOSIS_ID, Operator.EQUALS,
diagnosis.getId())).get(0);
joinTableParticipantDiagnosis.setDiagnosis_Id(diag);
joinTableParticipantDiagnosis.setDiagnosis_Id_Diagnosis_ID(diag.getDiagnosis_ID());
joinTableParticipantDiagnosis
.setDiagnosis_Id_DiagnosisType(diag.getDiagnosisType());
listOfParticipantDiagnosisLinkTable.put(uniqueIdentifer.toString().trim()
.toLowerCase(), joinTableParticipantDiagnosis);
}
}
// Add this participantSummary to the list
// collection
listOfParticipantSummary.put(participantSummary.getId(), participantCollectionSummary);
}
}
// Collect information for collection_protocol
Collection_Protocol cp = new Collection_Protocol();
String collectionProtocolName = collectionProtocolFromJaxb.getName();
String collectionProtocolIdentifier = collectionProtocolFromJaxb.getIdentifier();
Integer collectionProtocolID = collectionProtocolFromJaxb.getId();
cp.setCollectionProtocolID(collectionProtocolID);
cp.setName(collectionProtocolName);
cp.setIdentifier(collectionProtocolIdentifier);
// TODO: The date format comes in XMLDateFormat, need to
// convert it
// cp.setDate_Last_Updated(collectionProtocolFromJaxb.getDateLastUpdated().toString());
//
// TODO: The date format comes in XMLDateFormat, need to
// convert it
// cp.setEnd_Date(collectionProtocolFromJaxb.getEndDate().toString());
// Collection information for institution and organization
for (gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Institution cbmInsititue : collectionProtocolFromJaxb
.getResidesAt().getInstitution())
{
Institution institue = null;
if (!listOfOrganizations.containsKey(cbmInsititue.getId()))
{
Organization organization = new Organization();
organization.setName(cbmInsititue.getName());
organization.setOrganization_ID(cbmInsititue.getId());
institue = new Institution();
institue.setInstitution_ID(organization.getOrganization_ID());
institue.setHomepage_URL(cbmInsititue.getHomepageURL());
if (!listOfInstitues.containsKey(cbmInsititue.getId()))
{
listOfInstitues.put(cbmInsititue.getId(), institue);
}
listOfOrganizations.put(cbmInsititue.getId(), organization);
}
else
{
institue = listOfInstitues.get(cbmInsititue.getId());
}
StringBuilder builder = new StringBuilder();
if (!listOfCollectionInstituteLinkTable.containsKey(builder.append(collectionProtocolID)
.append(cbmInsititue.getId()).toString()))
{
Join_Collection_Protocol_To_Institution joinTable = new Join_Collection_Protocol_To_Institution();
joinTable.setInstitution_ID(institue);
joinTable.setCollection_Protocol_ID(cp);
listOfCollectionInstituteLinkTable.put(
builder.append(collectionProtocolID).append(cbmInsititue.getId()).toString(),
joinTable);
}
}
// Set the isconstrained entity
if (collectionProtocolFromJaxb.getIsConstrainedBy() != null)
{
SpecimenAvailabilitySummaryProfile profileJaxb = collectionProtocolFromJaxb
.getIsConstrainedBy();
Specimen_Availability_Summary_Profile specimenProfile = null;
if (!listOfCollectionConstrained.containsKey(profileJaxb.getId()))
{
specimenProfile = new Specimen_Availability_Summary_Profile();
specimenProfile.setIs_Collaboration_Required(profileJaxb.isIsCollaborationRequired());
specimenProfile.setIs_Available_To_Outside_Institution(profileJaxb
.isIsAvailableToOutsideInstitution());
specimenProfile.setIs_Available_To_Foreign_Investigators(profileJaxb
.isIsAvailableToForeignInvestigators());
specimenProfile.setIs_Available_To_Commercial_Organizations(profileJaxb
.isIsAvailableToCommercialOrganizations());
specimenProfile.setSpecimen_Availability_Summary_Profile_ID(profileJaxb.getId());
listOfCollectionConstrained.put(profileJaxb.getId(), specimenProfile);
}
else
{
specimenProfile = listOfCollectionConstrained.get(profileJaxb.getId());
}
cp.setIs_Constrained_By(specimenProfile);
}
if (collectionProtocolFromJaxb.getMakesAvailable() != null)
{
AnnotationAvailabilityProfile annotationProfileJaxb = collectionProtocolFromJaxb
.getMakesAvailable();
Annotation_Availability_Profile profile = null;
if (!listOfAnnotationProfile.containsKey(annotationProfileJaxb.getId()))
{
profile = new Annotation_Availability_Profile();
profile.setHas_Additional_Patient_Demographics(annotationProfileJaxb
.isHasAdditionalPatientDemographics());
profile.setHas_Exposure_History(annotationProfileJaxb.isHasExposureHistory());
profile.setHas_Family_History(annotationProfileJaxb.isHasFamilyHistory());
profile.setHas_Histopathologic_Information(annotationProfileJaxb
.isHasHistopathologicInformation());
profile.setHas_Lab_Data(annotationProfileJaxb.isHasLabData());
profile.setHas_Longitudinal_Specimens(annotationProfileJaxb.isHasLongitudinalSpecimens());
profile.setHas_Matched_Specimens(annotationProfileJaxb.isHasMatchedSpecimens());
profile.setHas_Outcome_Information(annotationProfileJaxb.isHasOutcomeInformation());
profile.setHas_Participants_Available_For_Followup(annotationProfileJaxb
.isHasParticipantsAvailableForFollowup());
profile.setHas_Treatment_Information(annotationProfileJaxb.isHasTreatmentInformation());
profile.setAnnotation_Availability_Profile_ID(annotationProfileJaxb.getId());
listOfAnnotationProfile.put(annotationProfileJaxb.getId(), profile);
}
else
{
profile = listOfAnnotationProfile.get(annotationProfileJaxb.getId());
}
cp.setMakes_Available(profile);
}
// Collect information on Specimen_collection_contact and
// Person
// and Address
if (collectionProtocolFromJaxb.getIsAssignedTo() != null)
{
SpecimenCollectionContact collectionContactJaxb = collectionProtocolFromJaxb.getIsAssignedTo();
Specimen_Collection_Contact contact = null;
if (!listOfContacts.containsKey(collectionContactJaxb.getId()))
{
Person person = new Person();
person.setFirst_Name(collectionContactJaxb.getFirstName());
person.setLast_Name(collectionContactJaxb.getLastName());
person.setFull_Name(collectionContactJaxb.getFullName());
person.setEmail_Address(collectionContactJaxb.getEmailAddress());
person.setMiddle_Name_Or_Initial(collectionContactJaxb.getMiddleNameOrInitial());
person.setPerson_ID(collectionContactJaxb.getId());
listOfPersons.put(collectionContactJaxb.getId(), person);
contact = new Specimen_Collection_Contact();
contact.setSpecimen_Collection_Contact_ID(person.getPerson_ID());
contact.setPhone(collectionContactJaxb.getPhone());
gme.cacore_cacore._3_2.gov_nih_nci_cbm_domain.Address addressJaxb = collectionContactJaxb
.getIsLocatedAt();
if (addressJaxb != null)
{
if (listOfAddress.containsKey(addressJaxb.getId()))
{
contact.setAddress_Id(listOfAddress.get(addressJaxb.getId()));
}
else
{
Address address = new Address();
address.setAddress_ID(addressJaxb.getId());
address.setCity(addressJaxb.getCity());
address.setCountry(addressJaxb.getCountry());
address.setDepartment_Or_Division(addressJaxb.getDepartmentOrDivision());
address.setEntity_Name(addressJaxb.getEntityName());
address.setEntity_Number(addressJaxb.getEntityNumber());
address.setFloor_Or_Premises(addressJaxb.getFloorOrPremises());
address.setPost_Office_Box(addressJaxb.getPostOfficeBox());
address.setState(addressJaxb.getState());
address.setStreet_Or_Thoroughfare_Extension_Name(addressJaxb
.getStreetOrThoroughfareExtensionName());
address.setStreet_Or_Thoroughfare_Name_And_Type(addressJaxb
.getStreetOrThoroughfareNameAndType());
address.setStreet_Or_Thoroughfare_Number(addressJaxb
.getStreetOrThoroughfareNumber());
address.setStreet_Or_Thoroughfare_Section_Name(addressJaxb
.getStreetOrThoroughfareSectionName());
address.setStreet_Post_Directional(addressJaxb.getStreetPostDirectional());
address.setStreet_Pre_Directional(addressJaxb.getStreetPreDirectional());
address.setZip_Code(addressJaxb.getZipCode());
listOfAddress.put(addressJaxb.getId(), address);
}
}
listOfContacts.put(collectionContactJaxb.getId(), contact);
}
else
{
contact = listOfContacts.get(collectionContactJaxb.getId());
}
cp.setIs_Assigned_To(contact);
}
listOfCollectionProtocol.put(collectionProtocolFromJaxb.getId(), cp);
}
}
db.add(new ArrayList<Person>(listOfPersons.values()));
db.add(new ArrayList<Address>(listOfAddress.values()));
db.add(new ArrayList<Specimen_Collection_Contact>(listOfContacts.values()));
db.add(new ArrayList<Annotation_Availability_Profile>(listOfAnnotationProfile.values()));
db.add(new ArrayList<Specimen_Availability_Summary_Profile>(listOfCollectionConstrained.values()));
db.add(new ArrayList<Organization>(listOfOrganizations.values()));
db.add(new ArrayList<Institution>(listOfInstitues.values()));
db.add(new ArrayList<Participant_Collection_Summary>(listOfParticipantSummary.values()));
db.add(new ArrayList<Collection_Protocol>(listOfCollectionProtocol.values()));
db.add(new ArrayList<Join_Participant_Collection_Summary_To_Race>(listOfParticipantRaceLinkTable.values()));
db.add(new ArrayList<Join_Participant_Collection_Summary_Todiagnosis>(listOfParticipantDiagnosisLinkTable
.values()));
}
}
|
diff --git a/Main.java b/Main.java
index f898b78..c4d8d2b 100644
--- a/Main.java
+++ b/Main.java
@@ -1,176 +1,173 @@
package abdjekt;
import static java.lang.System.*;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Main {
public static String verb;
public static String subject;
public static String withCheck;
public static int withIndex;
public static String object;
public static World world;
public static ArrayList<Item> spawned;
public static void main(String[] args) {
Scanner keyboard = new Scanner(in);
spawned = new ArrayList<Item>();
spawned.add(new Item("foo"));
world = new World(25);
out.println("Welcome to Abdjekt!");
out.println("To spawn an object, use: spawn <noun>. To remove them, use: remove <noun>");
out.println("To look at what you have spawned, type: look.");
out.println("To remove everything that is spawned, type: clean.");
out.println("The syntax for commands is <verb> <noun> with <noun>.");
out.println("To quit the game, simply type 'quit'.");
out.println("There are two gamemodes: sandbox and hardcore.");
out.println("In sandbox you can spawn and do whatever you want, within the bounds of the current content.");
out.println("In hardcore, there are limits to what you can spawn, you have to obtain them from the environment, and crafting.");
out.println("To change the gamemode, type 'mode 1' (sandbox) or 'mode 2' (hardcore). The game starts on hardcore.");
out.println("This game is NOT case-sensative.");
out.println("Please send us suggestions at [email protected]!");
out.println("NOTE: This programme requires an internet connetion!");
out.println();
//TODO Remove more welcome!
if (Double.parseDouble(Game.getClientVersion()) < Double.parseDouble(Game.getCurrentVersion())) {
out.println("IMPORTANT: YOU'RE CLIENT IS OUT OF DATE!\nDOWNLOAD THE NEWEST VERSION AT http://kicneoj.webs.com/abdjekt/download.html");
out.println();
}
Game.printNews();
out.println();
while (true) {
out.print("> ");
String inputLine = keyboard.nextLine();
Scanner inputsplit = new Scanner(inputLine);
String inputArray[] = new String[6];
for (int i = 0; i < inputArray.length; i++) {
try {
inputArray[i] = inputsplit.next().toLowerCase();
} catch (NoSuchElementException eo) {
}
}
verb = inputArray[0];
int withCounter = 0;
withIndex = -1;
for (int i = 2; i <= inputArray.length - 1; i++) {
if (inputArray[i] != null && inputArray[i].equals("with")) {
withCheck = inputArray[i];
withCounter++;
withIndex = i;
}
}
if (withIndex == -1) {
subject = inputArray[1];
- if (inputArray[2] != null) {
+ if (inputArray[2] != null && !inputArray[2].equals("")) {
subject += " " + inputArray[2];
}
} else {
- for (int i = 1; i < withIndex; i++) {
- if (i == 1) {
- subject = inputArray[i];
- } else {
- if (i > 1 && i < withIndex - 1) {
- subject += " " + inputArray[i];
- }
+ if (withIndex >= 2) {
+ subject = inputArray[1];
+ if (withIndex == 3) {
+ subject += " " + inputArray[2];
}
}
}
if (withIndex == -1) {
object = "";
} else {
object = inputArray[withIndex + 1];
if (inputArray[withIndex + 2] != null) {
object += " " + inputArray[withIndex + 2];
}
}
if (withCounter >= 2) {
out.println("Invalid syntax.");
continue;
}
if (verb == null) {
System.out.println("Do what?");
continue;
}
if (verb.equals("quit")) {
// System.out.println(""); //TODO add quit text
Game.quit();
continue;
}
if (verb.equals("clean")) {
world.clear();
System.out.println("Everything around you disappears in a flash of light.");
continue;
}
if (subject == null && !verb.equals("look")) {
System.out.println(verb + " what?");
continue;
}
if (!verb.equals("spawn") && !verb.equals("remove") && !verb.equals("look") && !verb.equals("mode") && !verb.equals("make")) {
if (withCheck == null) {
System.out.println("Invalid syntax.");
continue;
}
}
if (!verb.equals("spawn") && !verb.equals("remove") && !verb.equals("look") && !verb.equals("mode") && !verb.equals("make")) {
if (object == null) {
System.out.println(verb + " " + subject + " with what?");
continue;
}
}
if (verb.equals("look")) {
if (world.show() != null && !world.show().equals("")) {
out.println("Around you, you can see " + world.show() + ".");
} else {
out.println("There are no objects around you.");
}
continue;
}
if (!verb.equals("spawn") && !verb.equals("remove") && !verb.equals("look") && !verb.equals("mode") && !verb.equals("mode") && !verb.equals("make")) {
if (!withCheck.equals("with")) {
out.println("Invalid syntax.");
continue;
}
}
if (verb.equals("mode")) {
if (subject.equals("1")) {
if (Game.getMode() != 1) {
Game.setFree();
System.out.println("Mode changed to 'Sandbox'.");
} else {
System.out.println("Mode is already set to Sandbox.");
}
} else if (subject.equals("2")) {
if (Game.getMode() != 2) {
Game.setNonFree();
System.out.println("Mode changed to 'Hardcore'.");
} else {
System.out.println("Mode is already set to Hardcore.");
}
} else {
System.out.println("Unknown mode setting.");
}
continue;
}
if (object.equals("")) {
object = "foo";
}
- if(!Item.exists(subject) || subject.equalsIgnoreCase("foo")){
+ if (!Item.exists(subject) || subject.equalsIgnoreCase("foo")) {
System.out.println("What is a " + subject + "?");
continue;
}
abdjektReader.process(Game.newItem(subject), Game.newItem(object), verb);
}
}
}
| false | true | public static void main(String[] args) {
Scanner keyboard = new Scanner(in);
spawned = new ArrayList<Item>();
spawned.add(new Item("foo"));
world = new World(25);
out.println("Welcome to Abdjekt!");
out.println("To spawn an object, use: spawn <noun>. To remove them, use: remove <noun>");
out.println("To look at what you have spawned, type: look.");
out.println("To remove everything that is spawned, type: clean.");
out.println("The syntax for commands is <verb> <noun> with <noun>.");
out.println("To quit the game, simply type 'quit'.");
out.println("There are two gamemodes: sandbox and hardcore.");
out.println("In sandbox you can spawn and do whatever you want, within the bounds of the current content.");
out.println("In hardcore, there are limits to what you can spawn, you have to obtain them from the environment, and crafting.");
out.println("To change the gamemode, type 'mode 1' (sandbox) or 'mode 2' (hardcore). The game starts on hardcore.");
out.println("This game is NOT case-sensative.");
out.println("Please send us suggestions at [email protected]!");
out.println("NOTE: This programme requires an internet connetion!");
out.println();
//TODO Remove more welcome!
if (Double.parseDouble(Game.getClientVersion()) < Double.parseDouble(Game.getCurrentVersion())) {
out.println("IMPORTANT: YOU'RE CLIENT IS OUT OF DATE!\nDOWNLOAD THE NEWEST VERSION AT http://kicneoj.webs.com/abdjekt/download.html");
out.println();
}
Game.printNews();
out.println();
while (true) {
out.print("> ");
String inputLine = keyboard.nextLine();
Scanner inputsplit = new Scanner(inputLine);
String inputArray[] = new String[6];
for (int i = 0; i < inputArray.length; i++) {
try {
inputArray[i] = inputsplit.next().toLowerCase();
} catch (NoSuchElementException eo) {
}
}
verb = inputArray[0];
int withCounter = 0;
withIndex = -1;
for (int i = 2; i <= inputArray.length - 1; i++) {
if (inputArray[i] != null && inputArray[i].equals("with")) {
withCheck = inputArray[i];
withCounter++;
withIndex = i;
}
}
if (withIndex == -1) {
subject = inputArray[1];
if (inputArray[2] != null) {
subject += " " + inputArray[2];
}
} else {
for (int i = 1; i < withIndex; i++) {
if (i == 1) {
subject = inputArray[i];
} else {
if (i > 1 && i < withIndex - 1) {
subject += " " + inputArray[i];
}
}
}
}
if (withIndex == -1) {
object = "";
} else {
object = inputArray[withIndex + 1];
if (inputArray[withIndex + 2] != null) {
object += " " + inputArray[withIndex + 2];
}
}
if (withCounter >= 2) {
out.println("Invalid syntax.");
continue;
}
if (verb == null) {
System.out.println("Do what?");
continue;
}
if (verb.equals("quit")) {
// System.out.println(""); //TODO add quit text
Game.quit();
continue;
}
if (verb.equals("clean")) {
world.clear();
System.out.println("Everything around you disappears in a flash of light.");
continue;
}
if (subject == null && !verb.equals("look")) {
System.out.println(verb + " what?");
continue;
}
if (!verb.equals("spawn") && !verb.equals("remove") && !verb.equals("look") && !verb.equals("mode") && !verb.equals("make")) {
if (withCheck == null) {
System.out.println("Invalid syntax.");
continue;
}
}
if (!verb.equals("spawn") && !verb.equals("remove") && !verb.equals("look") && !verb.equals("mode") && !verb.equals("make")) {
if (object == null) {
System.out.println(verb + " " + subject + " with what?");
continue;
}
}
if (verb.equals("look")) {
if (world.show() != null && !world.show().equals("")) {
out.println("Around you, you can see " + world.show() + ".");
} else {
out.println("There are no objects around you.");
}
continue;
}
if (!verb.equals("spawn") && !verb.equals("remove") && !verb.equals("look") && !verb.equals("mode") && !verb.equals("mode") && !verb.equals("make")) {
if (!withCheck.equals("with")) {
out.println("Invalid syntax.");
continue;
}
}
if (verb.equals("mode")) {
if (subject.equals("1")) {
if (Game.getMode() != 1) {
Game.setFree();
System.out.println("Mode changed to 'Sandbox'.");
} else {
System.out.println("Mode is already set to Sandbox.");
}
} else if (subject.equals("2")) {
if (Game.getMode() != 2) {
Game.setNonFree();
System.out.println("Mode changed to 'Hardcore'.");
} else {
System.out.println("Mode is already set to Hardcore.");
}
} else {
System.out.println("Unknown mode setting.");
}
continue;
}
if (object.equals("")) {
object = "foo";
}
if(!Item.exists(subject) || subject.equalsIgnoreCase("foo")){
System.out.println("What is a " + subject + "?");
continue;
}
abdjektReader.process(Game.newItem(subject), Game.newItem(object), verb);
}
}
| public static void main(String[] args) {
Scanner keyboard = new Scanner(in);
spawned = new ArrayList<Item>();
spawned.add(new Item("foo"));
world = new World(25);
out.println("Welcome to Abdjekt!");
out.println("To spawn an object, use: spawn <noun>. To remove them, use: remove <noun>");
out.println("To look at what you have spawned, type: look.");
out.println("To remove everything that is spawned, type: clean.");
out.println("The syntax for commands is <verb> <noun> with <noun>.");
out.println("To quit the game, simply type 'quit'.");
out.println("There are two gamemodes: sandbox and hardcore.");
out.println("In sandbox you can spawn and do whatever you want, within the bounds of the current content.");
out.println("In hardcore, there are limits to what you can spawn, you have to obtain them from the environment, and crafting.");
out.println("To change the gamemode, type 'mode 1' (sandbox) or 'mode 2' (hardcore). The game starts on hardcore.");
out.println("This game is NOT case-sensative.");
out.println("Please send us suggestions at [email protected]!");
out.println("NOTE: This programme requires an internet connetion!");
out.println();
//TODO Remove more welcome!
if (Double.parseDouble(Game.getClientVersion()) < Double.parseDouble(Game.getCurrentVersion())) {
out.println("IMPORTANT: YOU'RE CLIENT IS OUT OF DATE!\nDOWNLOAD THE NEWEST VERSION AT http://kicneoj.webs.com/abdjekt/download.html");
out.println();
}
Game.printNews();
out.println();
while (true) {
out.print("> ");
String inputLine = keyboard.nextLine();
Scanner inputsplit = new Scanner(inputLine);
String inputArray[] = new String[6];
for (int i = 0; i < inputArray.length; i++) {
try {
inputArray[i] = inputsplit.next().toLowerCase();
} catch (NoSuchElementException eo) {
}
}
verb = inputArray[0];
int withCounter = 0;
withIndex = -1;
for (int i = 2; i <= inputArray.length - 1; i++) {
if (inputArray[i] != null && inputArray[i].equals("with")) {
withCheck = inputArray[i];
withCounter++;
withIndex = i;
}
}
if (withIndex == -1) {
subject = inputArray[1];
if (inputArray[2] != null && !inputArray[2].equals("")) {
subject += " " + inputArray[2];
}
} else {
if (withIndex >= 2) {
subject = inputArray[1];
if (withIndex == 3) {
subject += " " + inputArray[2];
}
}
}
if (withIndex == -1) {
object = "";
} else {
object = inputArray[withIndex + 1];
if (inputArray[withIndex + 2] != null) {
object += " " + inputArray[withIndex + 2];
}
}
if (withCounter >= 2) {
out.println("Invalid syntax.");
continue;
}
if (verb == null) {
System.out.println("Do what?");
continue;
}
if (verb.equals("quit")) {
// System.out.println(""); //TODO add quit text
Game.quit();
continue;
}
if (verb.equals("clean")) {
world.clear();
System.out.println("Everything around you disappears in a flash of light.");
continue;
}
if (subject == null && !verb.equals("look")) {
System.out.println(verb + " what?");
continue;
}
if (!verb.equals("spawn") && !verb.equals("remove") && !verb.equals("look") && !verb.equals("mode") && !verb.equals("make")) {
if (withCheck == null) {
System.out.println("Invalid syntax.");
continue;
}
}
if (!verb.equals("spawn") && !verb.equals("remove") && !verb.equals("look") && !verb.equals("mode") && !verb.equals("make")) {
if (object == null) {
System.out.println(verb + " " + subject + " with what?");
continue;
}
}
if (verb.equals("look")) {
if (world.show() != null && !world.show().equals("")) {
out.println("Around you, you can see " + world.show() + ".");
} else {
out.println("There are no objects around you.");
}
continue;
}
if (!verb.equals("spawn") && !verb.equals("remove") && !verb.equals("look") && !verb.equals("mode") && !verb.equals("mode") && !verb.equals("make")) {
if (!withCheck.equals("with")) {
out.println("Invalid syntax.");
continue;
}
}
if (verb.equals("mode")) {
if (subject.equals("1")) {
if (Game.getMode() != 1) {
Game.setFree();
System.out.println("Mode changed to 'Sandbox'.");
} else {
System.out.println("Mode is already set to Sandbox.");
}
} else if (subject.equals("2")) {
if (Game.getMode() != 2) {
Game.setNonFree();
System.out.println("Mode changed to 'Hardcore'.");
} else {
System.out.println("Mode is already set to Hardcore.");
}
} else {
System.out.println("Unknown mode setting.");
}
continue;
}
if (object.equals("")) {
object = "foo";
}
if (!Item.exists(subject) || subject.equalsIgnoreCase("foo")) {
System.out.println("What is a " + subject + "?");
continue;
}
abdjektReader.process(Game.newItem(subject), Game.newItem(object), verb);
}
}
|
diff --git a/src/org/inceptus/Mecanum.java b/src/org/inceptus/Mecanum.java
index 5d4f307..35cf444 100644
--- a/src/org/inceptus/Mecanum.java
+++ b/src/org/inceptus/Mecanum.java
@@ -1,60 +1,60 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
//Standard for inceptus code
package org.inceptus;
//Imports
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Watchdog;
import edu.wpi.first.wpilibj.DriverStationLCD;
//Mecanum class. We are using IterativeRobot as SimpleRobot was not working.
public class Mecanum extends IterativeRobot {
//Get the joysticks (keep joy* naming system so it can be adjusted later)
Joystick joy1 = new Joystick(1);
Joystick joy2 = new Joystick(2);
Joystick joy3 = new Joystick(3);
//Get the jaguars
Jaguar front_right = new Jaguar(2);
Jaguar front_left = new Jaguar(1);
Jaguar rear_right = new Jaguar(3);
Jaguar rear_left = new Jaguar(4);
//When robot starts
public void robotInit() {
}
//When robot is disabled
- public void disabled() {
+ public void disabledInit() {
//Log disabled status
DriverStationLCD.getInstance().println(DriverStationLCD.Line.kUser2, 1, "Disabled");
}
//Periodically called during autonomous
public void autonomousPeriodic() {
}
//Called at the start of teleop
public void teleopInit() {
//Log initiation success
DriverStationLCD.getInstance().println(DriverStationLCD.Line.kUser2, 1, "Teleop Initiated");
}
//Periodically called during teleop
public void teleopPeriodic() {
}
}
| true | true | public void disabled() {
//Log disabled status
DriverStationLCD.getInstance().println(DriverStationLCD.Line.kUser2, 1, "Disabled");
}
| public void disabledInit() {
//Log disabled status
DriverStationLCD.getInstance().println(DriverStationLCD.Line.kUser2, 1, "Disabled");
}
|
diff --git a/core/src/test/java/hudson/model/RunTest.java b/core/src/test/java/hudson/model/RunTest.java
index b03d8aae1..cba30858e 100644
--- a/core/src/test/java/hudson/model/RunTest.java
+++ b/core/src/test/java/hudson/model/RunTest.java
@@ -1,68 +1,68 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Jorg Heymans
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import junit.framework.TestCase;
import java.util.GregorianCalendar;
import java.util.List;
/**
* @author Kohsuke Kawaguchi
*/
public class RunTest extends TestCase {
private List<Run<?,?>.Artifact> createArtifactList(String... paths) {
Run<?,?> r = new Run(null,new GregorianCalendar()) {
- public int compareTo(Object arg0) {
+ public int compareTo(Run arg0) {
return 0;
}
};
Run<?,?>.ArtifactList list = r.new ArtifactList();
for (String p : paths) {
- list.add(r.new Artifact(p,p)); // Assuming all test inputs don't need urlencoding
+ list.add(r.new Artifact(p,p,p,"n"+list.size())); // Assuming all test inputs don't need urlencoding
}
list.computeDisplayName();
- return list;
+ return (List)list;
}
public void testArtifactListDisambiguation1() {
List<Run<?, ?>.Artifact> a = createArtifactList("a/b/c.xml", "d/f/g.xml", "h/i/j.xml");
assertEquals(a.get(0).getDisplayPath(),"c.xml");
assertEquals(a.get(1).getDisplayPath(),"g.xml");
assertEquals(a.get(2).getDisplayPath(),"j.xml");
}
public void testArtifactListDisambiguation2() {
List<Run<?, ?>.Artifact> a = createArtifactList("a/b/c.xml", "d/f/g.xml", "h/i/g.xml");
assertEquals(a.get(0).getDisplayPath(),"c.xml");
assertEquals(a.get(1).getDisplayPath(),"f/g.xml");
assertEquals(a.get(2).getDisplayPath(),"i/g.xml");
}
public void testArtifactListDisambiguation3() {
List<Run<?, ?>.Artifact> a = createArtifactList("a.xml","a/a.xml");
assertEquals(a.get(0).getDisplayPath(),"a.xml");
assertEquals(a.get(1).getDisplayPath(),"a/a.xml");
}
}
| false | true | private List<Run<?,?>.Artifact> createArtifactList(String... paths) {
Run<?,?> r = new Run(null,new GregorianCalendar()) {
public int compareTo(Object arg0) {
return 0;
}
};
Run<?,?>.ArtifactList list = r.new ArtifactList();
for (String p : paths) {
list.add(r.new Artifact(p,p)); // Assuming all test inputs don't need urlencoding
}
list.computeDisplayName();
return list;
}
| private List<Run<?,?>.Artifact> createArtifactList(String... paths) {
Run<?,?> r = new Run(null,new GregorianCalendar()) {
public int compareTo(Run arg0) {
return 0;
}
};
Run<?,?>.ArtifactList list = r.new ArtifactList();
for (String p : paths) {
list.add(r.new Artifact(p,p,p,"n"+list.size())); // Assuming all test inputs don't need urlencoding
}
list.computeDisplayName();
return (List)list;
}
|
diff --git a/src/java-common/org/xins/common/types/PatternType.java b/src/java-common/org/xins/common/types/PatternType.java
index 4ea63f3ea..71d598343 100644
--- a/src/java-common/org/xins/common/types/PatternType.java
+++ b/src/java-common/org/xins/common/types/PatternType.java
@@ -1,170 +1,169 @@
/*
* $Id$
*
* Copyright 2003-2005 Wanadoo Nederland B.V.
* See the COPYRIGHT file for redistribution and use restrictions.
*/
package org.xins.common.types;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.xins.common.Log;
import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.Utils;
import org.xins.logdoc.ExceptionUtils;
/**
* Abstract base class for pattern types. A pattern type only accepts values
* that match a certain regular expression.
*
* @version $Revision$ $Date$
* @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>)
*
* @since XINS 1.0.0
*/
public abstract class PatternType extends Type {
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* The fully-qualified name of this class.
*/
private static final String CLASSNAME = PatternType.class.getName();
/**
* Perl 5 pattern compiler.
*/
private static final Perl5Compiler PATTERN_COMPILER = new Perl5Compiler();
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
// Constructors
//-------------------------------------------------------------------------
/**
* Creates a new <code>PatternType</code> instance. The name of the type
* needs to be specified. The value class (see
* {@link Type#getValueClass()}) is set to {@link String String.class}.
*
* @param name
* the name of the type, not <code>null</code>.
*
* @param pattern
* the regular expression the values must match, not <code>null</code>.
*
* @throws IllegalArgumentException
* if <code>name == null || pattern == null</code>.
*
* @throws PatternCompileException
* if the specified pattern is considered invalid.
*/
protected PatternType(String name, String pattern)
throws IllegalArgumentException, PatternCompileException {
super(name, String.class);
if (pattern == null) {
throw new IllegalArgumentException("pattern == null");
}
// Compile the regular expression to a Pattern object
try {
synchronized (PATTERN_COMPILER) {
_pattern = PATTERN_COMPILER.compile(pattern,
Perl5Compiler.READ_ONLY_MASK);
}
// Handle pattern compilation error
} catch (MalformedPatternException mpe) {
PatternCompileException e = new PatternCompileException(pattern);
ExceptionUtils.setCause(e, mpe);
throw e;
}
// Store the original pattern string
_patternString = pattern;
}
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
/**
* Pattern string. This is the uncompiled version of {@link #_pattern}.
* This field cannot be <code>null</code>.
*/
private final String _patternString;
/**
* Compiled pattern. This is the compiled version of
* {@link #_patternString}. This field cannot be <code>null</code>.
*/
private final Pattern _pattern;
//-------------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------------
protected final boolean isValidValueImpl(String value) {
// Determine if the value matches the pattern
try {
Perl5Matcher patternMatcher = new Perl5Matcher();
return patternMatcher.matches(value, _pattern);
// If the call causes an exception, then log that exception and assume
// the value does not match the pattern
} catch (Throwable exception) {
String thisMethod = "isValidValueImpl(java.lang.String)";
String subjectClass = "org.apache.oro.text.regex.Perl5Matcher";
String subjectMethod = "matches(java.lang.String,"
+ _pattern.getClass().getName()
+ ')';
String detail = "Assuming the value \""
+ value
+ "\" is invalid for the pattern \""
+ _patternString
+ "\".";
- Utils.logProgrammingError(exception,
- CLASSNAME, thisMethod,
+ Utils.logProgrammingError(CLASSNAME, thisMethod,
subjectClass, subjectMethod,
- detail);
+ detail, exception);
return false;
}
}
protected final Object fromStringImpl(String value) {
return value;
}
public final String toString(Object value)
throws IllegalArgumentException, ClassCastException, TypeValueException {
MandatoryArgumentChecker.check("value", value);
String s = (String) value;
if (!isValidValueImpl(s)) {
throw new TypeValueException(this, s);
}
return s;
}
/**
* Returns the pattern.
*
* @return
* the pattern, not <code>null</code>.
*/
public String getPattern() {
return _patternString;
}
}
| false | true | protected final boolean isValidValueImpl(String value) {
// Determine if the value matches the pattern
try {
Perl5Matcher patternMatcher = new Perl5Matcher();
return patternMatcher.matches(value, _pattern);
// If the call causes an exception, then log that exception and assume
// the value does not match the pattern
} catch (Throwable exception) {
String thisMethod = "isValidValueImpl(java.lang.String)";
String subjectClass = "org.apache.oro.text.regex.Perl5Matcher";
String subjectMethod = "matches(java.lang.String,"
+ _pattern.getClass().getName()
+ ')';
String detail = "Assuming the value \""
+ value
+ "\" is invalid for the pattern \""
+ _patternString
+ "\".";
Utils.logProgrammingError(exception,
CLASSNAME, thisMethod,
subjectClass, subjectMethod,
detail);
return false;
}
}
| protected final boolean isValidValueImpl(String value) {
// Determine if the value matches the pattern
try {
Perl5Matcher patternMatcher = new Perl5Matcher();
return patternMatcher.matches(value, _pattern);
// If the call causes an exception, then log that exception and assume
// the value does not match the pattern
} catch (Throwable exception) {
String thisMethod = "isValidValueImpl(java.lang.String)";
String subjectClass = "org.apache.oro.text.regex.Perl5Matcher";
String subjectMethod = "matches(java.lang.String,"
+ _pattern.getClass().getName()
+ ')';
String detail = "Assuming the value \""
+ value
+ "\" is invalid for the pattern \""
+ _patternString
+ "\".";
Utils.logProgrammingError(CLASSNAME, thisMethod,
subjectClass, subjectMethod,
detail, exception);
return false;
}
}
|
diff --git a/src/org/ukiuni/irc4j/server/command/FileRecieveThread.java b/src/org/ukiuni/irc4j/server/command/FileRecieveThread.java
index e9c31be..e07591b 100644
--- a/src/org/ukiuni/irc4j/server/command/FileRecieveThread.java
+++ b/src/org/ukiuni/irc4j/server/command/FileRecieveThread.java
@@ -1,63 +1,63 @@
package org.ukiuni.irc4j.server.command;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.ukiuni.irc4j.Conf;
import org.ukiuni.irc4j.Log;
import org.ukiuni.irc4j.server.ClientConnection;
import org.ukiuni.irc4j.server.IRCServer;
import org.ukiuni.irc4j.server.ServerChannel;
import org.ukiuni.irc4j.storage.Storage;
import org.ukiuni.irc4j.storage.Storage.WriteHandle;
import org.ukiuni.lighthttpserver.util.FileUtil;
public class FileRecieveThread extends Thread {
private IRCServer ircServer;
private ClientConnection selfClientConnection;
private String parameterString;
public FileRecieveThread(IRCServer ircServer, ClientConnection selfClientConnection, String parameterString) {
this.ircServer = ircServer;
this.selfClientConnection = selfClientConnection;
this.parameterString = parameterString;
}
public void run() {
try {
final String[] param = parameterString.split(" ");
- Log.log("/////////////////// socket = " + param[4] + ":" + Integer.valueOf(param[5]));
- Socket socket = new Socket("localhost", Integer.valueOf(param[5]));
+ Log.log("/////////////////// socket = " + selfClientConnection.getUser().getHostName() + ":" + Integer.valueOf(param[5]));
+ Socket socket = new Socket(selfClientConnection.getUser().getHostName(), Integer.valueOf(param[5]));
long fileSize = Long.valueOf(Integer.valueOf(param[6]));
InputStream in = socket.getInputStream();
byte[] buffer = new byte[1024];
long totalReaded = 0;
int readed = in.read(buffer);
WriteHandle writeHandle = Storage.getInstance().createWriteHandle(param[3], FileUtil.getMimeType(param[6]));
OutputStream out = writeHandle.getOutputStream();
while (totalReaded < fileSize && readed > 0) {
out.write(buffer, 0, readed);
totalReaded += readed;
if (totalReaded + buffer.length > fileSize) {
buffer = new byte[(int) (fileSize - totalReaded)];
}
readed = in.read(buffer);
}
socket.close();
out.close();
writeHandle.save();
Log.log("/////////////////// upload complete");
ServerChannel channel = selfClientConnection.getCurrentFileUploadChannel();
selfClientConnection.setCurrentFileUploadChannel(null);
String responseMessage = "file upload to " + Conf.getHttpServerURL() + "/file/" + writeHandle.getKey();
channel.sendMessage("PRIVMSG", selfClientConnection, responseMessage);
selfClientConnection.sendMessage("PRIVMSG", selfClientConnection, channel, responseMessage);
selfClientConnection.sendPartCommand(ircServer.getFQSN(), channel.getName(), "upload is completed.");// TODO
} catch (Throwable e) {
Log.log(e);
}
};
}
| true | true | public void run() {
try {
final String[] param = parameterString.split(" ");
Log.log("/////////////////// socket = " + param[4] + ":" + Integer.valueOf(param[5]));
Socket socket = new Socket("localhost", Integer.valueOf(param[5]));
long fileSize = Long.valueOf(Integer.valueOf(param[6]));
InputStream in = socket.getInputStream();
byte[] buffer = new byte[1024];
long totalReaded = 0;
int readed = in.read(buffer);
WriteHandle writeHandle = Storage.getInstance().createWriteHandle(param[3], FileUtil.getMimeType(param[6]));
OutputStream out = writeHandle.getOutputStream();
while (totalReaded < fileSize && readed > 0) {
out.write(buffer, 0, readed);
totalReaded += readed;
if (totalReaded + buffer.length > fileSize) {
buffer = new byte[(int) (fileSize - totalReaded)];
}
readed = in.read(buffer);
}
socket.close();
out.close();
writeHandle.save();
Log.log("/////////////////// upload complete");
ServerChannel channel = selfClientConnection.getCurrentFileUploadChannel();
selfClientConnection.setCurrentFileUploadChannel(null);
String responseMessage = "file upload to " + Conf.getHttpServerURL() + "/file/" + writeHandle.getKey();
channel.sendMessage("PRIVMSG", selfClientConnection, responseMessage);
selfClientConnection.sendMessage("PRIVMSG", selfClientConnection, channel, responseMessage);
selfClientConnection.sendPartCommand(ircServer.getFQSN(), channel.getName(), "upload is completed.");// TODO
} catch (Throwable e) {
Log.log(e);
}
};
| public void run() {
try {
final String[] param = parameterString.split(" ");
Log.log("/////////////////// socket = " + selfClientConnection.getUser().getHostName() + ":" + Integer.valueOf(param[5]));
Socket socket = new Socket(selfClientConnection.getUser().getHostName(), Integer.valueOf(param[5]));
long fileSize = Long.valueOf(Integer.valueOf(param[6]));
InputStream in = socket.getInputStream();
byte[] buffer = new byte[1024];
long totalReaded = 0;
int readed = in.read(buffer);
WriteHandle writeHandle = Storage.getInstance().createWriteHandle(param[3], FileUtil.getMimeType(param[6]));
OutputStream out = writeHandle.getOutputStream();
while (totalReaded < fileSize && readed > 0) {
out.write(buffer, 0, readed);
totalReaded += readed;
if (totalReaded + buffer.length > fileSize) {
buffer = new byte[(int) (fileSize - totalReaded)];
}
readed = in.read(buffer);
}
socket.close();
out.close();
writeHandle.save();
Log.log("/////////////////// upload complete");
ServerChannel channel = selfClientConnection.getCurrentFileUploadChannel();
selfClientConnection.setCurrentFileUploadChannel(null);
String responseMessage = "file upload to " + Conf.getHttpServerURL() + "/file/" + writeHandle.getKey();
channel.sendMessage("PRIVMSG", selfClientConnection, responseMessage);
selfClientConnection.sendMessage("PRIVMSG", selfClientConnection, channel, responseMessage);
selfClientConnection.sendPartCommand(ircServer.getFQSN(), channel.getName(), "upload is completed.");// TODO
} catch (Throwable e) {
Log.log(e);
}
};
|
diff --git a/src/LPSolve/IntegerLP.java b/src/LPSolve/IntegerLP.java
index d4a45d7..7211a00 100644
--- a/src/LPSolve/IntegerLP.java
+++ b/src/LPSolve/IntegerLP.java
@@ -1,169 +1,166 @@
/**
* Models the problem as a linear program and solves using lp_solve's ILP.
*/
package LPSolve;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import lpsolve.LpSolve;
import lpsolve.LpSolveException;
import Items.Slot;
import Items.Tutor;
import Weighting.Weighting;
public class IntegerLP {
private static Tutor[] t;
private static Slot[] s;
private static Weighting w;
private static int n; // number of variables = t.length * s.length
// some structures for dealing with simultaneous slot constraints
private static ArrayList<String> uniqueTimes;
private static HashMap<String, ArrayList<Integer>> times;
private static final double MAX_ASSIGNMENTS_PER_TUTOR = 2.0;
public static void match(Tutor[] tutors, Slot[] slots, Weighting waiter) {
t = tutors;
s = slots;
w = waiter;
n = t.length * s.length;
try {
// create the LP solver: 0 constraints (for now),
// the variables are bindings between tutors and slots
LpSolve solver = LpSolve.makeLp(0, n);
// make lp_solve shut up about things that aren't important
solver.setVerbose(3);
// set all variables to binary
for (int i = 1; i < n + 1; ++i) {
solver.setBinary(i, true);
}
// OBJECTIVE FUNCTION (weight of each assignment)
solver.setObjFn(getObjective());
solver.setMaxim(); // sets the obj function to maximize
// CONSTRAINTS
// for each slot, assign exactly one (TODO modify for at least one)
for (int j = 0; j < s.length; ++j) {
solver.addConstraint(getConstraintSlotAtLeastOne(j),
LpSolve.GE, 1.0);
}
- // for each tutor, cannot assign more than twice, but at least once
+ // for each tutor, assign 'numAssignments' slots
for (int i = 0; i < t.length; ++i) {
- solver.addConstraint(getConstraintTutorN(i), LpSolve.LE,
+ solver.addConstraint(getConstraintTutorN(i), LpSolve.EQ,
t[i].numAssignments);
- solver.addConstraint(getConstraintTutorN(i), LpSolve.GE,
- t[i].numAssignments); // TODO replace with
- // assignments/per
}
// for each tutor, cannot to assign to two slots that share time
calculateSimultaneousSlots();
for (int i = 0; i < t.length; ++i) {
for (String time : uniqueTimes) {
solver.addConstraint(
getConstraintTutorNoSimultaneous(i, time),
LpSolve.LE, 1.0);
}
}
// ilp solution
solver.solve();
// System.out.println("the linear program");
// solver.printLp();
// use solution to set the assignments of each tutor
setMatching(solver.getPtrVariables());
// cleanup
solver.deleteLp();
} catch (LpSolveException e) {
e.printStackTrace();
}
}
// NOTE: LP solve double[] objectives are 1-indexed arrays...
private static double[] getObjective() {
double[] obj = new double[n + 1];
for (int i = 0; i < t.length; ++i) {
for (int j = 0; j < s.length; ++j) {
obj[(s.length * i) + j + 1] = w.weight(t[i], s[j]);
}
}
return obj;
}
// NOTE: LP solve double[] objectives are 1-indexed arrays...
private static double[] getConstraintTutorN(int tutindex) {
double[] constraint = new double[n + 1];
Arrays.fill(constraint, 0);
for (int j = 0; j < s.length; ++j) {
constraint[(s.length * tutindex) + j + 1] = 1;
}
return constraint;
}
private static void calculateSimultaneousSlots() {
uniqueTimes = new ArrayList<String>();
times = new HashMap<String, ArrayList<Integer>>();
String key;
ArrayList<Integer> idxs;
for (int j = 0; j < s.length; ++j) {
key = s[j].day + s[j].hour; // this is unique per time
if (times.get(key) == null) {
idxs = new ArrayList<Integer>();
times.put(key, idxs);
uniqueTimes.add(key);
}
times.get(key).add(j);
}
}
// NOTE: LP solve double[] objectives are 1-indexed arrays...
private static double[] getConstraintTutorNoSimultaneous(int tutindex,
String time) {
double[] constraint = new double[n + 1];
Arrays.fill(constraint, 0);
for (Integer idx : times.get(time)) {
constraint[(s.length * tutindex) + idx + 1] = 1;
}
return constraint;
}
// NOTE: LP solve double[] objectives are 1-indexed arrays...
private static double[] getConstraintSlotAtLeastOne(int slotindex) {
double[] constraint = new double[n + 1];
Arrays.fill(constraint, 0);
for (int i = 0; i < t.length; ++i) {
constraint[(s.length * i) + slotindex + 1] = 1;
}
return constraint;
}
private static void setMatching(double[] results) {
double k;
for (int i = 0; i < t.length; ++i) {
for (int j = 0; j < s.length; ++j) {
k = results[(s.length * i) + j];
if (k > 0) {
if (t[i].slot == null) {
t[i].slot = s[j];
} else {
t[i].slot2 = s[j];
}
if (s[j].tutor == null) {
s[j].tutor = t[i];
} else {
s[j].tutor2 = t[i];
}
}
}
}
}
}
| false | true | public static void match(Tutor[] tutors, Slot[] slots, Weighting waiter) {
t = tutors;
s = slots;
w = waiter;
n = t.length * s.length;
try {
// create the LP solver: 0 constraints (for now),
// the variables are bindings between tutors and slots
LpSolve solver = LpSolve.makeLp(0, n);
// make lp_solve shut up about things that aren't important
solver.setVerbose(3);
// set all variables to binary
for (int i = 1; i < n + 1; ++i) {
solver.setBinary(i, true);
}
// OBJECTIVE FUNCTION (weight of each assignment)
solver.setObjFn(getObjective());
solver.setMaxim(); // sets the obj function to maximize
// CONSTRAINTS
// for each slot, assign exactly one (TODO modify for at least one)
for (int j = 0; j < s.length; ++j) {
solver.addConstraint(getConstraintSlotAtLeastOne(j),
LpSolve.GE, 1.0);
}
// for each tutor, cannot assign more than twice, but at least once
for (int i = 0; i < t.length; ++i) {
solver.addConstraint(getConstraintTutorN(i), LpSolve.LE,
t[i].numAssignments);
solver.addConstraint(getConstraintTutorN(i), LpSolve.GE,
t[i].numAssignments); // TODO replace with
// assignments/per
}
// for each tutor, cannot to assign to two slots that share time
calculateSimultaneousSlots();
for (int i = 0; i < t.length; ++i) {
for (String time : uniqueTimes) {
solver.addConstraint(
getConstraintTutorNoSimultaneous(i, time),
LpSolve.LE, 1.0);
}
}
// ilp solution
solver.solve();
// System.out.println("the linear program");
// solver.printLp();
// use solution to set the assignments of each tutor
setMatching(solver.getPtrVariables());
// cleanup
solver.deleteLp();
} catch (LpSolveException e) {
e.printStackTrace();
}
}
| public static void match(Tutor[] tutors, Slot[] slots, Weighting waiter) {
t = tutors;
s = slots;
w = waiter;
n = t.length * s.length;
try {
// create the LP solver: 0 constraints (for now),
// the variables are bindings between tutors and slots
LpSolve solver = LpSolve.makeLp(0, n);
// make lp_solve shut up about things that aren't important
solver.setVerbose(3);
// set all variables to binary
for (int i = 1; i < n + 1; ++i) {
solver.setBinary(i, true);
}
// OBJECTIVE FUNCTION (weight of each assignment)
solver.setObjFn(getObjective());
solver.setMaxim(); // sets the obj function to maximize
// CONSTRAINTS
// for each slot, assign exactly one (TODO modify for at least one)
for (int j = 0; j < s.length; ++j) {
solver.addConstraint(getConstraintSlotAtLeastOne(j),
LpSolve.GE, 1.0);
}
// for each tutor, assign 'numAssignments' slots
for (int i = 0; i < t.length; ++i) {
solver.addConstraint(getConstraintTutorN(i), LpSolve.EQ,
t[i].numAssignments);
}
// for each tutor, cannot to assign to two slots that share time
calculateSimultaneousSlots();
for (int i = 0; i < t.length; ++i) {
for (String time : uniqueTimes) {
solver.addConstraint(
getConstraintTutorNoSimultaneous(i, time),
LpSolve.LE, 1.0);
}
}
// ilp solution
solver.solve();
// System.out.println("the linear program");
// solver.printLp();
// use solution to set the assignments of each tutor
setMatching(solver.getPtrVariables());
// cleanup
solver.deleteLp();
} catch (LpSolveException e) {
e.printStackTrace();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.