code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.googleimport;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.appengine.api.datastore.Entity;
import com.google.common.base.Objects;
import com.google.inject.Inject;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.AbstractDirectory;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.server.appengine.DatastoreUtil;
import com.google.walkaround.util.shared.Assert;
import com.google.walkaround.wave.server.gxp.SourceInstance;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.util.Pair;
import java.io.IOException;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Tracks information about shared imported wavelets.
*
* @author ohler@google.com (Christian Ohler)
*/
public class SharedImportTable {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(SharedImportTable.class.getName());
private static class Entry {
// By design, wave ids should be unique across all instances, but it's easy
// not to rely on this, so let's not.
private final SourceInstance sourceInstance;
private final WaveletName waveletName;
private final SlobId slobId;
public Entry(SourceInstance sourceInstance,
WaveletName waveletName,
SlobId slobId) {
this.sourceInstance = checkNotNull(sourceInstance, "Null sourceInstance");
this.waveletName = checkNotNull(waveletName, "Null waveletName");
this.slobId = checkNotNull(slobId, "Null slobId");
}
public SourceInstance getSourceInstance() {
return sourceInstance;
}
public WaveletName getWaveletName() {
return waveletName;
}
public SlobId getSlobId() {
return slobId;
}
@Override public String toString() {
return getClass().getSimpleName() + "("
+ sourceInstance + ", "
+ waveletName + ", "
+ slobId
+ ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof Entry)) { return false; }
Entry other = (Entry) o;
return Objects.equal(sourceInstance, other.sourceInstance)
&& Objects.equal(waveletName, other.waveletName)
&& Objects.equal(slobId, other.slobId);
}
@Override public final int hashCode() {
return Objects.hashCode(sourceInstance, waveletName, slobId);
}
}
private static final String ROOT_ENTITY_KIND = "SharedImportedWavelet";
private static final String SLOB_ID_PROPERTY = "slobId";
private static class Directory
extends AbstractDirectory<Entry, Pair<SourceInstance, WaveletName>> {
private final SourceInstance.Factory sourceInstanceFactory;
@Inject Directory(CheckedDatastore datastore,
SourceInstance.Factory sourceInstanceFactory) {
super(datastore, ROOT_ENTITY_KIND);
this.sourceInstanceFactory = sourceInstanceFactory;
}
private Pair<SourceInstance, WaveletName> parseId(String in) {
String[] components = in.split(" ", -1);
Assert.check(components.length == 3, "Wrong number of spaces: %s", in);
return Pair.of(
sourceInstanceFactory.parseUnchecked(components[0]),
WaveletName.of(WaveId.deserialise(components[1]),
WaveletId.deserialise(components[2])));
}
@Override protected String serializeId(Pair<SourceInstance, WaveletName> id) {
String out = id.getFirst().serialize()
+ " " + id.getSecond().waveId.serialise() + " " + id.getSecond().waveletId.serialise();
Assert.check(id.equals(parseId(out)), "Failed to serialize id: %s", id);
return out;
}
@Override protected Pair<SourceInstance, WaveletName> getId(Entry e) {
return Pair.of(e.getSourceInstance(), e.getWaveletName());
}
@Override protected void populateEntity(Entry in, Entity out) {
DatastoreUtil.setNonNullIndexedProperty(out, SLOB_ID_PROPERTY, in.getSlobId().getId());
}
@Override protected Entry parse(Entity in) {
Pair<SourceInstance, WaveletName> id = parseId(in.getKey().getName());
return new Entry(id.getFirst(), id.getSecond(),
new SlobId(DatastoreUtil.getExistingProperty(in, SLOB_ID_PROPERTY, String.class)));
}
}
private final Directory directory;
@Inject
public SharedImportTable(Directory directory) {
this.directory = directory;
}
@Nullable private SlobId nullableEntryToSlobId(@Nullable Entry entry) {
return entry == null ? null : entry.slobId;
}
@Nullable public SlobId lookup(
CheckedTransaction tx, SourceInstance instance, WaveletName waveletName)
throws PermanentFailure, RetryableFailure {
return nullableEntryToSlobId(directory.get(tx, Pair.of(instance, waveletName)));
}
@Nullable public SlobId lookupWithoutTx(SourceInstance instance, WaveletName waveletName)
throws IOException {
return nullableEntryToSlobId(directory.getWithoutTx(Pair.of(instance, waveletName)));
}
@Nullable public void put(CheckedTransaction tx, SourceInstance instance,
WaveletName waveletName, SlobId slobId) throws PermanentFailure, RetryableFailure {
directory.put(tx, new Entry(instance, waveletName, slobId));
}
}
| Java |
/*
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.robot;
import com.google.appengine.api.datastore.Entity;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.appengine.AbstractDirectory;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.DatastoreUtil;
import com.google.walkaround.util.shared.Assert;
import com.google.walkaround.wave.server.robot.VersionDirectory.RobotNotified;
import org.waveprotocol.wave.model.util.Pair;
import org.waveprotocol.wave.model.wave.ParticipantId;
/**
* A mapping from <SlobId, RobotId> to version number that the robot has last
* seen on the conversational wavelet.
*
* @author ljv@google.com (Lennard de Rijk)
*/
public class VersionDirectory extends AbstractDirectory<RobotNotified, Pair<SlobId, ParticipantId>> {
private static final String VERSION_PROPERTY = "Version";
public static class RobotNotified {
private final Pair<SlobId, ParticipantId> id;
private final long version;
RobotNotified(SlobId slobId, ParticipantId robotId, long version) {
Preconditions.checkNotNull(slobId);
Preconditions.checkNotNull(robotId);
this.id = Pair.of(slobId, robotId);
this.version = version;
}
public long getVersion() {
return version;
}
}
@Inject
public VersionDirectory(CheckedDatastore datastore) {
super(datastore, "RobotNotified");
}
@Override
protected Pair<SlobId, ParticipantId> getId(RobotNotified e) {
return e.id;
}
@Override
protected RobotNotified parse(Entity e) {
String[] parts = e.getKey().getName().split(" ", -1);
Assert.check(parts.length == 2, "Wrong number of spaces in key: %s", e);
SlobId slobId = new SlobId(parts[0]);
ParticipantId robotId = ParticipantId.ofUnsafe(parts[1]);
long version = DatastoreUtil.getExistingProperty(e, VERSION_PROPERTY, Long.class);
return new RobotNotified(slobId, robotId, version);
}
@Override
protected void populateEntity(RobotNotified in, Entity out) {
DatastoreUtil.setNonNullUnindexedProperty(out, VERSION_PROPERTY, in.version);
}
@Override
protected String serializeId(Pair<SlobId, ParticipantId> id) {
Assert.check(!id.getFirst().getId().contains(" "), "SlobId contains space: %s", id);
Assert.check(!id.getSecond().getAddress().contains(" "), "RobotId contains space: %s", id);
return id.getFirst().getId() + " " + id.getSecond().getAddress();
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
import com.google.walkaround.proto.ObsoleteWaveletMetadata;
import com.google.walkaround.proto.gson.ConvMetadataGsonImpl;
import com.google.walkaround.proto.gson.ObsoleteUdwMetadataGsonImpl;
import com.google.walkaround.proto.gson.ObsoleteWaveletMetadataGsonImpl;
import com.google.walkaround.slob.server.AccessDeniedException;
import com.google.walkaround.slob.server.GsonProto;
import com.google.walkaround.slob.server.SlobAlreadyExistsException;
import com.google.walkaround.slob.server.SlobStore;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.RetryHelper;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.shared.RandomBase64Generator;
import com.google.walkaround.wave.server.WaveletDirectory.ObjectIdAlreadyKnown;
import com.google.walkaround.wave.server.auth.StableUserId;
import com.google.walkaround.wave.server.conv.ConvMetadataStore;
import com.google.walkaround.wave.server.conv.ConvStore;
import com.google.walkaround.wave.server.model.InitialOps;
import com.google.walkaround.wave.server.model.ServerMessageSerializer;
import com.google.walkaround.wave.server.udw.UdwStore;
import com.google.walkaround.wave.server.udw.UserDataWaveletDirectory;
import com.google.walkaround.wave.shared.WaveSerializer;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Creates wavelets.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class WaveletCreator {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(WaveletCreator.class.getName());
private static final WaveSerializer SERIALIZER =
new WaveSerializer(new ServerMessageSerializer());
private final WaveletDirectory waveletDirectory;
private final UserDataWaveletDirectory udwDirectory;
private final ParticipantId participantId;
private final StableUserId userId;
private final SlobStore convStore;
private final SlobStore udwStore;
private final RandomBase64Generator random64;
private final CheckedDatastore datastore;
private final ConvMetadataStore convMetadataStore;
@Inject
public WaveletCreator(
WaveletDirectory waveletDirectory,
UserDataWaveletDirectory udwDirectory,
ParticipantId participantId,
StableUserId userId,
@ConvStore SlobStore convStore,
@UdwStore SlobStore udwStore,
RandomBase64Generator random64,
CheckedDatastore datastore,
ConvMetadataStore convMetadataStore) {
this.waveletDirectory = waveletDirectory;
this.udwDirectory = udwDirectory;
this.participantId = participantId;
this.userId = userId;
this.convStore = convStore;
this.udwStore = udwStore;
this.random64 = random64;
this.datastore = datastore;
this.convMetadataStore = convMetadataStore;
}
private WaveletMapping registerWavelet(SlobId objectId) throws IOException {
WaveletMapping mapping = new WaveletMapping(objectId);
log.info("Registering " + mapping);
try {
waveletDirectory.register(mapping);
} catch (ObjectIdAlreadyKnown e) {
throw new RuntimeException("Freshly-created object already known", e);
}
log.info("Registered " + mapping);
return mapping;
}
private String makeObsoleteUdwMetadata(SlobId convId) {
ObsoleteUdwMetadataGsonImpl udwMeta = new ObsoleteUdwMetadataGsonImpl();
udwMeta.setAssociatedConvId(convId.getId());
udwMeta.setOwner(userId.getId());
ObsoleteWaveletMetadataGsonImpl meta = new ObsoleteWaveletMetadataGsonImpl();
meta.setType(ObsoleteWaveletMetadata.Type.UDW);
meta.setUdwMetadata(udwMeta);
return GsonProto.toJson(meta);
}
private String makeObsoleteConvMetadata() {
ObsoleteWaveletMetadataGsonImpl meta = new ObsoleteWaveletMetadataGsonImpl();
meta.setType(ObsoleteWaveletMetadata.Type.CONV);
return GsonProto.toJson(meta);
}
private List<ChangeData<String>> serializeChanges(List<WaveletOperation> ops) {
ImmutableList.Builder<ChangeData<String>> out = ImmutableList.builder();
for (String delta : SERIALIZER.serializeDeltas(ops)) {
out.add(new ChangeData<String>(getFakeClientId(), delta));
}
return out.build();
}
private WaveletMapping createUdw(SlobId convId) throws IOException {
long creationTime = System.currentTimeMillis();
List<WaveletOperation> history = InitialOps.userDataWaveletOps(participantId, creationTime);
SlobId objectId = newUdwWithGeneratedId(makeObsoleteUdwMetadata(convId),
serializeChanges(history));
return registerWavelet(objectId);
}
public SlobId getOrCreateUdw(SlobId convId) throws IOException {
SlobId existing = udwDirectory.getUdwId(convId, userId);
if (existing != null) {
return existing;
} else {
SlobId newUdwId = createUdw(convId)
.getObjectId();
SlobId existingUdwId = udwDirectory.getOrAdd(convId, userId, newUdwId);
if (existingUdwId == null) {
return newUdwId;
} else {
log.log(Level.WARNING, "Multiple concurrent UDW creations for "
+ userId + " on " + convId + ": " + existingUdwId + ", " + newUdwId);
return existingUdwId;
}
}
}
private ClientId getFakeClientId() {
return new ClientId("");
}
public SlobId newConvWithGeneratedId(
@Nullable List<WaveletOperation> historyOps,
@Nullable final ConvMetadataGsonImpl convMetadata, final boolean inhibitPreAndPostCommit)
throws IOException {
final List<ChangeData<String>> history;
if (historyOps != null) {
history = serializeChanges(historyOps);
} else {
history = serializeChanges(
InitialOps.conversationWaveletOps(participantId, System.currentTimeMillis(), random64));
}
SlobId newId;
try {
newId = new RetryHelper().run(
new RetryHelper.Body<SlobId>() {
@Override public SlobId run() throws RetryableFailure, PermanentFailure {
SlobId convId = getRandomObjectId();
CheckedTransaction tx = datastore.beginTransaction();
try {
convStore.newObject(tx, convId, makeObsoleteConvMetadata(), history,
inhibitPreAndPostCommit);
convMetadataStore.put(tx, convId,
convMetadata != null ? convMetadata : new ConvMetadataGsonImpl());
tx.commit();
} catch (SlobAlreadyExistsException e) {
throw new RetryableFailure("Slob id collision, retrying: " + convId, e);
} catch (AccessDeniedException e) {
throw new RuntimeException(
"Unexpected AccessDeniedException creating conv " + convId, e);
} finally {
tx.close();
}
return convId;
}
});
} catch (PermanentFailure e) {
throw new IOException("PermanentFailure creating conv", e);
}
registerWavelet(newId);
return newId;
}
private SlobId getRandomObjectId() {
// 96 random bits. (6 bits per base64 character.) TODO(ohler): Justify the
// number 96.
return new SlobId(random64.next(96 / 6));
}
private SlobId newUdwWithGeneratedId(final String metadata,
final List<ChangeData<String>> initialHistory) throws IOException {
try {
return new RetryHelper().run(
new RetryHelper.Body<SlobId>() {
@Override public SlobId run() throws RetryableFailure, PermanentFailure {
SlobId udwId = getRandomObjectId();
CheckedTransaction tx = datastore.beginTransaction();
try {
udwStore.newObject(tx, udwId, metadata, initialHistory, false);
tx.commit();
} catch (SlobAlreadyExistsException e) {
throw new RetryableFailure("Slob id collision, retrying: " + udwId, e);
} catch (AccessDeniedException e) {
throw new RuntimeException(
"Unexpected AccessDeniedException creating udw " + udwId, e);
} finally {
tx.close();
}
return udwId;
}
});
} catch (PermanentFailure e) {
throw new IOException("PermanentFailure creating udw", e);
}
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.SlobId;
/**
* POJO form of {@code ObjectSessionProto}.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ObjectSession {
private final SlobId objectId;
private final ClientId clientId;
private final String storeType;
public ObjectSession(SlobId objectId, ClientId clientId, String storeType) {
Preconditions.checkNotNull(objectId, "Null objectId");
Preconditions.checkNotNull(clientId, "Null clientId");
Preconditions.checkNotNull(storeType, "Null storeType");
this.objectId = objectId;
this.clientId = clientId;
this.storeType = storeType;
}
public SlobId getObjectId() {
return objectId;
}
public ClientId getClientId() {
return clientId;
}
public String getStoreType() {
return storeType;
}
@Override public String toString() {
return "ObjectSession(" + objectId + ", " + clientId + ", " + storeType + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof ObjectSession)) { return false; }
ObjectSession other = (ObjectSession) o;
return Objects.equal(objectId, other.objectId)
&& Objects.equal(clientId, other.clientId)
&& Objects.equal(storeType, other.storeType);
}
@Override public final int hashCode() {
return Objects.hashCode(objectId, clientId, storeType);
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.servlet;
import com.google.gxp.base.GxpContext;
import com.google.gxp.html.HtmlClosure;
import com.google.inject.Inject;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.gxp.PageSkin;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Helper to invoke {@code PageSkin.write()} with common arguments.
*
* @author ohler@google.com (Christian Ohler)
*/
public class PageSkinWriter {
private final HttpServletRequest req;
private final HttpServletResponse resp;
private final String analyticsAccount;
@Inject
public PageSkinWriter(HttpServletRequest req,
HttpServletResponse resp,
@Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount) {
this.req = req;
this.resp = resp;
this.analyticsAccount = analyticsAccount;
}
public void write(String title, String userEmail, HtmlClosure content) throws IOException {
PageSkin.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, title, userEmail, content);
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.servlet;
import com.google.gson.JsonObject;
import com.google.walkaround.wave.shared.SharedConstants;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.PrintWriter;
/**
* Utilities for the servlets
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// TODO(ohler): This is near-empty now, should eliminate altogether, or give it
// a more specific name.
public class ServletUtil {
/**
* Writes the string to the print writer according to the protocol the client
* expects.
*
* @param w
* @param str must be valid JSON
*/
public static void writeJsonResult(PrintWriter w, String str) {
try {
assert new JSONObject(str) != null;
} catch (JSONException e) {
throw new IllegalArgumentException("Bad JSON: " + str, e);
}
w.print(SharedConstants.XSSI_PREFIX + "(" + str + ")");
}
public static String getSubmitDeltaResultJson(long resultingRevision) {
JsonObject json = new JsonObject();
json.addProperty("version", resultingRevision);
return json.toString();
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.servlet;
import com.google.inject.Inject;
import com.google.walkaround.proto.ServerMutateRequest;
import com.google.walkaround.proto.ServerMutateResponse;
import com.google.walkaround.proto.gson.ServerMutateRequestGsonImpl;
import com.google.walkaround.slob.server.GsonProto;
import com.google.walkaround.slob.server.SlobStoreSelector;
import com.google.walkaround.slob.server.StoreAccessChecker;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.ObjectSession;
import com.google.walkaround.wave.server.ObjectSessionHelper;
import org.waveprotocol.wave.communication.gson.GsonSerializable;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Directly mutates the data store. Looks for the "X-Walkaround-Trusted" header.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class StoreMutateHandler extends AbstractHandler {
private static final Logger log = Logger.getLogger(StoreMutateHandler.class.getName());
@Inject StoreAccessChecker accessChecker;
@Inject SlobStoreSelector storeSelector;
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
accessChecker.checkPermittedStoreRequest(req);
String requestString = requireParameter(req, "req");
ServerMutateRequest mutateRequest;
try {
mutateRequest = GsonProto.fromGson(new ServerMutateRequestGsonImpl(),
requestString);
} catch (MessageException e) {
throw new BadRequestException("Failed to parse request: " + requestString, e);
}
ObjectSession session = ObjectSessionHelper.objectSessionFromProto(mutateRequest.getSession());
ServerMutateResponse result =
storeSelector.get(session.getStoreType()).getLocalMutationProcessor()
.mutateObject(mutateRequest);
log.info("Success @" + result.getResultingVersion());
resp.setStatus(200);
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().print("OK" + GsonProto.toJson((GsonSerializable) result));
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.servlet;
import com.google.appengine.api.users.UserService;
import com.google.common.base.Throwables;
import com.google.gxp.html.HtmlClosure;
import com.google.gxp.html.HtmlClosures;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.walkaround.util.server.servlet.HttpException;
import com.google.walkaround.wave.server.gxp.ErrorPage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author ohler@google.com (Christian Ohler)
*/
@Singleton
public class ServerExceptionFilter implements Filter {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ServerExceptionFilter.class.getName());
/**
* Whether the current user whose request we are currently processing is trusted
* or untrusted.
*
* We keep this orthogonal to admin status for now.
*
* @author ohler@google.com (Christian Ohler)
*/
public enum UserTrustStatus {
UNTRUSTED,
TRUSTED;
}
@Inject Provider<UserService> userService;
@Inject Provider<UserTrustStatus> trusted;
@Inject Provider<PageSkinWriter> pageSkinWriter;
@Override public void init(FilterConfig filterConfig) {}
@Override public void destroy() {}
private void sendError(HttpServletRequest req, HttpServletResponse response, Level logLevel,
int errorCode, String publicMessage, Throwable t) throws IOException {
log.log(logLevel,
t.getClass().getSimpleName() + "; sending " + errorCode + ": " + publicMessage,
t);
try {
log.info("Trust status: " + trusted.get());
boolean isTrusted = trusted.get() == UserTrustStatus.TRUSTED
&& req.getParameter("simulateUntrusted") == null;
response.setStatus(errorCode);
UserService service = userService.get();
String userEmail = service.isUserLoggedIn()
? service.getCurrentUser().getEmail() : "(not logged in)";
pageSkinWriter.get().write("Error " + errorCode, userEmail,
ErrorPage.getGxpClosure(userEmail, "" + errorCode, isTrusted, publicMessage,
renderInternalMessage(Throwables.getStackTraceAsString(t))));
log.info("Successfully sent GXP error page");
} catch (RuntimeException e) {
// This can happen if the uncaught exception t occurred after the servlet
// had already called response.setContentType(). In that case, jetty
// throws an IllegalStateException("STREAM") when we call
// response.getWriter() above.
log.log(Level.SEVERE, "RuntimeException trying to serve error page", e);
// Try a more primitive mechanism.
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"An error occurred while reporting an error, see logs. Original error: "
+ errorCode + " " + publicMessage);
log.info("Successfully sent primitive error page");
}
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
throws IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
try {
filterChain.doFilter(req, resp);
} catch (HttpException e) {
sendError(request, response, Level.INFO, e.getResponseCode(), e.getPublicMessage(), e);
} catch (Throwable t) {
sendError(request, response, Level.SEVERE, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Internal server error", t);
}
}
// TODO(danilatos): Move this into the template.
private HtmlClosure renderInternalMessage(String message) {
return HtmlClosures.fromHtml(
com.google.walkaround.util.server.HtmlEscaper.HTML_ESCAPER.escape(message)
.replaceAll("walkaround", "<b>walkaround</b>"));
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.servlet;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gxp.base.GxpContext;
import com.google.inject.Inject;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.gxp.AuthPopup;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Logs out the current user. This is useful for switching between admin and
* non-admin when running locally.
*
* @author ohler@google.com (Christian Ohler)
*/
public class LogoutHandler extends AbstractHandler {
public static class SelfClosingPageHandler extends AbstractHandler {
@Inject @Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
AuthPopup.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, null);
}
}
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(LogoutHandler.class.getName());
public LogoutHandler() {
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String redirect;
if (req.getParameter("switchUser") != null) {
redirect = "/switchSuccess";
} else {
redirect = "/loggedout.html";
}
resp.sendRedirect(UserServiceFactory.getUserService().createLogoutURL(redirect));
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.servlet;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.gxp.base.GxpContext;
import com.google.gxp.html.HtmlClosure;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.google.walkaround.proto.ClientVars.ErrorVars;
import com.google.walkaround.proto.ClientVars.LiveClientVars;
import com.google.walkaround.proto.ClientVars.StaticClientVars;
import com.google.walkaround.proto.gson.ClientVarsGsonImpl;
import com.google.walkaround.proto.gson.ClientVarsGsonImpl.ErrorVarsGsonImpl;
import com.google.walkaround.proto.gson.ClientVarsGsonImpl.LiveClientVarsGsonImpl;
import com.google.walkaround.proto.gson.ClientVarsGsonImpl.StaticClientVarsGsonImpl;
import com.google.walkaround.proto.gson.ClientVarsGsonImpl.UdwLoadDataGsonImpl;
import com.google.walkaround.slob.server.AccessDeniedException;
import com.google.walkaround.slob.server.GsonProto;
import com.google.walkaround.slob.server.SlobFacilities;
import com.google.walkaround.slob.server.SlobNotFoundException;
import com.google.walkaround.slob.shared.ClientId;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.Util;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.shared.RandomBase64Generator;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.ObjectSession;
import com.google.walkaround.wave.server.ObjectSessionHelper;
import com.google.walkaround.wave.server.WaveLoader;
import com.google.walkaround.wave.server.WaveLoader.LoadedWave;
import com.google.walkaround.wave.server.auth.UserContext;
import com.google.walkaround.wave.server.conv.ConvStore;
import com.google.walkaround.wave.server.gxp.Client;
import com.google.walkaround.wave.server.udw.UdwStore;
import org.json.JSONException;
import org.json.JSONObject;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.util.Collections;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Serves the undercurrent client.
*
* @author ohler@google.com (Christian Ohler)
*/
public class UndercurrentHandler extends AbstractHandler {
private static final String nocacheJs = Util.slurpRequired(
"com.google.walkaround.wave.client.Walkaround.nocache.js");
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(UndercurrentHandler.class.getName());
@Inject @Flag(FlagName.CLIENT_VERSION) int clientVersion;
@Inject WaveLoader loader;
@Inject Random random;
@Inject RandomBase64Generator random64;
@Inject ParticipantId participantId;
@Inject @Named("channel api url") String channelApiUrl;
@Inject ObjectSessionHelper sessionHelper;
@Inject @Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount;
@Inject UserContext userContext;
@Inject @UdwStore SlobFacilities udwStore;
@Inject @ConvStore SlobFacilities convStore;
private void setResponseHeaders(HttpServletResponse resp) {
// TODO(ohler): Figure out how to make static versions cacheable. The
// problem is that we inline GWT's nocache JS, and having that cached is
// very confusing when debugging, and could lead to situations where a
// browser caches the nocache JS but not the cacheable JS and expects the
// server to still have the cacheable JS -- this won't be true if a new
// client binary has been deployed to the server.
// TODO(ohler): Find a systematic way of setting no-cache headers in all
// handlers that need them.
// http://www.mnot.net/cache_docs/#PRAGMA recommends not to use this;
// TODO(ohler): Figure out if it does any good. Walkaround doesn't work in
// old browsers anyway, so we shouldn't need hacks.
resp.setHeader("Pragma", "No-cache");
// NOTE(ohler): Using this rather than just "no-cache" seems to fix the
// client crash on back/forward due to re-use of client id.
resp.setHeader("Cache-Control", "no-store, must-revalidate");
resp.setContentType("text/html");
resp.setCharacterEncoding("UTF-8");
}
private JSONObject clientVarString(
@Nullable LiveClientVars liveClientVars,
@Nullable StaticClientVars staticClientVars,
@Nullable ErrorVars errorVars) {
Preconditions.checkArgument(Collections.frequency(
ImmutableList.of(liveClientVars != null, staticClientVars != null, errorVars != null),
true) == 1,
"%s/%s/%s", liveClientVars, staticClientVars, errorVars);
ClientVarsGsonImpl clientVars = new ClientVarsGsonImpl();
if (liveClientVars != null) {
clientVars.setLiveClientVars(liveClientVars);
} else if (staticClientVars != null) {
clientVars.setStaticClientVars(staticClientVars);
} else {
clientVars.setErrorVars(errorVars);
}
String jsonString = GsonProto.toJson(clientVars);
try {
// TODO(ohler): Find a way to embed a GSON-generated JSON literal in GXP
// without serializing and re-parsing to org.json.JSONObject. Perhaps
// through JavascriptClosure?
return new JSONObject(jsonString);
} catch (JSONException e) {
throw new RuntimeException("org.json failed to parse GSON's output: " + jsonString, e);
}
}
private void writeErrorResponse(HttpServletRequest req, HttpServletResponse resp,
String errorMessage) throws IOException {
ErrorVarsGsonImpl errorVars = new ErrorVarsGsonImpl();
errorVars.setErrorMessage(errorMessage);
setResponseHeaders(resp);
Client.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, clientVarString(null, null, errorVars), inlineNocacheJs(), channelApiUrl);
}
private void writeLiveClientResponse(HttpServletRequest req, HttpServletResponse resp,
ClientId clientId, LoadedWave wave) throws IOException {
LiveClientVarsGsonImpl vars = new LiveClientVarsGsonImpl();
vars.setClientVersion(clientVersion);
vars.setRandomSeed(random.nextInt());
vars.setUserEmail(participantId.getAddress());
vars.setHaveOauthToken(userContext.hasOAuthCredentials());
vars.setConvSnapshot(wave.getConvSnapshotWithDiffs());
vars.setConvConnectResponse(
sessionHelper.createConnectResponse(
new ObjectSession(wave.getConvObjectId(), clientId, convStore.getRootEntityKind()),
wave.getConvConnectResult()));
if (wave.getUdw() != null) {
UdwLoadDataGsonImpl udwLoadData = new UdwLoadDataGsonImpl();
udwLoadData.setConnectResponse(
sessionHelper.createConnectResponse(
new ObjectSession(wave.getUdw().getObjectId(), clientId,
udwStore.getRootEntityKind()),
wave.getUdw().getConnectResult()));
udwLoadData.setSnapshot(wave.getUdw().getSnapshot());
vars.setUdw(udwLoadData);
}
setResponseHeaders(resp);
Client.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, clientVarString(vars, null, null), inlineNocacheJs(), channelApiUrl);
}
private void writeStaticClientResponse(HttpServletRequest req, HttpServletResponse resp,
LoadedWave wave) throws IOException {
StaticClientVarsGsonImpl vars = new StaticClientVarsGsonImpl();
vars.setRandomSeed(random.nextInt());
vars.setUserEmail(participantId.getAddress());
vars.setHaveOauthToken(userContext.hasOAuthCredentials());
vars.setConvObjectId(wave.getConvObjectId().getId());
vars.setConvSnapshot(wave.getConvSnapshotWithDiffs());
setResponseHeaders(resp);
Client.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, clientVarString(null, vars, null), inlineNocacheJs(), channelApiUrl);
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
SlobId convObjectId = new SlobId(requireParameter(req, "id"));
String versionString = optionalParameter(req, "version", null);
@Nullable Long version = versionString == null ? null : Long.parseLong(versionString);
@Nullable ClientId clientId = version != null ? null
: new ClientId(random64.next(
// TODO(ohler): justify this number
8));
LoadedWave wave;
try {
if (version == null) {
wave = loader.load(convObjectId, clientId);
} else {
wave = loader.loadStaticAtVersion(convObjectId, version);
}
} catch (AccessDeniedException e) {
log.log(Level.SEVERE, "Wave not found or access denied", e);
writeErrorResponse(req, resp, "Wave not found or access denied");
return;
} catch (SlobNotFoundException e) {
log.log(Level.SEVERE, "Wave not found or access denied", e);
writeErrorResponse(req, resp, "Wave not found or access denied");
return;
} catch (IOException e) {
log.log(Level.SEVERE, "Server error loading wave", e);
writeErrorResponse(req, resp, "Server error loading wave");
return;
}
if (version == null) {
writeLiveClientResponse(req, resp, clientId, wave);
} else {
writeStaticClientResponse(req, resp, wave);
}
}
private HtmlClosure inlineNocacheJs() {
return new HtmlClosure() {
@Override public void write(Appendable out, GxpContext gxpContext) throws IOException {
out.append("<script type='text/javascript'>\n");
// No need to escape this, GWT's nocache javascript is already escaped for
// the purpose of direct inclusion into script elements.
out.append(nocacheJs);
out.append("</script>");
}
};
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.attachment;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.common.collect.Iterables;
import com.google.gxp.base.GxpContext;
import com.google.inject.Inject;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.gxp.UploadResult;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Handles attachment uploads.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class AttachmentUploadHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(AttachmentUploadHandler.class.getName());
/**
* Attachment file upload form field name.
*/
static final String ATTACHMENT_UPLOAD_PARAM = "attachment";
@Inject BlobstoreService blobstoreService;
@Inject MetadataDirectory metadataDirectory;
@Inject RawAttachmentService rawAttachmentService;
@Inject @Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount;
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
List<BlobKey> blobKeys = blobs.get(ATTACHMENT_UPLOAD_PARAM);
log.info("blobKeys: " + blobKeys);
BlobKey blobKey = Iterables.getOnlyElement(blobKeys);
AttachmentId newId = rawAttachmentService.turnBlobIntoAttachment(blobKey);
UploadResult.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, newId.getId());
}
}
| Java |
/*
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.attachment;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Objects;
import java.io.Serializable;
/**
* Attachment ID. This is distinct from an App Engine BlobKey since code
* outside the server shouldn't reason about BlobKeys.
*
* @author ohler@google.com (Christian Ohler)
*/
public class AttachmentId implements Serializable {
private static final long serialVersionUID = 112261689375404053L;
private final String id;
public AttachmentId(String id) {
this.id = checkNotNull(id, "Null id");
}
public String getId() {
return id;
}
@Override public String toString() {
return getClass().getSimpleName() + "(" + id + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof AttachmentId)) { return false; }
AttachmentId other = (AttachmentId) o;
return Objects.equal(id, other.id);
}
@Override public final int hashCode() {
return Objects.hashCode(id);
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.attachment;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.walkaround.util.shared.Assert;
import com.google.walkaround.util.shared.RandomBase64Generator;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Low level attachment facilities that always operate on the raw attachment
* data.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class RawAttachmentService {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(RawAttachmentService.class.getName());
private static final int MAX_THUMB_HEIGHT_PX = 120;
private static final int MAX_THUMB_WIDTH_PX = 120;
private final BlobstoreService blobstoreService;
private final BlobInfoFactory blobInfoFactory;
private final ImagesService imagesService;
private final int headerBytesUpperBound;
private final RandomBase64Generator random64;
private final MetadataDirectory metadataDirectory;
@Inject
public RawAttachmentService(BlobstoreService blobstoreService, ImagesService imagesService,
BlobInfoFactory blobInfoFactory,
@Flag(FlagName.ATTACHMENT_HEADER_BYTES_UPPER_BOUND) int headerBytesUpperBound,
RandomBase64Generator random64,
MetadataDirectory metadataDirectory) {
this.blobstoreService = blobstoreService;
this.imagesService = imagesService;
this.blobInfoFactory = blobInfoFactory;
this.headerBytesUpperBound = headerBytesUpperBound;
this.random64 = random64;
this.metadataDirectory = metadataDirectory;
}
private AttachmentMetadata computeMetadata(AttachmentId id, BlobKey blobKey) {
try {
BlobInfo info = blobInfoFactory.loadBlobInfo(blobKey);
if (info != null) {
JSONObject data = new JSONObject();
data.put("size", info.getSize());
String mimeType = info.getContentType();
data.put("mimeType", mimeType);
data.put("filename", info.getFilename());
if (mimeType.startsWith("image/")) {
Image img = attemptGetImageMetadata(blobstoreService, info);
if (img != null) {
JSONObject imgData = new JSONObject();
imgData.put("width", img.getWidth());
imgData.put("height", img.getHeight());
data.put("image", imgData);
JSONObject thumbData = new JSONObject();
double ratio = resizeRatio(img);
thumbData.put("width", ratio * img.getWidth());
thumbData.put("height", ratio * img.getHeight());
data.put("thumbnail", thumbData);
}
} else {
// TODO(danilatos): Thumbnails for non-images
log.info("Unimplemented: Thumbnails for non-images");
}
return new AttachmentMetadata(id, blobKey, data);
}
return null;
} catch (JSONException e) {
throw new Error(e);
}
}
public AttachmentId turnBlobIntoAttachment(BlobKey blobKey) throws IOException {
Preconditions.checkNotNull(blobKey, "Null blobKey");
AttachmentId newId = new AttachmentId(random64.next(
// 115 * 6 random bits; should be unguessable. (6 bits per random64 char.)
115));
Assert.check(metadataDirectory.getWithoutTx(newId) == null,
"Random attachment id already taken: %s", newId);
log.info("Computing metadata for " + newId + " (" + blobKey + ")");
AttachmentMetadata metadata = computeMetadata(newId, blobKey);
AttachmentMetadata existingMetadata = metadataDirectory.getOrAdd(metadata);
if (existingMetadata != null) {
// This is expected if, during getOrAdd, a commit times out from our
// perspective but succeeded in the datatstore, and we notice the existing
// data during a retry. Still, we log severe until we confirm that this
// is indeed harmless.
log.severe("Metadata for new attachment " + metadata
+ " already exists: " + existingMetadata);
}
log.info("Wrote metadata " + metadata);
return newId;
}
public byte[] getResizedImageBytes(BlobKey id, int width, int height) {
log.info("Resizing " + id + " to " + width + "x" + height);
// emptyImage is just a wrapper around the id.
Image emptyImage = ImagesServiceFactory.makeImageFromBlob(id);
Transform resize = ImagesServiceFactory.makeResize(width, height);
return imagesService.applyTransform(resize, emptyImage).getImageData();
}
@Nullable private Image attemptGetImageMetadata(BlobstoreService blobstore, BlobInfo info) {
if (info.getSize() == 0) {
// Special case since it would lead to an IllegalArgumentException below.
log.info("Empty attachment, can't get image metadata: " + info);
return null;
}
final int readPortion = headerBytesUpperBound;
BlobKey key = info.getBlobKey();
byte[] data = blobstore.fetchData(key, 0, readPortion);
try {
Image img = ImagesServiceFactory.makeImage(data);
// Force the image to be processed
img.getWidth();
img.getHeight();
return img;
} catch (RuntimeException e) {
log.log(Level.SEVERE, "Problem getting image metadata; ignoring", e);
return null;
}
}
private double resizeRatio(Image img) {
double width = img.getWidth();
double height = img.getHeight();
double cmpRatio = (double) MAX_THUMB_WIDTH_PX / MAX_THUMB_HEIGHT_PX;
double ratio = width / height;
if (ratio > cmpRatio) {
return Math.min(1, MAX_THUMB_WIDTH_PX / width);
} else {
return Math.min(1, MAX_THUMB_HEIGHT_PX / height);
}
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.attachment;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Entity;
import com.google.walkaround.util.server.appengine.AbstractDirectory;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.DatastoreUtil;
import com.google.walkaround.wave.server.attachment.ThumbnailDirectory.ThumbnailData;
/**
* Image thumbnails. They are small enough to be stored directly in the data
* store rather than in the blob store (by a very large margin, 2-3KB thumbnails
* vs 1MB entities).
*
* @author danilatos@google.com (Daniel Danilatos)
*/
class ThumbnailDirectory extends AbstractDirectory<ThumbnailData, BlobKey> {
static class ThumbnailData {
final BlobKey id;
final byte[] thumbnailBytes;
ThumbnailData(BlobKey id, byte[] thumbnailData) {
this.id = id;
this.thumbnailBytes = thumbnailData;
}
byte[] getBytes() {
return thumbnailBytes;
}
}
static final String THUMBNAIL_BYTES_PROPERTY = "ThumbnailBytes";
public ThumbnailDirectory(CheckedDatastore datastore) {
super(datastore, "ThumbnailDataEntity");
}
@Override
protected BlobKey getId(ThumbnailData e) {
return e.id;
}
@Override
protected ThumbnailData parse(Entity e) {
return new ThumbnailData(new BlobKey(e.getKey().getName()),
DatastoreUtil.getExistingProperty(e, THUMBNAIL_BYTES_PROPERTY, Blob.class).getBytes());
}
@Override
protected void populateEntity(ThumbnailData in, Entity out) {
DatastoreUtil.setNonNullUnindexedProperty(
out, THUMBNAIL_BYTES_PROPERTY, new Blob(in.thumbnailBytes));
}
@Override
protected String serializeId(BlobKey id) {
return id.getKeyString();
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.attachment;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.net.UriEscapers;
import com.google.inject.Inject;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.servlet.ServletUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Serves attachment metadata as JSON.
*
* We support POST because the client could legitimately ask for a very large
* number of attachment ids at once, which may not fit into a GET request.
*
* At the same time, we should support GET because it is appropriate for small
* requests and convenient for debugging.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class AttachmentMetadataHandler extends AbstractHandler {
/** Avoid doing too much work at once so the client can get incremental being loaded */
private static final long MAX_REQUEST_TIME_MS = 4 * 1000;
private static final String INVALID_ATTACHMENT_ID_METADATA_STRING = "{}";
private final AttachmentService attachments;
@Inject
public AttachmentMetadataHandler(AttachmentService attachments) {
this.attachments = attachments;
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doRequest(req, resp);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doRequest(req, resp);
}
private List<AttachmentId> getIds(HttpServletRequest req) {
ImmutableList.Builder<AttachmentId> out = ImmutableList.builder();
for (String id : requireParameter(req, "ids").split(",", -1)) {
out.add(new AttachmentId(id));
}
return out.build();
}
private void doRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Map<AttachmentId, Optional<AttachmentMetadata>> result = attachments.getMetadata(
getIds(req), MAX_REQUEST_TIME_MS);
JSONObject json = new JSONObject();
try {
for (Entry<AttachmentId, Optional<AttachmentMetadata>> entry : result.entrySet()) {
JSONObject metadata = new JSONObject(
entry.getValue().isPresent() ? entry.getValue().get().getMetadataJsonString()
: INVALID_ATTACHMENT_ID_METADATA_STRING);
String queryParams = "attachment=" +
UriEscapers.uriQueryStringEscaper(false).escape(entry.getKey().getId());
metadata.put("url", "/download?" + queryParams);
metadata.put("thumbnailUrl", "/thumbnail?" + queryParams);
json.put(entry.getKey().getId(), metadata);
}
} catch (JSONException e) {
throw new Error(e);
}
ServletUtil.writeJsonResult(resp.getWriter(), json.toString());
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.attachment;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.datastore.Entity;
import com.google.inject.Inject;
import com.google.walkaround.util.server.appengine.AbstractDirectory;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.DatastoreUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.logging.Logger;
/**
* Attachment metadata
*
* @author danilatos@google.com (Daniel Danilatos)
*/
class MetadataDirectory extends AbstractDirectory<AttachmentMetadata, AttachmentId> {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(MetadataDirectory.class.getName());
private static final String BLOB_KEY_PROPERTY = "BlobKey";
private static final String JSON_METADATA_PROPERTY = "Metadata";
@Inject public MetadataDirectory(CheckedDatastore datastore) {
super(datastore, "AttachmentMetadataEntity");
}
@Override
protected AttachmentId getId(AttachmentMetadata e) {
return e.getId();
}
@Override
protected AttachmentMetadata parse(Entity e) {
AttachmentId id = new AttachmentId(e.getKey().getName());
String blobKey = DatastoreUtil.getOptionalProperty(e, BLOB_KEY_PROPERTY, String.class);
if (blobKey == null) {
// For some legacy data, the attachment id is the blob key.
log.info("Legacy attachment without blob key: " + id);
blobKey = id.getId();
}
String metadata = DatastoreUtil.getExistingProperty(e, JSON_METADATA_PROPERTY, String.class);
try {
return new AttachmentMetadata(id, new BlobKey(blobKey), new JSONObject(metadata));
} catch (JSONException je) {
throw new DatastoreUtil.InvalidPropertyException(e, JSON_METADATA_PROPERTY,
"Invalid json metadata: " + metadata, je);
}
}
@Override
protected void populateEntity(AttachmentMetadata in, Entity out) {
DatastoreUtil.setNonNullIndexedProperty(
out, BLOB_KEY_PROPERTY, in.getBlobKey().getKeyString());
DatastoreUtil.setNonNullUnindexedProperty(
out, JSON_METADATA_PROPERTY, in.getMetadataJsonString());
}
@Override
protected String serializeId(AttachmentId id) {
return id.getId();
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.attachment;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.gxp.base.GxpContext;
import com.google.inject.Inject;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.gxp.UploadForm;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Displays an upload form suitable for inclusion in an iframe.
*
* We use iframes because the upload URL generated by the blobstore can only be
* used once, so the alternative would be to use an XHR to prepare the upload
* form's action each time, unecessary effort for now. In the future we could do
* a pre-emptive XHR to grab a few upload tokens in advance - I'm not sure how
* long it takes for them to expire though.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class AttachmentFormHandler extends AbstractHandler {
@Inject BlobstoreService blobstoreService;
@Inject @Flag(FlagName.ANALYTICS_ACCOUNT) String analyticsAccount;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String formAction = blobstoreService.createUploadUrl("/upload");
if (formAction == null) {
throw new RuntimeException("Null blobstore upload url");
}
UploadForm.write(resp.getWriter(), new GxpContext(req.getLocale()),
analyticsAccount, formAction);
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.attachment;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.common.base.Preconditions;
import com.google.walkaround.util.shared.Assert;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
/**
* Metadata associated with an attachment. Should not be changed for a given
* attachment, so that it can be cached indefinitely.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
// TODO(danilatos) Merge this with WalkaroundAttachment, once we have a json interface.
// Same goes for "ImageMetadata"
// TODO(danilatos) Consider using a proto-based implementation?
public class AttachmentMetadata implements Serializable {
private static final long serialVersionUID = 562560590763783822L;
public interface ImageMetadata {
public int getWidth();
public int getHeight();
}
private final AttachmentId id;
private final BlobKey blobKey;
// String for Serializable
private final String rawMetadata;
// Parsed version of rawMetadata.
private transient JSONObject maybeMetadata;
public AttachmentMetadata(AttachmentId id, BlobKey blobKey, JSONObject metadata) {
this.id = Preconditions.checkNotNull(id, "null id");
this.blobKey = Preconditions.checkNotNull(blobKey, "null blobKey");
this.maybeMetadata = Preconditions.checkNotNull(metadata, "null metadata");
this.rawMetadata = metadata.toString();
}
@Override
public String toString() {
return "AttachmentMetadata(" + id + ", " + blobKey + ", " + rawMetadata + ")";
}
public AttachmentId getId() {
return id;
}
public BlobKey getBlobKey() {
return blobKey;
}
private JSONObject getMetadata() {
if (maybeMetadata == null) {
Assert.check(rawMetadata != null, "rawMetadata is null");
try {
maybeMetadata = new JSONObject(rawMetadata);
} catch (JSONException e) {
throw new RuntimeException("Bad JSON: " + rawMetadata, e);
}
}
return maybeMetadata;
}
public String getMetadataJsonString() {
return rawMetadata;
}
public ImageMetadata getImage() {
return createImageMetadata("image");
}
public ImageMetadata getThumbnail() {
return createImageMetadata("thumbnail");
}
private ImageMetadata createImageMetadata(String key) {
final JSONObject imgData;
try {
imgData = getMetadata().has(key) ? getMetadata().getJSONObject(key) : null;
} catch (JSONException e) {
throw new Error(e);
}
if (imgData == null) {
return null;
}
return new ImageMetadata() {
@Override public int getWidth() {
try {
return imgData.getInt("width");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
@Override public int getHeight() {
try {
return imgData.getInt("height");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
};
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.attachment;
import com.google.inject.Inject;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Serves attachments and thumbnails.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class AttachmentDownloadHandler extends AbstractHandler {
@Inject AttachmentService attachments;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
AttachmentId id = new AttachmentId(requireParameter(req, "attachment"));
if (req.getRequestURI().startsWith("/thumbnail")) {
attachments.serveThumbnail(id, req, resp);
} else {
attachments.serveDownload(id, req, resp);
}
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.attachment;
import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.google.walkaround.util.server.appengine.CheckedDatastore;
import com.google.walkaround.util.server.appengine.MemcacheTable;
import com.google.walkaround.util.server.servlet.NotFoundException;
import com.google.walkaround.util.shared.Assert;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import com.google.walkaround.wave.server.attachment.AttachmentMetadata.ImageMetadata;
import com.google.walkaround.wave.server.attachment.ThumbnailDirectory.ThumbnailData;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Facilities for dealing with attachments. Caches various results in memcache
* and the datastore.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class AttachmentService {
// Don't save thumbnails larger than 50K (entity max size is 1MB).
// They should usually be around 2-3KB each.
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(AttachmentService.class.getName());
static final int INVALID_ID_CACHE_EXPIRY_SECONDS = 600;
private static final String MEMCACHE_TAG = "AT2";
private final RawAttachmentService rawService;
private final BlobstoreService blobstore;
private final MetadataDirectory metadataDirectory;
// We cache Optional.absent() for invalid attachment ids.
private final MemcacheTable<AttachmentId, Optional<AttachmentMetadata>> metadataCache;
private final ThumbnailDirectory thumbnailDirectory;
private final int maxThumbnailSavedSizeBytes;
@Inject
public AttachmentService(RawAttachmentService rawService, BlobstoreService blobStore,
CheckedDatastore datastore, MemcacheTable.Factory memcacheFactory,
@Flag(FlagName.MAX_THUMBNAIL_SAVED_SIZE_BYTES) int maxThumbnailSavedSizeBytes) {
this.rawService = rawService;
this.blobstore = blobStore;
this.metadataDirectory = new MetadataDirectory(datastore);
this.metadataCache = memcacheFactory.create(MEMCACHE_TAG);
this.thumbnailDirectory = new ThumbnailDirectory(datastore);
this.maxThumbnailSavedSizeBytes = maxThumbnailSavedSizeBytes;
}
/**
* Checks if the browser has the data cached.
* @return true if it was, and there's nothing more to do in serving this request.
*/
private boolean maybeCached(HttpServletRequest req, HttpServletResponse resp, String context) {
// Attachments are immutable, so we don't need to check the date.
// If the id was previously requested and yielded a 404, the browser shouldn't be
// using this header.
String ifModifiedSinceStr = req.getHeader("If-Modified-Since");
if (ifModifiedSinceStr != null) {
log.info("Telling browser to use cached attachment (" + context + ")");
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return true;
}
return false;
}
/**
* Serves the attachment with cache control.
*
* @param req Only used to check the If-Modified-Since header.
*/
public void serveDownload(AttachmentId id,
HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (maybeCached(req, resp, "download, id=" + id)) {
return;
}
AttachmentMetadata metadata = getMetadata(id);
if (metadata == null) {
throw NotFoundException.withInternalMessage("Attachment id unknown: " + id);
}
BlobKey key = metadata.getBlobKey();
BlobInfo info = new BlobInfoFactory().loadBlobInfo(key);
String disposition = "attachment; filename=\""
// TODO(ohler): Investigate what escaping we need here, and whether the
// blobstore service has already done some escaping that we need to undo
// (it seems to do percent-encoding on " characters).
+ info.getFilename().replace("\"", "\\\"").replace("\\", "\\\\")
+ "\"";
log.info("Serving " + info + " with Content-Disposition: " + disposition);
resp.setHeader("Content-Disposition", disposition);
blobstore.serve(key, resp);
}
public Void serveThumbnail(AttachmentId id,
HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (maybeCached(req, resp, "thumbnail, id=" + id)) {
return null;
}
AttachmentMetadata metadata = getMetadata(id);
if (metadata == null) {
throw NotFoundException.withInternalMessage("Attachment id unknown: " + id);
}
BlobKey key = metadata.getBlobKey();
// TODO(danilatos): Factor out some of this code into a separate method so that
// thumbnails can be eagerly created at upload time.
ThumbnailData thumbnail = thumbnailDirectory.getWithoutTx(key);
if (thumbnail == null) {
log.info("Generating and storing thumbnail for " + key);
ImageMetadata thumbDimensions = metadata.getThumbnail();
if (thumbDimensions == null) {
// TODO(danilatos): Provide a default thumbnail
throw NotFoundException.withInternalMessage("No thumbnail available for attachment " + id);
}
byte[] thumbnailBytes = rawService.getResizedImageBytes(key,
thumbDimensions.getWidth(), thumbDimensions.getHeight());
thumbnail = new ThumbnailData(key, thumbnailBytes);
if (thumbnailBytes.length > maxThumbnailSavedSizeBytes) {
log.warning("Thumbnail for " + key + " too large to store " +
"(" + thumbnailBytes.length + " bytes)");
// TODO(danilatos): Cache this condition in memcache.
throw NotFoundException.withInternalMessage("Thumbnail too large for attachment " + id);
}
thumbnailDirectory.getOrAdd(thumbnail);
} else {
log.info("Using already stored thumbnail for " + key);
}
// TODO(danilatos): Other headers for mime type, fileName + "Thumbnail", etc?
resp.getOutputStream().write(thumbnail.getBytes());
return null;
}
@Nullable public AttachmentMetadata getMetadata(AttachmentId id) throws IOException {
Preconditions.checkNotNull(id, "Null id");
Map<AttachmentId, Optional<AttachmentMetadata>> result =
getMetadata(ImmutableList.of(id), null);
return result.get(id).isPresent() ? result.get(id).get() : null;
}
/**
* @param maxTimeMillis Maximum time to take. -1 for indefinite. If the time
* runs out, some data may not be returned, so the resulting map may
* be missing some of the input ids. Callers may retry to get the
* remaining data for the missing ids.
*
* @return a map of input id to attachment metadata for each id. invalid ids
* will map to Optional.absent(). Some ids may be missing due to the time limit.
*
* At least one id is guaranteed to be returned.
*/
public Map<AttachmentId, Optional<AttachmentMetadata>> getMetadata(List<AttachmentId> ids,
@Nullable Long maxTimeMillis) throws IOException {
Stopwatch stopwatch = new Stopwatch().start();
Map<AttachmentId, Optional<AttachmentMetadata>> result = Maps.newHashMap();
for (AttachmentId id : ids) {
// TODO(danilatos): To optimise, re-arrange the code so that
// 1. Query all the ids from memcache in one go
// 2. Those that failed, query all remaining ids from the data store in one go
// 3. Finally, query all remaining ids from the raw service in one go (the
// raw service api should be changed to accept a list, and it needs to
// query the __BlobInfo__ entities directly.
Optional<AttachmentMetadata> metadata = metadataCache.get(id);
if (metadata == null) {
AttachmentMetadata storedMetadata = metadataDirectory.getWithoutTx(id);
if (storedMetadata != null) {
metadata = Optional.of(storedMetadata);
metadataCache.put(id, metadata);
} else {
metadata = Optional.absent();
metadataCache.put(id, metadata,
Expiration.byDeltaSeconds(INVALID_ID_CACHE_EXPIRY_SECONDS),
MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
}
}
Assert.check(metadata != null, "Null metadata");
result.put(id, metadata);
if (maxTimeMillis != null && stopwatch.elapsedMillis() > maxTimeMillis) {
break;
}
}
Assert.check(!result.isEmpty(), "Should return at least one id");
return result;
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server;
import com.google.appengine.api.users.User;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Stage;
import com.google.inject.multibindings.MapBinder;
import com.google.inject.name.Names;
import com.google.inject.servlet.ServletModule;
import com.google.inject.util.Modules;
import com.google.walkaround.slob.server.SlobFacilities;
import com.google.walkaround.wave.server.auth.StableUserId;
import com.google.walkaround.wave.server.conv.ConvStore;
import com.google.walkaround.wave.server.conv.ConvStoreModule;
import com.google.walkaround.wave.server.udw.UdwStore;
import com.google.walkaround.wave.server.udw.UdwStoreModule;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.lang.annotation.Annotation;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import javax.servlet.Filter;
/**
* @author ohler@google.com (Christian Ohler)
*/
public class GuiceSetup {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(GuiceSetup.class.getName());
private static final LinkedHashSet<Module> extraModules = Sets.newLinkedHashSet();
private static final LinkedHashSet<ServletModule> extraServletModules = Sets.newLinkedHashSet();
private static final LinkedHashSet<Filter> extraFilters = Sets.newLinkedHashSet();
/** Hacky hook to add extra modules. */
public static void addExtraModule(Module m) {
extraModules.add(m);
}
/** Hacky hook to add extra servlet modules. */
public static void addExtraServletModule(ServletModule m) {
extraServletModules.add(m);
}
/** Hacky hook to add extra filters. */
public static void addExtraFilter(Filter f) {
extraFilters.add(f);
}
public static Module getRootModule() {
return getRootModule("WEB-INF");
}
public static Module getRootModule(final String webinfRoot) {
return Modules.combine(
Modules.combine(extraModules),
new WalkaroundServerModule(),
new ConvStoreModule(),
new UdwStoreModule(),
new AbstractModule() {
@Override public void configure() {
bind(String.class).annotatedWith(Names.named("webinf root")).toInstance(webinfRoot);
// TODO(ohler): Find a way to create these bindings in StoreModuleHelper; but note that
// http://code.google.com/p/google-guice/wiki/Multibindings says something about
// private modules not interacting well with multibindings. I don't know if that
// refers to our situation here.
MapBinder<String, SlobFacilities> mapBinder =
MapBinder.newMapBinder(binder(), String.class, SlobFacilities.class);
for (Entry<String, Class<? extends Annotation>> entry
: ImmutableMap.of(ConvStoreModule.ROOT_ENTITY_KIND, ConvStore.class,
UdwStoreModule.ROOT_ENTITY_KIND, UdwStore.class).entrySet()) {
mapBinder.addBinding(entry.getKey())
.to(Key.get(SlobFacilities.class, entry.getValue()));
}
}
});
}
public static Module getServletModule() {
return Modules.combine(
Modules.combine(extraServletModules),
new WalkaroundServletModule(extraFilters));
}
private static <T> Provider<T> getThrowingProvider(final Class<T> clazz) {
return new Provider<T>() {
@Override public T get() {
throw new RuntimeException("Attempt to call get() on " + this);
}
@Override public String toString() {
return "ThrowingProvider(" + clazz + ")";
}
};
}
public static Module getTaskQueueTaskModule() {
return new AbstractModule() {
@Override public void configure() {
bind(User.class).toProvider(getThrowingProvider(User.class));
bind(StableUserId.class).toProvider(getThrowingProvider(StableUserId.class));
bind(ParticipantId.class).toProvider(getThrowingProvider(ParticipantId.class));
}
};
}
public static Injector getInjectorForTaskQueueTask() {
return Guice.createInjector(
// Stage.DEVELOPMENT here because this is meant to be called from
// mappers, possibly for each invocation, and the mappers probably won't
// need all singletons.
Stage.DEVELOPMENT,
getRootModule(),
getTaskQueueTaskModule());
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Stage;
import com.google.inject.servlet.GuiceServletContextListener;
/**
* @author ohler@google.com (Christian Ohler)
*/
public class ServletConfig extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(
// We use Stage.DEVELOPMENT to make start-up faster on App Engine. We
// have a test (GuiceSetupTest) that uses Stage.PRODUCTION to find
// errors. TODO(ohler): Find out if Stage.PRODUCTION combined with
// warmup requests is better.
Stage.DEVELOPMENT,
GuiceSetup.getRootModule(),
GuiceSetup.getServletModule());
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.rpc;
import com.google.common.net.UriEscapers;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.Link;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.util.ServiceException;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.auth.UserContext;
import com.google.walkaround.wave.shared.SharedConstants;
import org.waveprotocol.wave.model.util.Pair;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Serves contact information for the signed-in user.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class ContactsHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ContactsHandler.class.getName());
private final static int MAX_SIZE =
com.google.walkaround.wave.shared.ContactsService.MAX_SIZE;
private static final String FEED_URL = "https://www.google.com/m8/feeds/contacts/";
private static final String PHOTO_URL = "https://www.google.com/m8/feeds/photos/media/";
@Inject ParticipantId user;
@Inject UserContext userContext;
// Lazy because it will fail to instantiate if we don't have OAuth credentials.
@Inject Provider<ContactsService> contacts;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String encodedAddress = UriEscapers.uriEscaper().escape(user.getAddress());
if (!userContext.hasOAuthCredentials()) {
// Return an empty set of contacts; the client will show unknown avatars
// and never call PhotosHandler.
printJson(new ContactFeed(), encodedAddress, resp);
return;
}
Pair<Integer, Integer> range = getRange(req);
log.info("Fetching contacts for: " + user + ", [" + range.first + ", " + range.second + ")");
URL url = new URL(FEED_URL + encodedAddress + "/thin"
+ "?start-index=" + range.first + "&max-results=" + (range.second - range.first));
ContactFeed results;
try {
results = contacts.get().getFeed(url, ContactFeed.class);
} catch (ServiceException e) {
throw new IOException("Contact fetch failed: ", e);
}
log.info("Fetched " + results.getEntries().size() + " contacts for " + user);
// Support ?format=html for debugging.
if ("html".equals(req.getParameter("format"))) {
printHtml(results, encodedAddress, resp);
} else {
printJson(results, encodedAddress, resp);
}
}
/**
* Gets the request range, and validates it.
*/
private static Pair<Integer, Integer> getRange(HttpServletRequest req)
throws BadRequestException {
String fromStr = req.getParameter("from");
String toStr = req.getParameter("to");
int from;
int to;
try {
from = fromStr != null ? Integer.parseInt(fromStr) : 1;
to = toStr != null ? Integer.parseInt(toStr) : (from + MAX_SIZE);
} catch (NumberFormatException e) {
throw new BadRequestException("Range not numeric: " + req.getQueryString(), e);
}
if (1 > from || from > to) {
throw new BadRequestException("Invalid range: [" + from + ", " + to + ")");
}
if (to > from + MAX_SIZE) {
throw new BadRequestException(
"Range too large (max " + MAX_SIZE + "): [" + from + ", " + to + ")");
}
assert from <= to && to <= from + MAX_SIZE;
return Pair.of(from, to);
}
/**
* Prints a contact feed as pretty HTML into a servlet response. This feature
* is only for debugging.
*/
private void printHtml(ContactFeed results, String encodedAddress, HttpServletResponse resp)
throws IOException {
PrintWriter pw = resp.getWriter();
pw.println("<html>");
pw.println("<body>");
for (ContactEntry e : results.getEntries()) {
pw.println("<p>");
pw.println(
"<img src='/photos" + shortPhotoUrl(encodedAddress, e.getContactPhotoLink()) + "'>");
pw.println(e.getTitle().getPlainText());
pw.println("</p>");
}
pw.println("</body>");
pw.println("</html>");
}
/**
* Prints a contact feed as JSON into a servlet response.
*/
private void printJson(ContactFeed results, String encodedAddress, HttpServletResponse resp)
throws IOException {
// Since the fetch API is index based, this handler must return exactly one
// result per contact entry. If a contact has 0 email addresses, then an
// empty contact is returned, since without the email address, the
// information is useless. If a contact has >1 email addresses, a contact
// object based on just the first one is returned, due to the
// exactly-one-result-per-feed-entry constraint.
JsonArray res = new JsonArray();
for (ContactEntry e : results.getEntries()) {
JsonObject contact = new JsonObject();
List<Email> emails = e.getEmailAddresses();
if (!emails.isEmpty()) {
contact.add("a", new JsonPrimitive(emails.get(0).getAddress()));
contact.add("n", new JsonPrimitive(e.getTitle().getPlainText()));
contact.add("p", new JsonPrimitive(shortPhotoUrl(encodedAddress, e.getContactPhotoLink())));
}
res.add(contact);
}
resp.getWriter().print(SharedConstants.XSSI_PREFIX + "(" + res.toString() + ")");
}
/**
* Produces a possibly-shortened path for a contact's photo.
*
* @param encodedAddress url-encoded address of the viewer
* @param link contact link
*/
private String shortPhotoUrl(String encodedAddress, Link link) {
String baseUrl = PHOTO_URL + encodedAddress;
String href = link.getHref();
return href.startsWith(baseUrl) ? href.substring(baseUrl.length()) : href;
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.rpc;
import com.google.inject.Inject;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.Flag;
import com.google.walkaround.wave.server.FlagName;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
public class ClientVersionHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ClientVersionHandler.class.getName());
@Inject @Flag(FlagName.CLIENT_VERSION) private int requiredClientVersion;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String actualClientVersion = optionalParameter(req, "version", "<unknown>");
log.info("Client has version " + actualClientVersion
+ ", required version is " + requiredClientVersion);
resp.setContentType("text/plain");
resp.getWriter().print(requiredClientVersion + "");
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.rpc;
import com.google.appengine.api.urlfetch.FetchOptions;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.common.net.UriEscapers;
import com.google.inject.Inject;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.auth.OAuthedFetchService;
import com.google.walkaround.wave.server.util.ProxyHandler;
import com.google.walkaround.wave.shared.SharedConstants;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Handles photo requests by proxying them to the m8 feed.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class PhotosHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(PhotosHandler.class.getName());
private final OAuthedFetchService fetch;
@Inject
public PhotosHandler(OAuthedFetchService fetch) {
this.fetch = fetch;
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String photoId = requireParameter(req, "photoId");
// http://code.google.com/apis/contacts/docs/2.0/developers_guide_protocol.html#groups_feed_url
// says "You can also substitute 'default' for the user's email address,
// which tells the server to return the contact groups for the user whose
// credentials accompany the request". I didn't read the document in enough
// detail to check whether this is supposed to apply to photos as well, but
// it seems to work.
URL targetUrl = new URL("https://www.google.com/m8/feeds/photos/media/default/"
+ UriEscapers.uriQueryStringEscaper(false).escape(photoId));
HTTPResponse response = fetch.fetch(
new HTTPRequest(targetUrl, HTTPMethod.GET,
FetchOptions.Builder.withDefaults().disallowTruncate()));
if (response.getResponseCode() == 404) {
// Rather than a broken image, use the unknown avatar.
log.info("Missing image, using default");
resp.sendRedirect(SharedConstants.UNKNOWN_AVATAR_URL);
} else {
ProxyHandler.copyResponse(response, resp);
}
// TODO(hearnden): Do something to make the client cache photos sensibly.
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.rpc;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.wave.server.util.ProxyHandler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Handles gadget requests by proxying them to a gadget server.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class GadgetsHandler extends AbstractHandler {
/** Configured proxy. */
private final ProxyHandler delegate;
@Inject
public GadgetsHandler(
@Named("gadget serve path") String source,
@Named("gadget server") String target,
URLFetchService fetch) {
delegate = new ProxyHandler(source, target, fetch);
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
delegate.doGet(req, resp);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
delegate.doPost(req, resp);
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.rpc;
import com.google.inject.Inject;
import com.google.walkaround.proto.ServerMutateRequest;
import com.google.walkaround.proto.gson.ServerMutateRequestGsonImpl;
import com.google.walkaround.slob.server.AccessDeniedException;
import com.google.walkaround.slob.server.MutateResult;
import com.google.walkaround.slob.server.SlobStoreSelector;
import com.google.walkaround.slob.server.SlobNotFoundException;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.ObjectSession;
import com.google.walkaround.wave.server.ObjectSessionHelper;
import com.google.walkaround.wave.server.model.ServerMessageSerializer;
import com.google.walkaround.wave.server.servlet.ServletUtil;
import com.google.walkaround.wave.shared.WaveSerializer;
import org.waveprotocol.wave.model.operation.wave.WaveletOperation;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Submits a delta to a wavelet.
*
* @author ohler@google.com (Christian Ohler)
*/
public class SubmitDeltaHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(SubmitDeltaHandler.class.getName());
private static final WaveSerializer SERIALIZER =
new WaveSerializer(new ServerMessageSerializer());
@Inject SlobStoreSelector storeSelector;
@Inject ObjectSession session;
@Inject ParticipantId participantId;
private List<String> makeDeltas(long timestamp, String serializedOperationBatch) {
List<WaveletOperation> operations;
try {
operations = SERIALIZER.deserializeOperationBatch(participantId, serializedOperationBatch,
timestamp);
} catch (MessageException e) {
throw new RuntimeException(e);
}
return SERIALIZER.serializeDeltas(operations);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String versionString = requireParameter(req, "v");
long version;
try {
version = Long.parseLong(versionString);
} catch (NumberFormatException e) {
throw new RuntimeException(e);
}
long timestamp = System.currentTimeMillis();
List<String> deltas = makeDeltas(timestamp, requireParameter(req, "operations"));
ServerMutateRequest mutateRequest = new ServerMutateRequestGsonImpl();
mutateRequest.setSession(ObjectSessionHelper.protoFromObjectSession(session));
mutateRequest.setVersion(version);
mutateRequest.addAllPayload(deltas);
MutateResult res;
try {
res = storeSelector.get(session.getStoreType()).getSlobStore().mutateObject(mutateRequest);
} catch (SlobNotFoundException e) {
throw new BadRequestException("Object not found or access denied", e);
} catch (AccessDeniedException e) {
throw new BadRequestException("Object not found or access denied", e);
}
resp.setContentType("application/json");
ServletUtil.writeJsonResult(resp.getWriter(),
ServletUtil.getSubmitDeltaResultJson(res.getResultingVersion()));
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.rpc;
import com.google.inject.Inject;
import com.google.walkaround.slob.server.AccessDeniedException;
import com.google.walkaround.slob.server.SlobStoreSelector;
import com.google.walkaround.slob.server.SlobNotFoundException;
import com.google.walkaround.slob.server.SlobStore;
import com.google.walkaround.slob.server.SlobStore.ConnectResult;
import com.google.walkaround.slob.server.SlobStore.HistoryResult;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.ObjectSession;
import com.google.walkaround.wave.server.servlet.ServletUtil;
import com.google.walkaround.wave.shared.SharedConstants.Params;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Used by the client to notify the server of connection to an object at a
* specific revision, or to refresh a channel.
*
* @author danilatos@google.com (Daniel Danilatos)
*/
public class ChannelHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ChannelHandler.class.getName());
@Inject SlobStoreSelector storeSelector;
@Inject ObjectSession session;
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
inner(req, resp);
} catch (JSONException e) {
throw new Error(e);
}
}
private void inner(HttpServletRequest req, HttpServletResponse resp)
throws IOException, JSONException {
JSONObject result = new JSONObject();
SlobStore store = storeSelector.get(session.getStoreType()).getSlobStore();
try {
int revision = Integer.parseInt(requireParameter(req, Params.REVISION));
ConnectResult r = store.reconnect(session.getObjectId(), session.getClientId());
if (r.getChannelToken() != null) {
result.put("token", r.getChannelToken());
HistoryResult history = store.loadHistory(session.getObjectId(), revision, null);
result.put("history", HistoryHandler.serializeHistory(revision, history.getData()));
result.put("head", r.getVersion());
} else {
// TODO(ohler): Figure out and document how the client-server protocol
// works and what the different endpoints do. It's not clear to me why
// the above case returns history and head version (even though the
// javadoc doesn't mention this) and this case doesn't (even though it
// could).
result.put("error", "Too many concurrent connections");
}
} catch (SlobNotFoundException e) {
throw new BadRequestException("Object not found or access denied", e);
} catch (AccessDeniedException e) {
throw new BadRequestException("Object not found or access denied", e);
} catch (NumberFormatException nfe) {
throw new BadRequestException("Parse error", nfe);
}
resp.setContentType("application/json");
ServletUtil.writeJsonResult(resp.getWriter(), result.toString());
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.rpc;
import com.google.inject.Inject;
import com.google.walkaround.util.server.Util;
import com.google.walkaround.util.server.gwt.StackTraceDeobfuscator;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
public class ClientExceptionHandler extends AbstractHandler {
/**
* Represents an exception from the client.
*/
private static class ClientException extends Exception {
private static final long serialVersionUID = 276392586606896983L;
private ClientException(String className, String message, StackTraceElement[] st,
ClientException cause) {
super("(" + className + ") " + message, cause);
setStackTrace(st);
}
}
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ClientExceptionHandler.class.getName());
private final StackTraceDeobfuscator deobfuscator;
@Inject
public ClientExceptionHandler(StackTraceDeobfuscator deobfuscator) {
this.deobfuscator = deobfuscator;
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
handleData(Util.slurpUtf8(req.getInputStream()));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private void handleData(String raw) throws JSONException {
log.info("raw data: " + raw);
JSONObject data = new JSONObject(raw);
Level level = "SEVERE".equals(data.getString("level")) ? Level.SEVERE : Level.WARNING;
StringBuilder b = new StringBuilder();
b.append("[" + data.getString("stream") + ":" + data.getLong("timestamp") + "] ");
JSONArray objects = data.getJSONArray("objects");
for (int i = 0; i < objects.length(); i++) {
b.append(objects.getString(i));
}
ClientException ex = null;
if (data.has("exception")) {
ex = buildException(data.getJSONObject("exception"), data.getString("strongName"));
}
log.log(level, b.toString(), ex);
}
private ClientException buildException(JSONObject data, String strongName) throws JSONException {
ClientException cause = null;
if (data.has("cause")) {
cause = buildException(data.getJSONObject("cause"), strongName);
}
JSONArray stData = data.getJSONArray("stackTrace");
String[] st = new String[stData.length()];
for (int i = 0; i < st.length; i++) {
st[i] = stData.getString(i);
}
String exceptionConstructor = data.getString("name").replace("Class$", "");
return new ClientException(
deobfuscator.resymbolize(exceptionConstructor, strongName).getClassName()
+ "?", // NOTE(danilatos): sometimes the class name might be wrong.
data.getString("message"),
deobfuscator.deobfuscateStackTrace(st, strongName), cause);
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.rpc;
import com.google.inject.Inject;
import com.google.walkaround.slob.server.AccessDeniedException;
import com.google.walkaround.slob.server.ChangeDataSerializer;
import com.google.walkaround.slob.server.SlobStoreSelector;
import com.google.walkaround.slob.server.SlobNotFoundException;
import com.google.walkaround.slob.server.SlobStore;
import com.google.walkaround.slob.server.SlobStore.HistoryResult;
import com.google.walkaround.slob.shared.ChangeData;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.ObjectSession;
import com.google.walkaround.wave.server.servlet.ServletUtil;
import com.google.walkaround.wave.shared.SharedConstants.Params;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author danilatos@google.com (Daniel Danilatos)
*/
public class HistoryHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(HistoryHandler.class.getName());
@Inject SlobStoreSelector storeSelector;
@Inject ObjectSession session;
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
inner(req, resp);
} catch (JSONException e) {
throw new Error(e);
} catch (SlobNotFoundException e) {
throw new BadRequestException("Object not found or access denied", e);
} catch (AccessDeniedException e) {
throw new BadRequestException("Object not found or access denied", e);
}
}
private void inner(HttpServletRequest req, HttpServletResponse resp)
throws IOException, JSONException, SlobNotFoundException, AccessDeniedException {
long startVersion;
@Nullable Long endVersion;
try {
startVersion = Long.parseLong(requireParameter(req, Params.START_REVISION));
String endVersionString = req.getParameter(Params.END_REVISION);
if (endVersionString == null) {
endVersion = null;
} else {
endVersion = Long.parseLong(endVersionString);
}
} catch (NumberFormatException nfe) {
throw new BadRequestException(nfe);
}
SlobId objectId = session.getObjectId();
SlobStore store = storeSelector.get(session.getStoreType()).getSlobStore();
JSONObject result = new JSONObject();
HistoryResult history = store.loadHistory(objectId, startVersion, endVersion);
result.put("history", serializeHistory(startVersion, history.getData()));
result.put("more", history.hasMore());
resp.setContentType("application/json");
ServletUtil.writeJsonResult(resp.getWriter(), result.toString());
}
static JSONArray serializeHistory(long startVersion, List<ChangeData<String>> entries)
throws JSONException {
JSONArray history = new JSONArray();
int index = 0;
for (ChangeData<String> data : entries) {
history.put(index, ChangeDataSerializer.dataToClientJson(data, startVersion + index + 1));
index++;
}
return history;
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.rpc;
import com.google.inject.Inject;
import com.google.walkaround.proto.gson.ConnectResponseGsonImpl;
import com.google.walkaround.slob.server.AccessDeniedException;
import com.google.walkaround.slob.server.GsonProto;
import com.google.walkaround.slob.server.SlobStoreSelector;
import com.google.walkaround.slob.server.SlobNotFoundException;
import com.google.walkaround.slob.server.SlobStore.ConnectResult;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.wave.server.ObjectSession;
import com.google.walkaround.wave.server.ObjectSessionHelper;
import com.google.walkaround.wave.server.servlet.ServletUtil;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Gets current wavelet version and creates a new session. Used for
* reconnection.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ConnectHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ConnectHandler.class.getName());
@Inject SlobStoreSelector storeSelector;
@Inject ObjectSession session;
@Inject ObjectSessionHelper sessionHelper;
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
log.info("connect " + session);
ConnectResult result;
try {
result = storeSelector.get(session.getStoreType()).getSlobStore()
.reconnect(session.getObjectId(), session.getClientId());
} catch (SlobNotFoundException e) {
throw new BadRequestException("Object not found or access denied", e);
} catch (AccessDeniedException e) {
throw new BadRequestException("Object not found or access denied", e);
}
log.info("connect " + session + ": " + result);
ConnectResponseGsonImpl response = sessionHelper.createConnectResponse(session, result);
resp.setContentType("application/json");
ServletUtil.writeJsonResult(resp.getWriter(),
GsonProto.toJson(response));
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.conv;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.appengine.api.memcache.Expiration;
import com.google.common.base.Objects;
import com.google.inject.BindingAnnotation;
import com.google.inject.Inject;
import com.google.walkaround.slob.server.SlobRootEntityKind;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.appengine.MemcacheTable;
import com.google.walkaround.util.shared.Assert;
import com.google.walkaround.wave.server.auth.StableUserId;
import java.io.IOException;
import java.io.Serializable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Random;
import java.util.logging.Logger;
/**
* Retrieves permissions, with caching.
*
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class PermissionCache {
public interface PermissionSource {
/** Gets permissions for the current user. */
Permissions getPermissions(SlobId slobId) throws IOException;
}
public static final class Permissions implements Serializable {
private static final long serialVersionUID = 701252070396813298L;
// Really, canWrite > canRead, but yeah.
private final boolean canRead;
private final boolean canWrite;
public Permissions(boolean canRead, boolean canWrite) {
this.canRead = canRead;
this.canWrite = canWrite;
}
public boolean canRead() {
return canRead;
}
public boolean canWrite() {
return canWrite;
}
@Override
public String toString() {
return "Perms("
+ (canRead() ? "r" : "")
+ (canWrite() ? "w" : "")
+ ")";
}
}
private static class AccessKey implements Serializable {
private static final long serialVersionUID = 876732924768066692L;
private final StableUserId userId;
private final SlobId slobId;
public AccessKey(StableUserId userId,
SlobId slobId) {
this.userId = checkNotNull(userId, "Null userId");
this.slobId = checkNotNull(slobId, "Null slobId");
}
@Override public String toString() {
return "AccessKey(" + userId + ", " + slobId + ")";
}
@Override public final boolean equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof AccessKey)) { return false; }
AccessKey other = (AccessKey) o;
return Objects.equal(userId, other.userId)
&& Objects.equal(slobId, other.slobId);
}
@Override public final int hashCode() {
return Objects.hashCode(userId, slobId);
}
}
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(PermissionCache.class.getName());
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface PermissionCacheExpirationSeconds {}
private static final String MEMCACHE_TAG_PREFIX = "UAC-";
private final MemcacheTable<AccessKey, Permissions> memcache;
private final Random random;
private final PermissionSource source;
private final int expirationSeconds;
private final StableUserId userId;
@Inject
public PermissionCache(MemcacheTable.Factory memcacheFactory,
@SlobRootEntityKind String rootEntityKind,
Random random,
PermissionSource source,
@PermissionCacheExpirationSeconds int expirationSeconds,
StableUserId userId) {
// As long as we only use the access cache for conv wavelets, we don't need the rootEntityKind
// suffix; but this is safer if we ever reuse this code elsewhere.
this.memcache = memcacheFactory.create(MEMCACHE_TAG_PREFIX + rootEntityKind);
this.expirationSeconds = expirationSeconds;
this.source = source;
this.random = random;
this.userId = userId;
}
public Permissions getPermissions(SlobId slobId) throws IOException {
AccessKey key = new AccessKey(userId, slobId);
Permissions p = memcache.get(key);
if (p == null) {
p = source.getPermissions(slobId);
Assert.check(p != null);
memcache.put(key, p, Expiration.byDeltaSeconds(
(int) (expirationSeconds * (0.6 + 0.4 * random.nextDouble()))));
}
return p;
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.conv;
import com.google.inject.Inject;
import com.google.walkaround.slob.server.AccessChecker;
import com.google.walkaround.slob.server.AccessDeniedException;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.wave.server.conv.PermissionCache.Permissions;
import java.io.IOException;
import java.util.logging.Logger;
/**
* {@link AccessChecker} for conversation wavelets.
*
* @author ohler@google.com (Christian Ohler)
* @author danilatos@google.com (Daniel Danilatos)
*/
public class ConvAccessChecker implements AccessChecker {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ConvAccessChecker.class.getName());
private final PermissionCache permissionCache;
@Inject
public ConvAccessChecker(PermissionCache permissionCache) {
this.permissionCache = permissionCache;
}
@Override
public void checkCanRead(SlobId id) throws AccessDeniedException {
Permissions perms = getPerms(id);
if (!perms.canRead()) {
throw new AccessDeniedException("No read access to " + id + ": " + perms);
}
}
@Override
public void checkCanModify(SlobId id) throws AccessDeniedException {
Permissions perms = getPerms(id);
if (!perms.canWrite()) {
throw new AccessDeniedException("No write access to " + id + ": " + perms);
}
}
@Override
public void checkCanCreate(SlobId id) throws AccessDeniedException {
// SlobStoreImpl calls this on newObject(), but we only call that (on conv
// wavelets) through WaveletCreator.newConvWithGeneratedId(). Creation of a
// new object with a randomly-generated ID is always permitted.
}
private Permissions getPerms(SlobId objectId) {
try {
return permissionCache.getPermissions(objectId);
} catch (IOException e) {
// TODO(danilatos): Figure out a better way to handle this.
// For now, crashing should trigger the appropriate retry logic in clients.
throw new RuntimeException("Failed to get permissions for " + objectId, e);
}
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.conv;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Guice annotation for the SlobStore for conversation wavelets.
*
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface ConvStore {
}
| Java |
/*
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.conv;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.inject.Inject;
import com.google.walkaround.proto.ConvMetadata;
import com.google.walkaround.proto.gson.ConvMetadataGsonImpl;
import com.google.walkaround.slob.server.GsonProto;
import com.google.walkaround.slob.server.SlobFacilities;
import com.google.walkaround.slob.shared.MessageException;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.util.server.appengine.DatastoreUtil;
import java.util.logging.Logger;
/**
* Allows access to the non-model {@link ConvMetadata} that is stored in the
* same entity group as the slob data, but in an entity kind not under the slob
* layer's control.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ConvMetadataStore {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ConvMetadataStore.class.getName());
private static final String ENTITY_KIND = "ConvMetadata";
private static final String ENTITY_KEY = "ConvMetadata";
private static final String PROPERTY = "convMetadata";
private final SlobFacilities convSlobFacilities;
@Inject
public ConvMetadataStore(@ConvStore SlobFacilities convSlobFacilities) {
this.convSlobFacilities = convSlobFacilities;
}
private Key makeKey(SlobId convId) {
return KeyFactory.createKey(convSlobFacilities.makeRootEntityKey(convId),
ENTITY_KIND, ENTITY_KEY);
}
public ConvMetadataGsonImpl get(CheckedTransaction tx, SlobId convId)
throws PermanentFailure, RetryableFailure {
checkNotNull(tx, "Null tx");
checkNotNull(convId, "Null convId");
Entity entity = tx.get(makeKey(convId));
if (entity == null) {
log.info("No conv metadata found, using default");
return new ConvMetadataGsonImpl();
}
String metadataString =
DatastoreUtil.getExistingProperty(entity, PROPERTY, Text.class).getValue();
log.info("Found conv metadata: " + metadataString);
ConvMetadataGsonImpl metadata;
try {
metadata = GsonProto.fromGson(new ConvMetadataGsonImpl(), metadataString);
} catch (MessageException e) {
throw new RuntimeException("Failed to parse metadata: " + metadataString, e);
}
return metadata;
}
public void put(CheckedTransaction tx, SlobId convId, ConvMetadataGsonImpl metadata)
throws PermanentFailure, RetryableFailure {
checkNotNull(tx, "Null tx");
checkNotNull(convId, "Null convId");
checkNotNull(metadata, "Null metadata");
String jsonString = GsonProto.toJson(metadata);
log.info("Putting metadata: " + jsonString);
Entity entity = new Entity(makeKey(convId));
DatastoreUtil.setNonNullUnindexedProperty(entity, PROPERTY, new Text(jsonString));
tx.put(entity);
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.conv;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.inject.PrivateModule;
import com.google.inject.Provider;
import com.google.inject.multibindings.Multibinder;
import com.google.walkaround.slob.server.AccessChecker;
import com.google.walkaround.slob.server.MutateResult;
import com.google.walkaround.slob.server.PostCommitActionQueue;
import com.google.walkaround.slob.server.PostMutateHook;
import com.google.walkaround.slob.server.PreCommitAction;
import com.google.walkaround.slob.server.SlobManager;
import com.google.walkaround.slob.server.SlobManager.SlobIndexUpdate;
import com.google.walkaround.slob.server.StoreModuleHelper;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.SlobModel;
import com.google.walkaround.slob.shared.SlobModel.ReadableSlob;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.wave.server.conv.PermissionCache.PermissionSource;
import com.google.walkaround.wave.server.model.WaveObjectStoreModel;
import com.google.walkaround.wave.server.model.WaveObjectStoreModel.ReadableWaveletObject;
import com.google.walkaround.wave.server.wavemanager.WaveIndex;
import com.google.walkaround.wave.server.wavemanager.WaveManager;
import java.io.IOException;
import java.util.logging.Logger;
/**
* Guice module that configures an object store for conversation wavelets.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ConvStoreModule extends PrivateModule {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(ConvStoreModule.class.getName());
// Perhaps a better name would be "Conv", but we can't change it, for
// compatibility with existing data.
public static String ROOT_ENTITY_KIND = "Wavelet";
@Override protected void configure() {
StoreModuleHelper.makeBasicBindingsAndExposures(binder(), ConvStore.class);
StoreModuleHelper.bindEntityKinds(binder(), ROOT_ENTITY_KIND);
bind(SlobModel.class).to(WaveObjectStoreModel.class);
bind(AccessChecker.class).to(ConvAccessChecker.class);
bind(PermissionSource.class).to(WaveManager.class);
final Provider<WaveIndex> index = getProvider(WaveIndex.class);
Multibinder<PreCommitAction> preCommitActions =
Multibinder.newSetBinder(binder(), PreCommitAction.class);
preCommitActions.addBinding().toInstance(
new PreCommitAction() {
@Override public void run(CheckedTransaction tx, SlobId objectId,
long resultingVersion, ReadableSlob resultingState)
throws RetryableFailure, PermanentFailure {
// TODO(ohler): Introduce generics in SlobModel to avoid the cast.
index.get().update(tx, objectId, (ReadableWaveletObject) resultingState);
}
});
final Provider<SlobManager> manager = getProvider(SlobManager.class);
bind(PostMutateHook.class).toInstance(
new PostMutateHook() {
private String summarize(String data) {
return data.length() <= 50 ? data : (data.substring(0, 50) + "...");
}
@Override public void run(SlobId objectId, MutateResult result) {
if (result.getIndexData() != null) {
log.info("Updating index, index data is " + summarize(result.getIndexData()));
try {
manager.get().update(objectId,
new SlobIndexUpdate(result.getIndexData(), null));
} catch (IOException e) {
throw new RuntimeException("SlobManager update failed", e);
}
}
}
});
bind(Queue.class).annotatedWith(PostCommitActionQueue.class).toInstance(
QueueFactory.getQueue("post-commit-conv"));
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server.conv;
import com.google.inject.Inject;
import com.google.walkaround.slob.server.PreCommitAction;
import com.google.walkaround.slob.shared.SlobId;
import com.google.walkaround.slob.shared.SlobModel.ReadableSlob;
import com.google.walkaround.util.server.RetryHelper.PermanentFailure;
import com.google.walkaround.util.server.RetryHelper.RetryableFailure;
import com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction;
import com.google.walkaround.wave.server.model.WaveObjectStoreModel.ReadableWaveletObject;
import com.google.walkaround.wave.server.wavemanager.WaveIndex;
/**
* {@link PreCommitAction} for the conversation wavelet store.
*
* @author ohler@google.com (Christian Ohler)
*/
public class ConvPreCommitAction implements PreCommitAction {
private final WaveIndex index;
@Inject public ConvPreCommitAction(WaveIndex index) {
this.index = index;
}
@Override public void run(CheckedTransaction tx, SlobId objectId,
long resultingVersion, ReadableSlob resultingState)
throws RetryableFailure, PermanentFailure {
// TODO(ohler): Use generics to avoid the cast.
index.update(tx, objectId, (ReadableWaveletObject) resultingState);
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server;
import com.google.appengine.api.utils.SystemProperty;
import com.google.common.collect.ImmutableList;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.walkaround.util.server.MonitoringVars;
import com.google.walkaround.wave.server.gxp.SourceInstance;
import com.google.walkaround.wave.server.servlet.ServerExceptionFilter.UserTrustStatus;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.waveref.WaveRef;
import org.waveprotocol.wave.util.escapers.jvm.JavaWaverefEncoder;
import java.util.List;
import java.util.logging.Logger;
/**
* @author danilatos@google.com (Daniel Danilatos)
* @author ohler@google.com (Christian Ohler)
*/
public class DefaultModule extends AbstractModule {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(DefaultModule.class.getName());
private enum SourceInstanceImpl implements SourceInstance {
GOOGLEWAVE {
@Override public String getApiUrl() {
return "https://www-opensocial.googleusercontent.com/api/rpc";
}
@Override public String getShortName() { return "googlewave.com"; }
@Override public String getLongName() { return "googlewave.com"; }
@Override public String getWaveLink(WaveId waveId) {
return "https://wave.google.com/wave/waveref/"
+ JavaWaverefEncoder.encodeToUriPathSegment(WaveRef.of(waveId));
}
@Override public String getFullAttachmentUrl(String attachmentPath) {
return "https://wave.googleusercontent.com/wave" + attachmentPath;
}
},
WAVESANDBOX {
@Override public String getApiUrl() {
return "https://www-opensocial-sandbox.googleusercontent.com/api/rpc";
}
@Override public String getShortName() { return "wavesandbox.com"; }
@Override public String getLongName() { return "wavesandbox.com developer sandbox"; }
@Override public String getWaveLink(WaveId waveId) {
// TODO(ohler): test this
return "https://www.wavesandbox.com/wave/waveref/"
+ JavaWaverefEncoder.encodeToUriPathSegment(WaveRef.of(waveId));
}
@Override public String getFullAttachmentUrl(String attachmentPath) {
throw new RuntimeException(
"Attachment import from wavesandbox not implemented"
+ " -- please file a bug if you need this");
}
};
@Override public String serialize() {
return name();
}
}
@Override
protected void configure() {
bind(MonitoringVars.class).toInstance(MonitoringVars.NULL_IMPL);
bind(SourceInstance.Factory.class).toInstance(
new SourceInstance.Factory() {
@Override public List<? extends SourceInstance> getInstances() {
return ImmutableList.copyOf(SourceInstanceImpl.values());
}
@Override public SourceInstance parseUnchecked(String s) {
return SourceInstanceImpl.valueOf(s);
}
});
}
@Provides
UserTrustStatus provideUserTrustStatus(SystemProperty.Environment.Value systemEnvironment) {
if (systemEnvironment == SystemProperty.Environment.Value.Development) {
// Local SDK.
return UserTrustStatus.TRUSTED;
}
return UserTrustStatus.UNTRUSTED;
}
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import com.google.inject.BindingAnnotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* @author ohler@google.com (Christian Ohler)
*/
@BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
public @interface Flag {
/**
* Identifies the flag.
*/
FlagName value();
}
| Java |
/*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.walkaround.wave.server;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.utils.SystemProperty;
import com.google.appengine.tools.appstats.AppstatsFilter;
import com.google.appengine.tools.appstats.AppstatsServlet;
import com.google.appengine.tools.mapreduce.MapReduceServlet;
import com.google.common.collect.ImmutableMap;
import com.google.gdata.client.AuthTokenFactory;
import com.google.gdata.client.GoogleService.SessionExpiredException;
import com.google.gdata.client.Service.GDataRequest;
import com.google.gdata.client.Service.GDataRequest.RequestType;
import com.google.gdata.client.Service.GDataRequestFactory;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.client.http.GoogleGDataRequest;
import com.google.gdata.client.http.HttpAuthToken;
import com.google.gdata.util.ContentType;
import com.google.gdata.util.ServiceException;
import com.google.inject.Provides;
import com.google.inject.ProvisionException;
import com.google.inject.Singleton;
import com.google.inject.multibindings.MapBinder;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import com.google.inject.servlet.RequestScoped;
import com.google.inject.servlet.ServletModule;
import com.google.walkaround.slob.server.StoreModuleHelper;
import com.google.walkaround.slob.server.handler.PostCommitTaskHandler;
import com.google.walkaround.util.server.auth.InvalidSecurityTokenException;
import com.google.walkaround.util.server.servlet.AbstractHandler;
import com.google.walkaround.util.server.servlet.BadRequestException;
import com.google.walkaround.util.server.servlet.ExactPathHandlers;
import com.google.walkaround.util.server.servlet.HandlerServlet;
import com.google.walkaround.util.server.servlet.PrefixPathHandlers;
import com.google.walkaround.util.server.servlet.RedirectServlet;
import com.google.walkaround.util.server.servlet.RequestStatsFilter;
import com.google.walkaround.wave.server.admin.AdminHandler;
import com.google.walkaround.wave.server.admin.BuildinfoHandler;
import com.google.walkaround.wave.server.admin.ClearMemcacheHandler;
import com.google.walkaround.wave.server.admin.FlagsHandler;
import com.google.walkaround.wave.server.admin.StoreViewHandler;
import com.google.walkaround.wave.server.attachment.AttachmentDownloadHandler;
import com.google.walkaround.wave.server.attachment.AttachmentFormHandler;
import com.google.walkaround.wave.server.attachment.AttachmentMetadataHandler;
import com.google.walkaround.wave.server.attachment.AttachmentUploadHandler;
import com.google.walkaround.wave.server.auth.DeleteOAuthTokenHandler;
import com.google.walkaround.wave.server.auth.InteractiveAuthFilter;
import com.google.walkaround.wave.server.auth.OAuthCallbackHandler;
import com.google.walkaround.wave.server.auth.OAuthCredentials;
import com.google.walkaround.wave.server.auth.OAuthInterstitialHandler;
import com.google.walkaround.wave.server.auth.OAuthInterstitialHandler.CallbackPath;
import com.google.walkaround.wave.server.auth.OAuthRequestHelper;
import com.google.walkaround.wave.server.auth.RpcAuthFilter;
import com.google.walkaround.wave.server.auth.StableUserId;
import com.google.walkaround.wave.server.auth.UserContext;
import com.google.walkaround.wave.server.auth.XsrfHelper.XsrfTokenExpiredException;
import com.google.walkaround.wave.server.googleimport.ImportOverviewHandler;
import com.google.walkaround.wave.server.googleimport.ImportTaskHandler;
import com.google.walkaround.wave.server.googleimport.RobotApi;
import com.google.walkaround.wave.server.rpc.ChannelHandler;
import com.google.walkaround.wave.server.rpc.ClientExceptionHandler;
import com.google.walkaround.wave.server.rpc.ClientVersionHandler;
import com.google.walkaround.wave.server.rpc.ConnectHandler;
import com.google.walkaround.wave.server.rpc.ContactsHandler;
import com.google.walkaround.wave.server.rpc.GadgetsHandler;
import com.google.walkaround.wave.server.rpc.HistoryHandler;
import com.google.walkaround.wave.server.rpc.PhotosHandler;
import com.google.walkaround.wave.server.rpc.SubmitDeltaHandler;
import com.google.walkaround.wave.server.servlet.LogoutHandler;
import com.google.walkaround.wave.server.servlet.LogoutHandler.SelfClosingPageHandler;
import com.google.walkaround.wave.server.servlet.ServerExceptionFilter;
import com.google.walkaround.wave.server.servlet.StoreMutateHandler;
import com.google.walkaround.wave.server.servlet.UndercurrentHandler;
import com.google.walkaround.wave.server.wavemanager.InboxHandler;
import com.google.walkaround.wave.shared.SharedConstants.Services;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
/**
* @author ohler@google.com (Christian Ohler)
*/
public class WalkaroundServletModule extends ServletModule {
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(WalkaroundServletModule.class.getName());
// NOTE(danilatos): The callback path is displayed in the oauth permission
// dialog, so we're using something that sounds legitimate and secure
// (e.g. the suggested "oauth2callback" might be a bit odd to users).
private static final String OAUTH2_CALLBACK_PATH = "authenticate";
public static final String IMPORT_TASK_PATH = "/taskqueue/import";
static final String POST_COMMIT_TASK_PATH = "/taskqueue/postcommit";
/** Path bindings for handlers that serve exact paths only. */
private static final ImmutableMap<String, Class<? extends AbstractHandler>> EXACT_PATH_HANDLERS =
new ImmutableMap.Builder<String, Class<? extends AbstractHandler>>()
// Pages that browsers will navigate to.
.put("/inbox", InboxHandler.class)
.put("/wave", UndercurrentHandler.class)
.put("/logout", LogoutHandler.class)
.put("/switchSuccess", SelfClosingPageHandler.class)
.put("/enable", OAuthInterstitialHandler.class)
.put("/noauth", DeleteOAuthTokenHandler.class)
.put("/" + OAUTH2_CALLBACK_PATH, OAuthCallbackHandler.class)
// Endpoints for RPCs etc.
.put("/" + Services.CHANNEL, ChannelHandler.class)
.put("/" + Services.CONNECT, ConnectHandler.class)
.put("/" + Services.HISTORY, HistoryHandler.class)
.put("/" + Services.SUBMIT_DELTA, SubmitDeltaHandler.class)
.put("/contacts", ContactsHandler.class)
.put("/version", ClientVersionHandler.class)
.put("/photos", PhotosHandler.class)
.put("/gwterr", ClientExceptionHandler.class)
// Other stuff.
.put("/upload", AttachmentUploadHandler.class)
.put("/uploadform", AttachmentFormHandler.class)
.put("/download", AttachmentDownloadHandler.class)
.put("/thumbnail", AttachmentDownloadHandler.class)
.put("/attachmentinfo", AttachmentMetadataHandler.class)
.put("/admin", AdminHandler.class)
.put("/admin/buildinfo", BuildinfoHandler.class)
.put("/admin/clearmemcache", ClearMemcacheHandler.class)
.put("/admin/flags", FlagsHandler.class)
.put("/admin/storeview", StoreViewHandler.class)
// Backend servers. Could potentially use a separate Guice module.
.put("/store/mutate", StoreMutateHandler.class)
// Slob task queue stuff.
.put(POST_COMMIT_TASK_PATH, PostCommitTaskHandler.class)
// Import stuff. Should probably also be in a separate Guice module.
.put("/import", ImportOverviewHandler.class)
.put(IMPORT_TASK_PATH, ImportTaskHandler.class)
.build();
/** Path bindings for handlers that serve all paths under some prefix. */
private static final ImmutableMap<String, Class<? extends AbstractHandler>> PREFIX_PATH_HANDLERS =
new ImmutableMap.Builder<String, Class<? extends AbstractHandler>>()
.put("/gadgets", GadgetsHandler.class)
.build();
/** Checks that there are no conflicts between paths in the handler maps. */
private static void validatePaths() {
for (String prefix : PREFIX_PATH_HANDLERS.keySet()) {
for (String exact : EXACT_PATH_HANDLERS.keySet()) {
if (exact.startsWith(prefix)) {
throw new AssertionError(
"Handler conflict between prefix path " + prefix + " and exact path " + exact);
}
}
for (String otherPrefix : PREFIX_PATH_HANDLERS.keySet()) {
if (!otherPrefix.equals(prefix) && otherPrefix.startsWith(prefix)) {
throw new AssertionError(
"Handler conflict between prefix path " + prefix + " and prefix path " + otherPrefix);
}
}
}
}
private final Iterable<? extends Filter> extraFilters;
public WalkaroundServletModule(Iterable<? extends Filter> extraFilters) {
this.extraFilters = extraFilters;
}
@Provides @CallbackPath
String provideOauthCallbackPath(@Named("wave url base") String base) {
return base + OAUTH2_CALLBACK_PATH;
}
@Override protected void configureServlets() {
if (SystemProperty.environment.value() != SystemProperty.Environment.Value.Development) {
// Doesn't work in local dev server mode.
filter("*").through(AppstatsFilter.class, ImmutableMap.of("basePath", "/admin/appstats/"));
}
filter("*").through(ServerExceptionFilter.class);
// We want appstats and ServerExceptionFilter as the outermost layers. We
// use the extraFilters hook for monitoring, so it has to be before
// RequestStatsFilter; that means it has to be here. Other uses might need
// additional hooks to put filters elsewhere (e.g. after authentication).
for (Filter f : extraFilters) {
filter("*").through(f);
}
filter("*").through(RequestStatsFilter.class);
serve("/").with(new RedirectServlet("/inbox"));
serve("/admin/").with(new RedirectServlet("/admin"));
serve("/import/").with(new RedirectServlet("/import"));
serve("/admin/mapreduce").with(new RedirectServlet("/admin/mapreduce/status"));
serve("/admin/mapreduce/").with(new RedirectServlet("/admin/mapreduce/status"));
bind(String.class).annotatedWith(Names.named("gadget serve path")).toInstance("/gadgets");
bind(String.class).annotatedWith(Names.named("gadget server")).toInstance(
"http://gmodules.com/gadgets");
install(StoreModuleHelper.factoryModule(RobotApi.Factory.class, RobotApi.class));
// All of the exact paths in EXACT_PATH_HANDLERS, and all the path prefixes
// from PREFIX_PATH_HANDLERS, are served with HandlerServlet.
validatePaths();
{
MapBinder<String, AbstractHandler> exactPathBinder =
MapBinder.newMapBinder(binder(),
String.class, AbstractHandler.class, ExactPathHandlers.class);
for (Map.Entry<String, Class<? extends AbstractHandler>> e : EXACT_PATH_HANDLERS.entrySet()) {
serve(e.getKey()).with(HandlerServlet.class);
exactPathBinder.addBinding(e.getKey()).to(e.getValue());
}
}
{
MapBinder<String, AbstractHandler> prefixPathBinder =
MapBinder.newMapBinder(binder(),
String.class, AbstractHandler.class, PrefixPathHandlers.class);
for (Map.Entry<String, Class<? extends AbstractHandler>> e
: PREFIX_PATH_HANDLERS.entrySet()) {
serve(e.getKey() + "/*").with(HandlerServlet.class);
prefixPathBinder.addBinding(e.getKey()).to(e.getValue());
}
}
bind(AppstatsFilter.class).in(Singleton.class);
bind(AppstatsServlet.class).in(Singleton.class);
serve("/admin/appstats*").with(AppstatsServlet.class);
bind(MapReduceServlet.class).in(Singleton.class);
serve("/admin/mapreduce/*").with(MapReduceServlet.class);
for (String path : Arrays.asList(
"/inbox", "/noauth", "/wave", "/import")) {
filter(path).through(InteractiveAuthFilter.class);
}
for (String path : Arrays.asList(
"/connect", "/submitdelta", "/channel", "/history", "/contacts", "/photos")) {
filter(path).through(RpcAuthFilter.class);
}
}
// RequestScoped because it involves parsing and crypto, so we want it cached.
@Provides @RequestScoped
ObjectSession provideVerifiedSession(ObjectSessionHelper helper, HttpServletRequest req) {
try {
return helper.getVerifiedSession(req);
} catch (InvalidSecurityTokenException e) {
throw new BadRequestException(e);
} catch (XsrfTokenExpiredException e) {
throw new BadRequestException(e);
}
}
// RequestScoped because we don't know how efficient it is, so we want it cached.
@Provides @RequestScoped
User provideAppengineUser(UserService userService) {
User user = userService.getCurrentUser();
if (user == null) {
throw new ProvisionException("Not logged in");
}
return user;
}
@Provides
StableUserId provideStableUserId(UserContext context) {
return context.getUserId();
}
@Provides
ParticipantId provideParticipantId(UserContext context) {
return context.getParticipantId();
}
@Provides
OAuthCredentials provideOAuthCredentials(UserContext context) {
return context.getOAuthCredentials();
}
@Provides
ContactsService provideContactService(
@Flag(FlagName.OAUTH_CLIENT_ID) String clientId,
final OAuthRequestHelper helper) {
final HttpAuthToken authToken = new HttpAuthToken() {
@Override public String getAuthorizationHeader(URL requestUrl, String requestMethod) {
log.info("getAuthorizationHeader(" + requestUrl + ", " + requestMethod + ") = "
+ helper.getAuthorizationHeaderValue());
return helper.getAuthorizationHeaderValue();
}
};
GDataRequestFactory factory = new GoogleGDataRequest.Factory() {
@Override protected GDataRequest createRequest(RequestType type, URL requestUrl,
ContentType contentType) throws IOException, ServiceException {
return new GoogleGDataRequest(type, requestUrl, contentType, authToken,
headerMap, privateHeaderMap, connectionSource) {
// Superclass method barfs with a NullPointerException because it
// expects a WWW-Authenticate header that isn't there, so override
// it.
@Override protected void handleErrorResponse() throws ServiceException, IOException {
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new SessionExpiredException("Got response code " + httpConn.getResponseCode()
+ ", token has probably expired");
}
super.handleErrorResponse();
}
};
}
};
factory.setAuthToken(authToken);
ContactsService contacts = new ContactsService(clientId,
factory,
new AuthTokenFactory() {
@Override public AuthToken getAuthToken() {
log.info("getAuthToken()");
return authToken;
}
@Override public void handleSessionExpiredException(SessionExpiredException expired) {
// Let's not log the stack trace, the exception is usually harmless.
log.log(Level.INFO, "Session expired: " + expired);
try {
helper.refreshToken();
} catch (IOException e) {
throw new RuntimeException("IOException refreshing token", e);
}
}
});
return contacts;
}
// RequestScoped because it involves parsing and string construction, so we want it cached.
@Provides @RequestScoped @Named("wave url base")
String provideWaveUrlBase(HttpServletRequest req) throws MalformedURLException {
URL requestUrl = new URL(req.getRequestURL().toString());
String portString = requestUrl.getPort() == -1 ? "" : ":" + requestUrl.getPort();
String waveUrlBase = requestUrl.getProtocol() + "://" + requestUrl.getHost() + portString + "/";
log.info("requestUrl=" + requestUrl + ", waveUrlBase=" + waveUrlBase);
return waveUrlBase;
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DeleteInstancesListener;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.DeleteInstancesTask;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
/**
* Responsible for displaying and deleting all the valid forms in the forms
* directory.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class DataManagerList extends ListActivity implements
DeleteInstancesListener {
private static final String t = "DataManagerList";
private AlertDialog mAlertDialog;
private Button mDeleteButton;
private Button mToggleButton;
private SimpleCursorAdapter mInstances;
private ArrayList<Long> mSelected = new ArrayList<Long>();
DeleteInstancesTask mDeleteInstancesTask = null;
private static final String SELECTED = "selected";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data_manage_list);
mDeleteButton = (Button) findViewById(R.id.delete_button);
mDeleteButton.setText(getString(R.string.delete_file));
mDeleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logAction(this, "deleteButton", Integer.toString(mSelected.size()));
if (mSelected.size() > 0) {
createDeleteInstancesDialog();
} else {
Toast.makeText(getApplicationContext(),
R.string.noselect_error, Toast.LENGTH_SHORT).show();
}
}
});
mToggleButton = (Button) findViewById(R.id.toggle_button);
mToggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean checkAll = false;
// if everything is checked, uncheck
if (mSelected.size() == mInstances.getCount()) {
checkAll = false;
mSelected.clear();
mDeleteButton.setEnabled(false);
} else {
// otherwise check everything
checkAll = true;
for (int pos = 0; pos < DataManagerList.this.getListView().getCount(); pos++) {
Long id = getListAdapter().getItemId(pos);
if (!mSelected.contains(id)) {
mSelected.add(id);
}
}
mDeleteButton.setEnabled(true);
}
for (int pos = 0; pos < DataManagerList.this.getListView().getCount(); pos++) {
DataManagerList.this.getListView().setItemChecked(pos, checkAll);
}
}
});
Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, null, null,
InstanceColumns.DISPLAY_NAME + " ASC");
String[] data = new String[] { InstanceColumns.DISPLAY_NAME,
InstanceColumns.DISPLAY_SUBTEXT };
int[] view = new int[] { R.id.text1, R.id.text2 };
mInstances = new SimpleCursorAdapter(this,
R.layout.two_item_multiple_choice, c, data, view);
setListAdapter(mInstances);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setItemsCanFocus(false);
mDeleteButton.setEnabled(false);
mDeleteInstancesTask = (DeleteInstancesTask) getLastNonConfigurationInstance();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
public Object onRetainNonConfigurationInstance() {
// pass the tasks on orientation-change restart
return mDeleteInstancesTask;
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
long[] selectedArray = savedInstanceState.getLongArray(SELECTED);
for (int i = 0; i < selectedArray.length; i++) {
mSelected.add(selectedArray[i]);
}
mDeleteButton.setEnabled(selectedArray.length > 0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
long[] selectedArray = new long[mSelected.size()];
for (int i = 0; i < mSelected.size(); i++) {
selectedArray[i] = mSelected.get(i);
}
outState.putLongArray(SELECTED, selectedArray);
}
@Override
protected void onResume() {
// hook up to receive completion events
if (mDeleteInstancesTask != null) {
mDeleteInstancesTask.setDeleteListener(this);
}
super.onResume();
// async task may have completed while we were reorienting...
if (mDeleteInstancesTask != null
&& mDeleteInstancesTask.getStatus() == AsyncTask.Status.FINISHED) {
deleteComplete(mDeleteInstancesTask.getDeleteCount());
}
}
@Override
protected void onPause() {
if (mDeleteInstancesTask != null ) {
mDeleteInstancesTask.setDeleteListener(null);
}
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
super.onPause();
}
/**
* Create the instance delete dialog
*/
private void createDeleteInstancesDialog() {
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(getString(R.string.delete_file));
mAlertDialog.setMessage(getString(R.string.delete_confirm,
mSelected.size()));
DialogInterface.OnClickListener dialogYesNoListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // delete
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "delete");
deleteSelectedInstances();
break;
case DialogInterface.BUTTON2: // do nothing
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteInstancesDialog", "cancel");
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.delete_yes),
dialogYesNoListener);
mAlertDialog.setButton2(getString(R.string.delete_no),
dialogYesNoListener);
mAlertDialog.show();
}
/**
* Deletes the selected files. Content provider handles removing the files
* from the filesystem.
*/
private void deleteSelectedInstances() {
if (mDeleteInstancesTask == null) {
mDeleteInstancesTask = new DeleteInstancesTask();
mDeleteInstancesTask.setContentResolver(getContentResolver());
mDeleteInstancesTask.setDeleteListener(this);
mDeleteInstancesTask.execute(mSelected.toArray(new Long[mSelected
.size()]));
} else {
Toast.makeText(this, getString(R.string.file_delete_in_progress),
Toast.LENGTH_LONG).show();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// get row id from db
Cursor c = (Cursor) getListAdapter().getItem(position);
long k = c.getLong(c.getColumnIndex(InstanceColumns._ID));
// add/remove from selected list
if (mSelected.contains(k))
mSelected.remove(k);
else
mSelected.add(k);
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", Long.toString(k));
mDeleteButton.setEnabled(!(mSelected.size() == 0));
}
@Override
public void deleteComplete(int deletedInstances) {
Log.i(t, "Delete instances complete");
Collect.getInstance().getActivityLogger().logAction(this, "deleteComplete", Integer.toString(deletedInstances));
if (deletedInstances == mSelected.size()) {
// all deletes were successful
Toast.makeText(this,
getString(R.string.file_deleted_ok, deletedInstances),
Toast.LENGTH_SHORT).show();
} else {
// had some failures
Log.e(t, "Failed to delete "
+ (mSelected.size() - deletedInstances) + " instances");
Toast.makeText(
this,
getString(R.string.file_deleted_error, mSelected.size()
- deletedInstances, mSelected.size()),
Toast.LENGTH_LONG).show();
}
mDeleteInstancesTask = null;
mSelected.clear();
getListView().clearChoices(); // doesn't unset the checkboxes
for ( int i = 0 ; i < getListView().getCount() ; ++i ) {
getListView().setItemChecked(i, false);
}
mDeleteButton.setEnabled(false);
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DeleteFormsListener;
import org.odk.collect.android.listeners.DiskSyncListener;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.tasks.DeleteFormsTask;
import org.odk.collect.android.tasks.DiskSyncTask;
import org.odk.collect.android.utilities.VersionHidingCursorAdapter;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
/**
* Responsible for displaying and deleting all the valid forms in the forms
* directory.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class FormManagerList extends ListActivity implements DiskSyncListener,
DeleteFormsListener {
private static String t = "FormManagerList";
private static final String SELECTED = "selected";
private static final String syncMsgKey = "syncmsgkey";
private AlertDialog mAlertDialog;
private Button mDeleteButton;
private Button mToggleButton;
private SimpleCursorAdapter mInstances;
private ArrayList<Long> mSelected = new ArrayList<Long>();
static class BackgroundTasks {
DiskSyncTask mDiskSyncTask = null;
DeleteFormsTask mDeleteFormsTask = null;
BackgroundTasks() {
};
}
BackgroundTasks mBackgroundTasks; // handed across orientation changes
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.form_manage_list);
mDeleteButton = (Button) findViewById(R.id.delete_button);
mDeleteButton.setText(getString(R.string.delete_file));
mDeleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logAction(this, "deleteButton", Integer.toString(mSelected.size()));
if (mSelected.size() > 0) {
createDeleteFormsDialog();
} else {
Toast.makeText(getApplicationContext(),
R.string.noselect_error, Toast.LENGTH_SHORT).show();
}
}
});
mToggleButton = (Button) findViewById(R.id.toggle_button);
mToggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
boolean checkAll = false;
// if everything is checked, uncheck
if (mSelected.size() == mInstances.getCount()) {
checkAll = false;
mSelected.clear();
mDeleteButton.setEnabled(false);
} else {
// otherwise check everything
checkAll = true;
for (int pos = 0; pos < FormManagerList.this.getListView().getCount(); pos++) {
Long id = getListAdapter().getItemId(pos);
if (!mSelected.contains(id)) {
mSelected.add(id);
}
}
mDeleteButton.setEnabled(true);
}
for (int pos = 0; pos < FormManagerList.this.getListView().getCount(); pos++) {
FormManagerList.this.getListView().setItemChecked(pos, checkAll);
}
}
});
String sortOrder = FormsColumns.DISPLAY_NAME + " ASC, " + FormsColumns.JR_VERSION + " DESC";
Cursor c = managedQuery(FormsColumns.CONTENT_URI, null, null, null, sortOrder);
String[] data = new String[] { FormsColumns.DISPLAY_NAME,
FormsColumns.DISPLAY_SUBTEXT, FormsColumns.JR_VERSION };
int[] view = new int[] { R.id.text1, R.id.text2, R.id.text3 };
// render total instance view
mInstances = new VersionHidingCursorAdapter(FormsColumns.JR_VERSION, this,
R.layout.two_item_multiple_choice, c, data, view);
setListAdapter(mInstances);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setItemsCanFocus(false);
mDeleteButton.setEnabled(!(mSelected.size() == 0));
if (savedInstanceState != null
&& savedInstanceState.containsKey(syncMsgKey)) {
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setText(savedInstanceState.getString(syncMsgKey));
}
mBackgroundTasks = (BackgroundTasks) getLastNonConfigurationInstance();
if (mBackgroundTasks == null) {
mBackgroundTasks = new BackgroundTasks();
mBackgroundTasks.mDiskSyncTask = new DiskSyncTask();
mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(this);
mBackgroundTasks.mDiskSyncTask.execute((Void[]) null);
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
public Object onRetainNonConfigurationInstance() {
// pass the tasks on restart
return mBackgroundTasks;
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
long[] selectedArray = savedInstanceState.getLongArray(SELECTED);
for (int i = 0; i < selectedArray.length; i++) {
mSelected.add(selectedArray[i]);
}
mDeleteButton.setEnabled(selectedArray.length > 0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
long[] selectedArray = new long[mSelected.size()];
for (int i = 0; i < mSelected.size(); i++) {
selectedArray[i] = mSelected.get(i);
}
outState.putLongArray(SELECTED, selectedArray);
TextView tv = (TextView) findViewById(R.id.status_text);
outState.putString(syncMsgKey, tv.getText().toString());
}
@Override
protected void onResume() {
// hook up to receive completion events
mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(this);
if (mBackgroundTasks.mDeleteFormsTask != null) {
mBackgroundTasks.mDeleteFormsTask.setDeleteListener(this);
}
super.onResume();
// async task may have completed while we were reorienting...
if (mBackgroundTasks.mDiskSyncTask.getStatus() == AsyncTask.Status.FINISHED) {
SyncComplete(mBackgroundTasks.mDiskSyncTask.getStatusMessage());
}
if (mBackgroundTasks.mDeleteFormsTask != null
&& mBackgroundTasks.mDeleteFormsTask.getStatus() == AsyncTask.Status.FINISHED) {
deleteComplete(mBackgroundTasks.mDeleteFormsTask.getDeleteCount());
}
}
@Override
protected void onPause() {
mBackgroundTasks.mDiskSyncTask.setDiskSyncListener(null);
if (mBackgroundTasks.mDeleteFormsTask != null ) {
mBackgroundTasks.mDeleteFormsTask.setDeleteListener(null);
}
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
super.onPause();
}
/**
* Create the form delete dialog
*/
private void createDeleteFormsDialog() {
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(getString(R.string.delete_file));
mAlertDialog.setMessage(getString(R.string.delete_confirm,
mSelected.size()));
DialogInterface.OnClickListener dialogYesNoListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // delete
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "delete");
deleteSelectedForms();
break;
case DialogInterface.BUTTON2: // do nothing
Collect.getInstance().getActivityLogger().logAction(this, "createDeleteFormsDialog", "cancel");
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.delete_yes),
dialogYesNoListener);
mAlertDialog.setButton2(getString(R.string.delete_no),
dialogYesNoListener);
mAlertDialog.show();
}
/**
* Deletes the selected files.First from the database then from the file
* system
*/
private void deleteSelectedForms() {
// only start if no other task is running
if (mBackgroundTasks.mDeleteFormsTask == null) {
mBackgroundTasks.mDeleteFormsTask = new DeleteFormsTask();
mBackgroundTasks.mDeleteFormsTask
.setContentResolver(getContentResolver());
mBackgroundTasks.mDeleteFormsTask.setDeleteListener(this);
mBackgroundTasks.mDeleteFormsTask.execute(mSelected
.toArray(new Long[mSelected.size()]));
} else {
Toast.makeText(this, getString(R.string.file_delete_in_progress),
Toast.LENGTH_LONG).show();
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// get row id from db
Cursor c = (Cursor) getListAdapter().getItem(position);
long k = c.getLong(c.getColumnIndex(FormsColumns._ID));
// add/remove from selected list
if (mSelected.contains(k))
mSelected.remove(k);
else
mSelected.add(k);
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", Long.toString(k));
mDeleteButton.setEnabled(!(mSelected.size() == 0));
}
@Override
public void SyncComplete(String result) {
Log.i(t, "Disk scan complete");
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setText(result);
}
@Override
public void deleteComplete(int deletedForms) {
Log.i(t, "Delete forms complete");
Collect.getInstance().getActivityLogger().logAction(this, "deleteComplete", Integer.toString(deletedForms));
if (deletedForms == mSelected.size()) {
// all deletes were successful
Toast.makeText(getApplicationContext(),
getString(R.string.file_deleted_ok, deletedForms),
Toast.LENGTH_SHORT).show();
} else {
// had some failures
Log.e(t, "Failed to delete " + (mSelected.size() - deletedForms)
+ " forms");
Toast.makeText(
getApplicationContext(),
getString(R.string.file_deleted_error, mSelected.size()
- deletedForms, mSelected.size()),
Toast.LENGTH_LONG).show();
}
mBackgroundTasks.mDeleteFormsTask = null;
mSelected.clear();
getListView().clearChoices(); // doesn't unset the checkboxes
for ( int i = 0 ; i < getListView().getCount() ; ++i ) {
getListView().setItemChecked(i, false);
}
mDeleteButton.setEnabled(false);
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.Locale;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.model.xform.XFormsModule;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.AdvanceToNextListener;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.FormController.FailedConstraint;
import org.odk.collect.android.logic.PropertyManager;
import org.odk.collect.android.preferences.AdminPreferencesActivity;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.FormLoaderTask;
import org.odk.collect.android.tasks.SaveToDiskTask;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import org.odk.collect.android.views.ODKView;
import org.odk.collect.android.widgets.QuestionWidget;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore.Images;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* FormEntryActivity is responsible for displaying questions, animating
* transitions between questions, and allowing the user to enter data.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FormEntryActivity extends Activity implements AnimationListener,
FormLoaderListener, FormSavedListener, AdvanceToNextListener,
OnGestureListener {
private static final String t = "FormEntryActivity";
// save with every swipe forward or back. Timings indicate this takes .25
// seconds.
// if it ever becomes an issue, this value can be changed to save every n'th
// screen.
private static final int SAVEPOINT_INTERVAL = 1;
// Defines for FormEntryActivity
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private static final boolean EVALUATE_CONSTRAINTS = true;
private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false;
// Request codes for returning data from specified intent.
public static final int IMAGE_CAPTURE = 1;
public static final int BARCODE_CAPTURE = 2;
public static final int AUDIO_CAPTURE = 3;
public static final int VIDEO_CAPTURE = 4;
public static final int LOCATION_CAPTURE = 5;
public static final int HIERARCHY_ACTIVITY = 6;
public static final int IMAGE_CHOOSER = 7;
public static final int AUDIO_CHOOSER = 8;
public static final int VIDEO_CHOOSER = 9;
public static final int EX_STRING_CAPTURE = 10;
public static final int EX_INT_CAPTURE = 11;
public static final int EX_DECIMAL_CAPTURE = 12;
public static final int DRAW_IMAGE = 13;
public static final int SIGNATURE_CAPTURE = 14;
public static final int ANNOTATE_IMAGE = 15;
public static final int ALIGNED_IMAGE = 16;
// Extra returned from gp activity
public static final String LOCATION_RESULT = "LOCATION_RESULT";
public static final String KEY_INSTANCES = "instances";
public static final String KEY_SUCCESS = "success";
public static final String KEY_ERROR = "error";
// Identifies the gp of the form used to launch form entry
public static final String KEY_FORMPATH = "formpath";
// Identifies whether this is a new form, or reloading a form after a screen
// rotation (or similar)
private static final String NEWFORM = "newform";
// these are only processed if we shut down and are restoring after an
// external intent fires
public static final String KEY_INSTANCEPATH = "instancepath";
public static final String KEY_XPATH = "xpath";
public static final String KEY_XPATH_WAITING_FOR_DATA = "xpathwaiting";
private static final int MENU_LANGUAGES = Menu.FIRST;
private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1;
private static final int MENU_SAVE = Menu.FIRST + 2;
private static final int MENU_PREFERENCES = Menu.FIRST + 3;
private static final int PROGRESS_DIALOG = 1;
private static final int SAVING_DIALOG = 2;
// Random ID
private static final int DELETE_REPEAT = 654321;
private String mFormPath;
private GestureDetector mGestureDetector;
private Animation mInAnimation;
private Animation mOutAnimation;
private View mStaleView = null;
private LinearLayout mQuestionHolder;
private View mCurrentView;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private String mErrorMessage;
// used to limit forward/backward swipes to one per question
private boolean mBeenSwiped = false;
private int viewCount = 0;
private FormLoaderTask mFormLoaderTask;
private SaveToDiskTask mSaveToDiskTask;
private ImageButton mNextButton;
private ImageButton mBackButton;
enum AnimationType {
LEFT, RIGHT, FADE
}
private SharedPreferences mAdminPreferences;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an
// external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.form_entry);
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.loading_form));
mBeenSwiped = false;
mAlertDialog = null;
mCurrentView = null;
mInAnimation = null;
mOutAnimation = null;
mGestureDetector = new GestureDetector(this);
mQuestionHolder = (LinearLayout) findViewById(R.id.questionholder);
// get admin preference settings
mAdminPreferences = getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
mNextButton = (ImageButton) findViewById(R.id.form_forward_button);
mNextButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mBeenSwiped = true;
showNextView();
}
});
mBackButton = (ImageButton) findViewById(R.id.form_back_button);
mBackButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mBeenSwiped = true;
showPreviousView();
}
});
// Load JavaRosa modules. needed to restore forms.
new XFormsModule().registerModule();
// needed to override rms property manager
org.javarosa.core.services.PropertyManager
.setPropertyManager(new PropertyManager(getApplicationContext()));
String startingXPath = null;
String waitingXPath = null;
String instancePath = null;
Boolean newForm = true;
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_FORMPATH)) {
mFormPath = savedInstanceState.getString(KEY_FORMPATH);
}
if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) {
instancePath = savedInstanceState.getString(KEY_INSTANCEPATH);
}
if (savedInstanceState.containsKey(KEY_XPATH)) {
startingXPath = savedInstanceState.getString(KEY_XPATH);
Log.i(t, "startingXPath is: " + startingXPath);
}
if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) {
waitingXPath = savedInstanceState
.getString(KEY_XPATH_WAITING_FOR_DATA);
Log.i(t, "waitingXPath is: " + waitingXPath);
}
if (savedInstanceState.containsKey(NEWFORM)) {
newForm = savedInstanceState.getBoolean(NEWFORM, true);
}
if (savedInstanceState.containsKey(KEY_ERROR)) {
mErrorMessage = savedInstanceState.getString(KEY_ERROR);
}
}
// If a parse error message is showing then nothing else is loaded
// Dialogs mid form just disappear on rotation.
if (mErrorMessage != null) {
createErrorDialog(mErrorMessage, EXIT);
return;
}
// Check to see if this is a screen flip or a new form load.
Object data = getLastNonConfigurationInstance();
if (data instanceof FormLoaderTask) {
mFormLoaderTask = (FormLoaderTask) data;
} else if (data instanceof SaveToDiskTask) {
mSaveToDiskTask = (SaveToDiskTask) data;
} else if (data == null) {
if (!newForm) {
if (Collect.getInstance().getFormController() != null) {
refreshCurrentView();
} else {
Log.w(t, "Reloading form and restoring state.");
// we need to launch the form loader to load the form
// controller...
mFormLoaderTask = new FormLoaderTask(instancePath,
startingXPath, waitingXPath);
Collect.getInstance().getActivityLogger()
.logAction(this, "formReloaded", mFormPath);
// TODO: this doesn' work (dialog does not get removed):
// showDialog(PROGRESS_DIALOG);
// show dialog before we execute...
mFormLoaderTask.execute(mFormPath);
}
return;
}
// Not a restart from a screen orientation change (or other).
Collect.getInstance().setFormController(null);
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
if (getContentResolver().getType(uri) == InstanceColumns.CONTENT_ITEM_TYPE) {
// get the formId and version for this instance...
String jrFormId = null;
String jrVersion = null;
{
Cursor instanceCursor = null;
try {
instanceCursor = getContentResolver().query(uri,
null, null, null, null);
if (instanceCursor.getCount() != 1) {
this.createErrorDialog("Bad URI: " + uri, EXIT);
return;
} else {
instanceCursor.moveToFirst();
instancePath = instanceCursor
.getString(instanceCursor
.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
Collect.getInstance()
.getActivityLogger()
.logAction(this, "instanceLoaded",
instancePath);
jrFormId = instanceCursor
.getString(instanceCursor
.getColumnIndex(InstanceColumns.JR_FORM_ID));
int idxJrVersion = instanceCursor
.getColumnIndex(InstanceColumns.JR_VERSION);
jrVersion = instanceCursor.isNull(idxJrVersion) ? null
: instanceCursor
.getString(idxJrVersion);
}
} finally {
if (instanceCursor != null) {
instanceCursor.close();
}
}
}
String[] selectionArgs;
String selection;
if (jrVersion == null) {
selectionArgs = new String[] { jrFormId };
selection = FormsColumns.JR_FORM_ID + "=? AND "
+ FormsColumns.JR_VERSION + " IS NULL";
} else {
selectionArgs = new String[] { jrFormId, jrVersion };
selection = FormsColumns.JR_FORM_ID + "=? AND "
+ FormsColumns.JR_VERSION + "=?";
}
{
Cursor formCursor = null;
try {
formCursor = getContentResolver().query(
FormsColumns.CONTENT_URI, null, selection,
selectionArgs, null);
if (formCursor.getCount() == 1) {
formCursor.moveToFirst();
mFormPath = formCursor
.getString(formCursor
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
} else if (formCursor.getCount() < 1) {
this.createErrorDialog(
getString(
R.string.parent_form_not_present,
jrFormId)
+ ((jrVersion == null) ? ""
: "\n"
+ getString(R.string.version)
+ " "
+ jrVersion),
EXIT);
return;
} else if (formCursor.getCount() > 1) {
// still take the first entry, but warn that
// there are multiple rows.
// user will need to hand-edit the SQLite
// database to fix it.
formCursor.moveToFirst();
mFormPath = formCursor
.getString(formCursor
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
this.createErrorDialog(
"Multiple matching form definitions exist",
DO_NOT_EXIT);
}
} finally {
if (formCursor != null) {
formCursor.close();
}
}
}
} else if (getContentResolver().getType(uri) == FormsColumns.CONTENT_ITEM_TYPE) {
Cursor c = null;
try {
c = getContentResolver().query(uri, null, null, null,
null);
if (c.getCount() != 1) {
this.createErrorDialog("Bad URI: " + uri, EXIT);
return;
} else {
c.moveToFirst();
mFormPath = c
.getString(c
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
// This is the fill-blank-form code path.
// See if there is a savepoint for this form that
// has never been
// explicitly saved
// by the user. If there is, open this savepoint
// (resume this filled-in
// form).
// Savepoints for forms that were explicitly saved
// will be recovered
// when that
// explicitly saved instance is edited via
// edit-saved-form.
final String filePrefix = mFormPath.substring(
mFormPath.lastIndexOf('/') + 1,
mFormPath.lastIndexOf('.'))
+ "_";
final String fileSuffix = ".xml.save";
File cacheDir = new File(Collect.CACHE_PATH);
File[] files = cacheDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName();
return name.startsWith(filePrefix)
&& name.endsWith(fileSuffix);
}
});
// see if any of these savepoints are for a
// filled-in form that has never been
// explicitly saved by the user...
for (int i = 0; i < files.length; ++i) {
File candidate = files[i];
String instanceDirName = candidate.getName()
.substring(
0,
candidate.getName().length()
- fileSuffix.length());
File instanceDir = new File(
Collect.INSTANCES_PATH + File.separator
+ instanceDirName);
File instanceFile = new File(instanceDir,
instanceDirName + ".xml");
if (instanceDir.exists()
&& instanceDir.isDirectory()
&& !instanceFile.exists()) {
// yes! -- use this savepoint file
instancePath = instanceFile
.getAbsolutePath();
break;
}
}
}
} finally {
if (c != null) {
c.close();
}
}
} else {
Log.e(t, "unrecognized URI");
this.createErrorDialog("unrecognized URI: " + uri, EXIT);
return;
}
mFormLoaderTask = new FormLoaderTask(instancePath, null, null);
Collect.getInstance().getActivityLogger()
.logAction(this, "formLoaded", mFormPath);
showDialog(PROGRESS_DIALOG);
// show dialog before we execute...
mFormLoaderTask.execute(mFormPath);
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_FORMPATH, mFormPath);
FormController formController = Collect.getInstance()
.getFormController();
if (formController != null) {
outState.putString(KEY_INSTANCEPATH, formController
.getInstancePath().getAbsolutePath());
outState.putString(KEY_XPATH,
formController.getXPath(formController.getFormIndex()));
FormIndex waiting = formController.getIndexWaitingForData();
if (waiting != null) {
outState.putString(KEY_XPATH_WAITING_FOR_DATA,
formController.getXPath(waiting));
}
// save the instance to a temp path...
SaveToDiskTask.blockingExportTempData();
}
outState.putBoolean(NEWFORM, false);
outState.putString(KEY_ERROR, mErrorMessage);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
FormController formController = Collect.getInstance()
.getFormController();
if (formController == null) {
// we must be in the midst of a reload of the FormController.
// try to save this callback data to the FormLoaderTask
if (mFormLoaderTask != null
&& mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) {
mFormLoaderTask.setActivityResult(requestCode, resultCode,
intent);
} else {
Log.e(t,
"Got an activityResult without any pending form loader");
}
return;
}
if (resultCode == RESULT_CANCELED) {
// request was canceled...
if (requestCode != HIERARCHY_ACTIVITY) {
((ODKView) mCurrentView).cancelWaitingForBinaryData();
}
return;
}
switch (requestCode) {
case BARCODE_CAPTURE:
String sb = intent.getStringExtra("SCAN_RESULT");
((ODKView) mCurrentView).setBinaryData(sb);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case EX_STRING_CAPTURE:
String sv = intent.getStringExtra("value");
((ODKView) mCurrentView).setBinaryData(sv);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case EX_INT_CAPTURE:
Integer iv = intent.getIntExtra("value", 0);
((ODKView) mCurrentView).setBinaryData(iv);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case EX_DECIMAL_CAPTURE:
Double dv = intent.getDoubleExtra("value", 0.0);
((ODKView) mCurrentView).setBinaryData(dv);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case DRAW_IMAGE:
case ANNOTATE_IMAGE:
case SIGNATURE_CAPTURE:
case IMAGE_CAPTURE:
/*
* We saved the image to the tempfile_path, but we really want it to
* be in: /sdcard/odk/instances/[current instnace]/something.jpg so
* we move it there before inserting it into the content provider.
* Once the android image capture bug gets fixed, (read, we move on
* from Android 1.6) we want to handle images the audio and video
*/
// The intent is empty, but we know we saved the image to the temp
// file
File fi = new File(Collect.TMPFILE_PATH);
String mInstanceFolder = formController.getInstancePath()
.getParent();
String s = mInstanceFolder + File.separator
+ System.currentTimeMillis() + ".jpg";
File nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(t, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(t,
"renamed " + fi.getAbsolutePath() + " to "
+ nf.getAbsolutePath());
}
((ODKView) mCurrentView).setBinaryData(nf);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case ALIGNED_IMAGE:
/*
* We saved the image to the tempfile_path; the app returns the
* full path to the saved file in the EXTRA_OUTPUT extra. Take
* that file and move it into the instance folder.
*/
String path = intent.getStringExtra(android.provider.MediaStore.EXTRA_OUTPUT);
fi = new File(path);
mInstanceFolder = formController.getInstancePath()
.getParent();
s = mInstanceFolder + File.separator
+ System.currentTimeMillis() + ".jpg";
nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(t, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(t,
"renamed " + fi.getAbsolutePath() + " to "
+ nf.getAbsolutePath());
}
((ODKView) mCurrentView).setBinaryData(nf);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case IMAGE_CHOOSER:
/*
* We have a saved image somewhere, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move
* it there before inserting it into the content provider. Once the
* android image capture bug gets fixed, (read, we move on from
* Android 1.6) we want to handle images the audio and video
*/
// get gp of chosen file
String sourceImagePath = null;
Uri selectedImage = intent.getData();
if (selectedImage.toString().startsWith("file")) {
sourceImagePath = selectedImage.toString().substring(6);
} else {
String[] projection = { Images.Media.DATA };
Cursor cursor = null;
try {
cursor = getContentResolver().query(selectedImage,
projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(Images.Media.DATA);
cursor.moveToFirst();
sourceImagePath = cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
// Copy file to sdcard
String mInstanceFolder1 = formController.getInstancePath()
.getParent();
String destImagePath = mInstanceFolder1 + File.separator
+ System.currentTimeMillis() + ".jpg";
File source = new File(sourceImagePath);
File newImage = new File(destImagePath);
FileUtils.copyFile(source, newImage);
((ODKView) mCurrentView).setBinaryData(newImage);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case AUDIO_CAPTURE:
case VIDEO_CAPTURE:
case AUDIO_CHOOSER:
case VIDEO_CHOOSER:
// For audio/video capture/chooser, we get the URI from the content
// provider
// then the widget copies the file and makes a new entry in the
// content provider.
Uri media = intent.getData();
((ODKView) mCurrentView).setBinaryData(media);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case LOCATION_CAPTURE:
String sl = intent.getStringExtra(LOCATION_RESULT);
((ODKView) mCurrentView).setBinaryData(sl);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case HIERARCHY_ACTIVITY:
// We may have jumped to a new index in hierarchy activity, so
// refresh
break;
}
refreshCurrentView();
}
/**
* Refreshes the current view. the controller and the displayed view can get
* out of sync due to dialogs and restarts caused by screen orientation
* changes, so they're resynchronized here.
*/
public void refreshCurrentView() {
FormController formController = Collect.getInstance()
.getFormController();
int event = formController.getEvent();
// When we refresh, repeat dialog state isn't maintained, so step back
// to the previous
// question.
// Also, if we're within a group labeled 'field list', step back to the
// beginning of that
// group.
// That is, skip backwards over repeat prompts, groups that are not
// field-lists,
// repeat events, and indexes in field-lists that is not the containing
// group.
if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
createRepeatDialog();
} else {
View current = createView(event, false);
showView(current, AnimationType.FADE);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onPrepareOptionsMenu", "show");
FormController formController = Collect.getInstance()
.getFormController();
menu.removeItem(MENU_LANGUAGES);
menu.removeItem(MENU_HIERARCHY_VIEW);
menu.removeItem(MENU_SAVE);
menu.removeItem(MENU_PREFERENCES);
if (mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_MID,
true)) {
menu.add(0, MENU_SAVE, 0, R.string.save_all_answers).setIcon(
android.R.drawable.ic_menu_save);
}
if (mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_JUMP_TO,
true)) {
menu.add(0, MENU_HIERARCHY_VIEW, 0,
getString(R.string.view_hierarchy)).setIcon(
R.drawable.ic_menu_goto);
}
if (mAdminPreferences.getBoolean(
AdminPreferencesActivity.KEY_CHANGE_LANGUAGE, true)) {
menu.add(0, MENU_LANGUAGES, 0, getString(R.string.change_language))
.setIcon(R.drawable.ic_menu_start_conversation)
.setEnabled(
(formController.getLanguages() == null || formController
.getLanguages().length == 1) ? false : true);
}
if (mAdminPreferences.getBoolean(
AdminPreferencesActivity.KEY_ACCESS_SETTINGS, true)) {
menu.add(0, MENU_PREFERENCES, 0,
getString(R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FormController formController = Collect.getInstance()
.getFormController();
switch (item.getItemId()) {
case MENU_LANGUAGES:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onOptionsItemSelected",
"MENU_LANGUAGES");
createLanguageDialog();
return true;
case MENU_SAVE:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onOptionsItemSelected",
"MENU_SAVE");
// don't exit
saveDataToDisk(DO_NOT_EXIT, isInstanceComplete(false), null);
return true;
case MENU_HIERARCHY_VIEW:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onOptionsItemSelected",
"MENU_HIERARCHY_VIEW");
if (formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivityForResult(i, HIERARCHY_ACTIVITY);
return true;
case MENU_PREFERENCES:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onOptionsItemSelected",
"MENU_PREFERENCES");
Intent pref = new Intent(this, PreferencesActivity.class);
startActivity(pref);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Attempt to save the answer(s) in the current screen to into the data
* model.
*
* @param evaluateConstraints
* @return false if any error occurs while saving (constraint violated,
* etc...), true otherwise.
*/
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) {
FormController formController = Collect.getInstance()
.getFormController();
// only try to save if the current event is a question or a field-list
// group
if (formController.currentPromptIsQuestion()) {
LinkedHashMap<FormIndex, IAnswerData> answers = ((ODKView) mCurrentView)
.getAnswers();
FailedConstraint constraint = formController.saveAllScreenAnswers(
answers, evaluateConstraints);
if (constraint != null) {
createConstraintToast(constraint.index, constraint.status);
return false;
}
}
return true;
}
/**
* Clears the answer on the screen.
*/
private void clearAnswer(QuestionWidget qw) {
if ( qw.getAnswer() != null) {
qw.clearAnswer();
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onCreateContextMenu", "show");
FormController formController = Collect.getInstance()
.getFormController();
menu.add(0, v.getId(), 0, getString(R.string.clear_answer));
if (formController.indexContainsRepeatableGroup()) {
menu.add(0, DELETE_REPEAT, 0, getString(R.string.delete_repeat));
}
menu.setHeaderTitle(getString(R.string.edit_prompt));
}
@Override
public boolean onContextItemSelected(MenuItem item) {
/*
* We don't have the right view here, so we store the View's ID as the
* item ID and loop through the possible views to find the one the user
* clicked on.
*/
for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) {
if (item.getItemId() == qw.getId()) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onContextItemSelected",
"createClearDialog", qw.getPrompt().getIndex());
createClearDialog(qw);
}
}
if (item.getItemId() == DELETE_REPEAT) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onContextItemSelected",
"createDeleteRepeatConfirmDialog");
createDeleteRepeatConfirmDialog();
}
return super.onContextItemSelected(item);
}
/**
* If we're loading, then we pass the loading thread to our next instance.
*/
@Override
public Object onRetainNonConfigurationInstance() {
FormController formController = Collect.getInstance()
.getFormController();
// if a form is loading, pass the loader task
if (mFormLoaderTask != null
&& mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED)
return mFormLoaderTask;
// if a form is writing to disk, pass the save to disk task
if (mSaveToDiskTask != null
&& mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)
return mSaveToDiskTask;
// mFormEntryController is static so we don't need to pass it.
if (formController != null && formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
return null;
}
/**
* Creates a view given the View type and an event
*
* @param event
* @param advancingPage
* -- true if this results from advancing through the form
* @return newly created View
*/
private View createView(int event, boolean advancingPage) {
FormController formController = Collect.getInstance()
.getFormController();
setTitle(getString(R.string.app_name) + " > "
+ formController.getFormTitle());
switch (event) {
case FormEntryController.EVENT_BEGINNING_OF_FORM:
View startView = View
.inflate(this, R.layout.form_entry_start, null);
setTitle(getString(R.string.app_name) + " > "
+ formController.getFormTitle());
Drawable image = null;
File mediaFolder = formController.getMediaFolder();
String mediaDir = mediaFolder.getAbsolutePath();
BitmapDrawable bitImage = null;
// attempt to load the form-specific logo...
// this is arbitrarily silly
bitImage = new BitmapDrawable(mediaDir + File.separator
+ "form_logo.png");
if (bitImage != null && bitImage.getBitmap() != null
&& bitImage.getIntrinsicHeight() > 0
&& bitImage.getIntrinsicWidth() > 0) {
image = bitImage;
}
if (image == null) {
// show the opendatakit zig...
// image =
// getResources().getDrawable(R.drawable.opendatakit_zig);
((ImageView) startView.findViewById(R.id.form_start_bling))
.setVisibility(View.GONE);
} else {
ImageView v = ((ImageView) startView
.findViewById(R.id.form_start_bling));
v.setImageDrawable(image);
v.setContentDescription(formController.getFormTitle());
}
// change start screen based on navigation prefs
String navigationChoice = PreferenceManager.getDefaultSharedPreferences(this).getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION);
Boolean useSwipe = false;
Boolean useButtons = false;
ImageView ia = ((ImageView) startView.findViewById(R.id.image_advance));
ImageView ib = ((ImageView) startView.findViewById(R.id.image_backup));
TextView ta = ((TextView) startView.findViewById(R.id.text_advance));
TextView tb = ((TextView) startView.findViewById(R.id.text_backup));
TextView d = ((TextView) startView.findViewById(R.id.description));
if (navigationChoice != null) {
if (navigationChoice.contains(PreferencesActivity.NAVIGATION_SWIPE)) {
useSwipe = true;
}
if (navigationChoice.contains(PreferencesActivity.NAVIGATION_BUTTONS)) {
useButtons = true;
}
}
if (useSwipe && !useButtons) {
d.setText(getString(R.string.swipe_instructions,
formController.getFormTitle()));
} else if (useButtons && !useSwipe) {
ia.setVisibility(View.GONE);
ib.setVisibility(View.GONE);
ta.setVisibility(View.GONE);
tb.setVisibility(View.GONE);
d.setText(getString(R.string.buttons_instructions,
formController.getFormTitle()));
} else {
d.setText(getString(R.string.swipe_buttons_instructions,
formController.getFormTitle()));
}
if (mBackButton.isShown()) {
mBackButton.setEnabled(false);
}
if (mNextButton.isShown()) {
mNextButton.setEnabled(true);
}
return startView;
case FormEntryController.EVENT_END_OF_FORM:
View endView = View.inflate(this, R.layout.form_entry_end, null);
((TextView) endView.findViewById(R.id.description))
.setText(getString(R.string.save_enter_data_description,
formController.getFormTitle()));
// checkbox for if finished or ready to send
final CheckBox instanceComplete = ((CheckBox) endView
.findViewById(R.id.mark_finished));
instanceComplete.setChecked(isInstanceComplete(true));
if (!mAdminPreferences.getBoolean(
AdminPreferencesActivity.KEY_MARK_AS_FINALIZED, true)) {
instanceComplete.setVisibility(View.GONE);
}
// edittext to change the displayed name of the instance
final EditText saveAs = (EditText) endView
.findViewById(R.id.save_name);
// disallow carriage returns in the name
InputFilter returnFilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.getType((source.charAt(i))) == Character.CONTROL) {
return "";
}
}
return null;
}
};
saveAs.setFilters(new InputFilter[] { returnFilter });
String saveName = formController.getSubmissionMetadata().instanceName;
if (saveName == null) {
// no meta/instanceName field in the form -- see if we have a
// name for this instance from a previous save attempt...
if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) {
Uri instanceUri = getIntent().getData();
Cursor instance = null;
try {
instance = getContentResolver().query(instanceUri,
null, null, null, null);
if (instance.getCount() == 1) {
instance.moveToFirst();
saveName = instance
.getString(instance
.getColumnIndex(InstanceColumns.DISPLAY_NAME));
}
} finally {
if (instance != null) {
instance.close();
}
}
}
if (saveName == null) {
// last resort, default to the form title
saveName = formController.getFormTitle();
}
// present the prompt to allow user to name the form
TextView sa = (TextView) endView
.findViewById(R.id.save_form_as);
sa.setVisibility(View.VISIBLE);
saveAs.setText(saveName);
saveAs.setEnabled(true);
saveAs.setVisibility(View.VISIBLE);
} else {
// if instanceName is defined in form, this is the name -- no
// revisions
// display only the name, not the prompt, and disable edits
TextView sa = (TextView) endView
.findViewById(R.id.save_form_as);
sa.setVisibility(View.GONE);
saveAs.setText(saveName);
saveAs.setEnabled(false);
saveAs.setBackgroundColor(Color.WHITE);
saveAs.setVisibility(View.VISIBLE);
}
// override the visibility settings based upon admin preferences
if (!mAdminPreferences.getBoolean(
AdminPreferencesActivity.KEY_SAVE_AS, true)) {
saveAs.setVisibility(View.GONE);
TextView sa = (TextView) endView
.findViewById(R.id.save_form_as);
sa.setVisibility(View.GONE);
}
// Create 'save' button
((Button) endView.findViewById(R.id.save_exit_button))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
this,
"createView.saveAndExit",
instanceComplete.isChecked() ? "saveAsComplete"
: "saveIncomplete");
// Form is marked as 'saved' here.
if (saveAs.getText().length() < 1) {
Toast.makeText(FormEntryActivity.this,
R.string.save_as_error,
Toast.LENGTH_SHORT).show();
} else {
saveDataToDisk(EXIT, instanceComplete
.isChecked(), saveAs.getText()
.toString());
}
}
});
if (mBackButton.isShown()) {
mBackButton.setEnabled(true);
}
if (mNextButton.isShown()) {
mNextButton.setEnabled(false);
}
return endView;
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_GROUP:
case FormEntryController.EVENT_REPEAT:
ODKView odkv = null;
// should only be a group here if the event_group is a field-list
try {
FormEntryPrompt[] prompts = formController.getQuestionPrompts();
FormEntryCaption[] groups = formController
.getGroupsForCurrentIndex();
odkv = new ODKView(this, formController.getQuestionPrompts(),
groups, advancingPage);
Log.i(t,
"created view for group "
+ (groups.length > 0 ? groups[groups.length - 1]
.getLongText() : "[top]")
+ " "
+ (prompts.length > 0 ? prompts[0]
.getQuestionText() : "[no question]"));
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
e.printStackTrace();
// this is badness to avoid a crash.
event = formController.stepToNextScreenEvent();
return createView(event, advancingPage);
}
// Makes a "clear answer" menu pop up on long-click
for (QuestionWidget qw : odkv.getWidgets()) {
if (!qw.getPrompt().isReadOnly()) {
registerForContextMenu(qw);
}
}
if (mBackButton.isShown() && mNextButton.isShown()) {
mBackButton.setEnabled(true);
mNextButton.setEnabled(true);
}
return odkv;
default:
createErrorDialog("Internal error: step to prompt failed", EXIT);
Log.e(t, "Attempted to create a view that does not exist.");
// this is badness to avoid a crash.
event = formController.stepToNextScreenEvent();
return createView(event, advancingPage);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent mv) {
boolean handled = mGestureDetector.onTouchEvent(mv);
if (!handled) {
return super.dispatchTouchEvent(mv);
}
return handled; // this is always true
}
/**
* Determines what should be displayed on the screen. Possible options are:
* a question, an ask repeat dialog, or the submit screen. Also saves
* answers to the data model after checking constraints.
*/
private void showNextView() {
FormController formController = Collect.getInstance()
.getFormController();
if (formController.currentPromptIsQuestion()) {
if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) {
// A constraint was violated so a dialog should be showing.
mBeenSwiped = false;
return;
}
}
View next;
int event = formController.stepToNextScreenEvent();
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_GROUP:
// create a savepoint
if ((++viewCount) % SAVEPOINT_INTERVAL == 0) {
SaveToDiskTask.blockingExportTempData();
}
next = createView(event, true);
showView(next, AnimationType.RIGHT);
break;
case FormEntryController.EVENT_END_OF_FORM:
case FormEntryController.EVENT_REPEAT:
next = createView(event, true);
showView(next, AnimationType.RIGHT);
break;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
createRepeatDialog();
break;
case FormEntryController.EVENT_REPEAT_JUNCTURE:
Log.i(t, "repeat juncture: "
+ formController.getFormIndex().getReference());
// skip repeat junctures until we implement them
break;
default:
Log.w(t,
"JavaRosa added a new EVENT type and didn't tell us... shame on them.");
break;
}
}
/**
* Determines what should be displayed between a question, or the start
* screen and displays the appropriate view. Also saves answers to the data
* model without checking constraints.
*/
private void showPreviousView() {
FormController formController = Collect.getInstance()
.getFormController();
// The answer is saved on a back swipe, but question constraints are
// ignored.
if (formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
if (formController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
int event = formController.stepToPreviousScreenEvent();
if (event == FormEntryController.EVENT_BEGINNING_OF_FORM
|| event == FormEntryController.EVENT_GROUP
|| event == FormEntryController.EVENT_QUESTION) {
// create savepoint
if ((++viewCount) % SAVEPOINT_INTERVAL == 0) {
SaveToDiskTask.blockingExportTempData();
}
}
View next = createView(event, false);
showView(next, AnimationType.LEFT);
} else {
mBeenSwiped = false;
}
}
/**
* Displays the View specified by the parameter 'next', animating both the
* current view and next appropriately given the AnimationType. Also updates
* the progress bar.
*/
public void showView(View next, AnimationType from) {
// disable notifications...
if (mInAnimation != null) {
mInAnimation.setAnimationListener(null);
}
if (mOutAnimation != null) {
mOutAnimation.setAnimationListener(null);
}
// logging of the view being shown is already done, as this was handled
// by createView()
switch (from) {
case RIGHT:
mInAnimation = AnimationUtils.loadAnimation(this,
R.anim.push_left_in);
mOutAnimation = AnimationUtils.loadAnimation(this,
R.anim.push_left_out);
break;
case LEFT:
mInAnimation = AnimationUtils.loadAnimation(this,
R.anim.push_right_in);
mOutAnimation = AnimationUtils.loadAnimation(this,
R.anim.push_right_out);
break;
case FADE:
mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
break;
}
// complete setup for animations...
mInAnimation.setAnimationListener(this);
mOutAnimation.setAnimationListener(this);
// drop keyboard before transition...
if (mCurrentView != null) {
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(),
0);
}
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
// adjust which view is in the layout container...
mStaleView = mCurrentView;
mCurrentView = next;
mQuestionHolder.addView(mCurrentView, lp);
mAnimationCompletionSet = 0;
if (mStaleView != null) {
// start OutAnimation for transition...
mStaleView.startAnimation(mOutAnimation);
// and remove the old view (MUST occur after start of animation!!!)
mQuestionHolder.removeView(mStaleView);
} else {
mAnimationCompletionSet = 2;
}
// start InAnimation for transition...
mCurrentView.startAnimation(mInAnimation);
String logString = "";
switch (from) {
case RIGHT:
logString = "next";
break;
case LEFT:
logString = "previous";
break;
case FADE:
logString = "refresh";
break;
}
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "showView", logString);
}
// Hopefully someday we can use managed dialogs when the bugs are fixed
/*
* Ideally, we'd like to use Android to manage dialogs with onCreateDialog()
* and onPrepareDialog(), but dialogs with dynamic content are broken in 1.5
* (cupcake). We do use managed dialogs for our static loading
* ProgressDialog. The main issue we noticed and are waiting to see fixed
* is: onPrepareDialog() is not called after a screen orientation change.
* http://code.google.com/p/android/issues/detail?id=1639
*/
//
/**
* Creates and displays a dialog displaying the violated constraint.
*/
private void createConstraintToast(FormIndex index, int saveStatus) {
FormController formController = Collect.getInstance()
.getFormController();
String constraintText = formController.getQuestionPrompt(index)
.getConstraintText();
switch (saveStatus) {
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createConstraintToast.ANSWER_CONSTRAINT_VIOLATED",
"show", index);
if (constraintText == null) {
constraintText = formController.getQuestionPrompt(index)
.getSpecialFormQuestionText("constraintMsg");
if (constraintText == null) {
constraintText = getString(R.string.invalid_answer_error);
}
}
break;
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createConstraintToast.ANSWER_REQUIRED_BUT_EMPTY",
"show", index);
constraintText = formController.getQuestionPrompt(index)
.getSpecialFormQuestionText("requiredMsg");
if (constraintText == null) {
constraintText = getString(R.string.required_answer_error);
}
break;
}
showCustomToast(constraintText, Toast.LENGTH_SHORT);
}
/**
* Creates a toast with the specified message.
*
* @param message
*/
private void showCustomToast(String message, int duration) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_view, null);
// set the text in the view
TextView tv = (TextView) view.findViewById(R.id.message);
tv.setText(message);
Toast t = new Toast(this);
t.setView(view);
t.setDuration(duration);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
/**
* Creates and displays a dialog asking the user if they'd like to create a
* repeat of the current group.
*/
private void createRepeatDialog() {
FormController formController = Collect.getInstance()
.getFormController();
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createRepeatDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
DialogInterface.OnClickListener repeatListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
FormController formController = Collect.getInstance()
.getFormController();
switch (i) {
case DialogInterface.BUTTON1: // yes, repeat
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createRepeatDialog",
"addRepeat");
try {
formController.newRepeat();
} catch (XPathTypeMismatchException e) {
FormEntryActivity.this.createErrorDialog(
e.getMessage(), EXIT);
return;
}
if (!formController.indexIsInFieldList()) {
// we are at a REPEAT event that does not have a
// field-list appearance
// step to the next visible field...
// which could be the start of a new repeat group...
showNextView();
} else {
// we are at a REPEAT event that has a field-list
// appearance
// just display this REPEAT event's group.
refreshCurrentView();
}
break;
case DialogInterface.BUTTON2: // no, no repeat
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createRepeatDialog",
"showNext");
showNextView();
break;
}
}
};
if (formController.getLastRepeatCount() > 0) {
mAlertDialog.setTitle(getString(R.string.leaving_repeat_ask));
mAlertDialog.setMessage(getString(R.string.add_another_repeat,
formController.getLastGroupText()));
mAlertDialog.setButton(getString(R.string.add_another),
repeatListener);
mAlertDialog.setButton2(getString(R.string.leave_repeat_yes),
repeatListener);
} else {
mAlertDialog.setTitle(getString(R.string.entering_repeat_ask));
mAlertDialog.setMessage(getString(R.string.add_repeat,
formController.getLastGroupText()));
mAlertDialog.setButton(getString(R.string.entering_repeat),
repeatListener);
mAlertDialog.setButton2(getString(R.string.add_repeat_no),
repeatListener);
}
mAlertDialog.setCancelable(false);
mBeenSwiped = false;
mAlertDialog.show();
}
/**
* Creates and displays dialog with the given errorMsg.
*/
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createErrorDialog",
"show." + Boolean.toString(shouldExit));
mErrorMessage = errorMsg;
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setTitle(getString(R.string.error_occured));
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createErrorDialog", "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mBeenSwiped = false;
mAlertDialog.show();
}
/**
* Creates a confirm/cancel dialog for deleting repeats.
*/
private void createDeleteRepeatConfirmDialog() {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createDeleteRepeatConfirmDialog",
"show");
FormController formController = Collect.getInstance()
.getFormController();
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
String name = formController.getLastRepeatedGroupName();
int repeatcount = formController.getLastRepeatedGroupRepeatCount();
if (repeatcount != -1) {
name += " (" + (repeatcount + 1) + ")";
}
mAlertDialog.setTitle(getString(R.string.delete_repeat_ask));
mAlertDialog
.setMessage(getString(R.string.delete_repeat_confirm, name));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
FormController formController = Collect.getInstance()
.getFormController();
switch (i) {
case DialogInterface.BUTTON1: // yes
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createDeleteRepeatConfirmDialog", "OK");
formController.deleteRepeat();
showPreviousView();
break;
case DialogInterface.BUTTON2: // no
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createDeleteRepeatConfirmDialog", "cancel");
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.discard_group), quitListener);
mAlertDialog.setButton2(getString(R.string.delete_repeat_no),
quitListener);
mAlertDialog.show();
}
/**
* Saves data and writes it to disk. If exit is set, program will exit after
* save completes. Complete indicates whether the user has marked the
* isntancs as complete. If updatedSaveName is non-null, the instances
* content provider is updated with the new name
*/
private boolean saveDataToDisk(boolean exit, boolean complete,
String updatedSaveName) {
// save current answer
if (!saveAnswersForCurrentScreen(complete)) {
Toast.makeText(this, getString(R.string.data_saved_error),
Toast.LENGTH_SHORT).show();
return false;
}
mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit,
complete, updatedSaveName);
mSaveToDiskTask.setFormSavedListener(this);
showDialog(SAVING_DIALOG);
// show dialog before we execute...
mSaveToDiskTask.execute();
return true;
}
/**
* Create a dialog with options to save and exit, save, or quit without
* saving
*/
private void createQuitDialog() {
FormController formController = Collect.getInstance()
.getFormController();
String[] items;
if (mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_MID,
true)) {
String[] two = { getString(R.string.keep_changes),
getString(R.string.do_not_save) };
items = two;
} else {
String[] one = { getString(R.string.do_not_save) };
items = one;
}
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createQuitDialog", "show");
mAlertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(
getString(R.string.quit_application,
formController.getFormTitle()))
.setNeutralButton(getString(R.string.do_not_exit),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDialog", "cancel");
dialog.cancel();
}
})
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // save and exit
// this is slightly complicated because if the
// option is disabled in
// the admin menu, then case 0 actually becomes
// 'discard and exit'
// whereas if it's enabled it's 'save and exit'
if (mAdminPreferences
.getBoolean(
AdminPreferencesActivity.KEY_SAVE_MID,
true)) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDialog",
"saveAndExit");
saveDataToDisk(EXIT, isInstanceComplete(false),
null);
} else {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDialog",
"discardAndExit");
removeTempInstance();
finishReturnInstance();
}
break;
case 1: // discard changes and exit
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDialog",
"discardAndExit");
removeTempInstance();
finishReturnInstance();
break;
case 2:// do nothing
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDialog", "cancel");
break;
}
}
}).create();
mAlertDialog.show();
}
/**
* this method cleans up unneeded files when the user selects 'discard and
* exit'
*/
private void removeTempInstance() {
FormController formController = Collect.getInstance()
.getFormController();
// attempt to remove any scratch file
File temp = SaveToDiskTask.savepointFile(formController
.getInstancePath());
if (temp.exists()) {
temp.delete();
}
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = { formController.getInstancePath()
.getAbsolutePath() };
boolean erase = false;
{
Cursor c = null;
try {
c = getContentResolver().query(InstanceColumns.CONTENT_URI,
null, selection, selectionArgs, null);
erase = (c.getCount() < 1);
} finally {
if (c != null) {
c.close();
}
}
}
// if it's not already saved, erase everything
if (erase) {
// delete media first
String instanceFolder = formController.getInstancePath()
.getParent();
Log.i(t, "attempting to delete: " + instanceFolder);
int images = MediaUtils
.deleteImagesInFolderFromMediaProvider(formController
.getInstancePath().getParentFile());
int audio = MediaUtils
.deleteAudioInFolderFromMediaProvider(formController
.getInstancePath().getParentFile());
int video = MediaUtils
.deleteVideoInFolderFromMediaProvider(formController
.getInstancePath().getParentFile());
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files," + " and "
+ video + " video files.");
File f = new File(instanceFolder);
if (f.exists() && f.isDirectory()) {
for (File del : f.listFiles()) {
Log.i(t, "deleting file: " + del.getAbsolutePath());
del.delete();
}
f.delete();
}
}
}
/**
* Confirm clear answer dialog
*/
private void createClearDialog(final QuestionWidget qw) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createClearDialog", "show",
qw.getPrompt().getIndex());
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setTitle(getString(R.string.clear_answer_ask));
String question = qw.getPrompt().getLongText();
if (question == null) {
question = "";
}
if (question.length() > 50) {
question = question.substring(0, 50) + "...";
}
mAlertDialog.setMessage(getString(R.string.clearanswer_confirm,
question));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // yes
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createClearDialog",
"clearAnswer", qw.getPrompt().getIndex());
clearAnswer(qw);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case DialogInterface.BUTTON2: // no
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createClearDialog",
"cancel", qw.getPrompt().getIndex());
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog
.setButton(getString(R.string.discard_answer), quitListener);
mAlertDialog.setButton2(getString(R.string.clear_answer_no),
quitListener);
mAlertDialog.show();
}
/**
* Creates and displays a dialog allowing the user to set the language for
* the form.
*/
private void createLanguageDialog() {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createLanguageDialog", "show");
FormController formController = Collect.getInstance()
.getFormController();
final String[] languages = formController.getLanguages();
int selected = -1;
if (languages != null) {
String language = formController.getLanguage();
for (int i = 0; i < languages.length; i++) {
if (language.equals(languages[i])) {
selected = i;
}
}
}
mAlertDialog = new AlertDialog.Builder(this)
.setSingleChoiceItems(languages, selected,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
FormController formController = Collect
.getInstance().getFormController();
// Update the language in the content provider
// when selecting a new
// language
ContentValues values = new ContentValues();
values.put(FormsColumns.LANGUAGE,
languages[whichButton]);
String selection = FormsColumns.FORM_FILE_PATH
+ "=?";
String selectArgs[] = { mFormPath };
int updated = getContentResolver().update(
FormsColumns.CONTENT_URI, values,
selection, selectArgs);
Log.i(t, "Updated language to: "
+ languages[whichButton] + " in "
+ updated + " rows");
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
this,
"createLanguageDialog",
"changeLanguage."
+ languages[whichButton]);
formController
.setLanguage(languages[whichButton]);
dialog.dismiss();
if (formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
refreshCurrentView();
}
})
.setTitle(getString(R.string.change_language))
.setNegativeButton(getString(R.string.do_not_change),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createLanguageDialog",
"cancel");
}
}).create();
mAlertDialog.show();
}
/**
* We use Android's dialog management for loading/saving progress dialogs
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Log.e(t, "Creating PROGRESS_DIALOG");
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onCreateDialog.PROGRESS_DIALOG",
"show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onCreateDialog.PROGRESS_DIALOG", "cancel");
dialog.dismiss();
mFormLoaderTask.setFormLoaderListener(null);
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
finish();
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(getString(R.string.loading_form));
mProgressDialog.setMessage(getString(R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel_loading_form),
loadingButtonListener);
return mProgressDialog;
case SAVING_DIALOG:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onCreateDialog.SAVING_DIALOG",
"show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener savingButtonListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onCreateDialog.SAVING_DIALOG", "cancel");
dialog.dismiss();
mSaveToDiskTask.setFormSavedListener(null);
SaveToDiskTask t = mSaveToDiskTask;
mSaveToDiskTask = null;
t.cancel(true);
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(getString(R.string.saving_form));
mProgressDialog.setMessage(getString(R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel),
savingButtonListener);
mProgressDialog.setButton(getString(R.string.cancel_saving_form),
savingButtonListener);
return mProgressDialog;
}
return null;
}
/**
* Dismiss any showing dialogs that we manually manage.
*/
private void dismissDialogs() {
Log.e(t, "Dismiss dialogs");
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onPause() {
FormController formController = Collect.getInstance()
.getFormController();
dismissDialogs();
// make sure we're not already saving to disk. if we are, currentPrompt
// is getting constantly updated
if (mSaveToDiskTask == null
|| mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
if (mCurrentView != null && formController != null
&& formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
FormController formController = Collect.getInstance()
.getFormController();
Collect.getInstance().getActivityLogger().open();
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(this);
if (formController == null
&& mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
FormController fec = mFormLoaderTask.getFormController();
if (fec != null) {
loadingComplete(mFormLoaderTask);
} else {
dismissDialog(PROGRESS_DIALOG);
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
// there is no formController -- fire MainMenu activity?
startActivity(new Intent(this, MainMenuActivity.class));
}
}
} else {
refreshCurrentView();
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(this);
}
if (mErrorMessage != null
&& (mAlertDialog != null && !mAlertDialog.isShowing())) {
createErrorDialog(mErrorMessage, EXIT);
return;
}
// only check the buttons if it's enabled in preferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String navigation = sharedPreferences.getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION);
Boolean showButtons = false;
if (navigation.contains(PreferencesActivity.NAVIGATION_BUTTONS)) {
showButtons = true;
}
if (showButtons) {
mBackButton.setVisibility(View.VISIBLE);
mNextButton.setVisibility(View.VISIBLE);
} else {
mBackButton.setVisibility(View.GONE);
mNextButton.setVisibility(View.GONE);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit");
createQuitDialog();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onKeyDown.KEYCODE_DPAD_RIGHT", "showNext");
showNextView();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.isAltPressed() && !mBeenSwiped) {
mBeenSwiped = true;
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_LEFT",
"showPrevious");
showPreviousView();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
// but only if it's done, otherwise the thread never returns
if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
mSaveToDiskTask.cancel(true);
mSaveToDiskTask = null;
}
}
super.onDestroy();
}
private int mAnimationCompletionSet = 0;
private void afterAllAnimations() {
Log.i(t, "afterAllAnimations");
if (mStaleView != null) {
if (mStaleView instanceof ODKView) {
// http://code.google.com/p/android/issues/detail?id=8488
((ODKView) mStaleView).recycleDrawables();
}
mStaleView = null;
}
if (mCurrentView instanceof ODKView) {
((ODKView) mCurrentView).setFocus(this);
}
mBeenSwiped = false;
}
@Override
public void onAnimationEnd(Animation animation) {
Log.i(t, "onAnimationEnd "
+ ((animation == mInAnimation) ? "in"
: ((animation == mOutAnimation) ? "out" : "other")));
if (mInAnimation == animation) {
mAnimationCompletionSet |= 1;
} else if (mOutAnimation == animation) {
mAnimationCompletionSet |= 2;
} else {
Log.e(t, "Unexpected animation");
}
if (mAnimationCompletionSet == 3) {
this.afterAllAnimations();
}
}
@Override
public void onAnimationRepeat(Animation animation) {
// Added by AnimationListener interface.
Log.i(t, "onAnimationRepeat "
+ ((animation == mInAnimation) ? "in"
: ((animation == mOutAnimation) ? "out" : "other")));
}
@Override
public void onAnimationStart(Animation animation) {
// Added by AnimationListener interface.
Log.i(t, "onAnimationStart "
+ ((animation == mInAnimation) ? "in"
: ((animation == mOutAnimation) ? "out" : "other")));
}
/**
* loadingComplete() is called by FormLoaderTask once it has finished
* loading a form.
*/
@Override
public void loadingComplete(FormLoaderTask task) {
dismissDialog(PROGRESS_DIALOG);
FormController formController = task.getFormController();
boolean pendingActivityResult = task.hasPendingActivityResult();
boolean hasUsedSavepoint = task.hasUsedSavepoint();
int requestCode = task.getRequestCode(); // these are bogus if
// pendingActivityResult is
// false
int resultCode = task.getResultCode();
Intent intent = task.getIntent();
mFormLoaderTask.setFormLoaderListener(null);
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
Collect.getInstance().setFormController(formController);
// Set the language if one has already been set in the past
String[] languageTest = formController.getLanguages();
if (languageTest != null) {
String defaultLanguage = formController.getLanguage();
String newLanguage = "";
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String selectArgs[] = { mFormPath };
Cursor c = null;
try {
c = getContentResolver().query(FormsColumns.CONTENT_URI, null,
selection, selectArgs, null);
if (c.getCount() == 1) {
c.moveToFirst();
newLanguage = c.getString(c
.getColumnIndex(FormsColumns.LANGUAGE));
}
} finally {
if (c != null) {
c.close();
}
}
// if somehow we end up with a bad language, set it to the default
try {
formController.setLanguage(newLanguage);
} catch (Exception e) {
formController.setLanguage(defaultLanguage);
}
}
if (pendingActivityResult) {
// set the current view to whatever group we were at...
refreshCurrentView();
// process the pending activity request...
onActivityResult(requestCode, resultCode, intent);
return;
}
// it can be a normal flow for a pending activity result to restore from
// a savepoint
// (the call flow handled by the above if statement). For all other use
// cases, the
// user should be notified, as it means they wandered off doing other
// things then
// returned to ODK Collect and chose Edit Saved Form, but that the
// savepoint for that
// form is newer than the last saved version of their form data.
if (hasUsedSavepoint) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(FormEntryActivity.this,
getString(R.string.savepoint_used),
Toast.LENGTH_LONG).show();
}
});
}
// Set saved answer path
if (formController.getInstancePath() == null) {
// Create new answer folder.
String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
Locale.ENGLISH).format(Calendar.getInstance().getTime());
String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1,
mFormPath.lastIndexOf('.'));
String path = Collect.INSTANCES_PATH + File.separator + file + "_"
+ time;
if (FileUtils.createFolder(path)) {
formController.setInstancePath(new File(path + File.separator
+ file + "_" + time + ".xml"));
}
} else {
Intent reqIntent = getIntent();
boolean showFirst = reqIntent.getBooleanExtra("start", false);
if (!showFirst) {
// we've just loaded a saved form, so start in the hierarchy
// view
Intent i = new Intent(this, FormHierarchyActivity.class);
startActivity(i);
return; // so we don't show the intro screen before jumping to
// the hierarchy
}
}
refreshCurrentView();
}
/**
* called by the FormLoaderTask if something goes wrong.
*/
@Override
public void loadingError(String errorMsg) {
dismissDialog(PROGRESS_DIALOG);
if (errorMsg != null) {
createErrorDialog(errorMsg, EXIT);
} else {
createErrorDialog(getString(R.string.parse_error), EXIT);
}
}
/**
* Called by SavetoDiskTask if everything saves correctly.
*/
@Override
public void savingComplete(int saveStatus) {
dismissDialog(SAVING_DIALOG);
switch (saveStatus) {
case SaveToDiskTask.SAVED:
Toast.makeText(this, getString(R.string.data_saved_ok),
Toast.LENGTH_SHORT).show();
sendSavedBroadcast();
break;
case SaveToDiskTask.SAVED_AND_EXIT:
Toast.makeText(this, getString(R.string.data_saved_ok),
Toast.LENGTH_SHORT).show();
sendSavedBroadcast();
finishReturnInstance();
break;
case SaveToDiskTask.SAVE_ERROR:
Toast.makeText(this, getString(R.string.data_saved_error),
Toast.LENGTH_LONG).show();
break;
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
refreshCurrentView();
// an answer constraint was violated, so do a 'swipe' to the next
// question to display the proper toast(s)
next();
break;
}
}
/**
* Attempts to save an answer to the specified index.
*
* @param answer
* @param index
* @param evaluateConstraints
* @return status as determined in FormEntryController
*/
public int saveAnswer(IAnswerData answer, FormIndex index,
boolean evaluateConstraints) {
FormController formController = Collect.getInstance()
.getFormController();
if (evaluateConstraints) {
return formController.answerQuestion(index, answer);
} else {
formController.saveAnswer(index, answer);
return FormEntryController.ANSWER_OK;
}
}
/**
* Checks the database to determine if the current instance being edited has
* already been 'marked completed'. A form can be 'unmarked' complete and
* then resaved.
*
* @return true if form has been marked completed, false otherwise.
*/
private boolean isInstanceComplete(boolean end) {
FormController formController = Collect.getInstance()
.getFormController();
// default to false if we're mid form
boolean complete = false;
// if we're at the end of the form, then check the preferences
if (end) {
// First get the value from the preferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
complete = sharedPreferences.getBoolean(
PreferencesActivity.KEY_COMPLETED_DEFAULT, true);
}
// Then see if we've already marked this form as complete before
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = { formController.getInstancePath()
.getAbsolutePath() };
Cursor c = null;
try {
c = getContentResolver().query(InstanceColumns.CONTENT_URI, null,
selection, selectionArgs, null);
if (c != null && c.getCount() > 0) {
c.moveToFirst();
String status = c.getString(c
.getColumnIndex(InstanceColumns.STATUS));
if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) {
complete = true;
}
}
} finally {
if (c != null) {
c.close();
}
}
return complete;
}
public void next() {
if (!mBeenSwiped) {
mBeenSwiped = true;
showNextView();
}
}
/**
* Returns the instance that was just filled out to the calling activity, if
* requested.
*/
private void finishReturnInstance() {
FormController formController = Collect.getInstance()
.getFormController();
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action)
|| Intent.ACTION_EDIT.equals(action)) {
// caller is waiting on a picked form
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = { formController.getInstancePath()
.getAbsolutePath() };
Cursor c = null;
try {
c = getContentResolver().query(InstanceColumns.CONTENT_URI,
null, selection, selectionArgs, null);
if (c.getCount() > 0) {
// should only be one...
c.moveToFirst();
String id = c.getString(c
.getColumnIndex(InstanceColumns._ID));
Uri instance = Uri.withAppendedPath(
InstanceColumns.CONTENT_URI, id);
setResult(RESULT_OK, new Intent().setData(instance));
}
} finally {
if (c != null) {
c.close();
}
}
}
finish();
}
@Override
public boolean onDown(MotionEvent e) {
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// only check the swipe if it's enabled in preferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String navigation = sharedPreferences.getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.NAVIGATION_SWIPE);
Boolean doSwipe = false;
if (navigation.contains(PreferencesActivity.NAVIGATION_SWIPE)) {
doSwipe = true;
}
if (doSwipe) {
// Looks for user swipes. If the user has swiped, move to the
// appropriate screen.
// for all screens a swipe is left/right of at least
// .25" and up/down of less than .25"
// OR left/right of > .5"
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int xPixelLimit = (int) (dm.xdpi * .25);
int yPixelLimit = (int) (dm.ydpi * .25);
if (mCurrentView instanceof ODKView) {
if (((ODKView) mCurrentView).suppressFlingGesture(e1, e2,
velocityX, velocityY)) {
return false;
}
}
if (mBeenSwiped) {
return false;
}
if ((Math.abs(e1.getX() - e2.getX()) > xPixelLimit && Math.abs(e1
.getY() - e2.getY()) < yPixelLimit)
|| Math.abs(e1.getX() - e2.getX()) > xPixelLimit * 2) {
mBeenSwiped = true;
if (velocityX > 0) {
if (e1.getX() > e2.getX()) {
Log.e(t,
"showNextView VelocityX is bogus! " + e1.getX()
+ " > " + e2.getX());
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onFling", "showNext");
showNextView();
} else {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onFling",
"showPrevious");
showPreviousView();
}
} else {
if (e1.getX() < e2.getX()) {
Log.e(t,
"showPreviousView VelocityX is bogus! "
+ e1.getX() + " < " + e2.getX());
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onFling",
"showPrevious");
showPreviousView();
} else {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onFling", "showNext");
showNextView();
}
}
return true;
}
}
return false;
}
@Override
public void onLongPress(MotionEvent e) {
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// The onFling() captures the 'up' event so our view thinks it gets long
// pressed.
// We don't wnat that, so cancel it.
mCurrentView.cancelLongPress();
return false;
}
@Override
public void onShowPress(MotionEvent e) {
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
@Override
public void advance() {
next();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void sendSavedBroadcast() {
Intent i = new Intent();
i.setAction("org.odk.collect.android.FormSaved");
this.sendBroadcast(i);
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
/**
* A host activity for {@link InstanceChooserList}.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class InstanceChooserTabs extends TabActivity {
private static final String SAVED_TAB = "saved_tab";
private static final String COMPLETED_TAB = "completed_tab";
// count for tab menu bar
private int mSavedCount;
private int mCompletedCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data));
// create tab host and tweak color
final TabHost tabHost = getTabHost();
tabHost.setBackgroundColor(Color.WHITE);
tabHost.getTabWidget().setBackgroundColor(Color.BLACK);
// create intent for saved tab
Intent saved = new Intent(this, InstanceChooserList.class);
tabHost.addTab(tabHost.newTabSpec(SAVED_TAB)
.setIndicator(getString(R.string.saved_data, mSavedCount)).setContent(saved));
// create intent for completed tab
Intent completed = new Intent(this, InstanceChooserList.class);
tabHost.addTab(tabHost.newTabSpec(COMPLETED_TAB)
.setIndicator(getString(R.string.completed_data, mCompletedCount))
.setContent(completed));
// hack to set font size and padding in tab headers
// arrived at these paths by using hierarchy viewer
LinearLayout ll = (LinearLayout) tabHost.getChildAt(0);
TabWidget tw = (TabWidget) ll.getChildAt(0);
int fontsize = Collect.getQuestionFontsize();
RelativeLayout rls = (RelativeLayout) tw.getChildAt(0);
TextView tvs = (TextView) rls.getChildAt(1);
tvs.setTextSize(fontsize);
tvs.setPadding(0, 0, 0, 6);
RelativeLayout rlc = (RelativeLayout) tw.getChildAt(1);
TextView tvc = (TextView) rlc.getChildAt(1);
tvc.setTextSize(fontsize);
tvc.setPadding(0, 0, 0, 6);
if (mSavedCount >= mCompletedCount) {
getTabHost().setCurrentTabByTag(SAVED_TAB);
} else {
getTabHost().setCurrentTabByTag(COMPLETED_TAB);
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
/**
* An example of tab content that launches an activity via
* {@link android.widget.TabHost.TabSpec#setContent(android.content.Intent)}
*/
public class FileManagerTabs extends TabActivity {
private TextView mTVFF;
private TextView mTVDF;
private static final String FORMS_TAB = "forms_tab";
private static final String DATA_TAB = "data_tab";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.manage_files));
final TabHost tabHost = getTabHost();
tabHost.setBackgroundColor(Color.WHITE);
tabHost.getTabWidget().setBackgroundColor(Color.BLACK);
Intent remote = new Intent(this, DataManagerList.class);
tabHost.addTab(tabHost.newTabSpec(DATA_TAB).setIndicator(getString(R.string.data))
.setContent(remote));
Intent local = new Intent(this, FormManagerList.class);
tabHost.addTab(tabHost.newTabSpec(FORMS_TAB).setIndicator(getString(R.string.forms))
.setContent(local));
// hack to set font size
LinearLayout ll = (LinearLayout) tabHost.getChildAt(0);
TabWidget tw = (TabWidget) ll.getChildAt(0);
int fontsize = Collect.getQuestionFontsize();
RelativeLayout rllf = (RelativeLayout) tw.getChildAt(0);
mTVFF = (TextView) rllf.getChildAt(1);
mTVFF.setTextSize(fontsize);
mTVFF.setPadding(0, 0, 0, 6);
RelativeLayout rlrf = (RelativeLayout) tw.getChildAt(1);
mTVDF = (TextView) rlrf.getChildAt(1);
mTVDF.setTextSize(fontsize);
mTVDF.setPadding(0, 0, 0, 6);
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
/**
* Responsible for displaying all the valid instances in the instance directory.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class InstanceChooserList extends ListActivity {
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private AlertDialog mAlertDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.chooser_list_layout);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.review_data));
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setVisibility(View.GONE);
String selection = InstanceColumns.STATUS + " != ?";
String[] selectionArgs = {InstanceProviderAPI.STATUS_SUBMITTED};
String sortOrder = InstanceColumns.STATUS + " DESC, " + InstanceColumns.DISPLAY_NAME + " ASC";
Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, sortOrder);
String[] data = new String[] {
InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_SUBTEXT
};
int[] view = new int[] {
R.id.text1, R.id.text2
};
// render total instance view
SimpleCursorAdapter instances =
new SimpleCursorAdapter(this, R.layout.two_item, c, data, view);
setListAdapter(instances);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
/**
* Stores the path of selected instance in the parent class and finishes.
*/
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
Cursor c = (Cursor) getListAdapter().getItem(position);
startManagingCursor(c);
Uri instanceUri =
ContentUris.withAppendedId(InstanceColumns.CONTENT_URI,
c.getLong(c.getColumnIndex(InstanceColumns._ID)));
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", instanceUri.toString());
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action)) {
// caller is waiting on a picked form
setResult(RESULT_OK, new Intent().setData(instanceUri));
} else {
// the form can be edited if it is incomplete or if, when it was
// marked as complete, it was determined that it could be edited
// later.
String status = c.getString(c.getColumnIndex(InstanceColumns.STATUS));
String strCanEditWhenComplete =
c.getString(c.getColumnIndex(InstanceColumns.CAN_EDIT_WHEN_COMPLETE));
boolean canEdit = status.equals(InstanceProviderAPI.STATUS_INCOMPLETE)
|| Boolean.parseBoolean(strCanEditWhenComplete);
if (!canEdit) {
createErrorDialog(getString(R.string.cannot_edit_completed_form),
DO_NOT_EXIT);
return;
}
// caller wants to view/edit a form, so launch formentryactivity
startActivity(new Intent(Intent.ACTION_EDIT, instanceUri));
}
finish();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1:
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog",
shouldExit ? "exitApplication" : "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import org.javarosa.core.model.FormIndex;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.adapters.HierarchyListAdapter;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.HierarchyElement;
import android.app.ListActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class FormHierarchyActivity extends ListActivity {
private static final String t = "FormHierarchyActivity";
private static final int CHILD = 1;
private static final int EXPANDED = 2;
private static final int COLLAPSED = 3;
private static final int QUESTION = 4;
private static final String mIndent = " ";
private Button jumpPreviousButton;
List<HierarchyElement> formList;
TextView mPath;
FormIndex mStartIndex;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hierarchy_layout);
FormController formController = Collect.getInstance().getFormController();
// We use a static FormEntryController to make jumping faster.
mStartIndex = formController.getFormIndex();
setTitle(getString(R.string.app_name) + " > "
+ formController.getFormTitle());
mPath = (TextView) findViewById(R.id.pathtext);
jumpPreviousButton = (Button) findViewById(R.id.jumpPreviousButton);
jumpPreviousButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "goUpLevelButton", "click");
goUpLevel();
}
});
Button jumpBeginningButton = (Button) findViewById(R.id.jumpBeginningButton);
jumpBeginningButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "jumpToBeginning", "click");
Collect.getInstance().getFormController().jumpToIndex(FormIndex
.createBeginningOfFormIndex());
setResult(RESULT_OK);
finish();
}
});
Button jumpEndButton = (Button) findViewById(R.id.jumpEndButton);
jumpEndButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "jumpToEnd", "click");
Collect.getInstance().getFormController().jumpToIndex(FormIndex.createEndOfFormIndex());
setResult(RESULT_OK);
finish();
}
});
// kinda slow, but works.
// this scrolls to the last question the user was looking at
getListView().post(new Runnable() {
@Override
public void run() {
int position = 0;
for (int i = 0; i < getListAdapter().getCount(); i++) {
HierarchyElement he = (HierarchyElement) getListAdapter().getItem(i);
if (mStartIndex.equals(he.getFormIndex())) {
position = i;
break;
}
}
getListView().setSelection(position);
}
});
refreshView();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void goUpLevel() {
Collect.getInstance().getFormController().stepToOuterScreenEvent();
refreshView();
}
private String getCurrentPath() {
FormController formController = Collect.getInstance().getFormController();
FormIndex index = formController.getFormIndex();
// move to enclosing group...
index = formController.stepIndexOut(index);
String path = "";
while (index != null) {
path =
formController.getCaptionPrompt(index).getLongText()
+ " ("
+ (formController.getCaptionPrompt(index)
.getMultiplicity() + 1) + ") > " + path;
index = formController.stepIndexOut(index);
}
// return path?
return path.substring(0, path.length() - 2);
}
public void refreshView() {
FormController formController = Collect.getInstance().getFormController();
// Record the current index so we can return to the same place if the user hits 'back'.
FormIndex currentIndex = formController.getFormIndex();
// If we're not at the first level, we're inside a repeated group so we want to only display
// everything enclosed within that group.
String enclosingGroupRef = "";
formList = new ArrayList<HierarchyElement>();
// If we're currently at a repeat node, record the name of the node and step to the next
// node to display.
if (formController.getEvent() == FormEntryController.EVENT_REPEAT) {
enclosingGroupRef =
formController.getFormIndex().getReference().toString(false);
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
} else {
FormIndex startTest = formController.stepIndexOut(currentIndex);
// If we have a 'group' tag, we want to step back until we hit a repeat or the
// beginning.
while (startTest != null
&& formController.getEvent(startTest) == FormEntryController.EVENT_GROUP) {
startTest = formController.stepIndexOut(startTest);
}
if (startTest == null) {
// check to see if the question is at the first level of the hierarchy. If it is,
// display the root level from the beginning.
formController.jumpToIndex(FormIndex
.createBeginningOfFormIndex());
} else {
// otherwise we're at a repeated group
formController.jumpToIndex(startTest);
}
// now test again for repeat. This should be true at this point or we're at the
// beginning
if (formController.getEvent() == FormEntryController.EVENT_REPEAT) {
enclosingGroupRef =
formController.getFormIndex().getReference().toString(false);
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
}
}
int event = formController.getEvent();
if (event == FormEntryController.EVENT_BEGINNING_OF_FORM) {
// The beginning of form has no valid prompt to display.
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
mPath.setVisibility(View.GONE);
jumpPreviousButton.setEnabled(false);
} else {
mPath.setVisibility(View.VISIBLE);
mPath.setText(getCurrentPath());
jumpPreviousButton.setEnabled(true);
}
// Refresh the current event in case we did step forward.
event = formController.getEvent();
// There may be repeating Groups at this level of the hierarchy, we use this variable to
// keep track of them.
String repeatedGroupRef = "";
event_search: while (event != FormEntryController.EVENT_END_OF_FORM) {
switch (event) {
case FormEntryController.EVENT_QUESTION:
if (!repeatedGroupRef.equalsIgnoreCase("")) {
// We're in a repeating group, so skip this question and move to the next
// index.
event =
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
continue;
}
FormEntryPrompt fp = formController.getQuestionPrompt();
String label = fp.getLongText();
if ( !fp.isReadOnly() || (label != null && label.length() > 0) ) {
// show the question if it is an editable field.
// or if it is read-only and the label is not blank.
formList.add(new HierarchyElement(fp.getLongText(), fp.getAnswerText(), null,
Color.WHITE, QUESTION, fp.getIndex()));
}
break;
case FormEntryController.EVENT_GROUP:
// ignore group events
break;
case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
if (enclosingGroupRef.compareTo(formController
.getFormIndex().getReference().toString(false)) == 0) {
// We were displaying a set of questions inside of a repeated group. This is
// the end of that group.
break event_search;
}
if (repeatedGroupRef.compareTo(formController.getFormIndex()
.getReference().toString(false)) != 0) {
// We're in a repeating group, so skip this repeat prompt and move to the
// next event.
event =
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
continue;
}
if (repeatedGroupRef.compareTo(formController.getFormIndex()
.getReference().toString(false)) == 0) {
// This is the end of the current repeating group, so we reset the
// repeatedGroupName variable
repeatedGroupRef = "";
}
break;
case FormEntryController.EVENT_REPEAT:
FormEntryCaption fc = formController.getCaptionPrompt();
if (enclosingGroupRef.compareTo(formController
.getFormIndex().getReference().toString(false)) == 0) {
// We were displaying a set of questions inside a repeated group. This is
// the end of that group.
break event_search;
}
if (repeatedGroupRef.equalsIgnoreCase("") && fc.getMultiplicity() == 0) {
// This is the start of a repeating group. We only want to display
// "Group #", so we mark this as the beginning and skip all of its children
HierarchyElement group =
new HierarchyElement(fc.getLongText(), null, getResources()
.getDrawable(R.drawable.expander_ic_minimized), Color.WHITE,
COLLAPSED, fc.getIndex());
repeatedGroupRef =
formController.getFormIndex().getReference()
.toString(false);
formList.add(group);
}
if (repeatedGroupRef.compareTo(formController.getFormIndex()
.getReference().toString(false)) == 0) {
// Add this group name to the drop down list for this repeating group.
HierarchyElement h = formList.get(formList.size() - 1);
h.addChild(new HierarchyElement(mIndent + fc.getLongText() + " "
+ (fc.getMultiplicity() + 1), null, null, Color.WHITE, CHILD, fc
.getIndex()));
}
break;
}
event =
formController.stepToNextEvent(FormController.STEP_INTO_GROUP);
}
HierarchyListAdapter itla = new HierarchyListAdapter(this);
itla.setListItems(formList);
setListAdapter(itla);
// set the controller back to the current index in case the user hits 'back'
formController.jumpToIndex(currentIndex);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
HierarchyElement h = (HierarchyElement) l.getItemAtPosition(position);
FormIndex index = h.getFormIndex();
if (index == null) {
goUpLevel();
return;
}
switch (h.getType()) {
case EXPANDED:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "COLLAPSED", h.getFormIndex());
h.setType(COLLAPSED);
ArrayList<HierarchyElement> children = h.getChildren();
for (int i = 0; i < children.size(); i++) {
formList.remove(position + 1);
}
h.setIcon(getResources().getDrawable(R.drawable.expander_ic_minimized));
h.setColor(Color.WHITE);
break;
case COLLAPSED:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "EXPANDED", h.getFormIndex());
h.setType(EXPANDED);
ArrayList<HierarchyElement> children1 = h.getChildren();
for (int i = 0; i < children1.size(); i++) {
Log.i(t, "adding child: " + children1.get(i).getFormIndex());
formList.add(position + 1 + i, children1.get(i));
}
h.setIcon(getResources().getDrawable(R.drawable.expander_ic_maximized));
h.setColor(Color.WHITE);
break;
case QUESTION:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "QUESTION-JUMP", index);
Collect.getInstance().getFormController().jumpToIndex(index);
if ( Collect.getInstance().getFormController().indexIsInFieldList() ) {
Collect.getInstance().getFormController().stepToPreviousScreenEvent();
}
setResult(RESULT_OK);
finish();
return;
case CHILD:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onListItemClick", "REPEAT-JUMP", h.getFormIndex());
Collect.getInstance().getFormController().jumpToIndex(h.getFormIndex());
setResult(RESULT_OK);
refreshView();
return;
}
// Should only get here if we've expanded or collapsed a group
HierarchyListAdapter itla = new HierarchyListAdapter(this);
itla.setListItems(formList);
setListAdapter(itla);
getListView().setSelection(position);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onKeyDown", "KEYCODE_BACK.JUMP", mStartIndex);
Collect.getInstance().getFormController().jumpToIndex(mStartIndex);
}
return super.onKeyDown(keyCode, event);
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.activities;
import java.text.DecimalFormat;
import java.util.List;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.InfoLogger;
import org.odk.collect.android.widgets.GeoPointWidget;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
public class GeoPointMapActivity extends MapActivity implements LocationListener {
private static final String LOCATION_COUNT = "locationCount";
private MapView mMapView;
private TextView mLocationStatus;
private MapController mMapController;
private LocationManager mLocationManager;
private Overlay mLocationOverlay;
private Overlay mGeoPointOverlay;
private GeoPoint mGeoPoint;
private Location mLocation;
private Button mAcceptLocation;
private Button mCancelLocation;
private boolean mCaptureLocation = true;
private Button mShowLocation;
private boolean mGPSOn = false;
private boolean mNetworkOn = false;
private double mLocationAccuracy;
private int mLocationCount = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ( savedInstanceState != null ) {
mLocationCount = savedInstanceState.getInt(LOCATION_COUNT);
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.geopoint_layout);
Intent intent = getIntent();
mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY;
if (intent != null && intent.getExtras() != null) {
if ( intent.hasExtra(GeoPointWidget.LOCATION) ) {
double[] location = intent.getDoubleArrayExtra(GeoPointWidget.LOCATION);
mGeoPoint = new GeoPoint((int) (location[0] * 1E6), (int) (location[1] * 1E6));
mCaptureLocation = false;
}
if ( intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD) ) {
mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY);
}
}
/**
* Add the MapView dynamically to the placeholding frame so as to not
* incur the wrath of Android Lint...
*/
FrameLayout frame = (FrameLayout) findViewById(R.id.mapview_placeholder);
String apiKey = "017Xo9E6R7WmcCITvo-lU2V0ERblKPqCcguwxSQ";
// String apiKey = "0wsgFhRvVBLVpgaFzmwaYuqfU898z_2YtlKSlkg";
mMapView = new MapView(this, apiKey);
mMapView.setClickable(true);
mMapView.setId(R.id.mapview);
LayoutParams p = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
frame.addView(mMapView, p);
mCancelLocation = (Button) findViewById(R.id.cancel_location);
mCancelLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "cancelLocation", "cancel");
finish();
}
});
mMapController = mMapView.getController();
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mMapView.setBuiltInZoomControls(true);
mMapView.setSatellite(false);
mMapController.setZoom(16);
// make sure we have a good location provider before continuing
List<String> providers = mLocationManager.getProviders(true);
for (String provider : providers) {
if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
mGPSOn = true;
}
if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {
mNetworkOn = true;
}
}
if (!mGPSOn && !mNetworkOn) {
Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error),
Toast.LENGTH_SHORT).show();
finish();
}
if ( mGPSOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) null location");
}
}
if ( mNetworkOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) null location");
}
}
mLocationOverlay = new MyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mLocationOverlay);
if (mCaptureLocation) {
mLocationStatus = (TextView) findViewById(R.id.location_status);
mAcceptLocation = (Button) findViewById(R.id.accept_location);
mAcceptLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK");
returnLocation();
}
});
} else {
mGeoPointOverlay = new Marker(mGeoPoint);
mMapView.getOverlays().add(mGeoPointOverlay);
((Button) findViewById(R.id.accept_location)).setVisibility(View.GONE);
((TextView) findViewById(R.id.location_status)).setVisibility(View.GONE);
mShowLocation = ((Button) findViewById(R.id.show_location));
mShowLocation.setVisibility(View.VISIBLE);
mShowLocation.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "showLocation", "onClick");
mMapController.animateTo(mGeoPoint);
}
});
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void returnLocation() {
if (mLocation != null) {
Intent i = new Intent();
i.putExtra(
FormEntryActivity.LOCATION_RESULT,
mLocation.getLatitude() + " " + mLocation.getLongitude() + " "
+ mLocation.getAltitude() + " " + mLocation.getAccuracy());
setResult(RESULT_OK, i);
}
finish();
}
private String truncateFloat(float f) {
return new DecimalFormat("#.##").format(f);
}
@Override
protected void onPause() {
super.onPause();
mLocationManager.removeUpdates(this);
((MyLocationOverlay) mLocationOverlay).disableMyLocation();
}
@Override
protected void onResume() {
super.onResume();
((MyLocationOverlay) mLocationOverlay).enableMyLocation();
if (mGPSOn) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
if (mNetworkOn) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
@Override
public void onLocationChanged(Location location) {
if (mCaptureLocation) {
mLocation = location;
if (mLocation != null) {
// Bug report: cached GeoPoint is being returned as the first value.
// Wait for the 2nd value to be returned, which is hopefully not cached?
++mLocationCount;
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") lat: " +
mLocation.getLatitude() + " long: " +
mLocation.getLongitude() + " acc: " +
mLocation.getAccuracy() );
if (mLocationCount > 1) {
mLocationStatus.setText(getString(R.string.location_provider_accuracy,
mLocation.getProvider(), truncateFloat(mLocation.getAccuracy())));
mGeoPoint =
new GeoPoint((int) (mLocation.getLatitude() * 1E6),
(int) (mLocation.getLongitude() * 1E6));
mMapController.animateTo(mGeoPoint);
if (mLocation.getAccuracy() <= mLocationAccuracy) {
returnLocation();
}
}
} else {
InfoLogger.geolog("GeoPointMapActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") null location");
}
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
class Marker extends Overlay {
GeoPoint gp = null;
public Marker(GeoPoint gp) {
super();
this.gp = gp;
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
Point screenPoint = new Point();
mMapView.getProjection().toPixels(gp, screenPoint);
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),
R.drawable.ic_maps_indicator_current_position), screenPoint.x, screenPoint.y - 8,
null); // -8 as image is 16px high
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import java.text.DecimalFormat;
import java.util.List;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.InfoLogger;
import org.odk.collect.android.widgets.GeoPointWidget;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.Toast;
public class GeoPointActivity extends Activity implements LocationListener {
private static final String LOCATION_COUNT = "locationCount";
private ProgressDialog mLocationDialog;
private LocationManager mLocationManager;
private Location mLocation;
private boolean mGPSOn = false;
private boolean mNetworkOn = false;
private double mLocationAccuracy;
private int mLocationCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ( savedInstanceState != null ) {
mLocationCount = savedInstanceState.getInt(LOCATION_COUNT);
}
Intent intent = getIntent();
mLocationAccuracy = GeoPointWidget.DEFAULT_LOCATION_ACCURACY;
if (intent != null && intent.getExtras() != null) {
if ( intent.hasExtra(GeoPointWidget.ACCURACY_THRESHOLD) ) {
mLocationAccuracy = intent.getDoubleExtra(GeoPointWidget.ACCURACY_THRESHOLD, GeoPointWidget.DEFAULT_LOCATION_ACCURACY);
}
}
setTitle(getString(R.string.app_name) + " > " + getString(R.string.get_location));
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// make sure we have a good location provider before continuing
List<String> providers = mLocationManager.getProviders(true);
for (String provider : providers) {
if (provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
mGPSOn = true;
}
if (provider.equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)) {
mNetworkOn = true;
}
}
if (!mGPSOn && !mNetworkOn) {
Toast.makeText(getBaseContext(), getString(R.string.provider_disabled_error),
Toast.LENGTH_SHORT).show();
finish();
}
if ( mGPSOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(GPS) null location");
}
}
if ( mNetworkOn ) {
Location loc = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if ( loc != null ) {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) lat: " +
loc.getLatitude() + " long: " +
loc.getLongitude() + " acc: " +
loc.getAccuracy() );
} else {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" lastKnownLocation(Network) null location");
}
}
setupLocationDialog();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(LOCATION_COUNT, mLocationCount);
}
@Override
protected void onPause() {
super.onPause();
// stops the GPS. Note that this will turn off the GPS if the screen goes to sleep.
mLocationManager.removeUpdates(this);
// We're not using managed dialogs, so we have to dismiss the dialog to prevent it from
// leaking memory.
if (mLocationDialog != null && mLocationDialog.isShowing())
mLocationDialog.dismiss();
}
@Override
protected void onResume() {
super.onResume();
if (mGPSOn) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
if (mNetworkOn) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
mLocationDialog.show();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
/**
* Sets up the look and actions for the progress dialog while the GPS is searching.
*/
private void setupLocationDialog() {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "setupLocationDialog", "show");
// dialog displayed while fetching gps location
mLocationDialog = new ProgressDialog(this);
DialogInterface.OnClickListener geopointButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON1:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "acceptLocation", "OK");
returnLocation();
break;
case DialogInterface.BUTTON2:
Collect.getInstance().getActivityLogger().logInstanceAction(this, "cancelLocation", "cancel");
mLocation = null;
finish();
break;
}
}
};
// back button doesn't cancel
mLocationDialog.setCancelable(false);
mLocationDialog.setIndeterminate(true);
mLocationDialog.setIcon(android.R.drawable.ic_dialog_info);
mLocationDialog.setTitle(getString(R.string.getting_location));
mLocationDialog.setMessage(getString(R.string.please_wait_long));
mLocationDialog.setButton(DialogInterface.BUTTON1, getString(R.string.accept_location),
geopointButtonListener);
mLocationDialog.setButton(DialogInterface.BUTTON2, getString(R.string.cancel_location),
geopointButtonListener);
}
private void returnLocation() {
if (mLocation != null) {
Intent i = new Intent();
i.putExtra(
FormEntryActivity.LOCATION_RESULT,
mLocation.getLatitude() + " " + mLocation.getLongitude() + " "
+ mLocation.getAltitude() + " " + mLocation.getAccuracy());
setResult(RESULT_OK, i);
}
finish();
}
@Override
public void onLocationChanged(Location location) {
mLocation = location;
if (mLocation != null) {
// Bug report: cached GeoPoint is being returned as the first value.
// Wait for the 2nd value to be returned, which is hopefully not cached?
++mLocationCount;
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") lat: " +
mLocation.getLatitude() + " long: " +
mLocation.getLongitude() + " acc: " +
mLocation.getAccuracy() );
if (mLocationCount > 1) {
mLocationDialog.setMessage(getString(R.string.location_provider_accuracy,
mLocation.getProvider(), truncateDouble(mLocation.getAccuracy())));
if (mLocation.getAccuracy() <= mLocationAccuracy) {
returnLocation();
}
}
} else {
InfoLogger.geolog("GeoPointActivity: " + System.currentTimeMillis() +
" onLocationChanged(" + mLocationCount + ") null location");
}
}
private String truncateDouble(float number) {
DecimalFormat df = new DecimalFormat("#.##");
return df.format(number);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
if (mLocation != null) {
mLocationDialog.setMessage(getString(R.string.location_accuracy,
mLocation.getAccuracy()));
}
break;
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.receivers.NetworkReceiver;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
/**
* Responsible for displaying all the valid forms in the forms directory. Stores
* the path to selected form for use by {@link MainMenuActivity}.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class InstanceUploaderList extends ListActivity implements
OnLongClickListener {
private static final String BUNDLE_SELECTED_ITEMS_KEY = "selected_items";
private static final String BUNDLE_TOGGLED_KEY = "toggled";
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final int MENU_SHOW_UNSENT = Menu.FIRST + 1;
private static final int INSTANCE_UPLOADER = 0;
private Button mUploadButton;
private Button mToggleButton;
private boolean mShowUnsent = true;
private SimpleCursorAdapter mInstances;
private ArrayList<Long> mSelected = new ArrayList<Long>();
private boolean mRestored = false;
private boolean mToggled = false;
public Cursor getUnsentCursor() {
// get all complete or failed submission instances
String selection = InstanceColumns.STATUS + "=? or "
+ InstanceColumns.STATUS + "=?";
String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED };
String sortOrder = InstanceColumns.DISPLAY_NAME + " ASC";
Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection,
selectionArgs, sortOrder);
return c;
}
public Cursor getAllCursor() {
// get all complete or failed submission instances
String selection = InstanceColumns.STATUS + "=? or "
+ InstanceColumns.STATUS + "=? or " + InstanceColumns.STATUS
+ "=?";
String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED,
InstanceProviderAPI.STATUS_SUBMITTED };
String sortOrder = InstanceColumns.DISPLAY_NAME + " ASC";
Cursor c = managedQuery(InstanceColumns.CONTENT_URI, null, selection,
selectionArgs, sortOrder);
return c;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.instance_uploader_list);
// set up long click listener
mUploadButton = (Button) findViewById(R.id.upload_button);
mUploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (NetworkReceiver.running == true) {
Toast.makeText(
InstanceUploaderList.this,
"Background send running, please try again shortly",
Toast.LENGTH_SHORT).show();
} else if (ni == null || !ni.isConnected()) {
Collect.getInstance().getActivityLogger()
.logAction(this, "uploadButton", "noConnection");
Toast.makeText(InstanceUploaderList.this,
R.string.no_connection, Toast.LENGTH_SHORT).show();
} else {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "uploadButton",
Integer.toString(mSelected.size()));
if (mSelected.size() > 0) {
// items selected
uploadSelectedFiles();
mToggled = false;
mSelected.clear();
InstanceUploaderList.this.getListView().clearChoices();
mUploadButton.setEnabled(false);
} else {
// no items selected
Toast.makeText(getApplicationContext(),
getString(R.string.noselect_error),
Toast.LENGTH_SHORT).show();
}
}
}
});
mToggleButton = (Button) findViewById(R.id.toggle_button);
mToggleButton.setLongClickable(true);
mToggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// toggle selections of items to all or none
ListView ls = getListView();
mToggled = !mToggled;
Collect.getInstance()
.getActivityLogger()
.logAction(this, "toggleButton",
Boolean.toString(mToggled));
// remove all items from selected list
mSelected.clear();
for (int pos = 0; pos < ls.getCount(); pos++) {
ls.setItemChecked(pos, mToggled);
// add all items if mToggled sets to select all
if (mToggled)
mSelected.add(ls.getItemIdAtPosition(pos));
}
mUploadButton.setEnabled(!(mSelected.size() == 0));
}
});
mToggleButton.setOnLongClickListener(this);
Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor();
String[] data = new String[] { InstanceColumns.DISPLAY_NAME,
InstanceColumns.DISPLAY_SUBTEXT };
int[] view = new int[] { R.id.text1, R.id.text2 };
// render total instance view
mInstances = new SimpleCursorAdapter(this,
R.layout.two_item_multiple_choice, c, data, view);
setListAdapter(mInstances);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setItemsCanFocus(false);
mUploadButton.setEnabled(!(mSelected.size() == 0));
// set title
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.send_data));
// if current activity is being reinitialized due to changing
// orientation restore all check
// marks for ones selected
if (mRestored) {
ListView ls = getListView();
for (long id : mSelected) {
for (int pos = 0; pos < ls.getCount(); pos++) {
if (id == ls.getItemIdAtPosition(pos)) {
ls.setItemChecked(pos, true);
break;
}
}
}
mRestored = false;
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void uploadSelectedFiles() {
// send list of _IDs.
long[] instanceIDs = new long[mSelected.size()];
for (int i = 0; i < mSelected.size(); i++) {
instanceIDs[i] = mSelected.get(i);
}
Intent i = new Intent(this, InstanceUploaderActivity.class);
i.putExtra(FormEntryActivity.KEY_INSTANCES, instanceIDs);
startActivityForResult(i, INSTANCE_UPLOADER);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger()
.logAction(this, "onCreateOptionsMenu", "show");
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_PREFERENCES, 0,
getString(R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
menu.add(0, MENU_SHOW_UNSENT, 1, getString(R.string.change_view))
.setIcon(android.R.drawable.ic_menu_preferences);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Collect.getInstance().getActivityLogger()
.logAction(this, "onMenuItemSelected", "MENU_PREFERENCES");
createPreferencesMenu();
return true;
case MENU_SHOW_UNSENT:
Collect.getInstance().getActivityLogger()
.logAction(this, "onMenuItemSelected", "MENU_SHOW_UNSENT");
showSentAndUnsentChoices();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
private void createPreferencesMenu() {
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// get row id from db
Cursor c = (Cursor) getListAdapter().getItem(position);
long k = c.getLong(c.getColumnIndex(InstanceColumns._ID));
Collect.getInstance().getActivityLogger()
.logAction(this, "onListItemClick", Long.toString(k));
// add/remove from selected list
if (mSelected.contains(k))
mSelected.remove(k);
else
mSelected.add(k);
mUploadButton.setEnabled(!(mSelected.size() == 0));
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
long[] selectedArray = savedInstanceState
.getLongArray(BUNDLE_SELECTED_ITEMS_KEY);
for (int i = 0; i < selectedArray.length; i++)
mSelected.add(selectedArray[i]);
mToggled = savedInstanceState.getBoolean(BUNDLE_TOGGLED_KEY);
mRestored = true;
mUploadButton.setEnabled(selectedArray.length > 0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
long[] selectedArray = new long[mSelected.size()];
for (int i = 0; i < mSelected.size(); i++)
selectedArray[i] = mSelected.get(i);
outState.putLongArray(BUNDLE_SELECTED_ITEMS_KEY, selectedArray);
outState.putBoolean(BUNDLE_TOGGLED_KEY, mToggled);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (resultCode == RESULT_CANCELED) {
return;
}
switch (requestCode) {
// returns with a form path, start entry
case INSTANCE_UPLOADER:
if (intent.getBooleanExtra(FormEntryActivity.KEY_SUCCESS, false)) {
mSelected.clear();
getListView().clearChoices();
if (mInstances.isEmpty()) {
finish();
}
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, intent);
}
private void showUnsent() {
mShowUnsent = true;
Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor();
Cursor old = mInstances.getCursor();
try {
mInstances.changeCursor(c);
} finally {
if (old != null) {
old.close();
this.stopManagingCursor(old);
}
}
getListView().invalidate();
}
private void showAll() {
mShowUnsent = false;
Cursor c = mShowUnsent ? getUnsentCursor() : getAllCursor();
Cursor old = mInstances.getCursor();
try {
mInstances.changeCursor(c);
} finally {
if (old != null) {
old.close();
this.stopManagingCursor(old);
}
}
getListView().invalidate();
}
@Override
public boolean onLongClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "toggleButton.longClick",
Boolean.toString(mToggled));
return showSentAndUnsentChoices();
}
private boolean showSentAndUnsentChoices() {
/**
* Create a dialog with options to save and exit, save, or quit without
* saving
*/
String[] items = { getString(R.string.show_unsent_forms),
getString(R.string.show_sent_and_unsent_forms) };
Collect.getInstance().getActivityLogger()
.logAction(this, "changeView", "show");
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(getString(R.string.change_view))
.setNeutralButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "changeView", "cancel");
dialog.cancel();
}
})
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // show unsent
Collect.getInstance()
.getActivityLogger()
.logAction(this, "changeView", "showUnsent");
InstanceUploaderList.this.showUnsent();
break;
case 1: // show all
Collect.getInstance().getActivityLogger()
.logAction(this, "changeView", "showAll");
InstanceUploaderList.this.showAll();
break;
case 2:// do nothing
break;
}
}
}).create();
alertDialog.show();
return true;
}
}
| Java |
/*
* Copyright (C) 2012 University of Washington
* 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 org.odk.collect.android.activities;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.ColorPickerDialog;
import org.odk.collect.android.utilities.FileUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
/**
* Modified from the FingerPaint example found in The Android Open Source
* Project.
*
* @author BehrAtherton@gmail.com
*
*/
public class DrawActivity extends Activity {
public static final String t = "DrawActivity";
public static final String OPTION = "option";
public static final String OPTION_SIGNATURE = "signature";
public static final String OPTION_ANNOTATE = "annotate";
public static final String OPTION_DRAW = "draw";
public static final String REF_IMAGE = "refImage";
public static final String EXTRA_OUTPUT = android.provider.MediaStore.EXTRA_OUTPUT;
public static final String SAVEPOINT_IMAGE = "savepointImage"; // during
// restore
// incoming options...
private String loadOption = null;
private File refImage = null;
private File output = null;
private File savepointImage = null;
private Button btnDrawColor;
private Button btnFinished;
private Button btnReset;
private Button btnCancel;
private Paint paint;
private Paint pointPaint;
private int currentColor = 0xFF000000;
private DrawView drawView;
private String alertTitleString;
private AlertDialog alertDialog;
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
try {
saveFile(savepointImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if ( savepointImage.exists() ) {
outState.putString(SAVEPOINT_IMAGE, savepointImage.getAbsolutePath());
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Bundle extras = getIntent().getExtras();
if (extras == null) {
loadOption = OPTION_DRAW;
refImage = null;
savepointImage = new File(Collect.TMPDRAWFILE_PATH);
savepointImage.delete();
output = new File(Collect.TMPFILE_PATH);
} else {
loadOption = extras.getString(OPTION);
if (loadOption == null) {
loadOption = OPTION_DRAW;
}
// refImage can also be present if resuming a drawing
Uri uri = (Uri) extras.get(REF_IMAGE);
if (uri != null) {
refImage = new File(uri.getPath());
}
String savepoint = extras.getString(SAVEPOINT_IMAGE);
if (savepoint != null) {
savepointImage = new File(savepoint);
if (!savepointImage.exists() && refImage != null
&& refImage.exists()) {
FileUtils.copyFile(refImage, savepointImage);
}
} else {
savepointImage = new File(Collect.TMPDRAWFILE_PATH);
savepointImage.delete();
if (refImage != null && refImage.exists()) {
FileUtils.copyFile(refImage, savepointImage);
}
}
uri = (Uri) extras.get(EXTRA_OUTPUT);
if (uri != null) {
output = new File(uri.getPath());
} else {
output = new File(Collect.TMPFILE_PATH);
}
}
// At this point, we have:
// loadOption -- type of activity (draw, signature, annotate)
// refImage -- original image to work with
// savepointImage -- drawing to use as a starting point (may be copy of
// original)
// output -- where the output should be written
if (OPTION_SIGNATURE.equals(loadOption)) {
// set landscape
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
alertTitleString = getString(R.string.quit_application,
getString(R.string.sign_button));
} else if (OPTION_ANNOTATE.equals(loadOption)) {
alertTitleString = getString(R.string.quit_application,
getString(R.string.markup_image));
} else {
alertTitleString = getString(R.string.quit_application,
getString(R.string.draw_image));
}
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.draw_image));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout v = (RelativeLayout) inflater.inflate(
R.layout.draw_layout, null);
LinearLayout ll = (LinearLayout) v.findViewById(R.id.drawViewLayout);
drawView = new DrawView(this, OPTION_SIGNATURE.equals(loadOption),
savepointImage);
ll.addView(drawView);
setContentView(v);
paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
paint.setColor(currentColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(10);
pointPaint = new Paint();
pointPaint.setAntiAlias(true);
pointPaint.setDither(true);
pointPaint.setColor(currentColor);
pointPaint.setStyle(Paint.Style.FILL_AND_STROKE);
pointPaint.setStrokeWidth(10);
btnDrawColor = (Button) findViewById(R.id.btnSelectColor);
btnDrawColor.setTextColor(getInverseColor(currentColor));
btnDrawColor.getBackground().setColorFilter(currentColor,
PorterDuff.Mode.SRC_ATOP);
btnDrawColor.setText(getString(R.string.set_color));
btnDrawColor.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"setColorButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
ColorPickerDialog cpd = new ColorPickerDialog(
DrawActivity.this,
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(String key, int color) {
btnDrawColor
.setTextColor(getInverseColor(color));
btnDrawColor.getBackground().setColorFilter(
color, PorterDuff.Mode.SRC_ATOP);
currentColor = color;
paint.setColor(color);
pointPaint.setColor(color);
}
}, "key", currentColor, currentColor,
getString(R.string.select_drawing_color));
cpd.show();
}
});
btnFinished = (Button) findViewById(R.id.btnFinishDraw);
btnFinished.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"saveAndCloseButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
SaveAndClose();
}
});
btnReset = (Button) findViewById(R.id.btnResetDraw);
btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"resetButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
Reset();
}
});
btnCancel = (Button) findViewById(R.id.btnCancelDraw);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(
DrawActivity.this,
"cancelAndCloseButton",
"click",
Collect.getInstance().getFormController()
.getFormIndex());
CancelAndClose();
}
});
}
private int getInverseColor(int color) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = Color.alpha(color);
return Color.argb(alpha, 255 - red, 255 - green, 255 - blue);
}
private void SaveAndClose() {
try {
saveFile(output);
setResult(Activity.RESULT_OK);
} catch (FileNotFoundException e) {
e.printStackTrace();
setResult(Activity.RESULT_CANCELED);
}
this.finish();
}
private void saveFile(File f) throws FileNotFoundException {
if ( drawView.getWidth() == 0 || drawView.getHeight() == 0 ) {
// apparently on 4.x, the orientation change notification can occur
// sometime before the view is rendered. In that case, the view
// dimensions will not be known.
Log.e(t,"view has zero width or zero height");
} else {
FileOutputStream fos;
fos = new FileOutputStream(f);
Bitmap bitmap = Bitmap.createBitmap(drawView.getWidth(),
drawView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawView.draw(canvas);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
try {
if ( fos != null ) {
fos.flush();
fos.close();
}
} catch ( Exception e) {
}
}
}
private void Reset() {
savepointImage.delete();
if (!OPTION_SIGNATURE.equals(loadOption) && refImage != null
&& refImage.exists()) {
FileUtils.copyFile(refImage, savepointImage);
}
drawView.reset();
drawView.invalidate();
}
private void CancelAndClose() {
setResult(Activity.RESULT_CANCELED);
this.finish();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit");
createQuitDrawDialog();
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (event.isAltPressed()) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onKeyDown.KEYCODE_DPAD_RIGHT", "showNext");
createQuitDrawDialog();
return true;
}
break;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (event.isAltPressed()) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_LEFT",
"showPrevious");
createQuitDrawDialog();
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
/**
* Create a dialog with options to save and exit, save, or quit without
* saving
*/
private void createQuitDrawDialog() {
String[] items = { getString(R.string.keep_changes),
getString(R.string.do_not_save) };
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createQuitDrawDialog", "show");
alertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(alertTitleString)
.setNeutralButton(getString(R.string.do_not_exit),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog",
"cancel");
dialog.cancel();
}
})
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0: // save and exit
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog",
"saveAndExit");
SaveAndClose();
break;
case 1: // discard changes and exit
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog",
"discardAndExit");
CancelAndClose();
break;
case 2:// do nothing
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createQuitDrawDialog", "cancel");
break;
}
}
}).create();
alertDialog.show();
}
public class DrawView extends View {
private boolean isSignature;
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mCurrentPath;
private Paint mBitmapPaint;
private File mBackgroundBitmapFile;
public DrawView(final Context c) {
super(c);
isSignature = false;
mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mCurrentPath = new Path();
setBackgroundColor(0xFFFFFFFF);
mBackgroundBitmapFile = new File(Collect.TMPDRAWFILE_PATH);
}
public DrawView(Context c, boolean isSignature, File f) {
this(c);
this.isSignature = isSignature;
mBackgroundBitmapFile = f;
}
public void reset() {
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
resetImage(screenWidth, screenHeight);
}
public void resetImage(int w, int h) {
if (mBackgroundBitmapFile.exists()) {
mBitmap = FileUtils.getBitmapScaledToDisplay(
mBackgroundBitmapFile, w, h).copy(
Bitmap.Config.ARGB_8888, true);
// mBitmap =
// Bitmap.createScaledBitmap(BitmapFactory.decodeFile(mBackgroundBitmapFile.getPath()),
// w, h, true);
mCanvas = new Canvas(mBitmap);
} else {
mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mCanvas.drawColor(0xFFFFFFFF);
if (isSignature)
drawSignLine();
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
resetImage(w, h);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mCurrentPath, paint);
}
private float mX, mY;
private void touch_start(float x, float y) {
mCurrentPath.reset();
mCurrentPath.moveTo(x, y);
mX = x;
mY = y;
}
public void drawSignLine() {
mCanvas.drawLine(0, (int) (mCanvas.getHeight() * .7),
mCanvas.getWidth(), (int) (mCanvas.getHeight() * .7), paint);
}
private void touch_move(float x, float y) {
mCurrentPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
private void touch_up() {
if (mCurrentPath.isEmpty()) {
mCanvas.drawPoint(mX, mY, pointPaint);
} else {
mCurrentPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mCurrentPath, paint);
}
// kill this so we don't double draw
mCurrentPath.reset();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.Map.Entry;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.AdminPreferencesActivity;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Responsible for displaying buttons to launch the major activities. Launches
* some activities based on returns of others.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class MainMenuActivity extends Activity {
private static final String t = "MainMenuActivity";
private static final int PASSWORD_DIALOG = 1;
// menu options
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final int MENU_ADMIN = Menu.FIRST + 1;
// buttons
private Button mEnterDataButton;
private Button mManageFilesButton;
private Button mSendDataButton;
private Button mReviewDataButton;
private Button mGetFormsButton;
private View mReviewSpacer;
private View mGetFormsSpacer;
private AlertDialog mAlertDialog;
private SharedPreferences mAdminPreferences;
private int mCompletedCount;
private int mSavedCount;
private Cursor mFinalizedCursor;
private Cursor mSavedCursor;
private IncomingHandler mHandler = new IncomingHandler(this);
private MyContentObserver mContentObserver = new MyContentObserver();
private static boolean EXIT = true;
// private static boolean DO_NOT_EXIT = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an
// external intent
Log.i(t, "Starting up, creating directories");
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.main_menu);
{
// dynamically construct the "ODK Collect vA.B" string
TextView mainMenuMessageLabel = (TextView) findViewById(R.id.main_menu_header);
mainMenuMessageLabel.setText(Collect.getInstance()
.getVersionedAppName());
}
setTitle(getString(R.string.app_name) + " > "
+ getString(R.string.main_menu));
File f = new File(Collect.ODK_ROOT + "/collect.settings");
if (f.exists()) {
boolean success = loadSharedPreferencesFromFile(f);
if (success) {
Toast.makeText(this,
"Settings successfully loaded from file",
Toast.LENGTH_LONG).show();
f.delete();
} else {
Toast.makeText(
this,
"Sorry, settings file is corrupt and should be deleted or replaced",
Toast.LENGTH_LONG).show();
}
}
mReviewSpacer = findViewById(R.id.review_spacer);
mGetFormsSpacer = findViewById(R.id.get_forms_spacer);
mAdminPreferences = this.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
// enter data button. expects a result.
mEnterDataButton = (Button) findViewById(R.id.enter_data);
mEnterDataButton.setText(getString(R.string.enter_data_button));
mEnterDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "fillBlankForm", "click");
Intent i = new Intent(getApplicationContext(),
FormChooserList.class);
startActivity(i);
}
});
// review data button. expects a result.
mReviewDataButton = (Button) findViewById(R.id.review_data);
mReviewDataButton.setText(getString(R.string.review_data_button));
mReviewDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "editSavedForm", "click");
Intent i = new Intent(getApplicationContext(),
InstanceChooserList.class);
startActivity(i);
}
});
// send data button. expects a result.
mSendDataButton = (Button) findViewById(R.id.send_data);
mSendDataButton.setText(getString(R.string.send_data_button));
mSendDataButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "uploadForms", "click");
Intent i = new Intent(getApplicationContext(),
InstanceUploaderList.class);
startActivity(i);
}
});
// manage forms button. no result expected.
mGetFormsButton = (Button) findViewById(R.id.get_forms);
mGetFormsButton.setText(getString(R.string.get_forms));
mGetFormsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "downloadBlankForms", "click");
Intent i = new Intent(getApplicationContext(),
FormDownloadList.class);
startActivity(i);
}
});
// manage forms button. no result expected.
mManageFilesButton = (Button) findViewById(R.id.manage_forms);
mManageFilesButton.setText(getString(R.string.manage_files));
mManageFilesButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger()
.logAction(this, "deleteSavedForms", "click");
Intent i = new Intent(getApplicationContext(),
FileManagerTabs.class);
startActivity(i);
}
});
// count for finalized instances
String selection = InstanceColumns.STATUS + "=? or "
+ InstanceColumns.STATUS + "=?";
String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED };
mFinalizedCursor = managedQuery(InstanceColumns.CONTENT_URI, null,
selection, selectionArgs, null);
startManagingCursor(mFinalizedCursor);
mCompletedCount = mFinalizedCursor.getCount();
mFinalizedCursor.registerContentObserver(mContentObserver);
// count for finalized instances
String selectionSaved = InstanceColumns.STATUS + "=?";
String selectionArgsSaved[] = { InstanceProviderAPI.STATUS_INCOMPLETE };
mSavedCursor = managedQuery(InstanceColumns.CONTENT_URI, null,
selectionSaved, selectionArgsSaved, null);
startManagingCursor(mSavedCursor);
mSavedCount = mFinalizedCursor.getCount();
// don't need to set a content observer because it can't change in the
// background
updateButtons();
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = this.getSharedPreferences(
AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
boolean edit = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_EDIT_SAVED, true);
if (!edit) {
mReviewDataButton.setVisibility(View.GONE);
mReviewSpacer.setVisibility(View.GONE);
} else {
mReviewDataButton.setVisibility(View.VISIBLE);
mReviewSpacer.setVisibility(View.VISIBLE);
}
boolean send = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_SEND_FINALIZED, true);
if (!send) {
mSendDataButton.setVisibility(View.GONE);
} else {
mSendDataButton.setVisibility(View.VISIBLE);
}
boolean get_blank = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_GET_BLANK, true);
if (!get_blank) {
mGetFormsButton.setVisibility(View.GONE);
mGetFormsSpacer.setVisibility(View.GONE);
} else {
mGetFormsButton.setVisibility(View.VISIBLE);
mGetFormsSpacer.setVisibility(View.VISIBLE);
}
boolean delete_saved = sharedPreferences.getBoolean(
AdminPreferencesActivity.KEY_DELETE_SAVED, true);
if (!delete_saved) {
mManageFilesButton.setVisibility(View.GONE);
} else {
mManageFilesButton.setVisibility(View.VISIBLE);
}
}
@Override
protected void onPause() {
super.onPause();
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger()
.logAction(this, "onCreateOptionsMenu", "show");
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_PREFERENCES, 0,
getString(R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
menu.add(0, MENU_ADMIN, 0, getString(R.string.admin_preferences))
.setIcon(R.drawable.ic_menu_login);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Collect.getInstance()
.getActivityLogger()
.logAction(this, "onOptionsItemSelected",
"MENU_PREFERENCES");
Intent ig = new Intent(this, PreferencesActivity.class);
startActivity(ig);
return true;
case MENU_ADMIN:
Collect.getInstance().getActivityLogger()
.logAction(this, "onOptionsItemSelected", "MENU_ADMIN");
String pw = mAdminPreferences.getString(
AdminPreferencesActivity.KEY_ADMIN_PW, "");
if ("".equalsIgnoreCase(pw)) {
Intent i = new Intent(getApplicationContext(),
AdminPreferencesActivity.class);
startActivity(i);
} else {
showDialog(PASSWORD_DIALOG);
Collect.getInstance().getActivityLogger()
.logAction(this, "createAdminPasswordDialog", "show");
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger()
.logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1:
Collect.getInstance()
.getActivityLogger()
.logAction(this, "createErrorDialog",
shouldExit ? "exitApplication" : "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PASSWORD_DIALOG:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog passwordDialog = builder.create();
passwordDialog.setTitle(getString(R.string.enter_admin_password));
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
input.setTransformationMethod(PasswordTransformationMethod
.getInstance());
passwordDialog.setView(input, 20, 10, 20, 10);
passwordDialog.setButton(AlertDialog.BUTTON_POSITIVE,
getString(R.string.ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
String pw = mAdminPreferences.getString(
AdminPreferencesActivity.KEY_ADMIN_PW, "");
if (pw.compareTo(value) == 0) {
Intent i = new Intent(getApplicationContext(),
AdminPreferencesActivity.class);
startActivity(i);
input.setText("");
passwordDialog.dismiss();
} else {
Toast.makeText(
MainMenuActivity.this,
getString(R.string.admin_password_incorrect),
Toast.LENGTH_SHORT).show();
Collect.getInstance()
.getActivityLogger()
.logAction(this, "adminPasswordDialog",
"PASSWORD_INCORRECT");
}
}
});
passwordDialog.setButton(AlertDialog.BUTTON_NEGATIVE,
getString(R.string.cancel),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logAction(this, "adminPasswordDialog",
"cancel");
input.setText("");
return;
}
});
passwordDialog.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
return passwordDialog;
}
return null;
}
private void updateButtons() {
mFinalizedCursor.requery();
mCompletedCount = mFinalizedCursor.getCount();
if (mCompletedCount > 0) {
mSendDataButton.setText(getString(R.string.send_data_button,
mCompletedCount));
} else {
mSendDataButton.setText(getString(R.string.send_data));
}
mSavedCursor.requery();
mSavedCount = mSavedCursor.getCount();
if (mSavedCount > 0) {
mReviewDataButton.setText(getString(R.string.review_data_button,
mSavedCount));
} else {
mReviewDataButton.setText(getString(R.string.review_data));
}
}
/**
* notifies us that something changed
*
*/
private class MyContentObserver extends ContentObserver {
public MyContentObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
mHandler.sendEmptyMessage(0);
}
}
/*
* Used to prevent memory leaks
*/
static class IncomingHandler extends Handler {
private final WeakReference<MainMenuActivity> mTarget;
IncomingHandler(MainMenuActivity target) {
mTarget = new WeakReference<MainMenuActivity>(target);
}
@Override
public void handleMessage(Message msg) {
MainMenuActivity target = mTarget.get();
if (target != null) {
target.updateButtons();
}
}
}
private boolean loadSharedPreferencesFromFile(File src) {
// this should probably be in a thread if it ever gets big
boolean res = false;
ObjectInputStream input = null;
try {
input = new ObjectInputStream(new FileInputStream(src));
Editor prefEdit = PreferenceManager.getDefaultSharedPreferences(
this).edit();
prefEdit.clear();
// first object is preferences
Map<String, ?> entries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : entries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
prefEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
prefEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
prefEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
prefEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
prefEdit.putString(key, ((String) v));
}
prefEdit.commit();
// second object is admin options
Editor adminEdit = getSharedPreferences(AdminPreferencesActivity.ADMIN_PREFERENCES, 0).edit();
adminEdit.clear();
// first object is preferences
Map<String, ?> adminEntries = (Map<String, ?>) input.readObject();
for (Entry<String, ?> entry : adminEntries.entrySet()) {
Object v = entry.getValue();
String key = entry.getKey();
if (v instanceof Boolean)
adminEdit.putBoolean(key, ((Boolean) v).booleanValue());
else if (v instanceof Float)
adminEdit.putFloat(key, ((Float) v).floatValue());
else if (v instanceof Integer)
adminEdit.putInt(key, ((Integer) v).intValue());
else if (v instanceof Long)
adminEdit.putLong(key, ((Long) v).longValue());
else if (v instanceof String)
adminEdit.putString(key, ((String) v));
}
adminEdit.commit();
res = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return res;
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.activities;
import java.util.ArrayList;
import org.odk.collect.android.R;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
/**
* Allows the user to create desktop shortcuts to any form currently avaiable to Collect
*
* @author ctsims
* @author carlhartung (modified for ODK)
*/
public class AndroidShortcuts extends Activity {
private Uri[] mCommands;
private String[] mNames;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
final Intent intent = getIntent();
final String action = intent.getAction();
// The Android needs to know what shortcuts are available, generate the list
if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
buildMenuList();
}
}
/**
* Builds a list of shortcuts
*/
private void buildMenuList() {
ArrayList<String> names = new ArrayList<String>();
ArrayList<Uri> commands = new ArrayList<Uri>();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select ODK Shortcut");
Cursor c = null;
try {
c = getContentResolver().query(FormsColumns.CONTENT_URI, null, null, null, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
while (c.moveToNext()) {
String formName = c.getString(c.getColumnIndex(FormsColumns.DISPLAY_NAME));
names.add(formName);
Uri uri =
Uri.withAppendedPath(FormsColumns.CONTENT_URI,
c.getString(c.getColumnIndex(FormsColumns._ID)));
commands.add(uri);
}
}
} finally {
if ( c != null ) {
c.close();
}
}
mNames = names.toArray(new String[0]);
mCommands = commands.toArray(new Uri[0]);
builder.setItems(this.mNames, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
returnShortcut(mNames[item], mCommands[item]);
}
});
builder.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
AndroidShortcuts sc = AndroidShortcuts.this;
sc.setResult(RESULT_CANCELED);
sc.finish();
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
/**
* Returns the results to the calling intent.
*/
private void returnShortcut(String name, Uri command) {
Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
shortcutIntent.setData(command);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.notes);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Now, return the result to the launcher
setResult(RESULT_OK, intent);
finish();
return;
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.PreferencesActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class SplashScreenActivity extends Activity {
private static final int mSplashTimeout = 2000; // milliseconds
private static final boolean EXIT = true;
private int mImageMaxWidth;
private AlertDialog mAlertDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
mImageMaxWidth = getWindowManager().getDefaultDisplay().getWidth();
// this splash screen should be a blank slate
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_screen);
// get the shared preferences object
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = mSharedPreferences.edit();
// get the package info object with version number
PackageInfo packageInfo = null;
try {
packageInfo =
getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
boolean firstRun = mSharedPreferences.getBoolean(PreferencesActivity.KEY_FIRST_RUN, true);
boolean showSplash =
mSharedPreferences.getBoolean(PreferencesActivity.KEY_SHOW_SPLASH, false);
String splashPath =
mSharedPreferences.getString(PreferencesActivity.KEY_SPLASH_PATH,
getString(R.string.default_splash_path));
// if you've increased version code, then update the version number and set firstRun to true
if (mSharedPreferences.getLong(PreferencesActivity.KEY_LAST_VERSION, 0) < packageInfo.versionCode) {
editor.putLong(PreferencesActivity.KEY_LAST_VERSION, packageInfo.versionCode);
editor.commit();
firstRun = true;
}
// do all the first run things
if (firstRun || showSplash) {
editor.putBoolean(PreferencesActivity.KEY_FIRST_RUN, false);
editor.commit();
startSplashScreen(splashPath);
} else {
endSplashScreen();
}
}
private void endSplashScreen() {
// launch new activity and close splash screen
startActivity(new Intent(SplashScreenActivity.this, MainMenuActivity.class));
finish();
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
Bitmap b = null;
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int scale = 1;
if (o.outHeight > mImageMaxWidth || o.outWidth > mImageMaxWidth) {
scale =
(int) Math.pow(
2,
(int) Math.round(Math.log(mImageMaxWidth
/ (double) Math.max(o.outHeight, o.outWidth))
/ Math.log(0.5)));
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
}
return b;
}
private void startSplashScreen(String path) {
// add items to the splash screen here. makes things less distracting.
ImageView iv = (ImageView) findViewById(R.id.splash);
LinearLayout ll = (LinearLayout) findViewById(R.id.splash_default);
File f = new File(path);
if (f.exists()) {
iv.setImageBitmap(decodeFile(f));
ll.setVisibility(View.GONE);
iv.setVisibility(View.VISIBLE);
}
// create a thread that counts up to the timeout
Thread t = new Thread() {
int count = 0;
@Override
public void run() {
try {
super.run();
while (count < mSplashTimeout) {
sleep(100);
count += 100;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
endSplashScreen();
}
}
};
t.start();
}
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1:
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.DiskSyncListener;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.tasks.DiskSyncTask;
import org.odk.collect.android.utilities.VersionHidingCursorAdapter;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
/**
* Responsible for displaying all the valid forms in the forms directory. Stores the path to
* selected form for use by {@link MainMenuActivity}.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FormChooserList extends ListActivity implements DiskSyncListener {
private static final String t = "FormChooserList";
private static final boolean EXIT = true;
private static final String syncMsgKey = "syncmsgkey";
private DiskSyncTask mDiskSyncTask;
private AlertDialog mAlertDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an external intent
try {
Collect.createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.chooser_list_layout);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.enter_data));
String sortOrder = FormsColumns.DISPLAY_NAME + " ASC, " + FormsColumns.JR_VERSION + " DESC";
Cursor c = managedQuery(FormsColumns.CONTENT_URI, null, null, null, sortOrder);
String[] data = new String[] {
FormsColumns.DISPLAY_NAME, FormsColumns.DISPLAY_SUBTEXT, FormsColumns.JR_VERSION
};
int[] view = new int[] {
R.id.text1, R.id.text2, R.id.text3
};
// render total instance view
SimpleCursorAdapter instances =
new VersionHidingCursorAdapter(FormsColumns.JR_VERSION, this, R.layout.two_item, c, data, view);
setListAdapter(instances);
if (savedInstanceState != null && savedInstanceState.containsKey(syncMsgKey)) {
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setText(savedInstanceState.getString(syncMsgKey));
}
// DiskSyncTask checks the disk for any forms not already in the content provider
// that is, put here by dragging and dropping onto the SDCard
mDiskSyncTask = (DiskSyncTask) getLastNonConfigurationInstance();
if (mDiskSyncTask == null) {
Log.i(t, "Starting new disk sync task");
mDiskSyncTask = new DiskSyncTask();
mDiskSyncTask.setDiskSyncListener(this);
mDiskSyncTask.execute((Void[]) null);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
// pass the thread on restart
return mDiskSyncTask;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView tv = (TextView) findViewById(R.id.status_text);
outState.putString(syncMsgKey, tv.getText().toString());
}
/**
* Stores the path of selected form and finishes.
*/
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
// get uri to form
long idFormsTable = ((SimpleCursorAdapter) getListAdapter()).getItemId(position);
Uri formUri = ContentUris.withAppendedId(FormsColumns.CONTENT_URI, idFormsTable);
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", formUri.toString());
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action)) {
// caller is waiting on a picked form
setResult(RESULT_OK, new Intent().setData(formUri));
} else {
// caller wants to view/edit a form, so launch formentryactivity
startActivity(new Intent(Intent.ACTION_EDIT, formUri));
}
finish();
}
@Override
protected void onResume() {
mDiskSyncTask.setDiskSyncListener(this);
super.onResume();
if (mDiskSyncTask.getStatus() == AsyncTask.Status.FINISHED) {
SyncComplete(mDiskSyncTask.getStatusMessage());
}
}
@Override
protected void onPause() {
mDiskSyncTask.setDiskSyncListener(null);
super.onPause();
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
/**
* Called by DiskSyncTask when the task is finished
*/
@Override
public void SyncComplete(String result) {
Log.i(t, "disk sync task complete");
TextView tv = (TextView) findViewById(R.id.status_text);
tv.setText(result);
}
/**
* Creates a dialog with the given message. Will exit the activity when the user preses "ok" if
* shouldExit is set to true.
*
* @param errorMsg
* @param shouldExit
*/
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1:
Collect.getInstance().getActivityLogger().logAction(this, "createErrorDialog",
shouldExit ? "exitApplication" : "OK");
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
mAlertDialog.show();
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.InstanceUploaderListener;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.InstanceUploaderTask;
import org.odk.collect.android.utilities.WebUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
/**
* Activity to upload completed forms.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class InstanceUploaderActivity extends Activity implements InstanceUploaderListener {
private final static String t = "InstanceUploaderActivity";
private final static int PROGRESS_DIALOG = 1;
private final static int AUTH_DIALOG = 2;
private final static String AUTH_URI = "auth";
private static final String ALERT_MSG = "alertmsg";
private static final String ALERT_SHOWING = "alertshowing";
private static final String TO_SEND = "tosend";
private ProgressDialog mProgressDialog;
private AlertDialog mAlertDialog;
private String mAlertMsg;
private boolean mAlertShowing;
private InstanceUploaderTask mInstanceUploaderTask;
// maintain a list of what we've yet to send, in case we're interrupted by auth requests
private Long[] mInstancesToSend;
// maintain a list of what we've sent, in case we're interrupted by auth requests
private HashMap<String, String> mUploadedInstances;
private String mUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(t, "onCreate: " + ((savedInstanceState == null) ? "creating" : "re-initializing"));
mAlertMsg = getString(R.string.please_wait);
mAlertShowing = false;
mUploadedInstances = new HashMap<String, String>();
setTitle(getString(R.string.app_name) + " > " + getString(R.string.send_data));
// get any simple saved state...
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(ALERT_MSG)) {
mAlertMsg = savedInstanceState.getString(ALERT_MSG);
}
if (savedInstanceState.containsKey(ALERT_SHOWING)) {
mAlertShowing = savedInstanceState.getBoolean(ALERT_SHOWING, false);
}
mUrl = savedInstanceState.getString(AUTH_URI);
}
// and if we are resuming, use the TO_SEND list of not-yet-sent submissions
// Otherwise, construct the list from the incoming intent value
long[] selectedInstanceIDs = null;
if (savedInstanceState != null && savedInstanceState.containsKey(TO_SEND)) {
selectedInstanceIDs = savedInstanceState.getLongArray(TO_SEND);
} else {
// get instances to upload...
Intent intent = getIntent();
selectedInstanceIDs = intent.getLongArrayExtra(FormEntryActivity.KEY_INSTANCES);
}
mInstancesToSend = new Long[(selectedInstanceIDs == null) ? 0 : selectedInstanceIDs.length];
if ( selectedInstanceIDs != null ) {
for ( int i = 0 ; i < selectedInstanceIDs.length ; ++i ) {
mInstancesToSend[i] = selectedInstanceIDs[i];
}
}
// at this point, we don't expect this to be empty...
if (mInstancesToSend.length == 0) {
Log.e(t, "onCreate: No instances to upload!");
// drop through -- everything will process through OK
} else {
Log.i(t, "onCreate: Beginning upload of " + mInstancesToSend.length + " instances!");
}
// get the task if we've changed orientations. If it's null it's a new upload.
mInstanceUploaderTask = (InstanceUploaderTask) getLastNonConfigurationInstance();
if (mInstanceUploaderTask == null) {
// setup dialog and upload task
showDialog(PROGRESS_DIALOG);
mInstanceUploaderTask = new InstanceUploaderTask();
// register this activity with the new uploader task
mInstanceUploaderTask.setUploaderListener(InstanceUploaderActivity.this);
mInstanceUploaderTask.execute(mInstancesToSend);
}
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onResume() {
Log.i(t, "onResume: Resuming upload of " + mInstancesToSend.length + " instances!");
if (mInstanceUploaderTask != null) {
mInstanceUploaderTask.setUploaderListener(this);
}
if (mAlertShowing) {
createAlertDialog(mAlertMsg);
}
super.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(ALERT_MSG, mAlertMsg);
outState.putBoolean(ALERT_SHOWING, mAlertShowing);
outState.putString(AUTH_URI, mUrl);
long[] toSend = new long[mInstancesToSend.length];
for ( int i = 0 ; i < mInstancesToSend.length ; ++i ) {
toSend[i] = mInstancesToSend[i];
}
outState.putLongArray(TO_SEND, toSend);
}
@Override
public Object onRetainNonConfigurationInstance() {
return mInstanceUploaderTask;
}
@Override
protected void onPause() {
Log.i(t, "onPause: Pausing upload of " + mInstancesToSend.length + " instances!");
super.onPause();
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
@Override
protected void onDestroy() {
if (mInstanceUploaderTask != null) {
mInstanceUploaderTask.setUploaderListener(null);
}
super.onDestroy();
}
@Override
public void uploadingComplete(HashMap<String, String> result) {
Log.i(t, "uploadingComplete: Processing results (" + result.size() + ") from upload of " + mInstancesToSend.length + " instances!");
try {
dismissDialog(PROGRESS_DIALOG);
} catch (Exception e) {
// tried to close a dialog not open. don't care.
}
StringBuilder selection = new StringBuilder();
Set<String> keys = result.keySet();
Iterator<String> it = keys.iterator();
String[] selectionArgs = new String[keys.size()];
int i = 0;
while (it.hasNext()) {
String id = it.next();
selection.append(InstanceColumns._ID + "=?");
selectionArgs[i++] = id;
if (i != keys.size()) {
selection.append(" or ");
}
}
StringBuilder message = new StringBuilder();
{
Cursor results = null;
try {
results = getContentResolver().query(InstanceColumns.CONTENT_URI,
null, selection.toString(), selectionArgs, null);
if (results.getCount() > 0) {
results.moveToPosition(-1);
while (results.moveToNext()) {
String name =
results.getString(results.getColumnIndex(InstanceColumns.DISPLAY_NAME));
String id = results.getString(results.getColumnIndex(InstanceColumns._ID));
message.append(name + " - " + result.get(id) + "\n\n");
}
} else {
message.append(getString(R.string.no_forms_uploaded));
}
} finally {
if ( results != null ) {
results.close();
}
}
}
createAlertDialog(message.toString().trim());
}
@Override
public void progressUpdate(int progress, int total) {
mAlertMsg = getString(R.string.sending_items, progress, total);
mProgressDialog.setMessage(mAlertMsg);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "cancel");
dialog.dismiss();
mInstanceUploaderTask.cancel(true);
mInstanceUploaderTask.setUploaderListener(null);
finish();
}
};
mProgressDialog.setTitle(getString(R.string.uploading_data));
mProgressDialog.setMessage(mAlertMsg);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener);
return mProgressDialog;
case AUTH_DIALOG:
Log.i(t, "onCreateDialog(AUTH_DIALOG): for upload of " + mInstancesToSend.length + " instances!");
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "show");
AlertDialog.Builder b = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(R.layout.server_auth_dialog, null);
// Get the server, username, and password from the settings
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String server = mUrl;
if (server == null) {
Log.e(t, "onCreateDialog(AUTH_DIALOG): No failing mUrl specified for upload of " + mInstancesToSend.length + " instances!");
// if the bundle is null, we're looking for a formlist
String submissionUrl = getString(R.string.default_odk_submission);
server =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
getString(R.string.default_server_url))
+ settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, submissionUrl);
}
final String url = server;
Log.i(t, "Trying connecting to: " + url);
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null);
username.setText(storedUsername);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null);
password.setText(storedPassword);
b.setTitle(getString(R.string.server_requires_auth));
b.setMessage(getString(R.string.server_auth_credentials, url));
b.setView(dialogView);
b.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "OK");
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
Uri u = Uri.parse(url);
WebUtils.addCredentials(username.getText().toString(), password.getText()
.toString(), u.getHost());
showDialog(PROGRESS_DIALOG);
mInstanceUploaderTask = new InstanceUploaderTask();
// register this activity with the new uploader task
mInstanceUploaderTask.setUploaderListener(InstanceUploaderActivity.this);
mInstanceUploaderTask.execute(mInstancesToSend);
}
});
b.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "cancel");
finish();
}
});
b.setCancelable(false);
return b.create();
}
return null;
}
@Override
public void authRequest(Uri url, HashMap<String, String> doneSoFar) {
if (mProgressDialog.isShowing()) {
// should always be showing here
mProgressDialog.dismiss();
}
// add our list of completed uploads to "completed"
// and remove them from our toSend list.
ArrayList<Long> workingSet = new ArrayList<Long>();
Collections.addAll(workingSet, mInstancesToSend);
if (doneSoFar != null) {
Set<String> uploadedInstances = doneSoFar.keySet();
Iterator<String> itr = uploadedInstances.iterator();
while (itr.hasNext()) {
Long removeMe = Long.valueOf(itr.next());
boolean removed = workingSet.remove(removeMe);
if (removed) {
Log.i(t, removeMe
+ " was already sent, removing from queue before restarting task");
}
}
mUploadedInstances.putAll(doneSoFar);
}
// and reconstruct the pending set of instances to send
Long[] updatedToSend = new Long[workingSet.size()];
for ( int i = 0 ; i < workingSet.size() ; ++i ) {
updatedToSend[i] = workingSet.get(i);
}
mInstancesToSend = updatedToSend;
mUrl = url.toString();
showDialog(AUTH_DIALOG);
}
private void createAlertDialog(String message) {
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(getString(R.string.upload_results));
mAlertDialog.setMessage(message);
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // ok
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "OK");
// always exit this activity since it has no interface
mAlertShowing = false;
finish();
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), quitListener);
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertShowing = true;
mAlertMsg = message;
mAlertDialog.show();
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.FormDownloaderListener;
import org.odk.collect.android.listeners.FormListDownloaderListener;
import org.odk.collect.android.logic.FormDetails;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.tasks.DownloadFormListTask;
import org.odk.collect.android.tasks.DownloadFormsTask;
import org.odk.collect.android.utilities.WebUtils;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
/**
* Responsible for displaying, adding and deleting all the valid forms in the forms directory. One
* caveat. If the server requires authentication, a dialog will pop up asking when you request the
* form list. If somehow you manage to wait long enough and then try to download selected forms and
* your authorization has timed out, it won't again ask for authentication, it will just throw a 401
* and you'll have to hit 'refresh' where it will ask for credentials again. Technically a server
* could point at other servers requiring authentication to download the forms, but the current
* implementation in Collect doesn't allow for that. Mostly this is just because it's a pain in the
* butt to keep track of which forms we've downloaded and where we're needing to authenticate. I
* think we do something similar in the instanceuploader task/activity, so should change the
* implementation eventually.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FormDownloadList extends ListActivity implements FormListDownloaderListener,
FormDownloaderListener {
private static final String t = "RemoveFileManageList";
private static final int PROGRESS_DIALOG = 1;
private static final int AUTH_DIALOG = 2;
private static final int MENU_PREFERENCES = Menu.FIRST;
private static final String BUNDLE_TOGGLED_KEY = "toggled";
private static final String BUNDLE_SELECTED_COUNT = "selectedcount";
private static final String BUNDLE_FORM_MAP = "formmap";
private static final String DIALOG_TITLE = "dialogtitle";
private static final String DIALOG_MSG = "dialogmsg";
private static final String DIALOG_SHOWING = "dialogshowing";
private static final String FORMLIST = "formlist";
public static final String LIST_URL = "listurl";
private static final String FORMNAME = "formname";
private static final String FORMDETAIL_KEY = "formdetailkey";
private static final String FORMID_DISPLAY = "formiddisplay";
private String mAlertMsg;
private boolean mAlertShowing = false;
private String mAlertTitle;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private Button mDownloadButton;
private DownloadFormListTask mDownloadFormListTask;
private DownloadFormsTask mDownloadFormsTask;
private Button mToggleButton;
private Button mRefreshButton;
private HashMap<String, FormDetails> mFormNamesAndURLs = new HashMap<String,FormDetails>();
private SimpleAdapter mFormListAdapter;
private ArrayList<HashMap<String, String>> mFormList;
private boolean mToggled = false;
private int mSelectedCount = 0;
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private boolean mShouldExit;
private static final String SHOULD_EXIT = "shouldexit";
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remote_file_manage_list);
setTitle(getString(R.string.app_name) + " > " + getString(R.string.get_forms));
mAlertMsg = getString(R.string.please_wait);
// need white background before load
getListView().setBackgroundColor(Color.WHITE);
mDownloadButton = (Button) findViewById(R.id.add_button);
mDownloadButton.setEnabled(selectedItemCount() > 0);
mDownloadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// this is callled in downloadSelectedFiles():
// Collect.getInstance().getActivityLogger().logAction(this, "downloadSelectedFiles", ...);
downloadSelectedFiles();
mToggled = false;
clearChoices();
}
});
mToggleButton = (Button) findViewById(R.id.toggle_button);
mToggleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// toggle selections of items to all or none
ListView ls = getListView();
mToggled = !mToggled;
Collect.getInstance().getActivityLogger().logAction(this, "toggleFormCheckbox", Boolean.toString(mToggled));
for (int pos = 0; pos < ls.getCount(); pos++) {
ls.setItemChecked(pos, mToggled);
}
mDownloadButton.setEnabled(!(selectedItemCount() == 0));
}
});
mRefreshButton = (Button) findViewById(R.id.refresh_button);
mRefreshButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logAction(this, "refreshForms", "");
mToggled = false;
downloadFormList();
FormDownloadList.this.getListView().clearChoices();
clearChoices();
}
});
if (savedInstanceState != null) {
// If the screen has rotated, the hashmap with the form ids and urls is passed here.
if (savedInstanceState.containsKey(BUNDLE_FORM_MAP)) {
mFormNamesAndURLs =
(HashMap<String, FormDetails>) savedInstanceState
.getSerializable(BUNDLE_FORM_MAP);
}
// indicating whether or not select-all is on or off.
if (savedInstanceState.containsKey(BUNDLE_TOGGLED_KEY)) {
mToggled = savedInstanceState.getBoolean(BUNDLE_TOGGLED_KEY);
}
// how many items we've selected
// Android should keep track of this, but broken on rotate...
if (savedInstanceState.containsKey(BUNDLE_SELECTED_COUNT)) {
mSelectedCount = savedInstanceState.getInt(BUNDLE_SELECTED_COUNT);
mDownloadButton.setEnabled(!(mSelectedCount == 0));
}
// to restore alert dialog.
if (savedInstanceState.containsKey(DIALOG_TITLE)) {
mAlertTitle = savedInstanceState.getString(DIALOG_TITLE);
}
if (savedInstanceState.containsKey(DIALOG_MSG)) {
mAlertMsg = savedInstanceState.getString(DIALOG_MSG);
}
if (savedInstanceState.containsKey(DIALOG_SHOWING)) {
mAlertShowing = savedInstanceState.getBoolean(DIALOG_SHOWING);
}
if (savedInstanceState.containsKey(SHOULD_EXIT)) {
mShouldExit = savedInstanceState.getBoolean(SHOULD_EXIT);
}
}
if (savedInstanceState != null && savedInstanceState.containsKey(FORMLIST)) {
mFormList =
(ArrayList<HashMap<String, String>>) savedInstanceState.getSerializable(FORMLIST);
} else {
mFormList = new ArrayList<HashMap<String, String>>();
}
if (getLastNonConfigurationInstance() instanceof DownloadFormListTask) {
mDownloadFormListTask = (DownloadFormListTask) getLastNonConfigurationInstance();
if (mDownloadFormListTask.getStatus() == AsyncTask.Status.FINISHED) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (IllegalArgumentException e) {
Log.i(t, "Attempting to close a dialog that was not previously opened");
}
mDownloadFormsTask = null;
}
} else if (getLastNonConfigurationInstance() instanceof DownloadFormsTask) {
mDownloadFormsTask = (DownloadFormsTask) getLastNonConfigurationInstance();
if (mDownloadFormsTask.getStatus() == AsyncTask.Status.FINISHED) {
try {
dismissDialog(PROGRESS_DIALOG);
} catch (IllegalArgumentException e) {
Log.i(t, "Attempting to close a dialog that was not previously opened");
}
mDownloadFormsTask = null;
}
} else if (getLastNonConfigurationInstance() == null) {
// first time, so get the formlist
downloadFormList();
}
String[] data = new String[] {
FORMNAME, FORMID_DISPLAY, FORMDETAIL_KEY
};
int[] view = new int[] {
R.id.text1, R.id.text2
};
mFormListAdapter =
new SimpleAdapter(this, mFormList, R.layout.two_item_multiple_choice, data, view);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setItemsCanFocus(false);
setListAdapter(mFormListAdapter);
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void clearChoices() {
FormDownloadList.this.getListView().clearChoices();
mDownloadButton.setEnabled(false);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mDownloadButton.setEnabled(!(selectedItemCount() == 0));
Object o = getListAdapter().getItem(position);
@SuppressWarnings("unchecked")
HashMap<String, String> item = (HashMap<String, String>) o;
FormDetails detail = mFormNamesAndURLs.get(item.get(FORMDETAIL_KEY));
Collect.getInstance().getActivityLogger().logAction(this, "onListItemClick", detail.downloadUrl);
}
/**
* Starts the download task and shows the progress dialog.
*/
private void downloadFormList() {
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni == null || !ni.isConnected()) {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
} else {
mFormNamesAndURLs = new HashMap<String, FormDetails>();
if (mProgressDialog != null) {
// This is needed because onPrepareDialog() is broken in 1.6.
mProgressDialog.setMessage(getString(R.string.please_wait));
}
showDialog(PROGRESS_DIALOG);
if (mDownloadFormListTask != null &&
mDownloadFormListTask.getStatus() != AsyncTask.Status.FINISHED) {
return; // we are already doing the download!!!
} else if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask.cancel(true);
mDownloadFormListTask = null;
}
mDownloadFormListTask = new DownloadFormListTask();
mDownloadFormListTask.setDownloaderListener(this);
mDownloadFormListTask.execute();
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(BUNDLE_TOGGLED_KEY, mToggled);
outState.putInt(BUNDLE_SELECTED_COUNT, selectedItemCount());
outState.putSerializable(BUNDLE_FORM_MAP, mFormNamesAndURLs);
outState.putString(DIALOG_TITLE, mAlertTitle);
outState.putString(DIALOG_MSG, mAlertMsg);
outState.putBoolean(DIALOG_SHOWING, mAlertShowing);
outState.putBoolean(SHOULD_EXIT, mShouldExit);
outState.putSerializable(FORMLIST, mFormList);
}
/**
* returns the number of items currently selected in the list.
*
* @return
*/
private int selectedItemCount() {
int count = 0;
SparseBooleanArray sba = getListView().getCheckedItemPositions();
for (int i = 0; i < getListView().getCount(); i++) {
if (sba.get(i, false)) {
count++;
}
}
return count;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateOptionsMenu", "show");
menu.add(0, MENU_PREFERENCES, 0, getString(R.string.general_preferences)).setIcon(
android.R.drawable.ic_menu_preferences);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Collect.getInstance().getActivityLogger().logAction(this, "onMenuItemSelected", "MENU_PREFERENCES");
Intent i = new Intent(this, PreferencesActivity.class);
startActivity(i);
return true;
}
return super.onMenuItemSelected(featureId, item);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener =
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.PROGRESS_DIALOG", "OK");
dialog.dismiss();
// we use the same progress dialog for both
// so whatever isn't null is running
if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask.cancel(true);
mDownloadFormListTask = null;
}
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(null);
mDownloadFormsTask.cancel(true);
mDownloadFormsTask = null;
}
}
};
mProgressDialog.setTitle(getString(R.string.downloading_data));
mProgressDialog.setMessage(mAlertMsg);
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel), loadingButtonListener);
return mProgressDialog;
case AUTH_DIALOG:
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "show");
AlertDialog.Builder b = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(R.layout.server_auth_dialog, null);
// Get the server, username, and password from the settings
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String server =
settings.getString(PreferencesActivity.KEY_SERVER_URL,
getString(R.string.default_server_url));
String formListUrl = getString(R.string.default_odk_formlist);
final String url =
server + settings.getString(PreferencesActivity.KEY_FORMLIST_URL, formListUrl);
Log.i(t, "Trying to get formList from: " + url);
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null);
username.setText(storedUsername);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null);
password.setText(storedPassword);
b.setTitle(getString(R.string.server_requires_auth));
b.setMessage(getString(R.string.server_auth_credentials, url));
b.setView(dialogView);
b.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "OK");
EditText username = (EditText) dialogView.findViewById(R.id.username_edit);
EditText password = (EditText) dialogView.findViewById(R.id.password_edit);
Uri u = Uri.parse(url);
WebUtils.addCredentials(username.getText().toString(), password.getText()
.toString(), u.getHost());
downloadFormList();
}
});
b.setNegativeButton(getString(R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance().getActivityLogger().logAction(this, "onCreateDialog.AUTH_DIALOG", "Cancel");
finish();
}
});
b.setCancelable(false);
mAlertShowing = false;
return b.create();
}
return null;
}
/**
* starts the task to download the selected forms, also shows progress dialog
*/
@SuppressWarnings("unchecked")
private void downloadSelectedFiles() {
int totalCount = 0;
ArrayList<FormDetails> filesToDownload = new ArrayList<FormDetails>();
SparseBooleanArray sba = getListView().getCheckedItemPositions();
for (int i = 0; i < getListView().getCount(); i++) {
if (sba.get(i, false)) {
HashMap<String, String> item =
(HashMap<String, String>) getListAdapter().getItem(i);
filesToDownload.add(mFormNamesAndURLs.get(item.get(FORMDETAIL_KEY)));
}
}
totalCount = filesToDownload.size();
Collect.getInstance().getActivityLogger().logAction(this, "downloadSelectedFiles", Integer.toString(totalCount));
if (totalCount > 0) {
// show dialog box
showDialog(PROGRESS_DIALOG);
mDownloadFormsTask = new DownloadFormsTask();
mDownloadFormsTask.setDownloaderListener(this);
mDownloadFormsTask.execute(filesToDownload);
} else {
Toast.makeText(getApplicationContext(), R.string.noselect_error, Toast.LENGTH_SHORT)
.show();
}
}
@Override
public Object onRetainNonConfigurationInstance() {
if (mDownloadFormsTask != null) {
return mDownloadFormsTask;
} else {
return mDownloadFormListTask;
}
}
@Override
protected void onDestroy() {
if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(null);
}
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(null);
}
super.onDestroy();
}
@Override
protected void onResume() {
if (mDownloadFormListTask != null) {
mDownloadFormListTask.setDownloaderListener(this);
}
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(this);
}
if (mAlertShowing) {
createAlertDialog(mAlertTitle, mAlertMsg, mShouldExit);
}
super.onResume();
}
@Override
protected void onPause() {
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
super.onPause();
}
/**
* Called when the form list has finished downloading. results will either contain a set of
* <formname, formdetails> tuples, or one tuple of DL.ERROR.MSG and the associated message.
*
* @param result
*/
public void formListDownloadingComplete(HashMap<String, FormDetails> result) {
dismissDialog(PROGRESS_DIALOG);
mDownloadFormListTask.setDownloaderListener(null);
mDownloadFormListTask = null;
if (result == null) {
Log.e(t, "Formlist Downloading returned null. That shouldn't happen");
// Just displayes "error occured" to the user, but this should never happen.
createAlertDialog(getString(R.string.load_remote_form_error),
getString(R.string.error_occured), EXIT);
return;
}
if (result.containsKey(DownloadFormListTask.DL_AUTH_REQUIRED)) {
// need authorization
showDialog(AUTH_DIALOG);
} else if (result.containsKey(DownloadFormListTask.DL_ERROR_MSG)) {
// Download failed
String dialogMessage =
getString(R.string.list_failed_with_error,
result.get(DownloadFormListTask.DL_ERROR_MSG).errorStr);
String dialogTitle = getString(R.string.load_remote_form_error);
createAlertDialog(dialogTitle, dialogMessage, DO_NOT_EXIT);
} else {
// Everything worked. Clear the list and add the results.
mFormNamesAndURLs = result;
mFormList.clear();
ArrayList<String> ids = new ArrayList<String>(mFormNamesAndURLs.keySet());
for (int i = 0; i < result.size(); i++) {
String formDetailsKey = ids.get(i);
FormDetails details = mFormNamesAndURLs.get(formDetailsKey);
HashMap<String, String> item = new HashMap<String, String>();
item.put(FORMNAME, details.formName);
item.put(FORMID_DISPLAY,
((details.formVersion == null) ? "" : (getString(R.string.version) + " " + details.formVersion + " ")) +
"ID: " + details.formID );
item.put(FORMDETAIL_KEY, formDetailsKey);
// Insert the new form in alphabetical order.
if (mFormList.size() == 0) {
mFormList.add(item);
} else {
int j;
for (j = 0; j < mFormList.size(); j++) {
HashMap<String, String> compareMe = mFormList.get(j);
String name = compareMe.get(FORMNAME);
if (name.compareTo(mFormNamesAndURLs.get(ids.get(i)).formName) > 0) {
break;
}
}
mFormList.add(j, item);
}
}
mFormListAdapter.notifyDataSetChanged();
}
}
/**
* Creates an alert dialog with the given tite and message. If shouldExit is set to true, the
* activity will exit when the user clicks "ok".
*
* @param title
* @param message
* @param shouldExit
*/
private void createAlertDialog(String title, String message, final boolean shouldExit) {
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "show");
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setTitle(title);
mAlertDialog.setMessage(message);
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON1: // ok
Collect.getInstance().getActivityLogger().logAction(this, "createAlertDialog", "OK");
// just close the dialog
mAlertShowing = false;
// successful download, so quit
if (shouldExit) {
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), quitListener);
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertMsg = message;
mAlertTitle = title;
mAlertShowing = true;
mShouldExit = shouldExit;
mAlertDialog.show();
}
@Override
public void progressUpdate(String currentFile, int progress, int total) {
mAlertMsg = getString(R.string.fetching_file, currentFile, progress, total);
mProgressDialog.setMessage(mAlertMsg);
}
@Override
public void formsDownloadingComplete(HashMap<FormDetails, String> result) {
if (mDownloadFormsTask != null) {
mDownloadFormsTask.setDownloaderListener(null);
}
if (mProgressDialog.isShowing()) {
// should always be true here
mProgressDialog.dismiss();
}
Set<FormDetails> keys = result.keySet();
StringBuilder b = new StringBuilder();
for (FormDetails k : keys) {
b.append(k.formName +
" (" +
((k.formVersion != null) ?
(this.getString(R.string.version) + ": " + k.formVersion + " ")
: "") +
"ID: " + k.formID + ") - " +
result.get(k));
b.append("\n\n");
}
createAlertDialog(getString(R.string.download_forms_result), b.toString().trim(), EXIT);
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.adapters;
import org.odk.collect.android.logic.HierarchyElement;
import org.odk.collect.android.views.HierarchyElementView;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.ArrayList;
import java.util.List;
public class HierarchyListAdapter extends BaseAdapter {
private Context mContext;
private List<HierarchyElement> mItems = new ArrayList<HierarchyElement>();
public HierarchyListAdapter(Context context) {
mContext = context;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HierarchyElementView hev;
if (convertView == null) {
hev = new HierarchyElementView(mContext, mItems.get(position));
} else {
hev = (HierarchyElementView) convertView;
hev.setPrimaryText(mItems.get(position).getPrimaryText());
hev.setSecondaryText(mItems.get(position).getSecondaryText());
hev.setIcon(mItems.get(position).getIcon());
hev.setColor(mItems.get(position).getColor());
}
if (mItems.get(position).getSecondaryText() == null
|| mItems.get(position).getSecondaryText().equals("")) {
hev.showSecondary(false);
} else {
hev.showSecondary(true);
}
return hev;
}
/**
* Sets the list of items for this adapter to use.
*/
public void setListItems(List<HierarchyElement> it) {
mItems = it;
}
}
| Java |
/*
* 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 org.odk.collect.android.provider;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Convenience definitions for NotePadProvider
*/
public final class InstanceProviderAPI {
public static final String AUTHORITY = "org.odk.collect.android.provider.odk.instances";
// This class cannot be instantiated
private InstanceProviderAPI() {}
// status for instances
public static final String STATUS_INCOMPLETE = "incomplete";
public static final String STATUS_COMPLETE = "complete";
public static final String STATUS_SUBMITTED = "submitted";
public static final String STATUS_SUBMISSION_FAILED = "submissionFailed";
/**
* Notes table
*/
public static final class InstanceColumns implements BaseColumns {
// This class cannot be instantiated
private InstanceColumns() {}
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/instances");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.odk.instance";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.odk.instance";
// These are the only things needed for an insert
public static final String DISPLAY_NAME = "displayName";
public static final String SUBMISSION_URI = "submissionUri";
public static final String INSTANCE_FILE_PATH = "instanceFilePath";
public static final String JR_FORM_ID = "jrFormId";
public static final String JR_VERSION = "jrVersion";
//public static final String FORM_ID = "formId";
// these are generated for you (but you can insert something else if you want)
public static final String STATUS = "status";
public static final String CAN_EDIT_WHEN_COMPLETE = "canEditWhenComplete";
public static final String LAST_STATUS_CHANGE_DATE = "date";
public static final String DISPLAY_SUBTEXT = "displaySubtext";
//public static final String DISPLAY_SUB_SUBTEXT = "displaySubSubtext";
// public static final String DEFAULT_SORT_ORDER = "modified DESC";
// public static final String TITLE = "title";
// public static final String NOTE = "note";
// public static final String CREATED_DATE = "created";
// public static final String MODIFIED_DATE = "modified";
}
}
| Java |
/*
* 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 org.odk.collect.android.provider;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.database.ODKSQLiteOpenHelper;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.utilities.MediaUtils;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
/**
*
*/
public class InstanceProvider extends ContentProvider {
private static final String t = "InstancesProvider";
private static final String DATABASE_NAME = "instances.db";
private static final int DATABASE_VERSION = 3;
private static final String INSTANCES_TABLE_NAME = "instances";
private static HashMap<String, String> sInstancesProjectionMap;
private static final int INSTANCES = 1;
private static final int INSTANCE_ID = 2;
private static final UriMatcher sUriMatcher;
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends ODKSQLiteOpenHelper {
DatabaseHelper(String databaseName) {
super(Collect.METADATA_PATH, databaseName, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + INSTANCES_TABLE_NAME + " ("
+ InstanceColumns._ID + " integer primary key, "
+ InstanceColumns.DISPLAY_NAME + " text not null, "
+ InstanceColumns.SUBMISSION_URI + " text, "
+ InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " text, "
+ InstanceColumns.INSTANCE_FILE_PATH + " text not null, "
+ InstanceColumns.JR_FORM_ID + " text not null, "
+ InstanceColumns.JR_VERSION + " text, "
+ InstanceColumns.STATUS + " text not null, "
+ InstanceColumns.LAST_STATUS_CHANGE_DATE + " date not null, "
+ InstanceColumns.DISPLAY_SUBTEXT + " text not null );");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int initialVersion = oldVersion;
if ( oldVersion == 1 ) {
db.execSQL("ALTER TABLE " + INSTANCES_TABLE_NAME + " ADD COLUMN " +
InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " text;");
db.execSQL("UPDATE " + INSTANCES_TABLE_NAME + " SET " +
InstanceColumns.CAN_EDIT_WHEN_COMPLETE + " = '" + Boolean.toString(true) + "' WHERE " +
InstanceColumns.STATUS + " IS NOT NULL AND " +
InstanceColumns.STATUS + " != '" + InstanceProviderAPI.STATUS_INCOMPLETE + "'");
oldVersion = 2;
}
if ( oldVersion == 2 ) {
db.execSQL("ALTER TABLE " + INSTANCES_TABLE_NAME + " ADD COLUMN " +
InstanceColumns.JR_VERSION + " text;");
}
Log.w(t, "Successfully upgraded database from version " + initialVersion + " to " + newVersion
+ ", without destroying all the old data");
}
}
private DatabaseHelper mDbHelper;
@Override
public boolean onCreate() {
// must be at the beginning of any activity that can be called from an external intent
Collect.createODKDirs();
mDbHelper = new DatabaseHelper(DATABASE_NAME);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(INSTANCES_TABLE_NAME);
switch (sUriMatcher.match(uri)) {
case INSTANCES:
qb.setProjectionMap(sInstancesProjectionMap);
break;
case INSTANCE_ID:
qb.setProjectionMap(sInstancesProjectionMap);
qb.appendWhere(InstanceColumns._ID + "=" + uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Get the database and run the query
SQLiteDatabase db = mDbHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
// Tell the cursor what uri to watch, so it knows when its source data changes
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public String getType(Uri uri) {
switch (sUriMatcher.match(uri)) {
case INSTANCES:
return InstanceColumns.CONTENT_TYPE;
case INSTANCE_ID:
return InstanceColumns.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues initialValues) {
// Validate the requested uri
if (sUriMatcher.match(uri) != INSTANCES) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
}
Long now = Long.valueOf(System.currentTimeMillis());
// Make sure that the fields are all set
if (values.containsKey(InstanceColumns.LAST_STATUS_CHANGE_DATE) == false) {
values.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, now);
}
if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String text = getDisplaySubtext(InstanceProviderAPI.STATUS_INCOMPLETE, today);
values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
}
if (values.containsKey(InstanceColumns.STATUS) == false) {
values.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_INCOMPLETE);
}
SQLiteDatabase db = mDbHelper.getWritableDatabase();
long rowId = db.insert(INSTANCES_TABLE_NAME, null, values);
if (rowId > 0) {
Uri instanceUri = ContentUris.withAppendedId(InstanceColumns.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(instanceUri, null);
Collect.getInstance().getActivityLogger().logActionParam(this, "insert",
instanceUri.toString(), values.getAsString(InstanceColumns.INSTANCE_FILE_PATH));
return instanceUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
private String getDisplaySubtext(String state, Date date) {
if (state == null) {
return new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_INCOMPLETE.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.saved_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_COMPLETE.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.finalized_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_SUBMITTED.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.sent_on_date_at_time), Locale.getDefault()).format(date);
} else if (InstanceProviderAPI.STATUS_SUBMISSION_FAILED.equalsIgnoreCase(state)) {
return new SimpleDateFormat(getContext().getString(R.string.sending_failed_on_date_at_time), Locale.getDefault()).format(date);
} else {
return new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(date);
}
}
private void deleteAllFilesInDirectory(File directory) {
if (directory.exists()) {
if (directory.isDirectory()) {
// delete any media entries for files in this directory...
int images = MediaUtils.deleteImagesInFolderFromMediaProvider(directory);
int audio = MediaUtils.deleteAudioInFolderFromMediaProvider(directory);
int video = MediaUtils.deleteVideoInFolderFromMediaProvider(directory);
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files,"
+ " and " + video + " video files.");
// delete all the files in the directory
File[] files = directory.listFiles();
for (File f : files) {
// should make this recursive if we get worried about
// the media directory containing directories
f.delete();
}
}
directory.delete();
}
}
/**
* This method removes the entry from the content provider, and also removes any associated files.
* files: form.xml, [formmd5].formdef, formname-media {directory}
*/
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case INSTANCES:
Cursor del = null;
try {
del = this.query(uri, null, where, whereArgs, null);
del.moveToPosition(-1);
while (del.moveToNext()) {
String instanceFile = del.getString(del.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "delete", instanceFile);
File instanceDir = (new File(instanceFile)).getParentFile();
deleteAllFilesInDirectory(instanceDir);
}
} finally {
if ( del != null ) {
del.close();
}
}
count = db.delete(INSTANCES_TABLE_NAME, where, whereArgs);
break;
case INSTANCE_ID:
String instanceId = uri.getPathSegments().get(1);
Cursor c = null;
try {
c = this.query(uri, null, where, whereArgs, null);
// This should only ever return 1 record. I hope.
c.moveToPosition(-1);
while (c.moveToNext()) {
String instanceFile = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "delete", instanceFile);
File instanceDir = (new File(instanceFile)).getParentFile();
deleteAllFilesInDirectory(instanceDir);
}
} finally {
if ( c != null ) {
c.close();
}
}
count =
db.delete(INSTANCES_TABLE_NAME,
InstanceColumns._ID + "=" + instanceId
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int count;
String status = null;
switch (sUriMatcher.match(uri)) {
case INSTANCES:
if (values.containsKey(InstanceColumns.STATUS)) {
status = values.getAsString(InstanceColumns.STATUS);
if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String text = getDisplaySubtext(status, today);
values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
}
}
count = db.update(INSTANCES_TABLE_NAME, values, where, whereArgs);
break;
case INSTANCE_ID:
String instanceId = uri.getPathSegments().get(1);
if (values.containsKey(InstanceColumns.STATUS)) {
status = values.getAsString(InstanceColumns.STATUS);
if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String text = getDisplaySubtext(status, today);
values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
}
}
count =
db.update(INSTANCES_TABLE_NAME, values, InstanceColumns._ID + "=" + instanceId
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(InstanceProviderAPI.AUTHORITY, "instances", INSTANCES);
sUriMatcher.addURI(InstanceProviderAPI.AUTHORITY, "instances/#", INSTANCE_ID);
sInstancesProjectionMap = new HashMap<String, String>();
sInstancesProjectionMap.put(InstanceColumns._ID, InstanceColumns._ID);
sInstancesProjectionMap.put(InstanceColumns.DISPLAY_NAME, InstanceColumns.DISPLAY_NAME);
sInstancesProjectionMap.put(InstanceColumns.SUBMISSION_URI, InstanceColumns.SUBMISSION_URI);
sInstancesProjectionMap.put(InstanceColumns.CAN_EDIT_WHEN_COMPLETE, InstanceColumns.CAN_EDIT_WHEN_COMPLETE);
sInstancesProjectionMap.put(InstanceColumns.INSTANCE_FILE_PATH, InstanceColumns.INSTANCE_FILE_PATH);
sInstancesProjectionMap.put(InstanceColumns.JR_FORM_ID, InstanceColumns.JR_FORM_ID);
sInstancesProjectionMap.put(InstanceColumns.JR_VERSION, InstanceColumns.JR_VERSION);
sInstancesProjectionMap.put(InstanceColumns.STATUS, InstanceColumns.STATUS);
sInstancesProjectionMap.put(InstanceColumns.LAST_STATUS_CHANGE_DATE, InstanceColumns.LAST_STATUS_CHANGE_DATE);
sInstancesProjectionMap.put(InstanceColumns.DISPLAY_SUBTEXT, InstanceColumns.DISPLAY_SUBTEXT);
}
}
| Java |
/*
* 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 org.odk.collect.android.provider;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Convenience definitions for NotePadProvider
*/
public final class FormsProviderAPI {
public static final String AUTHORITY = "org.odk.collect.android.provider.odk.forms";
// This class cannot be instantiated
private FormsProviderAPI() {}
/**
* Notes table
*/
public static final class FormsColumns implements BaseColumns {
// This class cannot be instantiated
private FormsColumns() {}
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/forms");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.odk.form";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.odk.form";
// These are the only things needed for an insert
public static final String DISPLAY_NAME = "displayName";
public static final String DESCRIPTION = "description"; // can be null
public static final String JR_FORM_ID = "jrFormId";
public static final String JR_VERSION = "jrVersion"; // can be null
public static final String FORM_FILE_PATH = "formFilePath";
public static final String SUBMISSION_URI = "submissionUri"; // can be null
public static final String BASE64_RSA_PUBLIC_KEY = "base64RsaPublicKey"; // can be null
// these are generated for you (but you can insert something else if you want)
public static final String DISPLAY_SUBTEXT = "displaySubtext";
public static final String MD5_HASH = "md5Hash";
public static final String DATE = "date";
public static final String JRCACHE_FILE_PATH = "jrcacheFilePath";
public static final String FORM_MEDIA_PATH = "formMediaPath";
// this is null on create, and can only be set on an update.
public static final String LANGUAGE = "language";
}
}
| Java |
/*
* 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 org.odk.collect.android.provider;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.database.ODKSQLiteOpenHelper;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
/**
*
*/
public class FormsProvider extends ContentProvider {
private static final String t = "FormsProvider";
private static final String DATABASE_NAME = "forms.db";
private static final int DATABASE_VERSION = 4;
private static final String FORMS_TABLE_NAME = "forms";
private static HashMap<String, String> sFormsProjectionMap;
private static final int FORMS = 1;
private static final int FORM_ID = 2;
private static final UriMatcher sUriMatcher;
/**
* This class helps open, create, and upgrade the database file.
*/
private static class DatabaseHelper extends ODKSQLiteOpenHelper {
// These exist in database versions 2 and 3, but not in 4...
private static final String TEMP_FORMS_TABLE_NAME = "forms_v4";
private static final String MODEL_VERSION = "modelVersion";
DatabaseHelper(String databaseName) {
super(Collect.METADATA_PATH, databaseName, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
onCreateNamed(db, FORMS_TABLE_NAME);
}
private void onCreateNamed(SQLiteDatabase db, String tableName) {
db.execSQL("CREATE TABLE " + tableName + " ("
+ FormsColumns._ID + " integer primary key, "
+ FormsColumns.DISPLAY_NAME + " text not null, "
+ FormsColumns.DISPLAY_SUBTEXT + " text not null, "
+ FormsColumns.DESCRIPTION + " text, "
+ FormsColumns.JR_FORM_ID + " text not null, "
+ FormsColumns.JR_VERSION + " text, "
+ FormsColumns.MD5_HASH + " text not null, "
+ FormsColumns.DATE + " integer not null, " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + " text not null, "
+ FormsColumns.FORM_FILE_PATH + " text not null, "
+ FormsColumns.LANGUAGE + " text, "
+ FormsColumns.SUBMISSION_URI + " text, "
+ FormsColumns.BASE64_RSA_PUBLIC_KEY + " text, "
+ FormsColumns.JRCACHE_FILE_PATH + " text not null );");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
int initialVersion = oldVersion;
if ( oldVersion < 2 ) {
Log.w(t, "Upgrading database from version " + oldVersion + " to " + newVersion
+ ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FORMS_TABLE_NAME);
onCreate(db);
return;
} else {
// adding BASE64_RSA_PUBLIC_KEY and changing type and name of integer MODEL_VERSION to text VERSION
db.execSQL("DROP TABLE IF EXISTS " + TEMP_FORMS_TABLE_NAME);
onCreateNamed(db, TEMP_FORMS_TABLE_NAME);
db.execSQL("INSERT INTO " + TEMP_FORMS_TABLE_NAME + " ("
+ FormsColumns._ID + ", "
+ FormsColumns.DISPLAY_NAME + ", "
+ FormsColumns.DISPLAY_SUBTEXT + ", "
+ FormsColumns.DESCRIPTION + ", "
+ FormsColumns.JR_FORM_ID + ", "
+ FormsColumns.MD5_HASH + ", "
+ FormsColumns.DATE + ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + ", "
+ FormsColumns.FORM_FILE_PATH + ", "
+ FormsColumns.LANGUAGE + ", "
+ FormsColumns.SUBMISSION_URI + ", "
+ FormsColumns.JR_VERSION + ", "
+ ((oldVersion != 3) ? "" : (FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "))
+ FormsColumns.JRCACHE_FILE_PATH + ") SELECT "
+ FormsColumns._ID + ", "
+ FormsColumns.DISPLAY_NAME + ", "
+ FormsColumns.DISPLAY_SUBTEXT + ", "
+ FormsColumns.DESCRIPTION + ", "
+ FormsColumns.JR_FORM_ID + ", "
+ FormsColumns.MD5_HASH + ", "
+ FormsColumns.DATE + ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + ", "
+ FormsColumns.FORM_FILE_PATH + ", "
+ FormsColumns.LANGUAGE + ", "
+ FormsColumns.SUBMISSION_URI + ", "
+ "CASE WHEN " + MODEL_VERSION + " IS NOT NULL THEN " +
"CAST(" + MODEL_VERSION + " AS TEXT) ELSE NULL END, "
+ ((oldVersion != 3) ? "" : (FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "))
+ FormsColumns.JRCACHE_FILE_PATH + " FROM " + FORMS_TABLE_NAME);
// risky failures here...
db.execSQL("DROP TABLE IF EXISTS " + FORMS_TABLE_NAME);
onCreateNamed(db, FORMS_TABLE_NAME);
db.execSQL("INSERT INTO " + FORMS_TABLE_NAME + " ("
+ FormsColumns._ID + ", "
+ FormsColumns.DISPLAY_NAME + ", "
+ FormsColumns.DISPLAY_SUBTEXT + ", "
+ FormsColumns.DESCRIPTION + ", "
+ FormsColumns.JR_FORM_ID + ", "
+ FormsColumns.MD5_HASH + ", "
+ FormsColumns.DATE + ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + ", "
+ FormsColumns.FORM_FILE_PATH + ", "
+ FormsColumns.LANGUAGE + ", "
+ FormsColumns.SUBMISSION_URI + ", "
+ FormsColumns.JR_VERSION + ", "
+ FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "
+ FormsColumns.JRCACHE_FILE_PATH + ") SELECT "
+ FormsColumns._ID + ", "
+ FormsColumns.DISPLAY_NAME + ", "
+ FormsColumns.DISPLAY_SUBTEXT + ", "
+ FormsColumns.DESCRIPTION + ", "
+ FormsColumns.JR_FORM_ID + ", "
+ FormsColumns.MD5_HASH + ", "
+ FormsColumns.DATE + ", " // milliseconds
+ FormsColumns.FORM_MEDIA_PATH + ", "
+ FormsColumns.FORM_FILE_PATH + ", "
+ FormsColumns.LANGUAGE + ", "
+ FormsColumns.SUBMISSION_URI + ", "
+ FormsColumns.JR_VERSION + ", "
+ FormsColumns.BASE64_RSA_PUBLIC_KEY + ", "
+ FormsColumns.JRCACHE_FILE_PATH + " FROM " + TEMP_FORMS_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TEMP_FORMS_TABLE_NAME);
Log.w(t, "Successfully upgraded database from version " + initialVersion + " to " + newVersion
+ ", without destroying all the old data");
}
}
}
private DatabaseHelper mDbHelper;
@Override
public boolean onCreate() {
// must be at the beginning of any activity that can be called from an external intent
Collect.createODKDirs();
mDbHelper = new DatabaseHelper(DATABASE_NAME);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(FORMS_TABLE_NAME);
switch (sUriMatcher.match(uri)) {
case FORMS:
qb.setProjectionMap(sFormsProjectionMap);
break;
case FORM_ID:
qb.setProjectionMap(sFormsProjectionMap);
qb.appendWhere(FormsColumns._ID + "=" + uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Get the database and run the query
SQLiteDatabase db = mDbHelper.getReadableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
// Tell the cursor what uri to watch, so it knows when its source data changes
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public String getType(Uri uri) {
switch (sUriMatcher.match(uri)) {
case FORMS:
return FormsColumns.CONTENT_TYPE;
case FORM_ID:
return FormsColumns.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
@Override
public synchronized Uri insert(Uri uri, ContentValues initialValues) {
// Validate the requested uri
if (sUriMatcher.match(uri) != FORMS) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
ContentValues values;
if (initialValues != null) {
values = new ContentValues(initialValues);
} else {
values = new ContentValues();
}
if (!values.containsKey(FormsColumns.FORM_FILE_PATH)) {
throw new IllegalArgumentException(FormsColumns.FORM_FILE_PATH + " must be specified.");
}
// Normalize the file path.
// (don't trust the requester).
String filePath = values.getAsString(FormsColumns.FORM_FILE_PATH);
File form = new File(filePath);
filePath = form.getAbsolutePath(); // normalized
values.put(FormsColumns.FORM_FILE_PATH, filePath);
Long now = Long.valueOf(System.currentTimeMillis());
// Make sure that the necessary fields are all set
if (values.containsKey(FormsColumns.DATE) == false) {
values.put(FormsColumns.DATE, now);
}
if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) {
Date today = new Date();
String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today);
values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
}
if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) {
values.put(FormsColumns.DISPLAY_NAME, form.getName());
}
// don't let users put in a manual md5 hash
if (values.containsKey(FormsColumns.MD5_HASH)) {
values.remove(FormsColumns.MD5_HASH);
}
String md5 = FileUtils.getMd5Hash(form);
values.put(FormsColumns.MD5_HASH, md5);
if (values.containsKey(FormsColumns.JRCACHE_FILE_PATH) == false) {
String cachePath = Collect.CACHE_PATH + File.separator + md5 + ".formdef";
values.put(FormsColumns.JRCACHE_FILE_PATH, cachePath);
}
if (values.containsKey(FormsColumns.FORM_MEDIA_PATH) == false) {
String pathNoExtension = filePath.substring(0, filePath.lastIndexOf("."));
String mediaPath = pathNoExtension + "-media";
values.put(FormsColumns.FORM_MEDIA_PATH, mediaPath);
}
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// first try to see if a record with this filename already exists...
String[] projection = {
FormsColumns._ID, FormsColumns.FORM_FILE_PATH
};
String[] selectionArgs = { filePath };
String selection = FormsColumns.FORM_FILE_PATH + "=?";
Cursor c = null;
try {
c = db.query(FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);
if ( c.getCount() > 0 ) {
// already exists
throw new SQLException("FAILED Insert into " + uri + " -- row already exists for form definition file: " + filePath);
}
} finally {
if ( c != null ) {
c.close();
}
}
long rowId = db.insert(FORMS_TABLE_NAME, null, values);
if (rowId > 0) {
Uri formUri = ContentUris.withAppendedId(FormsColumns.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(formUri, null);
Collect.getInstance().getActivityLogger().logActionParam(this, "insert",
formUri.toString(), values.getAsString(FormsColumns.FORM_FILE_PATH));
return formUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
private void deleteFileOrDir(String fileName) {
File file = new File(fileName);
if (file.exists()) {
if (file.isDirectory()) {
// delete any media entries for files in this directory...
int images = MediaUtils.deleteImagesInFolderFromMediaProvider(file);
int audio = MediaUtils.deleteAudioInFolderFromMediaProvider(file);
int video = MediaUtils.deleteVideoInFolderFromMediaProvider(file);
Log.i(t, "removed from content providers: " + images
+ " image files, " + audio + " audio files,"
+ " and " + video + " video files.");
// delete all the containing files
File[] files = file.listFiles();
for (File f : files) {
// should make this recursive if we get worried about
// the media directory containing directories
Log.i(t, "attempting to delete file: " + f.getAbsolutePath());
f.delete();
}
}
file.delete();
Log.i(t, "attempting to delete file: " + file.getAbsolutePath());
}
}
/**
* This method removes the entry from the content provider, and also removes any associated
* files. files: form.xml, [formmd5].formdef, formname-media {directory}
*/
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int count;
switch (sUriMatcher.match(uri)) {
case FORMS:
Cursor del = null;
try {
del = this.query(uri, null, where, whereArgs, null);
del.moveToPosition(-1);
while (del.moveToNext()) {
deleteFileOrDir(del.getString(del
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
String formFilePath = del.getString(del.getColumnIndex(FormsColumns.FORM_FILE_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "delete", formFilePath);
deleteFileOrDir(formFilePath);
deleteFileOrDir(del.getString(del.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)));
}
} finally {
if ( del != null ) {
del.close();
}
}
count = db.delete(FORMS_TABLE_NAME, where, whereArgs);
break;
case FORM_ID:
String formId = uri.getPathSegments().get(1);
Cursor c = null;
try {
c = this.query(uri, null, where, whereArgs, null);
// This should only ever return 1 record.
c.moveToPosition(-1);
while (c.moveToNext()) {
deleteFileOrDir(c.getString(c.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
String formFilePath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
Collect.getInstance().getActivityLogger().logAction(this, "delete", formFilePath);
deleteFileOrDir(formFilePath);
deleteFileOrDir(c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)));
}
} finally {
if ( c != null ) {
c.close();
}
}
count =
db.delete(FORMS_TABLE_NAME,
FormsColumns._ID + "=" + formId
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int count = 0;
switch (sUriMatcher.match(uri)) {
case FORMS:
// don't let users manually update md5
if (values.containsKey(FormsColumns.MD5_HASH)) {
values.remove(FormsColumns.MD5_HASH);
}
// if values contains path, then all filepaths and md5s will get updated
// this probably isn't a great thing to do.
if (values.containsKey(FormsColumns.FORM_FILE_PATH)) {
String formFile = values.getAsString(FormsColumns.FORM_FILE_PATH);
values.put(FormsColumns.MD5_HASH, FileUtils.getMd5Hash(new File(formFile)));
}
Cursor c = null;
try {
c = this.query(uri, null, where, whereArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
while (c.moveToNext()) {
// before updating the paths, delete all the files
if (values.containsKey(FormsColumns.FORM_FILE_PATH)) {
String newFile = values.getAsString(FormsColumns.FORM_FILE_PATH);
String delFile =
c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
if (newFile.equalsIgnoreCase(delFile)) {
// same file, so don't delete anything
} else {
// different files, delete the old one
deleteFileOrDir(delFile);
}
// either way, delete the old cache because we'll calculate a new one.
deleteFileOrDir(c.getString(c
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
}
}
}
} finally {
if ( c != null ) {
c.close();
}
}
// Make sure that the necessary fields are all set
if (values.containsKey(FormsColumns.DATE) == true) {
Date today = new Date();
String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today);
values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
}
count = db.update(FORMS_TABLE_NAME, values, where, whereArgs);
break;
case FORM_ID:
String formId = uri.getPathSegments().get(1);
// Whenever file paths are updated, delete the old files.
Cursor update = null;
try {
update = this.query(uri, null, where, whereArgs, null);
// This should only ever return 1 record.
if (update.getCount() > 0) {
update.moveToFirst();
// don't let users manually update md5
if (values.containsKey(FormsColumns.MD5_HASH)) {
values.remove(FormsColumns.MD5_HASH);
}
// the order here is important (jrcache needs to be before form file)
// because we update the jrcache file if there's a new form file
if (values.containsKey(FormsColumns.JRCACHE_FILE_PATH)) {
deleteFileOrDir(update.getString(update
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
}
if (values.containsKey(FormsColumns.FORM_FILE_PATH)) {
String formFile = values.getAsString(FormsColumns.FORM_FILE_PATH);
String oldFile =
update.getString(update.getColumnIndex(FormsColumns.FORM_FILE_PATH));
if (formFile != null && formFile.equalsIgnoreCase(oldFile)) {
// Files are the same, so we may have just copied over something we had
// already
} else {
// New file name. This probably won't ever happen, though.
deleteFileOrDir(oldFile);
}
// we're updating our file, so update the md5
// and get rid of the cache (doesn't harm anything)
deleteFileOrDir(update.getString(update
.getColumnIndex(FormsColumns.JRCACHE_FILE_PATH)));
String newMd5 = FileUtils.getMd5Hash(new File(formFile));
values.put(FormsColumns.MD5_HASH, newMd5);
values.put(FormsColumns.JRCACHE_FILE_PATH,
Collect.CACHE_PATH + File.separator + newMd5 + ".formdef");
}
// Make sure that the necessary fields are all set
if (values.containsKey(FormsColumns.DATE) == true) {
Date today = new Date();
String ts =
new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time), Locale.getDefault()).format(today);
values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
}
count =
db.update(FORMS_TABLE_NAME, values, FormsColumns._ID + "=" + formId
+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
whereArgs);
} else {
Log.e(t, "Attempting to update row that does not exist");
}
} finally {
if ( update != null ) {
update.close();
}
}
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
static {
sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sUriMatcher.addURI(FormsProviderAPI.AUTHORITY, "forms", FORMS);
sUriMatcher.addURI(FormsProviderAPI.AUTHORITY, "forms/#", FORM_ID);
sFormsProjectionMap = new HashMap<String, String>();
sFormsProjectionMap.put(FormsColumns._ID, FormsColumns._ID);
sFormsProjectionMap.put(FormsColumns.DISPLAY_NAME, FormsColumns.DISPLAY_NAME);
sFormsProjectionMap.put(FormsColumns.DISPLAY_SUBTEXT, FormsColumns.DISPLAY_SUBTEXT);
sFormsProjectionMap.put(FormsColumns.DESCRIPTION, FormsColumns.DESCRIPTION);
sFormsProjectionMap.put(FormsColumns.JR_FORM_ID, FormsColumns.JR_FORM_ID);
sFormsProjectionMap.put(FormsColumns.JR_VERSION, FormsColumns.JR_VERSION);
sFormsProjectionMap.put(FormsColumns.SUBMISSION_URI, FormsColumns.SUBMISSION_URI);
sFormsProjectionMap.put(FormsColumns.BASE64_RSA_PUBLIC_KEY, FormsColumns.BASE64_RSA_PUBLIC_KEY);
sFormsProjectionMap.put(FormsColumns.MD5_HASH, FormsColumns.MD5_HASH);
sFormsProjectionMap.put(FormsColumns.DATE, FormsColumns.DATE);
sFormsProjectionMap.put(FormsColumns.FORM_MEDIA_PATH, FormsColumns.FORM_MEDIA_PATH);
sFormsProjectionMap.put(FormsColumns.FORM_FILE_PATH, FormsColumns.FORM_FILE_PATH);
sFormsProjectionMap.put(FormsColumns.JRCACHE_FILE_PATH, FormsColumns.JRCACHE_FILE_PATH);
sFormsProjectionMap.put(FormsColumns.LANGUAGE, FormsColumns.LANGUAGE);
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.views;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.widgets.IBinaryWidget;
import org.odk.collect.android.widgets.QuestionWidget;
import org.odk.collect.android.widgets.WidgetFactory;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
/**
* This class is
*
* @author carlhartung
*/
public class ODKView extends ScrollView implements OnLongClickListener {
// starter random number for view IDs
private final static int VIEW_ID = 12345;
private final static String t = "ODKView";
private LinearLayout mView;
private LinearLayout.LayoutParams mLayout;
private ArrayList<QuestionWidget> widgets;
private Handler h = null;
public final static String FIELD_LIST = "field-list";
public ODKView(Context context, FormEntryPrompt[] questionPrompts,
FormEntryCaption[] groups, boolean advancingPage) {
super(context);
widgets = new ArrayList<QuestionWidget>();
mView = new LinearLayout(getContext());
mView.setOrientation(LinearLayout.VERTICAL);
mView.setGravity(Gravity.TOP);
mView.setPadding(0, 7, 0, 0);
mLayout =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mLayout.setMargins(10, 0, 10, 0);
// display which group you are in as well as the question
addGroupText(groups);
boolean first = true;
int id = 0;
for (FormEntryPrompt p : questionPrompts) {
if (!first) {
View divider = new View(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
divider.setMinimumHeight(3);
mView.addView(divider);
} else {
first = false;
}
// if question or answer type is not supported, use text widget
QuestionWidget qw =
WidgetFactory.createWidgetFromPrompt(p, getContext());
qw.setLongClickable(true);
qw.setOnLongClickListener(this);
qw.setId(VIEW_ID + id++);
widgets.add(qw);
mView.addView((View) qw, mLayout);
}
addView(mView);
// see if there is an autoplay option.
// Only execute it during forward swipes through the form
if ( advancingPage && questionPrompts.length == 1 ) {
final String playOption = widgets.get(0).getPrompt().getFormElement().getAdditionalAttribute(null, "autoplay");
if ( playOption != null ) {
h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
if ( playOption.equalsIgnoreCase("audio") ) {
widgets.get(0).playAudio();
} else if ( playOption.equalsIgnoreCase("video") ) {
widgets.get(0).playVideo();
}
}
}, 150);
}
}
}
/**
* http://code.google.com/p/android/issues/detail?id=8488
*/
public void recycleDrawables() {
this.destroyDrawingCache();
mView.destroyDrawingCache();
for ( QuestionWidget q : widgets ) {
q.recycleDrawables();
}
}
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
Collect.getInstance().getActivityLogger().logScrollAction(this, t - oldt);
}
/**
* @return a HashMap of answers entered by the user for this set of widgets
*/
public LinkedHashMap<FormIndex, IAnswerData> getAnswers() {
LinkedHashMap<FormIndex, IAnswerData> answers = new LinkedHashMap<FormIndex, IAnswerData>();
Iterator<QuestionWidget> i = widgets.iterator();
while (i.hasNext()) {
/*
* The FormEntryPrompt has the FormIndex, which is where the answer gets stored. The
* QuestionWidget has the answer the user has entered.
*/
QuestionWidget q = i.next();
FormEntryPrompt p = q.getPrompt();
answers.put(p.getIndex(), q.getAnswer());
}
return answers;
}
/**
* // * Add a TextView containing the hierarchy of groups to which the question belongs. //
*/
private void addGroupText(FormEntryCaption[] groups) {
StringBuffer s = new StringBuffer("");
String t = "";
int i;
// list all groups in one string
for (FormEntryCaption g : groups) {
i = g.getMultiplicity() + 1;
t = g.getLongText();
if (t != null) {
s.append(t);
if (g.repeats() && i > 0) {
s.append(" (" + i + ")");
}
s.append(" > ");
}
}
// build view
if (s.length() > 0) {
TextView tv = new TextView(getContext());
tv.setText(s.substring(0, s.length() - 3));
int questionFontsize = Collect.getQuestionFontsize();
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, questionFontsize - 4);
tv.setPadding(0, 0, 0, 5);
mView.addView(tv, mLayout);
}
}
public void setFocus(Context context) {
if (widgets.size() > 0) {
widgets.get(0).setFocus(context);
}
}
/**
* Called when another activity returns information to answer this question.
*
* @param answer
*/
public void setBinaryData(Object answer) {
boolean set = false;
for (QuestionWidget q : widgets) {
if (q instanceof IBinaryWidget) {
if (((IBinaryWidget) q).isWaitingForBinaryData()) {
((IBinaryWidget) q).setBinaryData(answer);
set = true;
break;
}
}
}
if (!set) {
Log.w(t, "Attempting to return data to a widget or set of widgets not looking for data");
}
}
public void cancelWaitingForBinaryData() {
int count = 0;
for (QuestionWidget q : widgets) {
if (q instanceof IBinaryWidget) {
if (((IBinaryWidget) q).isWaitingForBinaryData()) {
((IBinaryWidget) q).cancelWaitingForBinaryData();
++count;
}
}
}
if (count != 1) {
Log.w(t, "Attempting to cancel waiting for binary data to a widget or set of widgets not looking for data");
}
}
public boolean suppressFlingGesture(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
for (QuestionWidget q : widgets) {
if ( q.suppressFlingGesture(e1, e2, velocityX, velocityY) ) {
return true;
}
}
return false;
}
/**
* @return true if the answer was cleared, false otherwise.
*/
public boolean clearAnswer() {
// If there's only one widget, clear the answer.
// If there are more, then force a long-press to clear the answer.
if (widgets.size() == 1 && !widgets.get(0).getPrompt().isReadOnly()) {
widgets.get(0).clearAnswer();
return true;
} else {
return false;
}
}
public ArrayList<QuestionWidget> getWidgets() {
return widgets;
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener l) {
for (int i = 0; i < widgets.size(); i++) {
QuestionWidget qw = widgets.get(i);
qw.setOnFocusChangeListener(l);
}
}
@Override
public boolean onLongClick(View v) {
return false;
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (QuestionWidget qw : widgets) {
qw.cancelLongPress();
}
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.views;
import java.io.File;
import java.io.IOException;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
/**
* @author ctsims
* @author carlhartung
*/
public class AudioButton extends ImageButton implements OnClickListener {
private final static String t = "AudioButton";
/**
* Useful class for handling the playing and stopping of audio prompts.
* This is used here, and also in the GridMultiWidget and GridWidget
* to play prompts as items are selected.
*
* @author mitchellsundt@gmail.com
*
*/
public static class AudioHandler {
private FormIndex index;
private String selectionDesignator;
private String URI;
private MediaPlayer player;
public AudioHandler(FormIndex index, String selectionDesignator, String URI) {
this.index = index;
this.selectionDesignator = selectionDesignator;
this.URI = URI;
player = null;
}
public void playAudio(Context c) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick.playAudioPrompt", selectionDesignator, index);
if (URI == null) {
// No audio file specified
Log.e(t, "No audio file was specified");
Toast.makeText(c, c.getString(R.string.audio_file_error),
Toast.LENGTH_LONG).show();
return;
}
String audioFilename = "";
try {
audioFilename = ReferenceManager._().DeriveReference(URI).getLocalURI();
} catch (InvalidReferenceException e) {
Log.e(t, "Invalid reference exception");
e.printStackTrace();
}
File audioFile = new File(audioFilename);
if (!audioFile.exists()) {
// We should have an audio clip, but the file doesn't exist.
String errorMsg = c.getString(R.string.file_missing, audioFile);
Log.e(t, errorMsg);
Toast.makeText(c, errorMsg, Toast.LENGTH_LONG).show();
return;
}
// In case we're currently playing sounds.
stopPlaying();
player = new MediaPlayer();
try {
player.setDataSource(audioFilename);
player.prepare();
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
});
} catch (IOException e) {
String errorMsg = c.getString(R.string.audio_file_invalid);
Log.e(t, errorMsg);
Toast.makeText(c, errorMsg, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
public void stopPlaying() {
if (player != null) {
player.release();
}
}
}
AudioHandler handler;
public AudioButton(Context context, FormIndex index, String selectionDesignator, String URI) {
super(context);
this.setOnClickListener(this);
handler = new AudioHandler( index, selectionDesignator, URI);
Bitmap b =
BitmapFactory.decodeResource(context.getResources(),
android.R.drawable.ic_lock_silent_mode_off);
this.setImageBitmap(b);
}
public void playAudio() {
handler.playAudio(getContext());
}
@Override
public void onClick(View v) {
playAudio();
}
public void stopPlaying() {
handler.stopPlaying();
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.views;
import java.io.File;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.widgets.QuestionWidget;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* This layout is used anywhere we can have image/audio/video/text. TODO: It would probably be nice
* to put this in a layout.xml file of some sort at some point.
*
* @author carlhartung
*/
public class MediaLayout extends RelativeLayout {
private static final String t = "AVTLayout";
private String mSelectionDesignator;
private FormIndex mIndex;
private TextView mView_Text;
private AudioButton mAudioButton;
private ImageButton mVideoButton;
private ImageView mImageView;
private TextView mMissingImage;
private String mVideoURI = null;
public MediaLayout(Context c) {
super(c);
mView_Text = null;
mAudioButton = null;
mImageView = null;
mMissingImage = null;
mVideoButton = null;
mIndex = null;
}
public void playAudio() {
if ( mAudioButton != null ) {
mAudioButton.playAudio();
}
}
public void playVideo() {
if ( mVideoURI != null ) {
String videoFilename = "";
try {
videoFilename =
ReferenceManager._().DeriveReference(mVideoURI).getLocalURI();
} catch (InvalidReferenceException e) {
Log.e(t, "Invalid reference exception");
e.printStackTrace();
}
File videoFile = new File(videoFilename);
if (!videoFile.exists()) {
// We should have a video clip, but the file doesn't exist.
String errorMsg =
getContext().getString(R.string.file_missing, videoFilename);
Log.e(t, errorMsg);
Toast.makeText(getContext(), errorMsg, Toast.LENGTH_LONG).show();
return;
}
Intent i = new Intent("android.intent.action.VIEW");
i.setDataAndType(Uri.fromFile(videoFile), "video/*");
try {
((Activity) getContext()).startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "view video"),
Toast.LENGTH_SHORT).show();
}
}
}
public void setAVT(FormIndex index, String selectionDesignator, TextView text, String audioURI, String imageURI, String videoURI,
final String bigImageURI) {
mSelectionDesignator = selectionDesignator;
mIndex = index;
mView_Text = text;
mView_Text.setId(QuestionWidget.newUniqueId());
mVideoURI = videoURI;
// Layout configurations for our elements in the relative layout
RelativeLayout.LayoutParams textParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams audioParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams imageParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams videoParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// First set up the audio button
if (audioURI != null) {
// An audio file is specified
mAudioButton = new AudioButton(getContext(), mIndex, mSelectionDesignator, audioURI);
mAudioButton.setId(QuestionWidget.newUniqueId()); // random ID to be used by the
// relative layout.
} else {
// No audio file specified, so ignore.
}
// Then set up the video button
if (videoURI != null) {
// An video file is specified
mVideoButton = new ImageButton(getContext());
Bitmap b =
BitmapFactory.decodeResource(getContext().getResources(),
android.R.drawable.ic_media_play);
mVideoButton.setImageBitmap(b);
mVideoButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick", "playVideoPrompt"+mSelectionDesignator, mIndex);
MediaLayout.this.playVideo();
}
});
mVideoButton.setId(QuestionWidget.newUniqueId());
} else {
// No video file specified, so ignore.
}
// Now set up the image view
String errorMsg = null;
final int imageId = QuestionWidget.newUniqueId();
if (imageURI != null) {
try {
String imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
Bitmap b = FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight, screenWidth);
if (b != null) {
mImageView = new ImageView(getContext());
mImageView.setPadding(2, 2, 2, 2);
mImageView.setBackgroundColor(Color.WHITE);
mImageView.setImageBitmap(b);
mImageView.setId(imageId);
if (bigImageURI != null) {
mImageView.setOnClickListener(new OnClickListener() {
String bigImageFilename = ReferenceManager._()
.DeriveReference(bigImageURI).getLocalURI();
File bigImage = new File(bigImageFilename);
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onClick", "showImagePromptBigImage"+mSelectionDesignator, mIndex);
Intent i = new Intent("android.intent.action.VIEW");
i.setDataAndType(Uri.fromFile(bigImage), "image/*");
try {
getContext().startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"view image"), Toast.LENGTH_SHORT).show();
}
}
});
}
} else {
// Loading the image failed, so it's likely a bad file.
errorMsg = getContext().getString(R.string.file_invalid, imageFile);
}
} else {
// We should have an image, but the file doesn't exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
if (errorMsg != null) {
// errorMsg is only set when an error has occurred
Log.e(t, errorMsg);
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMsg);
mMissingImage.setPadding(10, 10, 10, 10);
mMissingImage.setId(imageId);
}
} catch (InvalidReferenceException e) {
Log.e(t, "image invalid reference exception");
e.printStackTrace();
}
} else {
// There's no imageURI listed, so just ignore it.
}
// Determine the layout constraints...
// Assumes LTR, TTB reading bias!
if (mView_Text.getText().length() == 0 && (mImageView != null || mMissingImage != null)) {
// No text; has image. The image is treated as question/choice icon.
// The Text view may just have a radio button or checkbox. It
// needs to remain in the layout even though it is blank.
//
// The image view, as created above, will dynamically resize and
// center itself. We want it to resize but left-align itself
// in the resized area and we want a white background, as otherwise
// it will show a grey bar to the right of the image icon.
if (mImageView != null) {
mImageView.setScaleType(ScaleType.FIT_START);
}
//
// In this case, we have:
// Text upper left; image upper, left edge aligned with text right edge;
// audio upper right; video below audio on right.
textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
imageParams.addRule(RelativeLayout.RIGHT_OF, mView_Text.getId());
imageParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if (mAudioButton != null && mVideoButton == null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imageParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
} else if (mAudioButton == null && mVideoButton != null) {
videoParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imageParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
} else if (mAudioButton != null && mVideoButton != null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
imageParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
imageParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
} else {
// the image will implicitly scale down to fit within parent...
// no need to bound it by the width of the parent...
imageParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
imageParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
} else {
// We have a non-blank text label -- image is below the text.
// In this case, we want the image to be centered...
if (mImageView != null) {
mImageView.setScaleType(ScaleType.FIT_START);
}
//
// Text upper left; audio upper right; video below audio on right.
// image below text, audio and video buttons; left-aligned with text.
textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if (mAudioButton != null && mVideoButton == null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
} else if (mAudioButton == null && mVideoButton != null) {
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mVideoButton.getId());
} else if (mAudioButton != null && mVideoButton != null) {
audioParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textParams.addRule(RelativeLayout.LEFT_OF, mAudioButton.getId());
videoParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
videoParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
} else {
textParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
}
if (mImageView != null || mMissingImage != null) {
imageParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
imageParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
imageParams.addRule(RelativeLayout.BELOW, mView_Text.getId());
} else {
textParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
}
}
addView(mView_Text, textParams);
if (mAudioButton != null)
addView(mAudioButton, audioParams);
if (mVideoButton != null)
addView(mVideoButton, videoParams);
if (mImageView != null)
addView(mImageView, imageParams);
else if (mMissingImage != null)
addView(mMissingImage, imageParams);
}
/**
* This adds a divider at the bottom of this layout. Used to separate fields in lists.
*
* @param v
*/
public void addDivider(ImageView v) {
RelativeLayout.LayoutParams dividerParams =
new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
if (mImageView != null) {
dividerParams.addRule(RelativeLayout.BELOW, mImageView.getId());
} else if (mMissingImage != null) {
dividerParams.addRule(RelativeLayout.BELOW, mMissingImage.getId());
} else if (mVideoButton != null) {
dividerParams.addRule(RelativeLayout.BELOW, mVideoButton.getId());
} else if (mAudioButton != null) {
dividerParams.addRule(RelativeLayout.BELOW, mAudioButton.getId());
} else if (mView_Text != null) {
// No picture
dividerParams.addRule(RelativeLayout.BELOW, mView_Text.getId());
} else {
Log.e(t, "Tried to add divider to uninitialized ATVWidget");
return;
}
addView(v, dividerParams);
}
@Override
protected void onWindowVisibilityChanged(int visibility) {
super.onWindowVisibilityChanged(visibility);
if (visibility != View.VISIBLE) {
if (mAudioButton != null) {
mAudioButton.stopPlaying();
}
}
}
}
| Java |
/*
* Copyright (C) 2013 University of Washington
*
* http://creativecommons.org/licenses/by-sa/3.0/ -- code is based upon an answer on Stack Overflow:
* http://stackoverflow.com/questions/8481844/gridview-height-gets-cut
*
* 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.odk.collect.android.views;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.GridView;
/**
* From Stack Overflow: http://stackoverflow.com/questions/8481844/gridview-height-gets-cut
* Changed to always be expanded, since widgets are always embedded in a scroll view.
*
* @author tacone based on answer by Neil Traft
* @author mitchellsundt@gmail.com
*
*/
public class ExpandedHeightGridView extends GridView
{
public ExpandedHeightGridView(Context context)
{
super(context);
}
public ExpandedHeightGridView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ExpandedHeightGridView(Context context, AttributeSet attrs,
int defStyle)
{
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// HACK! TAKE THAT ANDROID!
// Calculate entire height by providing a very large height hint.
// But do not use the highest 2 bits of this integer; those are
// reserved for the MeasureSpec mode.
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.views;
import org.odk.collect.android.R;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.CheckBox;
import android.widget.Checkable;
import android.widget.RelativeLayout;
public class TwoItemMultipleChoiceView extends RelativeLayout implements Checkable {
public TwoItemMultipleChoiceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public TwoItemMultipleChoiceView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TwoItemMultipleChoiceView(Context context) {
super(context);
}
@Override
public boolean isChecked() {
CheckBox c = (CheckBox) findViewById(R.id.checkbox);
return c.isChecked();
}
@Override
public void setChecked(boolean checked) {
CheckBox c = (CheckBox) findViewById(R.id.checkbox);
c.setChecked(checked);
}
@Override
public void toggle() {
CheckBox c = (CheckBox) findViewById(R.id.checkbox);
c.setChecked(!c.isChecked());
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.views;
import org.odk.collect.android.logic.HierarchyElement;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class HierarchyElementView extends RelativeLayout {
private TextView mPrimaryTextView;
private TextView mSecondaryTextView;
private ImageView mIcon;
public HierarchyElementView(Context context, HierarchyElement it) {
super(context);
setColor(it.getColor());
mIcon = new ImageView(context);
mIcon.setImageDrawable(it.getIcon());
mIcon.setId(1);
mIcon.setPadding(0, 0, dipToPx(4), 0);
addView(mIcon, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mPrimaryTextView = new TextView(context);
mPrimaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Large);
mPrimaryTextView.setText(it.getPrimaryText());
mPrimaryTextView.setId(2);
mPrimaryTextView.setGravity(Gravity.CENTER_VERTICAL);
LayoutParams l =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
l.addRule(RelativeLayout.RIGHT_OF, mIcon.getId());
addView(mPrimaryTextView, l);
mSecondaryTextView = new TextView(context);
mSecondaryTextView.setText(it.getSecondaryText());
mSecondaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Small);
mSecondaryTextView.setGravity(Gravity.CENTER_VERTICAL);
LayoutParams lp =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, mPrimaryTextView.getId());
lp.addRule(RelativeLayout.RIGHT_OF, mIcon.getId());
addView(mSecondaryTextView, lp);
setPadding(dipToPx(8), dipToPx(4), dipToPx(8), dipToPx(8));
}
public void setPrimaryText(String text) {
mPrimaryTextView.setText(text);
}
public void setSecondaryText(String text) {
mSecondaryTextView.setText(text);
}
public void setIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
}
public void setColor(int color) {
setBackgroundColor(color);
}
public void showSecondary(boolean bool) {
if (bool) {
mSecondaryTextView.setVisibility(VISIBLE);
setMinimumHeight(dipToPx(64));
} else {
mSecondaryTextView.setVisibility(GONE);
setMinimumHeight(dipToPx(32));
}
}
public int dipToPx(int dip) {
return (int) (dip * getResources().getDisplayMetrics().density + 0.5f);
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.views;
import org.odk.collect.android.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
/**
* Builds view for arrow animation
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class ArrowAnimationView extends View {
private final static String t = "ArrowAnimationView";
private Animation mAnimation;
private Bitmap mArrow;
private int mImgXOffset;
public ArrowAnimationView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.i(t, "called constructor");
init();
}
public ArrowAnimationView(Context context) {
super(context);
init();
}
private void init() {
mArrow = BitmapFactory.decodeResource(getResources(), R.drawable.left_arrow);
mImgXOffset = mArrow.getWidth() / 2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mAnimation == null) {
createAnim(canvas);
}
int centerX = canvas.getWidth() / 2;
canvas.drawBitmap(mArrow, centerX - mImgXOffset, (float) mArrow.getHeight() / 4, null);
}
private void createAnim(Canvas canvas) {
mAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.start_arrow);
startAnimation(mAnimation);
}
}
| Java |
/*
* Copyright (C) 2012 University of Washington
*
* 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.odk.collect.android.utilities;
import org.odk.collect.android.R;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
/**
* Implementation of cursor adapter that displays the version of a form if a form has a version.
*
* @author mitchellsundt@gmail.com
*
*/
public class VersionHidingCursorAdapter extends SimpleCursorAdapter {
private final Context ctxt;
private final String versionColumnName;
private final ViewBinder originalBinder;
public VersionHidingCursorAdapter(String versionColumnName, Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.versionColumnName = versionColumnName;
ctxt = context;
originalBinder = getViewBinder();
setViewBinder( new ViewBinder(){
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
String columnName = cursor.getColumnName(columnIndex);
if ( !columnName.equals(VersionHidingCursorAdapter.this.versionColumnName) ) {
if ( originalBinder != null ) {
return originalBinder.setViewValue(view, cursor, columnIndex);
}
return false;
} else {
String version = cursor.getString(columnIndex);
TextView v = (TextView) view;
if ( version != null ) {
v.setText(ctxt.getString(R.string.version) + " " + version);
v.setVisibility(View.VISIBLE);
} else {
v.setText(null);
v.setVisibility(View.GONE);
}
}
return true;
}} );
}
} | Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.utilities;
import org.javarosa.xform.parse.XFormParser;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
/**
* Static methods used for common file operations.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class FileUtils {
private final static String t = "FileUtils";
// Used to validate and display valid form names.
public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml";
public static final String FORMID = "formid";
public static final String VERSION = "version"; // arbitrary string in OpenRosa 1.0
public static final String TITLE = "title";
public static final String SUBMISSIONURI = "submission";
public static final String BASE64_RSA_PUBLIC_KEY = "base64RsaPublicKey";
public static boolean createFolder(String path) {
boolean made = true;
File dir = new File(path);
if (!dir.exists()) {
made = dir.mkdirs();
}
return made;
}
public static byte[] getFileAsBytes(File file) {
byte[] bytes = null;
InputStream is = null;
try {
is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
// Create the byte array to hold the data
bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int read = 0;
try {
while (offset < bytes.length && read >= 0) {
read = is.read(bytes, offset, bytes.length - offset);
offset += read;
}
} catch (IOException e) {
Log.e(t, "Cannot read " + file.getName());
e.printStackTrace();
return null;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
try {
throw new IOException("Could not completely read file " + file.getName());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return bytes;
} catch (FileNotFoundException e) {
Log.e(t, "Cannot find " + file.getName());
e.printStackTrace();
return null;
} finally {
// Close the input stream
try {
is.close();
} catch (IOException e) {
Log.e(t, "Cannot close input stream for " + file.getName());
e.printStackTrace();
return null;
}
}
}
public static String getMd5Hash(File file) {
try {
// CTS (6/15/2010) : stream file through digest instead of handing it the byte[]
MessageDigest md = MessageDigest.getInstance("MD5");
int chunkSize = 256;
byte[] chunk = new byte[chunkSize];
// Get the size of the file
long lLength = file.length();
if (lLength > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
int length = (int) lLength;
InputStream is = null;
is = new FileInputStream(file);
int l = 0;
for (l = 0; l + chunkSize < length; l += chunkSize) {
is.read(chunk, 0, chunkSize);
md.update(chunk, 0, chunkSize);
}
int remaining = length - l;
if (remaining > 0) {
is.read(chunk, 0, remaining);
md.update(chunk, 0, remaining);
}
byte[] messageDigest = md.digest();
BigInteger number = new BigInteger(1, messageDigest);
String md5 = number.toString(16);
while (md5.length() < 32)
md5 = "0" + md5;
is.close();
return md5;
} catch (NoSuchAlgorithmException e) {
Log.e("MD5", e.getMessage());
return null;
} catch (FileNotFoundException e) {
Log.e("No Cache File", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Problem reading from file", e.getMessage());
return null;
}
}
public static Bitmap getBitmapScaledToDisplay(File f, int screenHeight, int screenWidth) {
// Determine image size of f
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(f.getAbsolutePath(), o);
int heightScale = o.outHeight / screenHeight;
int widthScale = o.outWidth / screenWidth;
// Powers of 2 work faster, sometimes, according to the doc.
// We're just doing closest size that still fills the screen.
int scale = Math.max(widthScale, heightScale);
// get bitmap with scale ( < 1 is the same as 1)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inInputShareable = true;
options.inPurgeable = true;
options.inSampleSize = scale;
Bitmap b = BitmapFactory.decodeFile(f.getAbsolutePath(), options);
if (b != null) {
Log.i(t,
"Screen is " + screenHeight + "x" + screenWidth + ". Image has been scaled down by "
+ scale + " to " + b.getHeight() + "x" + b.getWidth());
}
return b;
}
public static void copyFile(File sourceFile, File destFile) {
if (sourceFile.exists()) {
FileChannel src;
try {
src = new FileInputStream(sourceFile).getChannel();
FileChannel dst = new FileOutputStream(destFile).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
} catch (FileNotFoundException e) {
Log.e(t, "FileNotFoundExeception while copying audio");
e.printStackTrace();
} catch (IOException e) {
Log.e(t, "IOExeception while copying audio");
e.printStackTrace();
}
} else {
Log.e(t, "Source file does not exist: " + sourceFile.getAbsolutePath());
}
}
public static HashMap<String, String> parseXML(File xmlFile) {
HashMap<String, String> fields = new HashMap<String, String>();
InputStream is;
try {
is = new FileInputStream(xmlFile);
} catch (FileNotFoundException e1) {
throw new IllegalStateException(e1);
}
InputStreamReader isr;
try {
isr = new InputStreamReader(is, "UTF-8");
} catch (UnsupportedEncodingException uee) {
Log.w(t, "UTF 8 encoding unavailable, trying default encoding");
isr = new InputStreamReader(is);
}
if (isr != null) {
Document doc;
try {
doc = XFormParser.getXMLDocument(isr);
} finally {
try {
isr.close();
} catch (IOException e) {
Log.w(t, xmlFile.getAbsolutePath() + " Error closing form reader");
e.printStackTrace();
}
}
String xforms = "http://www.w3.org/2002/xforms";
String html = doc.getRootElement().getNamespace();
Element head = doc.getRootElement().getElement(html, "head");
Element title = head.getElement(html, "title");
if (title != null) {
fields.put(TITLE, XFormParser.getXMLText(title, true));
}
Element model = getChildElement(head, "model");
Element cur = getChildElement(model,"instance");
int idx = cur.getChildCount();
int i;
for (i = 0; i < idx; ++i) {
if (cur.isText(i))
continue;
if (cur.getType(i) == Node.ELEMENT) {
break;
}
}
if (i < idx) {
cur = cur.getElement(i); // this is the first data element
String id = cur.getAttributeValue(null, "id");
String xmlns = cur.getNamespace();
String version = cur.getAttributeValue(null, "version");
String uiVersion = cur.getAttributeValue(null, "uiVersion");
if ( uiVersion != null ) {
// pre-OpenRosa 1.0 variant of spec
Log.e(t, "Obsolete use of uiVersion -- IGNORED -- only using version: " + version);
}
fields.put(FORMID, (id == null) ? xmlns : id);
fields.put(VERSION, (version == null) ? null : version);
} else {
throw new IllegalStateException(xmlFile.getAbsolutePath() + " could not be parsed");
}
try {
Element submission = model.getElement(xforms, "submission");
String submissionUri = submission.getAttributeValue(null, "action");
fields.put(SUBMISSIONURI, (submissionUri == null) ? null : submissionUri);
String base64RsaPublicKey = submission.getAttributeValue(null, "base64RsaPublicKey");
fields.put(BASE64_RSA_PUBLIC_KEY,
(base64RsaPublicKey == null || base64RsaPublicKey.trim().length() == 0)
? null : base64RsaPublicKey.trim());
} catch (Exception e) {
Log.i(t, xmlFile.getAbsolutePath() + " does not have a submission element");
// and that's totally fine.
}
}
return fields;
}
// needed because element.getelement fails when there are attributes
private static Element getChildElement(Element parent, String childName) {
Element e = null;
int c = parent.getChildCount();
int i = 0;
for (i = 0; i < c; i++) {
if (parent.getType(i) == Node.ELEMENT) {
if (parent.getElement(i).getName().equalsIgnoreCase(childName)) {
return parent.getElement(i);
}
}
}
return e;
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.kxml2.io.KXmlSerializer;
import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.logic.FormController.InstanceMetadata;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
/**
* Utility class for encrypting submissions during the SaveToDiskTask.
*
* @author mitchellsundt@gmail.com
*
*/
public class EncryptionUtils {
private static final String t = "EncryptionUtils";
public static final String RSA_ALGORITHM = "RSA";
// the symmetric key we are encrypting with RSA is only 256 bits... use SHA-256
public static final String ASYMMETRIC_ALGORITHM = "RSA/NONE/OAEPWithSHA256AndMGF1Padding";
public static final String SYMMETRIC_ALGORITHM = "AES/CFB/PKCS5Padding";
public static final String UTF_8 = "UTF-8";
public static final int SYMMETRIC_KEY_LENGTH = 256;
public static final int IV_BYTE_LENGTH = 16;
// tags in the submission manifest
private static final String XML_ENCRYPTED_TAG_NAMESPACE = "http://www.opendatakit.org/xforms/encrypted";
private static final String XML_OPENROSA_NAMESPACE = "http://openrosa.org/xforms";
private static final String DATA = "data";
private static final String ID = "id";
private static final String VERSION = "version";
private static final String ENCRYPTED = "encrypted";
private static final String BASE64_ENCRYPTED_KEY = "base64EncryptedKey";
private static final String ENCRYPTED_XML_FILE = "encryptedXmlFile";
private static final String META = "meta";
private static final String INSTANCE_ID = "instanceID";
private static final String MEDIA = "media";
private static final String FILE = "file";
private static final String BASE64_ENCRYPTED_ELEMENT_SIGNATURE = "base64EncryptedElementSignature";
private static final String NEW_LINE = "\n";
private EncryptionUtils() {
};
public static final class EncryptedFormInformation {
public final String formId;
public final String formVersion;
public final InstanceMetadata instanceMetadata;
public final PublicKey rsaPublicKey;
public final String base64RsaEncryptedSymmetricKey;
public final SecretKeySpec symmetricKey;
public final byte[] ivSeedArray;
private int ivCounter = 0;
public final StringBuilder elementSignatureSource = new StringBuilder();
public final Base64Wrapper wrapper;
EncryptedFormInformation(String formId, String formVersion,
InstanceMetadata instanceMetadata, PublicKey rsaPublicKey, Base64Wrapper wrapper) {
this.formId = formId;
this.formVersion = formVersion;
this.instanceMetadata = instanceMetadata;
this.rsaPublicKey = rsaPublicKey;
this.wrapper = wrapper;
// generate the symmetric key from random bits...
SecureRandom r = new SecureRandom();
byte[] key = new byte[SYMMETRIC_KEY_LENGTH/8];
r.nextBytes(key);
SecretKeySpec sk = new SecretKeySpec(key, SYMMETRIC_ALGORITHM);
symmetricKey = sk;
// construct the fixed portion of the iv -- the ivSeedArray
// this is the md5 hash of the instanceID and the symmetric key
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(instanceMetadata.instanceId.getBytes(UTF_8));
md.update(key);
byte[] messageDigest = md.digest();
ivSeedArray = new byte[IV_BYTE_LENGTH];
for ( int i = 0 ; i < IV_BYTE_LENGTH ; ++i ) {
ivSeedArray[i] = messageDigest[(i % messageDigest.length)];
}
} catch (NoSuchAlgorithmException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (UnsupportedEncodingException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
// construct the base64-encoded RSA-encrypted symmetric key
try {
Cipher pkCipher;
pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM);
// write AES key
pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
byte[] pkEncryptedKey = pkCipher.doFinal(key);
String alg = pkCipher.getAlgorithm();
Log.i(t, "AlgorithmUsed: " + alg);
base64RsaEncryptedSymmetricKey = wrapper
.encodeToString(pkEncryptedKey);
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (NoSuchPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvalidKeyException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (IllegalBlockSizeException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (BadPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
// start building elementSignatureSource...
appendElementSignatureSource(formId);
if ( formVersion != null ) {
appendElementSignatureSource(formVersion.toString());
}
appendElementSignatureSource(base64RsaEncryptedSymmetricKey);
appendElementSignatureSource( instanceMetadata.instanceId );
}
public void appendElementSignatureSource(String value) {
elementSignatureSource.append(value).append("\n");
}
public void appendFileSignatureSource(File file) {
String md5Hash = FileUtils.getMd5Hash(file);
appendElementSignatureSource(file.getName()+"::"+md5Hash);
}
public String getBase64EncryptedElementSignature() {
// Step 0: construct the text of the elements in elementSignatureSource (done)
// Where...
// * Elements are separated by newline characters.
// * Filename is the unencrypted filename (no .enc suffix).
// * Md5 hashes of the unencrypted files' contents are converted
// to zero-padded 32-character strings before concatenation.
// Assumes this is in the order:
// formId
// version (omitted if null)
// base64RsaEncryptedSymmetricKey
// instanceId
// for each media file { filename "::" md5Hash }
// submission.xml "::" md5Hash
// Step 1: construct the (raw) md5 hash of Step 0.
byte[] messageDigest;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(elementSignatureSource.toString().getBytes(UTF_8));
messageDigest = md.digest();
} catch (NoSuchAlgorithmException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (UnsupportedEncodingException e) {
Log.e(t, e.toString());
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
// Step 2: construct the base64-encoded RSA-encrypted md5
try {
Cipher pkCipher;
pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM);
// write AES key
pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
byte[] pkEncryptedKey = pkCipher.doFinal(messageDigest);
return wrapper.encodeToString(pkEncryptedKey);
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (NoSuchPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (InvalidKeyException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (IllegalBlockSizeException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
} catch (BadPaddingException e) {
Log.e(t, "Unable to encrypt the symmetric key");
e.printStackTrace();
throw new IllegalArgumentException(e.getMessage());
}
}
public Cipher getCipher() throws InvalidKeyException,
InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException {
++ivSeedArray[ivCounter % ivSeedArray.length];
++ivCounter;
IvParameterSpec baseIv = new IvParameterSpec(ivSeedArray);
Cipher c = Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, symmetricKey, baseIv);
return c;
}
}
/**
* Retrieve the encryption information for this uri.
*
* @param mUri either an instance URI (if previously saved) or a form URI
* @param instanceMetadata
* @return
*/
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri, InstanceMetadata instanceMetadata) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// fetch the form information
String formId;
String formVersion;
PublicKey pk;
Base64Wrapper wrapper;
Cursor formCursor = null;
try {
if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
// chain back to the Form record...
String[] selectionArgs = null;
String selection = null;
Cursor instanceCursor = null;
try {
instanceCursor = cr.query(mUri, null, null, null, null);
if ( instanceCursor.getCount() != 1 ) {
Log.e(t, "Not exactly one record for this instance!");
return null; // save unencrypted.
}
instanceCursor.moveToFirst();
String jrFormId = instanceCursor.getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
if ( !instanceCursor.isNull(idxJrVersion) ) {
selectionArgs = new String[] {jrFormId, instanceCursor.getString(idxJrVersion)};
selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
} else {
selectionArgs = new String[] {jrFormId};
selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
}
} finally {
if ( instanceCursor != null ) {
instanceCursor.close();
}
}
formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs,
null);
if (formCursor.getCount() != 1) {
Log.e(t, "Not exactly one blank form matches this jr_form_id");
return null; // save unencrypted
}
formCursor.moveToFirst();
} else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
formCursor = cr.query(mUri, null, null, null, null);
if ( formCursor.getCount() != 1 ) {
Log.e(t, "Not exactly one blank form!");
return null; // save unencrypted.
}
formCursor.moveToFirst();
}
formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
if (formId == null || formId.length() == 0) {
Log.e(t, "No FormId specified???");
return null;
}
int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey)
? null : formCursor.getString(idxBase64RsaPublicKey);
if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
return null; // this is legitimately not an encrypted form
}
int version = android.os.Build.VERSION.SDK_INT;
if (version < 8) {
Log.e(t, "Phone does not support encryption.");
return null; // save unencrypted
}
// this constructor will throw an exception if we are not
// running on version 8 or above (if Base64 is not found).
try {
wrapper = new Base64Wrapper();
} catch (ClassNotFoundException e) {
Log.e(t, "Phone does not have Base64 class but API level is "
+ version);
e.printStackTrace();
return null; // save unencrypted
}
// OK -- Base64 decode (requires API Version 8 or higher)
byte[] publicKey = wrapper.decode(base64RsaPublicKey);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
KeyFactory kf;
try {
kf = KeyFactory.getInstance(RSA_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Phone does not support RSA encryption.");
e.printStackTrace();
return null;
}
try {
pk = kf.generatePublic(publicKeySpec);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
Log.e(t, "Invalid RSA public key.");
return null;
}
} finally {
if (formCursor != null) {
formCursor.close();
}
}
// submission must have an OpenRosa metadata block with a non-null
// instanceID value.
if (instanceMetadata.instanceId == null) {
Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
return null;
}
return new EncryptedFormInformation(formId, formVersion, instanceMetadata,
pk, wrapper);
}
private static void encryptFile(File file, EncryptedFormInformation formInfo)
throws IOException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException {
File encryptedFile = new File(file.getParentFile(), file.getName()
+ ".enc");
// add elementSignatureSource for this file...
formInfo.appendFileSignatureSource(file);
try {
Cipher c = formInfo.getCipher();
OutputStream fout;
fout = new FileOutputStream(encryptedFile);
fout = new CipherOutputStream(fout, c);
InputStream fin;
fin = new FileInputStream(file);
byte[] buffer = new byte[2048];
int len = fin.read(buffer);
while (len != -1) {
fout.write(buffer, 0, len);
len = fin.read(buffer);
}
fin.close();
fout.flush();
fout.close();
Log.i(t,
"Encrpyted:" + file.getName() + " -> "
+ encryptedFile.getName());
} catch (IOException e) {
Log.e(t, "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName());
e.printStackTrace();
throw e;
} catch (NoSuchAlgorithmException e) {
Log.e(t, "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName());
e.printStackTrace();
throw e;
} catch (NoSuchPaddingException e) {
Log.e(t, "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName());
e.printStackTrace();
throw e;
} catch (InvalidKeyException e) {
Log.e(t, "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName());
e.printStackTrace();
throw e;
} catch (InvalidAlgorithmParameterException e) {
Log.e(t, "Error encrypting: " + file.getName() + " -> "
+ encryptedFile.getName());
e.printStackTrace();
throw e;
}
}
public static boolean deletePlaintextFiles(File instanceXml) {
// NOTE: assume the directory containing the instanceXml contains ONLY
// files related to this one instance.
File instanceDir = instanceXml.getParentFile();
boolean allSuccessful = true;
// encrypt files that do not end with ".enc", and do not start with ".";
// ignore directories
File[] allFiles = instanceDir.listFiles();
for (File f : allFiles) {
if (f.equals(instanceXml))
continue; // don't touch instance file
if (f.isDirectory())
continue; // don't handle directories
if (!f.getName().endsWith(".enc")) {
// not an encrypted file -- delete it!
allSuccessful = allSuccessful & f.delete(); // DO NOT
// short-circuit
}
}
return allSuccessful;
}
private static List<File> encryptSubmissionFiles(File instanceXml,
File submissionXml, EncryptedFormInformation formInfo) {
// NOTE: assume the directory containing the instanceXml contains ONLY
// files related to this one instance.
File instanceDir = instanceXml.getParentFile();
// encrypt files that do not end with ".enc", and do not start with ".";
// ignore directories
File[] allFiles = instanceDir.listFiles();
List<File> filesToProcess = new ArrayList<File>();
for (File f : allFiles) {
if (f.equals(instanceXml))
continue; // don't touch restore file
if (f.equals(submissionXml))
continue; // handled last
if (f.isDirectory())
continue; // don't handle directories
if (f.getName().startsWith("."))
continue; // MacOSX garbage
if (f.getName().endsWith(".enc")) {
f.delete(); // try to delete this (leftover junk)
} else {
filesToProcess.add(f);
}
}
// encrypt here...
for (File f : filesToProcess) {
try {
encryptFile(f, formInfo);
} catch (IOException e) {
return null;
} catch (InvalidKeyException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
} catch (NoSuchPaddingException e) {
return null;
} catch (InvalidAlgorithmParameterException e) {
return null;
}
}
// encrypt the submission.xml as the last file...
try {
encryptFile(submissionXml, formInfo);
} catch (IOException e) {
return null;
} catch (InvalidKeyException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
} catch (NoSuchPaddingException e) {
return null;
} catch (InvalidAlgorithmParameterException e) {
return null;
}
return filesToProcess;
}
/**
* Constructs the encrypted attachments, encrypted form xml, and the
* plaintext submission manifest (with signature) for the form submission.
*
* Does not delete any of the original files.
*
* @param instanceXml
* @param submissionXml
* @param metadata
* @param formInfo
* @return
*/
public static boolean generateEncryptedSubmission(File instanceXml,
File submissionXml, EncryptedFormInformation formInfo) {
// submissionXml is the submission data to be published to Aggregate
if (!submissionXml.exists() || !submissionXml.isFile()) {
Log.e(t, "No submission.xml found");
return false;
}
// TODO: confirm that this xml is not already encrypted...
// Step 1: encrypt the submission and all the media files...
List<File> mediaFiles = encryptSubmissionFiles(instanceXml,
submissionXml, formInfo);
if (mediaFiles == null) {
return false; // something failed...
}
// Step 2: build the encrypted-submission manifest (overwrites
// submission.xml)...
if (!writeSubmissionManifest(formInfo, submissionXml, mediaFiles)) {
return false;
}
return true;
}
private static boolean writeSubmissionManifest(
EncryptedFormInformation formInfo,
File submissionXml, List<File> mediaFiles) {
Document d = new Document();
d.setStandalone(true);
d.setEncoding(UTF_8);
Element e = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, DATA);
e.setPrefix(null, XML_ENCRYPTED_TAG_NAMESPACE);
e.setAttribute(null, ID, formInfo.formId);
if ( formInfo.formVersion != null ) {
e.setAttribute(null, VERSION, formInfo.formVersion);
}
e.setAttribute(null, ENCRYPTED, "yes");
d.addChild(0, Node.ELEMENT, e);
int idx = 0;
Element c;
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_KEY);
c.addChild(0, Node.TEXT, formInfo.base64RsaEncryptedSymmetricKey);
e.addChild(idx++, Node.ELEMENT, c);
c = d.createElement(XML_OPENROSA_NAMESPACE, META);
c.setPrefix("orx", XML_OPENROSA_NAMESPACE);
{
Element instanceTag = d.createElement(XML_OPENROSA_NAMESPACE, INSTANCE_ID);
instanceTag.addChild(0, Node.TEXT, formInfo.instanceMetadata.instanceId);
c.addChild(0, Node.ELEMENT, instanceTag);
}
e.addChild(idx++, Node.ELEMENT, c);
e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
for (File file : mediaFiles) {
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, MEDIA);
Element fileTag = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, FILE);
fileTag.addChild(0, Node.TEXT, file.getName() + ".enc");
c.addChild(0, Node.ELEMENT, fileTag);
e.addChild(idx++, Node.ELEMENT, c);
e.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
}
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, ENCRYPTED_XML_FILE);
c.addChild(0, Node.TEXT, submissionXml.getName() + ".enc");
e.addChild(idx++, Node.ELEMENT, c);
c = d.createElement(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_ELEMENT_SIGNATURE);
c.addChild(0, Node.TEXT, formInfo.getBase64EncryptedElementSignature());
e.addChild(idx++, Node.ELEMENT, c);
FileOutputStream out;
try {
out = new FileOutputStream(submissionXml);
OutputStreamWriter writer = new OutputStreamWriter(out, UTF_8);
KXmlSerializer serializer = new KXmlSerializer();
serializer.setOutput(writer);
// setting the response content type emits the xml header.
// just write the body here...
d.writeChildren(serializer);
serializer.flush();
writer.flush();
writer.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
Log.e(t, "Error writing submission.xml for encrypted submission: "
+ submissionXml.getParentFile().getName());
return false;
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
Log.e(t, "Error writing submission.xml for encrypted submission: "
+ submissionXml.getParentFile().getName());
return false;
} catch (IOException ex) {
ex.printStackTrace();
Log.e(t, "Error writing submission.xml for encrypted submission: "
+ submissionXml.getParentFile().getName());
return false;
}
return true;
}
}
| Java |
/*
* Copyright (C) 2012 University of Washington
*
* 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.odk.collect.android.utilities;
import org.odk.collect.android.R;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.ScrollView;
/**
* Based heavily upon:
* http://www.yougli.net/android/a-photoshop-like-color-picker
* -for-your-android-application/
*
* @author BehrAtherton@gmail.com
* @author yougli@yougli.net
*
*/
public class ColorPickerDialog extends Dialog {
public interface OnColorChangedListener {
void colorChanged(String key, int color);
}
private OnColorChangedListener mListener;
private int mInitialColor, mDefaultColor;
private String mKey;
/**
* Modified HorizontalScrollView that communicates scroll
* actions to interior Vertical scroll view.
* From: http://stackoverflow.com/questions/3866499/two-directional-scroll-view
*
*/
public class WScrollView extends HorizontalScrollView
{
public ScrollView sv;
public WScrollView(Context context)
{
super(context);
}
public WScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public WScrollView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override public boolean onTouchEvent(MotionEvent event)
{
boolean ret = super.onTouchEvent(event);
ret = ret | sv.onTouchEvent(event);
return ret;
}
@Override public boolean onInterceptTouchEvent(MotionEvent event)
{
boolean ret = super.onInterceptTouchEvent(event);
ret = ret | sv.onInterceptTouchEvent(event);
return ret;
}
}
private static class ColorPickerView extends View {
private Paint mPaint;
private float mCurrentHue = 0;
private int mCurrentX = 0, mCurrentY = 0;
private int mCurrentColor, mDefaultColor;
private final int[] mHueBarColors = new int[258];
private int[] mMainColors = new int[65536];
private OnColorChangedListener mListener;
ColorPickerView(Context c, OnColorChangedListener l, int color,
int defaultColor) {
super(c);
mListener = l;
mDefaultColor = defaultColor;
// Get the current hue from the current color and update the main
// color field
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
mCurrentHue = hsv[0];
updateMainColors();
mCurrentColor = color;
// Initialize the colors of the hue slider bar
int index = 0;
for (float i = 0; i < 256; i += 256 / 42) // Red (#f00) to pink
// (#f0f)
{
mHueBarColors[index] = Color.rgb(255, 0, (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Pink (#f0f) to blue
// (#00f)
{
mHueBarColors[index] = Color.rgb(255 - (int) i, 0, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Blue (#00f) to light
// blue (#0ff)
{
mHueBarColors[index] = Color.rgb(0, (int) i, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Light blue (#0ff) to
// green (#0f0)
{
mHueBarColors[index] = Color.rgb(0, 255, 255 - (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Green (#0f0) to yellow
// (#ff0)
{
mHueBarColors[index] = Color.rgb((int) i, 255, 0);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) // Yellow (#ff0) to red
// (#f00)
{
mHueBarColors[index] = Color.rgb(255, 255 - (int) i, 0);
index++;
}
// Initializes the Paint that will draw the View
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(12);
}
// Get the current selected color from the hue bar
private int getCurrentMainColor() {
int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
int index = 0;
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(255, 0, (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(255 - (int) i, 0, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(0, (int) i, 255);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(0, 255, 255 - (int) i);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb((int) i, 255, 0);
index++;
}
for (float i = 0; i < 256; i += 256 / 42) {
if (index == translatedHue)
return Color.rgb(255, 255 - (int) i, 0);
index++;
}
return Color.RED;
}
// Update the main field colors depending on the current selected hue
private void updateMainColors() {
int mainColor = getCurrentMainColor();
int index = 0;
int[] topColors = new int[256];
for (int y = 0; y < 256; y++) {
for (int x = 0; x < 256; x++) {
if (y == 0) {
mMainColors[index] = Color.rgb(
255 - (255 - Color.red(mainColor)) * x / 255,
255 - (255 - Color.green(mainColor)) * x / 255,
255 - (255 - Color.blue(mainColor)) * x / 255);
topColors[x] = mMainColors[index];
} else
mMainColors[index] = Color.rgb(
(255 - y) * Color.red(topColors[x]) / 255,
(255 - y) * Color.green(topColors[x]) / 255,
(255 - y) * Color.blue(topColors[x]) / 255);
index++;
}
}
}
@Override
protected void onDraw(Canvas canvas) {
int translatedHue = 255 - (int) (mCurrentHue * 255 / 360);
// Display all the colors of the hue bar with lines
for (int x = 0; x < 256; x++) {
// If this is not the current selected hue, display the actual
// color
if (translatedHue != x) {
mPaint.setColor(mHueBarColors[x]);
mPaint.setStrokeWidth(1);
} else // else display a slightly larger black line
{
mPaint.setColor(Color.BLACK);
mPaint.setStrokeWidth(3);
}
canvas.drawLine(x + 10, 0, x + 10, 40, mPaint);
}
// Display the main field colors using LinearGradient
for (int x = 0; x < 256; x++) {
int[] colors = new int[2];
colors[0] = mMainColors[x];
colors[1] = Color.BLACK;
Shader shader = new LinearGradient(0, 50, 0, 306, colors, null,
Shader.TileMode.REPEAT);
mPaint.setShader(shader);
canvas.drawLine(x + 10, 50, x + 10, 306, mPaint);
}
mPaint.setShader(null);
// Display the circle around the currently selected color in the
// main field
if (mCurrentX != 0 && mCurrentY != 0) {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(Color.BLACK);
canvas.drawCircle(mCurrentX, mCurrentY, 10, mPaint);
}
// Draw a 'button' with the currently selected color
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mCurrentColor);
canvas.drawRect(10, 316, 138, 356, mPaint);
// Set the text color according to the brightness of the color
mPaint.setColor(getInverseColor(mCurrentColor));
canvas.drawText(getContext().getString(R.string.ok), 74, 340,
mPaint);
// Draw a 'button' with the default color
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mDefaultColor);
canvas.drawRect(138, 316, 266, 356, mPaint);
// Set the text color according to the brightness of the color
mPaint.setColor(getInverseColor(mDefaultColor));
canvas.drawText(getContext().getString(R.string.cancel), 202, 340,
mPaint);
}
private int getInverseColor(int color) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
int alpha = Color.alpha(color);
return Color.argb(alpha, 255 - red, 255 - green, 255 - blue);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(276, 366);
}
private boolean afterFirstDown = false;
private float startX;
private float startY;
@Override
public boolean onTouchEvent(MotionEvent event) {
// allow scrolling...
boolean ret = super.onTouchEvent(event);
int action = event.getAction();
int pointerCount = event.getPointerCount();
if ( action == MotionEvent.ACTION_CANCEL ) {
afterFirstDown = false;
} else if ( pointerCount == 1 && action == MotionEvent.ACTION_DOWN ) {
afterFirstDown = true;
startX = event.getX();
startY = event.getY();
} else if ( pointerCount == 1 && action == MotionEvent.ACTION_MOVE && !afterFirstDown ) {
afterFirstDown = true;
startX = event.getX();
startY = event.getY();
}
if ( !afterFirstDown || pointerCount != 1 || action != MotionEvent.ACTION_UP ) {
return true;
}
// on an ACTION_UP, we reset the afterFirstDown flag.
// processing uses the lifting of the finger to choose
// the color...
afterFirstDown = false;
float x = event.getX();
float y = event.getY();
if ( Math.abs(x - startX) > 10 && Math.abs(y - startY) > 10 ) {
// the color location drifted, so it must just be a scrolling action
// ignore it...
return ret;
}
// If the touch event is located in the hue bar
if (x > 10 && x < 266 && y > 0 && y < 40) {
// Update the main field colors
mCurrentHue = (255 - x) * 360 / 255;
updateMainColors();
// Update the current selected color
int transX = mCurrentX - 10;
int transY = mCurrentY - 60;
int index = 256 * (transY - 1) + transX;
if (index > 0 && index < mMainColors.length)
mCurrentColor = mMainColors[256 * (transY - 1) + transX];
// Force the redraw of the dialog
invalidate();
}
// If the touch event is located in the main field
if (x > 10 && x < 266 && y > 50 && y < 306) {
mCurrentX = (int) x;
mCurrentY = (int) y;
int transX = mCurrentX - 10;
int transY = mCurrentY - 60;
int index = 256 * (transY - 1) + transX;
if (index > 0 && index < mMainColors.length) {
// Update the current color
mCurrentColor = mMainColors[index];
// Force the redraw of the dialog
invalidate();
}
}
// If the touch event is located in the left button, notify the
// listener with the current color
if (x > 10 && x < 138 && y > 316 && y < 356)
mListener.colorChanged("", mCurrentColor);
// If the touch event is located in the right button, notify the
// listener with the default color
if (x > 138 && x < 266 && y > 316 && y < 356)
mListener.colorChanged("", mDefaultColor);
return true;
}
}
public ColorPickerDialog(Context context, OnColorChangedListener listener,
String key, int initialColor, int defaultColor, String title) {
super(context);
mListener = listener;
mKey = key;
mInitialColor = initialColor;
mDefaultColor = defaultColor;
setTitle(title);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OnColorChangedListener l = new OnColorChangedListener() {
public void colorChanged(String key, int color) {
mListener.colorChanged(mKey, color);
dismiss();
}
};
/*BIDIRECTIONAL SCROLLVIEW*/
ScrollView sv = new ScrollView(this.getContext());
WScrollView hsv = new WScrollView(this.getContext());
hsv.sv = sv;
/*END OF BIDIRECTIONAL SCROLLVIEW*/
sv.addView(new ColorPickerView(getContext(), l, mInitialColor,
mDefaultColor), new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
hsv.addView(sv, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
setContentView(hsv, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setCanceledOnTouchOutside(true);
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.utilities;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Wrapper class for accessing Base64 functionality.
* This allows API Level 7 deployment of ODK Collect while
* enabling API Level 8 and higher phone to support encryption.
*
* @author mitchellsundt@gmail.com
*
*/
public class Base64Wrapper {
private static final int FLAGS = 2;// NO_WRAP
private Class<?> base64 = null;
public Base64Wrapper() throws ClassNotFoundException {
base64 = this.getClass().getClassLoader()
.loadClass("android.util.Base64");
}
public String encodeToString(byte[] ba) {
Class<?>[] argClassList = new Class[]{byte[].class, int.class};
try {
Method m = base64.getDeclaredMethod("encode", argClassList);
Object[] argList = new Object[]{ ba, FLAGS };
Object o = m.invoke(null, argList);
byte[] outArray = (byte[]) o;
String s = new String(outArray, "UTF-8");
return s;
} catch (SecurityException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
}
}
public byte[] decode(String base64String) {
Class<?>[] argClassList = new Class[]{String.class, int.class};
Object o;
try {
Method m = base64.getDeclaredMethod("decode", argClassList);
Object[] argList = new Object[]{ base64String, FLAGS };
o = m.invoke(null, argList);
} catch (SecurityException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalArgumentException(e.toString());
}
return (byte[]) o;
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.
*
* Original License from BasicCredentialsProvider:
* ====================================================================
*
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.odk.collect.android.utilities;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.opendatakit.httpclientandroidlib.annotation.ThreadSafe;
import org.opendatakit.httpclientandroidlib.auth.AuthScope;
import org.opendatakit.httpclientandroidlib.auth.Credentials;
import org.opendatakit.httpclientandroidlib.client.CredentialsProvider;
/**
* Modified BasicCredentialsProvider that will clear the provider
* after 'expiryInterval' milliseconds of inactivity. Use the WebUtils
* methods to manipulate the credentials in the local context. You should
* first check that the credentials exist (which will reset the expiration
* date), then set them if they are missing.
*
* Largely a cut-and-paste of BasicCredentialsProvider.
*
* @author mitchellsundt@gmail.com
*
*/
@ThreadSafe
public class AgingCredentialsProvider implements CredentialsProvider {
private final ConcurrentHashMap<AuthScope, Credentials> credMap;
private final long expiryInterval;
private long nextClearTimestamp;
/**
* Default constructor.
*/
public AgingCredentialsProvider(int expiryInterval) {
super();
this.credMap = new ConcurrentHashMap<AuthScope, Credentials>();
this.expiryInterval = expiryInterval;
nextClearTimestamp = System.currentTimeMillis() + expiryInterval;
}
public void setCredentials(
final AuthScope authscope,
final Credentials credentials) {
if (authscope == null) {
throw new IllegalArgumentException("Authentication scope may not be null");
}
if (nextClearTimestamp < System.currentTimeMillis()) {
clear();
}
nextClearTimestamp = System.currentTimeMillis() + expiryInterval;
if ( credentials == null ) {
credMap.remove(authscope);
} else {
credMap.put(authscope, credentials);
}
}
/**
* Find matching {@link Credentials credentials} for the given authentication scope.
*
* @param map the credentials hash map
* @param authscope the {@link AuthScope authentication scope}
* @return the credentials
*
*/
private static Credentials matchCredentials(
final Map<AuthScope, Credentials> map,
final AuthScope authscope) {
// see if we get a direct hit
Credentials creds = map.get(authscope);
if (creds == null) {
// Nope.
// Do a full scan
int bestMatchFactor = -1;
AuthScope bestMatch = null;
for (AuthScope current: map.keySet()) {
int factor = authscope.match(current);
if (factor > bestMatchFactor) {
bestMatchFactor = factor;
bestMatch = current;
}
}
if (bestMatch != null) {
creds = map.get(bestMatch);
}
}
return creds;
}
public Credentials getCredentials(final AuthScope authscope) {
if (authscope == null) {
throw new IllegalArgumentException("Authentication scope may not be null");
}
if (nextClearTimestamp < System.currentTimeMillis()) {
clear();
}
nextClearTimestamp = System.currentTimeMillis() + expiryInterval;
Credentials c = matchCredentials(this.credMap, authscope);
return c;
}
public void clear() {
this.credMap.clear();
}
@Override
public String toString() {
return credMap.toString();
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.utilities;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.odk.collect.android.application.Collect;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Video;
import android.util.Log;
/**
* Consolidate all interactions with media providers here.
*
* @author mitchellsundt@gmail.com
*
*/
public class MediaUtils {
private static final String t = "MediaUtils";
private MediaUtils() {
// static methods only
}
private static String escapePath(String path) {
String ep = path;
ep = ep.replaceAll("\\!", "!!");
ep = ep.replaceAll("_", "!_");
ep = ep.replaceAll("%", "!%");
return ep;
}
public static final Uri getImageUriFromMediaProvider(String imageFile) {
String selection = Images.ImageColumns.DATA + "=?";
String[] selectArgs = { imageFile };
String[] projection = { Images.ImageColumns._ID };
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectArgs, null);
if (c.getCount() > 0) {
c.moveToFirst();
String id = c.getString(c.getColumnIndex(Images.ImageColumns._ID));
return Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
}
return null;
} finally {
if ( c != null ) {
c.close();
}
}
}
public static final int deleteImageFileFromMediaProvider(String imageFile) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// images
int count = 0;
Cursor imageCursor = null;
try {
String select =
Images.Media.DATA + "=?";
String[] selectArgs = { imageFile };
String[] projection = {
Images.ImageColumns._ID
};
imageCursor = cr.query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (imageCursor.getCount() > 0) {
imageCursor.moveToFirst();
List<Uri> imagesToDelete = new ArrayList<Uri>();
do {
String id =
imageCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
imagesToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id));
} while ( imageCursor.moveToNext());
for ( Uri uri : imagesToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( imageCursor != null ) {
imageCursor.close();
}
}
File f = new File(imageFile);
if ( f.exists() ) {
f.delete();
}
return count;
}
public static final int deleteImagesInFolderFromMediaProvider(File folder) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// images
int count = 0;
Cursor imageCursor = null;
try {
String select =
Images.Media.DATA + " like ? escape '!'";
String[] selectArgs = { escapePath(folder.getAbsolutePath()) };
String[] projection = {
Images.ImageColumns._ID
};
imageCursor = cr.query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (imageCursor.getCount() > 0) {
imageCursor.moveToFirst();
List<Uri> imagesToDelete = new ArrayList<Uri>();
do {
String id =
imageCursor.getString(imageCursor
.getColumnIndex(Images.ImageColumns._ID));
imagesToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
id));
} while ( imageCursor.moveToNext());
for ( Uri uri : imagesToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( imageCursor != null ) {
imageCursor.close();
}
}
return count;
}
public static final Uri getAudioUriFromMediaProvider(String audioFile) {
String selection = Audio.AudioColumns.DATA + "=?";
String[] selectArgs = { audioFile };
String[] projection = { Audio.AudioColumns._ID };
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver().query(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectArgs, null);
if (c.getCount() > 0) {
c.moveToFirst();
String id = c.getString(c.getColumnIndex(Audio.AudioColumns._ID));
return Uri.withAppendedPath(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
}
return null;
} finally {
if ( c != null ) {
c.close();
}
}
}
public static final int deleteAudioFileFromMediaProvider(String audioFile) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// audio
int count = 0;
Cursor audioCursor = null;
try {
String select =
Audio.Media.DATA + "=?";
String[] selectArgs = { audioFile };
String[] projection = {
Audio.AudioColumns._ID
};
audioCursor = cr.query(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (audioCursor.getCount() > 0) {
audioCursor.moveToFirst();
List<Uri> audioToDelete = new ArrayList<Uri>();
do {
String id =
audioCursor.getString(audioCursor
.getColumnIndex(Audio.AudioColumns._ID));
audioToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id));
} while ( audioCursor.moveToNext());
for ( Uri uri : audioToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( audioCursor != null ) {
audioCursor.close();
}
}
File f = new File(audioFile);
if ( f.exists() ) {
f.delete();
}
return count;
}
public static final int deleteAudioInFolderFromMediaProvider(File folder) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// audio
int count = 0;
Cursor audioCursor = null;
try {
String select =
Audio.Media.DATA + " like ? escape '!'";
String[] selectArgs = { escapePath(folder.getAbsolutePath()) };
String[] projection = {
Audio.AudioColumns._ID
};
audioCursor = cr.query(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (audioCursor.getCount() > 0) {
audioCursor.moveToFirst();
List<Uri> audioToDelete = new ArrayList<Uri>();
do {
String id =
audioCursor.getString(audioCursor
.getColumnIndex(Audio.AudioColumns._ID));
audioToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
id));
} while ( audioCursor.moveToNext());
for ( Uri uri : audioToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( audioCursor != null ) {
audioCursor.close();
}
}
return count;
}
public static final Uri getVideoUriFromMediaProvider(String videoFile) {
String selection = Video.VideoColumns.DATA + "=?";
String[] selectArgs = { videoFile };
String[] projection = { Video.VideoColumns._ID };
Cursor c = null;
try {
c = Collect.getInstance().getContentResolver().query(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, selection, selectArgs, null);
if (c.getCount() > 0) {
c.moveToFirst();
String id = c.getString(c.getColumnIndex(Video.VideoColumns._ID));
return Uri.withAppendedPath(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);
}
return null;
} finally {
if ( c != null ) {
c.close();
}
}
}
public static final int deleteVideoFileFromMediaProvider(String videoFile) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// video
int count = 0;
Cursor videoCursor = null;
try {
String select =
Video.Media.DATA + "=?";
String[] selectArgs = { videoFile };
String[] projection = {
Video.VideoColumns._ID
};
videoCursor = cr.query(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (videoCursor.getCount() > 0) {
videoCursor.moveToFirst();
List<Uri> videoToDelete = new ArrayList<Uri>();
do {
String id =
videoCursor.getString(videoCursor
.getColumnIndex(Video.VideoColumns._ID));
videoToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id));
} while ( videoCursor.moveToNext());
for ( Uri uri : videoToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( videoCursor != null ) {
videoCursor.close();
}
}
File f = new File(videoFile);
if ( f.exists() ) {
f.delete();
}
return count;
}
public static final int deleteVideoInFolderFromMediaProvider(File folder) {
ContentResolver cr = Collect.getInstance().getContentResolver();
// video
int count = 0;
Cursor videoCursor = null;
try {
String select =
Video.Media.DATA + " like ? escape '!'";
String[] selectArgs = { escapePath(folder.getAbsolutePath()) };
String[] projection = {
Video.VideoColumns._ID
};
videoCursor = cr.query(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, select, selectArgs, null);
if (videoCursor.getCount() > 0) {
videoCursor.moveToFirst();
List<Uri> videoToDelete = new ArrayList<Uri>();
do {
String id =
videoCursor.getString(videoCursor
.getColumnIndex(Video.VideoColumns._ID));
videoToDelete.add(Uri.withAppendedPath(
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
id));
} while ( videoCursor.moveToNext());
for ( Uri uri : videoToDelete ) {
Log.i(t,"attempting to delete: " + uri );
count += cr.delete(uri, null, null);
}
}
} catch ( Exception e ) {
Log.e(t, e.toString());
} finally {
if ( videoCursor != null ) {
videoCursor.close();
}
}
return count;
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.utilities;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.http.HttpStatus;
import org.kxml2.io.KXmlParser;
import org.kxml2.kdom.Document;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.opendatakit.httpclientandroidlib.Header;
import org.opendatakit.httpclientandroidlib.HttpEntity;
import org.opendatakit.httpclientandroidlib.HttpHost;
import org.opendatakit.httpclientandroidlib.HttpRequest;
import org.opendatakit.httpclientandroidlib.HttpResponse;
import org.opendatakit.httpclientandroidlib.auth.AuthScope;
import org.opendatakit.httpclientandroidlib.auth.Credentials;
import org.opendatakit.httpclientandroidlib.auth.UsernamePasswordCredentials;
import org.opendatakit.httpclientandroidlib.auth.params.AuthPNames;
import org.opendatakit.httpclientandroidlib.client.AuthCache;
import org.opendatakit.httpclientandroidlib.client.CredentialsProvider;
import org.opendatakit.httpclientandroidlib.client.HttpClient;
import org.opendatakit.httpclientandroidlib.client.methods.HttpGet;
import org.opendatakit.httpclientandroidlib.client.methods.HttpHead;
import org.opendatakit.httpclientandroidlib.client.methods.HttpPost;
import org.opendatakit.httpclientandroidlib.client.params.AuthPolicy;
import org.opendatakit.httpclientandroidlib.client.params.ClientPNames;
import org.opendatakit.httpclientandroidlib.client.params.CookiePolicy;
import org.opendatakit.httpclientandroidlib.client.params.HttpClientParams;
import org.opendatakit.httpclientandroidlib.client.protocol.ClientContext;
import org.opendatakit.httpclientandroidlib.conn.ClientConnectionManager;
import org.opendatakit.httpclientandroidlib.impl.auth.BasicScheme;
import org.opendatakit.httpclientandroidlib.impl.client.BasicAuthCache;
import org.opendatakit.httpclientandroidlib.impl.client.DefaultHttpClient;
import org.opendatakit.httpclientandroidlib.params.BasicHttpParams;
import org.opendatakit.httpclientandroidlib.params.HttpConnectionParams;
import org.opendatakit.httpclientandroidlib.params.HttpParams;
import org.opendatakit.httpclientandroidlib.protocol.HttpContext;
import org.xmlpull.v1.XmlPullParser;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
import android.util.Log;
/**
* Common utility methods for managing the credentials associated with the
* request context and constructing http context, client and request with the
* proper parameters and OpenRosa headers.
*
* @author mitchellsundt@gmail.com
*/
public final class WebUtils {
public static final String t = "WebUtils";
public static final String OPEN_ROSA_VERSION_HEADER = "X-OpenRosa-Version";
public static final String OPEN_ROSA_VERSION = "1.0";
private static final String DATE_HEADER = "Date";
public static final String HTTP_CONTENT_TYPE_TEXT_XML = "text/xml";
public static final int CONNECTION_TIMEOUT = 30000;
private static ClientConnectionManager httpConnectionManager = null;
public static final List<AuthScope> buildAuthScopes(String host) {
List<AuthScope> asList = new ArrayList<AuthScope>();
AuthScope a;
// allow digest auth on any port...
a = new AuthScope(host, -1, null, AuthPolicy.DIGEST);
asList.add(a);
// and allow basic auth on the standard TLS/SSL ports...
a = new AuthScope(host, 443, null, AuthPolicy.BASIC);
asList.add(a);
a = new AuthScope(host, 8443, null, AuthPolicy.BASIC);
asList.add(a);
return asList;
}
public static final void clearAllCredentials() {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
Log.i(t, "clearAllCredentials");
credsProvider.clear();
}
public static final boolean hasCredentials(String userEmail, String host) {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
List<AuthScope> asList = buildAuthScopes(host);
boolean hasCreds = true;
for (AuthScope a : asList) {
Credentials c = credsProvider.getCredentials(a);
if (c == null) {
hasCreds = false;
continue;
}
}
return hasCreds;
}
/**
* Remove all credentials for accessing the specified host.
*
* @param host
*/
private static final void clearHostCredentials(String host) {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
Log.i(t, "clearHostCredentials: " + host);
List<AuthScope> asList = buildAuthScopes(host);
for (AuthScope a : asList) {
credsProvider.setCredentials(a, null);
}
}
/**
* Remove all credentials for accessing the specified host and, if the
* username is not null or blank then add a (username, password) credential
* for accessing this host.
*
* @param username
* @param password
* @param host
*/
public static final void addCredentials(String username, String password,
String host) {
// to ensure that this is the only authentication available for this
// host...
clearHostCredentials(host);
if (username != null && username.trim().length() != 0) {
Log.i(t, "adding credential for host: " + host + " username:"
+ username);
Credentials c = new UsernamePasswordCredentials(username, password);
addCredentials(c, host);
}
}
private static final void addCredentials(Credentials c, String host) {
CredentialsProvider credsProvider = Collect.getInstance()
.getCredentialsProvider();
List<AuthScope> asList = buildAuthScopes(host);
for (AuthScope a : asList) {
credsProvider.setCredentials(a, c);
}
}
public static final void enablePreemptiveBasicAuth(
HttpContext localContext, String host) {
AuthCache ac = (AuthCache) localContext
.getAttribute(ClientContext.AUTH_CACHE);
HttpHost h = new HttpHost(host);
if (ac == null) {
ac = new BasicAuthCache();
localContext.setAttribute(ClientContext.AUTH_CACHE, ac);
}
List<AuthScope> asList = buildAuthScopes(host);
for (AuthScope a : asList) {
if (a.getScheme() == AuthPolicy.BASIC) {
ac.put(h, new BasicScheme());
}
}
}
private static final void setOpenRosaHeaders(HttpRequest req) {
req.setHeader(OPEN_ROSA_VERSION_HEADER, OPEN_ROSA_VERSION);
GregorianCalendar g = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
g.setTime(new Date());
req.setHeader(DATE_HEADER,
DateFormat.format("E, dd MMM yyyy hh:mm:ss zz", g).toString());
}
public static final HttpHead createOpenRosaHttpHead(Uri u) {
HttpHead req = new HttpHead(URI.create(u.toString()));
setOpenRosaHeaders(req);
return req;
}
public static final HttpGet createOpenRosaHttpGet(URI uri) {
HttpGet req = new HttpGet();
setOpenRosaHeaders(req);
setGoogleHeaders(req);
req.setURI(uri);
return req;
}
public static final void setGoogleHeaders(HttpRequest req) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance().getApplicationContext());
String protocol = settings.getString(PreferencesActivity.KEY_PROTOCOL, PreferencesActivity.PROTOCOL_ODK_DEFAULT);
if ( protocol.equals(PreferencesActivity.PROTOCOL_GOOGLE) ) {
String auth = settings.getString(PreferencesActivity.KEY_AUTH, "");
if ((auth != null) && (auth.length() > 0)) {
req.setHeader("Authorization", "GoogleLogin auth=" + auth);
}
}
}
public static final HttpPost createOpenRosaHttpPost(Uri u) {
HttpPost req = new HttpPost(URI.create(u.toString()));
setOpenRosaHeaders(req);
setGoogleHeaders(req);
return req;
}
/**
* Create an httpClient with connection timeouts and other parameters set.
* Save and reuse the connection manager across invocations (this is what
* requires synchronized access).
*
* @param timeout
* @return HttpClient properly configured.
*/
public static final synchronized HttpClient createHttpClient(int timeout) {
// configure connection
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, timeout);
HttpConnectionParams.setSoTimeout(params, 2 * timeout);
// support redirecting to handle http: => https: transition
HttpClientParams.setRedirecting(params, true);
// support authenticating
HttpClientParams.setAuthenticating(params, true);
HttpClientParams.setCookiePolicy(params,
CookiePolicy.BROWSER_COMPATIBILITY);
// if possible, bias toward digest auth (may not be in 4.0 beta 2)
List<String> authPref = new ArrayList<String>();
authPref.add(AuthPolicy.DIGEST);
authPref.add(AuthPolicy.BASIC);
// does this work in Google's 4.0 beta 2 snapshot?
params.setParameter(AuthPNames.TARGET_AUTH_PREF, authPref);
params.setParameter(ClientPNames.MAX_REDIRECTS, 1);
params.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
// setup client
DefaultHttpClient httpclient;
// reuse the connection manager across all clients this ODK Collect
// creates.
if (httpConnectionManager == null) {
// let Apache stack create a connection manager.
httpclient = new DefaultHttpClient(params);
httpConnectionManager = httpclient.getConnectionManager();
} else {
// reuse the connection manager we already got.
httpclient = new DefaultHttpClient(httpConnectionManager, params);
}
return httpclient;
}
/**
* Utility to ensure that the entity stream of a response is drained of
* bytes.
*
* @param response
*/
public static final void discardEntityBytes(HttpResponse response) {
// may be a server that does not handle
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Common method for returning a parsed xml document given a url and the
* http context and client objects involved in the web connection.
*
* @param urlString
* @param localContext
* @param httpclient
* @return
*/
public static DocumentFetchResult getXmlDocument(String urlString,
HttpContext localContext, HttpClient httpclient) {
URI u = null;
try {
URL url = new URL(urlString);
u = url.toURI();
} catch (Exception e) {
e.printStackTrace();
return new DocumentFetchResult(e.getLocalizedMessage()
// + app.getString(R.string.while_accessing) + urlString);
+ ("while accessing") + urlString, 0);
}
if (u.getHost() == null ) {
return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0);
}
// if https then enable preemptive basic auth...
if (u.getScheme().equals("https")) {
enablePreemptiveBasicAuth(localContext, u.getHost());
}
// set up request...
HttpGet req = WebUtils.createOpenRosaHttpGet(u);
HttpResponse response = null;
try {
response = httpclient.execute(req, localContext);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (statusCode != HttpStatus.SC_OK) {
WebUtils.discardEntityBytes(response);
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
// clear the cookies -- should not be necessary?
Collect.getInstance().getCookieStore().clear();
}
String webError = response.getStatusLine().getReasonPhrase()
+ " (" + statusCode + ")";
return new DocumentFetchResult(u.toString()
+ " responded with: " + webError, statusCode);
}
if (entity == null) {
String error = "No entity body returned from: " + u.toString();
Log.e(t, error);
return new DocumentFetchResult(error, 0);
}
if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH)
.contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) {
WebUtils.discardEntityBytes(response);
String error = "ContentType: "
+ entity.getContentType().getValue()
+ " returned from: "
+ u.toString()
+ " is not text/xml. This is often caused a network proxy. Do you need to login to your network?";
Log.e(t, error);
return new DocumentFetchResult(error, 0);
}
// parse response
Document doc = null;
try {
InputStream is = null;
InputStreamReader isr = null;
try {
is = entity.getContent();
isr = new InputStreamReader(is, "UTF-8");
doc = new Document();
KXmlParser parser = new KXmlParser();
parser.setInput(isr);
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,
true);
doc.parse(parser);
isr.close();
isr = null;
} finally {
if (isr != null) {
try {
// ensure stream is consumed...
final long count = 1024L;
while (isr.skip(count) == count)
;
} catch (Exception e) {
// no-op
}
try {
isr.close();
} catch (Exception e) {
// no-op
}
}
if (is != null) {
try {
is.close();
} catch (Exception e) {
// no-op
}
}
}
} catch (Exception e) {
e.printStackTrace();
String error = "Parsing failed with " + e.getMessage()
+ "while accessing " + u.toString();
Log.e(t, error);
return new DocumentFetchResult(error, 0);
}
boolean isOR = false;
Header[] fields = response
.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER);
if (fields != null && fields.length >= 1) {
isOR = true;
boolean versionMatch = false;
boolean first = true;
StringBuilder b = new StringBuilder();
for (Header h : fields) {
if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) {
versionMatch = true;
break;
}
if (!first) {
b.append("; ");
}
first = false;
b.append(h.getValue());
}
if (!versionMatch) {
Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER
+ " unrecognized version(s): " + b.toString());
}
}
return new DocumentFetchResult(doc, isOR);
} catch (Exception e) {
clearHttpConnectionManager();
e.printStackTrace();
String cause;
Throwable c = e;
while (c.getCause() != null) {
c = c.getCause();
}
cause = c.toString();
String error = "Error: " + cause + " while accessing "
+ u.toString();
Log.w(t, error);
return new DocumentFetchResult(error, 0);
}
}
public static void clearHttpConnectionManager() {
// If we get an unexpected exception, the safest thing is to close
// all connections
// so that if there is garbage on the connection we ensure it is
// removed. This
// is especially important if the connection times out.
if ( httpConnectionManager != null ) {
httpConnectionManager.shutdown();
httpConnectionManager = null;
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.utilities;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlUtils {
public static boolean isValidUrl(String url) {
try {
new URL(url);
return true;
} catch (MalformedURLException e) {
return false;
}
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.utilities;
import org.kxml2.kdom.Document;
public class DocumentFetchResult {
public final String errorMessage;
public final int responseCode;
public final Document doc;
public final boolean isOpenRosaResponse;
public DocumentFetchResult(String msg, int response) {
responseCode = response;
errorMessage = msg;
doc = null;
isOpenRosaResponse = false;
}
public DocumentFetchResult(Document doc, boolean isOpenRosaResponse) {
responseCode = 0;
errorMessage = null;
this.doc = doc;
this.isOpenRosaResponse = isOpenRosaResponse;
}
} | Java |
/*
* Copyright (C) 2013 University of Washington
*
* 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.odk.collect.android.utilities;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.odk.collect.android.application.Collect;
import android.util.Log;
/**
* Used for logging data to log files that could be retrieved after a field deployment.
* The initial use for this is to assist in diagnosing a report of a cached geopoints
* being reported, causing stale GPS coordinates to be recorded (issue 780).
*
* @author mitchellsundt@gmail.com
*
*/
public class InfoLogger {
private static final String t = "InfoLogger";
private static final String LOG_DIRECTORY = "logging";
private static final String LOG_FILE = "geotrace.log";
public static final void geolog(String msg) {
geologToLogcat(msg);
}
private static final void geologToLogcat(String msg) {
Log.i(t, msg);
}
@SuppressWarnings("unused")
private static final void geologToFile(String msg) {
File dir = new File( Collect.ODK_ROOT + File.separator + LOG_DIRECTORY );
if ( !dir.exists() ) {
dir.mkdirs();
}
File log = new File(dir, LOG_FILE);
FileOutputStream fo = null;
try {
fo = new FileOutputStream(log, true);
msg = msg + "\n";
fo.write( msg.getBytes("UTF-8") );
fo.flush();
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e(t, "exception: " + e.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e(t, "exception: " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e(t, "exception: " + e.toString());
}
}
}
| Java |
/*
* Copyright (C) 2012 University of Washington
*
* 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.odk.collect.android.database;
import java.io.File;
import java.util.Calendar;
import java.util.LinkedList;
import org.javarosa.core.model.FormIndex;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.logic.FormController;
import android.app.Activity;
import android.content.ContentValues;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
/**
* Log all user interface activity into a SQLite database. Logging is disabled by default.
*
* The logging database will be "/sdcard/odk/log/activityLog.db"
*
* Logging is enabled if the file "/sdcard/odk/log/enabled" exists.
*
* @author mitchellsundt@gmail.com
* @author Carl Hartung (carlhartung@gmail.com)
*
*/
public final class ActivityLogger {
private static class DatabaseHelper extends ODKSQLiteOpenHelper {
DatabaseHelper() {
super(Collect.LOG_PATH, DATABASE_NAME, null, DATABASE_VERSION);
new File(Collect.LOG_PATH).mkdirs();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
/**
* The minimum delay, in milliseconds, for a scroll action to be considered new.
*/
private static final long MIN_SCROLL_DELAY = 400L;
/**
* The maximum size of the scroll action buffer. After it reaches this size,
* it will be flushed.
*/
private static final int MAX_SCROLL_ACTION_BUFFER_SIZE = 8;
private static final String DATABASE_TABLE = "log";
private static final String ENABLE_LOGGING = "enabled";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "activityLog.db";
// Database columns
private static final String ID = "_id";
private static final String TIMESTAMP = "timestamp";
private static final String DEVICEID = "device_id";
private static final String CLASS = "class";
private static final String CONTEXT = "context";
private static final String ACTION = "action";
private static final String INSTANCE_PATH = "instance_path";
private static final String QUESTION = "question";
private static final String PARAM1 = "param1";
private static final String PARAM2 = "param2";
private static final String DATABASE_CREATE =
"create table " + DATABASE_TABLE + " (" +
ID + " integer primary key autoincrement, " +
TIMESTAMP + " integer not null, " +
DEVICEID + " text not null, " +
CLASS + " text not null, " +
CONTEXT + " text not null, " +
ACTION + " text, " +
INSTANCE_PATH + " text, " +
QUESTION + " text, " +
PARAM1 + " text, " +
PARAM2 + " text);";
private final boolean mLoggingEnabled;
private final String mDeviceId;
private DatabaseHelper mDbHelper = null;
private SQLiteDatabase mDb = null;
private boolean mIsOpen = false;
// We buffer scroll actions to make sure there aren't too many pauses
// during scrolling. This list is flushed every time any other type of
// action is logged.
private LinkedList<ContentValues> mScrollActions = new LinkedList<ContentValues>();
public ActivityLogger(String deviceId) {
this.mDeviceId = deviceId;
mLoggingEnabled = new File(Collect.LOG_PATH, ENABLE_LOGGING).exists();
open();
}
public boolean isOpen() {
return mLoggingEnabled && mIsOpen;
}
public void open() throws SQLException {
if (!mLoggingEnabled || mIsOpen) return;
try {
mDbHelper = new DatabaseHelper();
mDb = mDbHelper.getWritableDatabase();
mIsOpen = true;
} catch (SQLiteException e) {
System.err.println("Error: " + e.getMessage());
mIsOpen = false;
}
}
// cached to improve logging performance...
// only access these through getXPath(FormIndex index);
private FormIndex cachedXPathIndex = null;
private String cachedXPathValue = null;
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
// DO NOT CALL THIS OUTSIDE OF synchronized(mScrollActions) !!!!
private String getXPath(FormIndex index) {
if ( index == cachedXPathIndex ) return cachedXPathValue;
cachedXPathIndex = index;
cachedXPathValue = Collect.getInstance().getFormController().getXPath(index);
return cachedXPathValue;
}
private void log(String object, String context, String action, String instancePath, FormIndex index, String param1, String param2) {
if (!isOpen()) return;
ContentValues cv = new ContentValues();
cv.put(DEVICEID, mDeviceId);
cv.put(CLASS, object);
cv.put(CONTEXT, context);
cv.put(ACTION, action);
cv.put(INSTANCE_PATH, instancePath);
cv.put(PARAM1, param1);
cv.put(PARAM2, param2);
cv.put(TIMESTAMP, Calendar.getInstance().getTimeInMillis());
insertContentValues(cv, index);
}
public void logScrollAction(Object t, int distance) {
if (!isOpen()) return;
synchronized(mScrollActions) {
long timeStamp = Calendar.getInstance().getTimeInMillis();
// Check to see if we can add this scroll action to the previous action.
if (!mScrollActions.isEmpty()) {
ContentValues lastCv = mScrollActions.get(mScrollActions.size() - 1);
long oldTimeStamp = lastCv.getAsLong(TIMESTAMP);
int oldDistance = Integer.parseInt(lastCv.getAsString(PARAM1));
if (Integer.signum(distance) == Integer.signum(oldDistance) &&
timeStamp - oldTimeStamp < MIN_SCROLL_DELAY) {
lastCv.put(PARAM1, oldDistance + distance);
lastCv.put(TIMESTAMP, timeStamp);
return;
}
}
if (mScrollActions.size() >= MAX_SCROLL_ACTION_BUFFER_SIZE) {
insertContentValues(null, null); // flush scroll list...
}
String idx = "";
String instancePath = "";
FormController formController = Collect.getInstance().getFormController();
if ( formController != null ) {
idx = getXPath(formController.getFormIndex());
instancePath = formController.getInstancePath().getAbsolutePath();
}
// Add a new scroll action to the buffer.
ContentValues cv = new ContentValues();
cv.put(DEVICEID, mDeviceId);
cv.put(CLASS, t.getClass().getName());
cv.put(CONTEXT, "scroll");
cv.put(ACTION, "");
cv.put(PARAM1, distance);
cv.put(QUESTION, idx);
cv.put(INSTANCE_PATH, instancePath);
cv.put(TIMESTAMP, timeStamp);
cv.put(PARAM2, timeStamp);
mScrollActions.add(cv);
}
}
private void insertContentValues(ContentValues cv, FormIndex index) {
synchronized(mScrollActions) {
try {
while ( !mScrollActions.isEmpty() ) {
ContentValues scv = mScrollActions.removeFirst();
mDb.insert(DATABASE_TABLE, null, scv);
}
if ( cv != null ) {
String idx = "";
if ( index != null ) {
idx = getXPath(index);
}
cv.put(QUESTION,idx);
mDb.insert(DATABASE_TABLE, null, cv);
}
} catch (SQLiteConstraintException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
// Convenience methods
public void logOnStart(Activity a) {
log( a.getClass().getName(), "onStart", null, null, null, null, null);
}
public void logOnStop(Activity a) {
log( a.getClass().getName(), "onStop", null, null, null, null, null);
}
public void logAction(Object t, String context, String action) {
log( t.getClass().getName(), context, action, null, null, null, null);
}
public void logActionParam(Object t, String context, String action, String param1) {
log( t.getClass().getName(), context, action, null, null, param1, null);
}
public void logInstanceAction(Object t, String context, String action) {
FormIndex index = null;
String instancePath = null;
FormController formController = Collect.getInstance().getFormController();
if ( formController != null ) {
index = formController.getFormIndex();
instancePath = formController.getInstancePath().getAbsolutePath();
}
log( t.getClass().getName(), context, action, instancePath, index, null, null);
}
public void logInstanceAction(Object t, String context, String action, FormIndex index) {
String instancePath = null;
FormController formController = Collect.getInstance().getFormController();
if ( formController != null ) {
index = formController.getFormIndex();
instancePath = formController.getInstancePath().getAbsolutePath();
}
log( t.getClass().getName(), context, action, instancePath, index, null, null);
}
}
| Java |
/*
* 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 org.odk.collect.android.database;
import java.io.File;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.util.Log;
/**
* We've taken this from Android's SQLiteOpenHelper. However, we can't appropriately lock the
* database so there may be issues if a thread opens the database read-only and another thread tries
* to open the database read/write. I don't think this will ever happen in ODK, though. (fingers
* crossed).
*/
/**
* A helper class to manage database creation and version management. You create a subclass
* implementing {@link #onCreate}, {@link #onUpgrade} and optionally {@link #onOpen}, and this class
* takes care of opening the database if it exists, creating it if it does not, and upgrading it as
* necessary. Transactions are used to make sure the database is always in a sensible state.
* <p>
* For an example, see the NotePadProvider class in the NotePad sample application, in the
* <em>samples/</em> directory of the SDK.
* </p>
*/
public abstract class ODKSQLiteOpenHelper {
private static final String t = ODKSQLiteOpenHelper.class.getSimpleName();
private final String mPath;
private final String mName;
private final CursorFactory mFactory;
private final int mNewVersion;
private SQLiteDatabase mDatabase = null;
private boolean mIsInitializing = false;
/**
* Create a helper object to create, open, and/or manage a database. The database is not
* actually created or opened until one of {@link #getWritableDatabase} or
* {@link #getReadableDatabase} is called.
*
* @param path to the file
* @param name of the database file, or null for an in-memory database
* @param factory to use for creating cursor objects, or null for the default
* @param version number of the database (starting at 1); if the database is older,
* {@link #onUpgrade} will be used to upgrade the database
*/
public ODKSQLiteOpenHelper(String path, String name, CursorFactory factory, int version) {
if (version < 1)
throw new IllegalArgumentException("Version must be >= 1, was " + version);
mPath = path;
mName = name;
mFactory = factory;
mNewVersion = version;
}
/**
* Create and/or open a database that will be used for reading and writing. Once opened
* successfully, the database is cached, so you can call this method every time you need to
* write to the database. Make sure to call {@link #close} when you no longer need it.
* <p>
* Errors such as bad permissions or a full disk may cause this operation to fail, but future
* attempts may succeed if the problem is fixed.
* </p>
*
* @throws SQLiteException if the database cannot be opened for writing
* @return a read/write database object valid until {@link #close} is called
*/
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
return mDatabase; // The database is already open for business
}
if (mIsInitializing) {
throw new IllegalStateException("getWritableDatabase called recursively");
}
// If we have a read-only database open, someone could be using it
// (though they shouldn't), which would cause a lock to be held on
// the file, and our attempts to open the database read-write would
// fail waiting for the file lock. To prevent that, we acquire the
// lock on the read-only database, which shuts out other users.
boolean success = false;
SQLiteDatabase db = null;
// if (mDatabase != null) mDatabase.lock();
try {
mIsInitializing = true;
if (mName == null) {
db = SQLiteDatabase.create(null);
} else {
db = SQLiteDatabase.openOrCreateDatabase(mPath + File.separator + mName, mFactory);
// db = mContext.openOrCreateDatabase(mName, 0, mFactory);
}
int version = db.getVersion();
if (version != mNewVersion) {
db.beginTransaction();
try {
if (version == 0) {
onCreate(db);
} else {
onUpgrade(db, version, mNewVersion);
}
db.setVersion(mNewVersion);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
onOpen(db);
success = true;
return db;
} finally {
mIsInitializing = false;
if (success) {
if (mDatabase != null) {
try {
mDatabase.close();
} catch (Exception e) {
}
// mDatabase.unlock();
}
mDatabase = db;
} else {
// if (mDatabase != null) mDatabase.unlock();
if (db != null)
db.close();
}
}
}
/**
* Create and/or open a database. This will be the same object returned by
* {@link #getWritableDatabase} unless some problem, such as a full disk, requires the database
* to be opened read-only. In that case, a read-only database object will be returned. If the
* problem is fixed, a future call to {@link #getWritableDatabase} may succeed, in which case
* the read-only database object will be closed and the read/write object will be returned in
* the future.
*
* @throws SQLiteException if the database cannot be opened
* @return a database object valid until {@link #getWritableDatabase} or {@link #close} is
* called.
*/
public synchronized SQLiteDatabase getReadableDatabase() {
if (mDatabase != null && mDatabase.isOpen()) {
return mDatabase; // The database is already open for business
}
if (mIsInitializing) {
throw new IllegalStateException("getReadableDatabase called recursively");
}
try {
return getWritableDatabase();
} catch (SQLiteException e) {
if (mName == null)
throw e; // Can't open a temp database read-only!
Log.e(t, "Couldn't open " + mName + " for writing (will try read-only):", e);
}
SQLiteDatabase db = null;
try {
mIsInitializing = true;
String path = mPath + File.separator + mName;
// mContext.getDatabasePath(mName).getPath();
db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
if (db.getVersion() != mNewVersion) {
throw new SQLiteException("Can't upgrade read-only database from version "
+ db.getVersion() + " to " + mNewVersion + ": " + path);
}
onOpen(db);
Log.w(t, "Opened " + mName + " in read-only mode");
mDatabase = db;
return mDatabase;
} finally {
mIsInitializing = false;
if (db != null && db != mDatabase)
db.close();
}
}
/**
* Close any open database object.
*/
public synchronized void close() {
if (mIsInitializing)
throw new IllegalStateException("Closed during initialization");
if (mDatabase != null && mDatabase.isOpen()) {
mDatabase.close();
mDatabase = null;
}
}
/**
* Called when the database is created for the first time. This is where the creation of tables
* and the initial population of the tables should happen.
*
* @param db The database.
*/
public abstract void onCreate(SQLiteDatabase db);
/**
* Called when the database needs to be upgraded. The implementation should use this method to
* drop tables, add tables, or do anything else it needs to upgrade to the new schema version.
* <p>
* The SQLite ALTER TABLE documentation can be found <a
* href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns you can use
* ALTER TABLE to insert them into a live table. If you rename or remove columns you can use
* ALTER TABLE to rename the old table, then create the new table and then populate the new
* table with the contents of the old table.
*
* @param db The database.
* @param oldVersion The old database version.
* @param newVersion The new database version.
*/
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
/**
* Called when the database has been opened. Override method should check
* {@link SQLiteDatabase#isReadOnly} before updating the database.
*
* @param db The database.
*/
public void onOpen(SQLiteDatabase db) {
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.widgets;
import java.io.File;
import java.util.ArrayList;
import java.util.Vector;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* ListMultiWidget handles multiple selection fields using check boxes. The check boxes are aligned
* horizontally. They are typically meant to be used in a field list, where multiple questions with
* the same multiple choice answers can sit on top of each other and make a grid of buttons that is
* easy to navigate quickly. Optionally, you can turn off the labels. This would be done if a label
* widget was at the top of your field list to provide the labels. If audio or video are specified
* in the select answers they are ignored. This class is almost identical to ListWidget, except it
* uses checkboxes. It also did not require a custom clickListener class.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class ListMultiWidget extends QuestionWidget {
private static final String t = "ListMultiWidget";
// Holds the entire question and answers. It is a horizontally aligned linear layout
// needed because it is created in the super() constructor via addQuestionText() call.
LinearLayout questionLayout;
private boolean mCheckboxInit = true;
private Vector<SelectChoice> mItems; // may take a while to compute...
private ArrayList<CheckBox> mCheckboxes;
@SuppressWarnings("unchecked")
public ListMultiWidget(Context context, FormEntryPrompt prompt, boolean displayLabel) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mCheckboxes = new ArrayList<CheckBox>();
mPrompt = prompt;
// Layout holds the horizontal list of buttons
LinearLayout buttonLayout = new LinearLayout(context);
Vector<Selection> ve = new Vector<Selection>();
if (prompt.getAnswerValue() != null) {
ve = (Vector<Selection>) prompt.getAnswerValue().getValue();
}
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
CheckBox c = new CheckBox(getContext());
c.setTag(Integer.valueOf(i));
c.setId(QuestionWidget.newUniqueId());
c.setFocusable(!prompt.isReadOnly());
c.setEnabled(!prompt.isReadOnly());
for (int vi = 0; vi < ve.size(); vi++) {
// match based on value, not key
if (mItems.get(i).getValue().equals(ve.elementAt(vi).getValue())) {
c.setChecked(true);
break;
}
}
mCheckboxes.add(c);
// when clicked, check for readonly before toggling
c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!mCheckboxInit && mPrompt.isReadOnly()) {
if (buttonView.isChecked()) {
buttonView.setChecked(false);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
} else {
buttonView.setChecked(true);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
}
}
}
});
String imageURI = null;
imageURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_IMAGE);
// build image view (if an image is provided)
ImageView mImageView = null;
TextView mMissingImage = null;
final int labelId = QuestionWidget.newUniqueId();
// Now set up the image view
String errorMsg = null;
if (imageURI != null) {
try {
String imageFilename =
ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Bitmap b = null;
try {
Display display =
((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
b =
FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight,
screenWidth);
} catch (OutOfMemoryError e) {
errorMsg = "ERROR: " + e.getMessage();
}
if (b != null) {
mImageView = new ImageView(getContext());
mImageView.setPadding(2, 2, 2, 2);
mImageView.setAdjustViewBounds(true);
mImageView.setImageBitmap(b);
mImageView.setId(labelId);
} else if (errorMsg == null) {
// An error hasn't been logged and loading the image failed, so it's
// likely
// a bad file.
errorMsg = getContext().getString(R.string.file_invalid, imageFile);
}
} else if (errorMsg == null) {
// An error hasn't been logged. We should have an image, but the file
// doesn't
// exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
if (errorMsg != null) {
// errorMsg is only set when an error has occured
Log.e(t, errorMsg);
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMsg);
mMissingImage.setPadding(2, 2, 2, 2);
mMissingImage.setId(labelId);
}
} catch (InvalidReferenceException e) {
Log.e(t, "image invalid reference exception");
e.printStackTrace();
}
} else {
// There's no imageURI listed, so just ignore it.
}
// build text label. Don't assign the text to the built in label to he
// button because it aligns horizontally, and we want the label on top
TextView label = new TextView(getContext());
label.setText(prompt.getSelectChoiceText(mItems.get(i)));
label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
label.setGravity(Gravity.CENTER_HORIZONTAL);
if (!displayLabel) {
label.setVisibility(View.GONE);
}
// answer layout holds the label text/image on top and the radio button on bottom
RelativeLayout answer = new RelativeLayout(getContext());
RelativeLayout.LayoutParams headerParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
headerParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
headerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
RelativeLayout.LayoutParams buttonParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
if (mImageView != null) {
mImageView.setScaleType(ScaleType.CENTER);
if (!displayLabel) {
mImageView.setVisibility(View.GONE);
}
answer.addView(mImageView, headerParams);
} else if (mMissingImage != null) {
answer.addView(mMissingImage, headerParams);
} else {
if (displayLabel) {
label.setId(labelId);
answer.addView(label, headerParams);
}
}
if (displayLabel) {
buttonParams.addRule(RelativeLayout.BELOW, labelId);
}
answer.addView(c, buttonParams);
answer.setPadding(4, 0, 4, 0);
// /Each button gets equal weight
LinearLayout.LayoutParams answerParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
answerParams.weight = 1;
buttonLayout.addView(answer, answerParams);
}
}
// Align the buttons so that they appear horizonally and are right justified
// buttonLayout.setGravity(Gravity.RIGHT);
buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
// LinearLayout.LayoutParams params = new
// LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// buttonLayout.setLayoutParams(params);
// The buttons take up the right half of the screen
LinearLayout.LayoutParams buttonParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
buttonParams.weight = 1;
questionLayout.addView(buttonLayout, buttonParams);
addView(questionLayout);
}
@Override
public void clearAnswer() {
for (int i = 0; i < mCheckboxes.size(); i++) {
CheckBox c = mCheckboxes.get(i);
if (c.isChecked()) {
c.setChecked(false);
}
}
}
@Override
public IAnswerData getAnswer() {
Vector<Selection> vc = new Vector<Selection>();
for (int i = 0; i < mCheckboxes.size(); i++) {
CheckBox c = mCheckboxes.get(i);
if (c.isChecked()) {
vc.add(new Selection(mItems.get(i)));
}
}
if (vc.size() == 0) {
return null;
} else {
return new SelectMultiData(vc);
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
// Override QuestionWidget's add question text. Build it the same
// but add it to the questionLayout
protected void addQuestionText(FormEntryPrompt p) {
// Add the text view. Textview always exists, regardless of whether there's text.
TextView questionText = new TextView(getContext());
questionText.setText(p.getLongText());
questionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
questionText.setTypeface(null, Typeface.BOLD);
questionText.setPadding(0, 0, 0, 7);
questionText.setId(QuestionWidget.newUniqueId()); // assign random id
// Wrap to the size of the parent view
questionText.setHorizontallyScrolling(false);
if (p.getLongText() == null) {
questionText.setVisibility(GONE);
}
// Put the question text on the left half of the screen
LinearLayout.LayoutParams labelParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
labelParams.weight = 1;
questionLayout = new LinearLayout(getContext());
questionLayout.setOrientation(LinearLayout.HORIZONTAL);
questionLayout.addView(questionText, labelParams);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (CheckBox c : mCheckboxes) {
c.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (CheckBox c : mCheckboxes) {
c.cancelLongPress();
}
}
}
| Java |
/*
* Copyright (C) 2012 University of Washington
*
* 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.odk.collect.android.widgets;
import java.io.File;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.DrawActivity;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Signature widget.
*
* @author BehrAtherton@gmail.com
*
*/
public class SignatureWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "SignatureWidget";
private Button mSignButton;
private String mBinaryName;
private String mInstanceFolder;
private ImageView mImageView;
private TextView mErrorTextView;
public SignatureWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mInstanceFolder =
Collect.getInstance().getFormController().getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
mErrorTextView = new TextView(context);
mErrorTextView.setId(QuestionWidget.newUniqueId());
mErrorTextView.setText("Selected file is not a valid image");
// setup Blank Image Button
mSignButton = new Button(getContext());
mSignButton.setId(QuestionWidget.newUniqueId());
mSignButton.setText(getContext().getString(R.string.sign_button));
mSignButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mSignButton.setPadding(20, 20, 20, 20);
mSignButton.setEnabled(!prompt.isReadOnly());
mSignButton.setLayoutParams(params);
// launch capture intent on click
mSignButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "signButton", "click",
mPrompt.getIndex());
launchSignatureActivity();
}
});
// finish complex layout
addView(mSignButton);
addView(mErrorTextView);
// and hide the sign button if read-only
if ( prompt.isReadOnly() ) {
mSignButton.setVisibility(View.GONE);
}
mErrorTextView.setVisibility(View.GONE);
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
// Only add the imageView if the user has signed
if (mBinaryName != null) {
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "viewImage",
"click", mPrompt.getIndex());
launchSignatureActivity();
}
});
addView(mImageView);
}
}
private void launchSignatureActivity() {
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(getContext(), DrawActivity.class);
i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_SIGNATURE);
// copy...
if ( mBinaryName != null ) {
File f = new File(mInstanceFolder + File.separator + mBinaryName);
i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f));
}
i.putExtra(DrawActivity.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i, FormEntryActivity.SIGNATURE_CAPTURE);
}
catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "signature capture"),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder + File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
// reset buttons
mSignButton.setText(getContext().getString(R.string.sign_button));
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
@Override
public void setBinaryData(Object answer) {
// you are replacing an answer. delete the previous image using the
// content provider.
if (mBinaryName != null) {
deleteMedia();
}
File newImage = (File) answer;
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
Uri imageURI = getContext().getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
mBinaryName = newImage.getName();
Log.i(t, "Setting current answer to " + newImage.getName());
} else {
Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
}
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mSignButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mSignButton.cancelLongPress();
if (mImageView != null) {
mImageView.cancelLongPress();
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.application.Collect;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.TextKeyListener;
import android.text.method.TextKeyListener.Capitalize;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TableLayout;
/**
* The most basic widget that allows for entry of any text.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class StringWidget extends QuestionWidget {
private static final String ROWS = "rows";
boolean mReadOnly = false;
protected EditText mAnswer;
public StringWidget(Context context, FormEntryPrompt prompt) {
this(context, prompt, true);
setupChangeListener();
}
protected StringWidget(Context context, FormEntryPrompt prompt, boolean derived) {
super(context, prompt);
mAnswer = new EditText(context);
mAnswer.setId(QuestionWidget.newUniqueId());
mReadOnly = prompt.isReadOnly();
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
/**
* If a 'rows' attribute is on the input tag, set the minimum number of lines
* to display in the field to that value.
*
* I.e.,
* <input ref="foo" rows="5">
* ...
* </input>
*
* will set the height of the EditText box to 5 rows high.
*/
String height = prompt.getQuestion().getAdditionalAttribute(null, ROWS);
if ( height != null && height.length() != 0 ) {
try {
int rows = Integer.valueOf(height);
mAnswer.setMinLines(rows);
mAnswer.setGravity(Gravity.TOP); // to write test starting at the top of the edit area
} catch (Exception e) {
Log.e(this.getClass().getName(), "Unable to process the rows setting for the answer field: " + e.toString());
}
}
params.setMargins(7, 5, 7, 5);
mAnswer.setLayoutParams(params);
// capitalize the first letter of the sentence
mAnswer.setKeyListener(new TextKeyListener(Capitalize.SENTENCES, false));
// needed to make long read only text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
String s = prompt.getAnswerText();
if (s != null) {
mAnswer.setText(s);
}
if (mReadOnly) {
mAnswer.setBackgroundDrawable(null);
mAnswer.setFocusable(false);
mAnswer.setClickable(false);
}
addView(mAnswer);
}
protected void setupChangeListener() {
mAnswer.addTextChangedListener(new TextWatcher() {
private String oldText = "";
@Override
public void afterTextChanged(Editable s) {
if (!s.toString().equals(oldText)) {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "answerTextChanged", s.toString(), getPrompt().getIndex());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
oldText = s.toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) { }
});
}
@Override
public void clearAnswer() {
mAnswer.setText(null);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
@Override
public void setFocus(Context context) {
// Put focus on text input field and display soft keyboard if appropriate.
mAnswer.requestFocus();
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (!mReadOnly) {
inputManager.showSoftInput(mAnswer, 0);
/*
* If you do a multi-question screen after a "add another group" dialog, this won't
* automatically pop up. It's an Android issue.
*
* That is, if I have an edit text in an activity, and pop a dialog, and in that
* dialog's button's OnClick() I call edittext.requestFocus() and
* showSoftInput(edittext, 0), showSoftinput() returns false. However, if the edittext
* is focused before the dialog pops up, everything works fine. great.
*/
} else {
inputManager.hideSoftInputFromWindow(mAnswer.getWindowToken(), 0);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isAltPressed() == true) {
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAnswer.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mAnswer.cancelLongPress();
}
}
| Java |
/*
* Copyright (C) 2012 University of Washington
*
* 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.odk.collect.android.widgets;
import java.io.File;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.DrawActivity;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Free drawing widget.
*
* @author BehrAtherton@gmail.com
*
*/
public class DrawWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "DrawWidget";
private Button mDrawButton;
private String mBinaryName;
private String mInstanceFolder;
private ImageView mImageView;
private TextView mErrorTextView;
public DrawWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mErrorTextView = new TextView(context);
mErrorTextView.setId(QuestionWidget.newUniqueId());
mErrorTextView.setText("Selected file is not a valid image");
mInstanceFolder = Collect.getInstance().getFormController()
.getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
// setup Blank Image Button
mDrawButton = new Button(getContext());
mDrawButton.setId(QuestionWidget.newUniqueId());
mDrawButton.setText(getContext().getString(R.string.draw_image));
mDrawButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mDrawButton.setPadding(20, 20, 20, 20);
mDrawButton.setEnabled(!prompt.isReadOnly());
mDrawButton.setLayoutParams(params);
// launch capture intent on click
mDrawButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "drawButton", "click",
mPrompt.getIndex());
launchDrawActivity();
}
});
// finish complex layout
addView(mDrawButton);
addView(mErrorTextView);
if (mPrompt.isReadOnly()) {
mDrawButton.setVisibility(View.GONE);
}
mErrorTextView.setVisibility(View.GONE);
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
// Only add the imageView if the user has signed
if (mBinaryName != null) {
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f,
screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "viewImage", "click",
mPrompt.getIndex());
launchDrawActivity();
}
});
addView(mImageView);
}
}
private void launchDrawActivity() {
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(getContext(), DrawActivity.class);
i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_DRAW);
// copy...
if (mBinaryName != null) {
File f = new File(mInstanceFolder + File.separator + mBinaryName);
i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f));
}
i.putExtra(DrawActivity.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.DRAW_IMAGE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"draw image"), Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder
+ File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
// reset buttons
mDrawButton.setText(getContext().getString(R.string.draw_image));
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
@Override
public void setBinaryData(Object answer) {
// you are replacing an answer. delete the previous image using the
// content provider.
if (mBinaryName != null) {
deleteMedia();
}
File newImage = (File) answer;
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
Uri imageURI = getContext().getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
mBinaryName = newImage.getName();
Log.i(t, "Setting current answer to " + newImage.getName());
} else {
Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
}
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(
Collect.getInstance().getFormController()
.getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mDrawButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mDrawButton.cancelLongPress();
if (mImageView != null) {
mImageView.cancelLongPress();
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
import java.util.Locale;
import org.javarosa.core.model.Constants;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.util.Log;
/**
* Convenience class that handles creation of widgets.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class WidgetFactory {
/**
* Returns the appropriate QuestionWidget for the given FormEntryPrompt.
*
* @param fep prompt element to be rendered
* @param context Android context
*/
static public QuestionWidget createWidgetFromPrompt(FormEntryPrompt fep, Context context) {
// get appearance hint and clean it up so it is lower case and never null...
String appearance = fep.getAppearanceHint();
if ( appearance == null ) appearance = "";
// for now, all appearance tags are in english...
appearance = appearance.toLowerCase(Locale.ENGLISH);
QuestionWidget questionWidget = null;
switch (fep.getControlType()) {
case Constants.CONTROL_INPUT:
switch (fep.getDataType()) {
case Constants.DATATYPE_DATE_TIME:
questionWidget = new DateTimeWidget(context, fep);
break;
case Constants.DATATYPE_DATE:
questionWidget = new DateWidget(context, fep);
break;
case Constants.DATATYPE_TIME:
questionWidget = new TimeWidget(context, fep);
break;
case Constants.DATATYPE_DECIMAL:
if ( appearance.startsWith("ex:") ) {
questionWidget = new ExDecimalWidget(context, fep);
} else {
questionWidget = new DecimalWidget(context, fep);
}
break;
case Constants.DATATYPE_INTEGER:
if ( appearance.startsWith("ex:") ) {
questionWidget = new ExIntegerWidget(context, fep);
} else {
questionWidget = new IntegerWidget(context, fep);
}
break;
case Constants.DATATYPE_GEOPOINT:
questionWidget = new GeoPointWidget(context, fep);
break;
case Constants.DATATYPE_BARCODE:
questionWidget = new BarcodeWidget(context, fep);
break;
case Constants.DATATYPE_TEXT:
if (appearance.startsWith("printer")) {
questionWidget = new ExPrinterWidget(context, fep);
} else if (appearance.startsWith("ex:")) {
questionWidget = new ExStringWidget(context, fep);
} else if (appearance.equals("numbers")) {
questionWidget = new StringNumberWidget(context, fep);
} else {
questionWidget = new StringWidget(context, fep);
}
break;
default:
questionWidget = new StringWidget(context, fep);
break;
}
break;
case Constants.CONTROL_IMAGE_CHOOSE:
if (appearance.equals("web")) {
questionWidget = new ImageWebViewWidget(context, fep);
} else if(appearance.equals("signature")) {
questionWidget = new SignatureWidget(context, fep);
} else if(appearance.equals("annotate")) {
questionWidget = new AnnotateWidget(context, fep);
} else if(appearance.equals("draw")) {
questionWidget = new DrawWidget(context, fep);
} else if(appearance.startsWith("align:")) {
questionWidget = new AlignedImageWidget(context, fep);
} else {
questionWidget = new ImageWidget(context, fep);
}
break;
case Constants.CONTROL_AUDIO_CAPTURE:
questionWidget = new AudioWidget(context, fep);
break;
case Constants.CONTROL_VIDEO_CAPTURE:
questionWidget = new VideoWidget(context, fep);
break;
case Constants.CONTROL_SELECT_ONE:
if (appearance.contains("compact")) {
int numColumns = -1;
try {
int idx = appearance.indexOf("-");
if ( idx != -1 ) {
numColumns =
Integer.parseInt(appearance.substring(idx + 1));
}
} catch (Exception e) {
// Do nothing, leave numColumns as -1
Log.e("WidgetFactory", "Exception parsing numColumns");
}
if (appearance.contains("quick")) {
questionWidget = new GridWidget(context, fep, numColumns, true);
} else {
questionWidget = new GridWidget(context, fep, numColumns, false);
}
} else if (appearance.equals("minimal")) {
questionWidget = new SpinnerWidget(context, fep);
}
// else if (appearance != null && appearance.contains("autocomplete")) {
// String filterType = null;
// try {
// filterType = appearance.substring(appearance.indexOf('-') + 1);
// } catch (Exception e) {
// // Do nothing, leave filerType null
// Log.e("WidgetFactory", "Exception parsing filterType");
// }
// questionWidget = new AutoCompleteWidget(context, fep, filterType);
//
// }
else if (appearance.equals("quick")) {
questionWidget = new SelectOneAutoAdvanceWidget(context, fep);
} else if (appearance.equals("list")) {
questionWidget = new ListWidget(context, fep, true);
} else if (appearance.equals("list-nolabel")) {
questionWidget = new ListWidget(context, fep, false);
} else if (appearance.equals("label")) {
questionWidget = new LabelWidget(context, fep);
} else {
questionWidget = new SelectOneWidget(context, fep);
}
break;
case Constants.CONTROL_SELECT_MULTI:
if (appearance.contains("compact")) {
int numColumns = -1;
try {
int idx = appearance.indexOf("-");
if ( idx != -1 ) {
numColumns =
Integer.parseInt(appearance.substring(idx + 1));
}
} catch (Exception e) {
// Do nothing, leave numColumns as -1
Log.e("WidgetFactory", "Exception parsing numColumns");
}
questionWidget = new GridMultiWidget(context, fep, numColumns);
} else if (appearance.equals("minimal")) {
questionWidget = new SpinnerMultiWidget(context, fep);
} else if (appearance.equals("list")) {
questionWidget = new ListMultiWidget(context, fep, true);
} else if (appearance.equals("list-nolabel")) {
questionWidget = new ListMultiWidget(context, fep, false);
} else if (appearance.equals("label")) {
questionWidget = new LabelWidget(context, fep);
} else {
questionWidget = new SelectMultiWidget(context, fep);
}
break;
case Constants.CONTROL_TRIGGER:
questionWidget = new TriggerWidget(context, fep);
break;
default:
questionWidget = new StringWidget(context, fep);
break;
}
return questionWidget;
}
}
| Java |
/*
* Copyright (C) 2013 University of Washington
*
* 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.odk.collect.android.widgets;
import java.io.File;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Widget that allows user to invoke the aligned-image camera to take pictures and add them to the form.
* Modified to launch the Aligned-image camera app.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
* @author mitchellsundt@gmail.com
*/
public class AlignedImageWidget extends QuestionWidget implements IBinaryWidget {
private static final String ODK_CAMERA_TAKE_PICTURE_INTENT_COMPONENT = "org.opendatakit.camera.TakePicture";
private static final String ODK_CAMERA_INTENT_PACKAGE = "org.opendatakit.camera";
private static final String RETAKE_OPTION_EXTRA = "retakeOption";
private static final String DIMENSIONS_EXTRA = "dimensions";
private static final String FILE_PATH_EXTRA = "filePath";
private final static String t = "AlignedImageWidget";
private Button mCaptureButton;
private Button mChooseButton;
private ImageView mImageView;
private String mBinaryName;
private String mInstanceFolder;
private TextView mErrorTextView;
private int iArray[] = new int[6];
public AlignedImageWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
String appearance = prompt.getAppearanceHint();
String alignments = appearance.substring(appearance.indexOf(":") + 1);
String[] splits = alignments.split(" ");
if ( splits.length != 6 ) {
Log.w(t, "Only have " + splits.length + " alignment values");
}
for ( int i = 0 ; i < 6 ; ++i ) {
if ( splits.length < i ) {
iArray[i] = 0;
} else {
iArray[i] = Integer.valueOf(splits[i]);
}
}
mInstanceFolder =
Collect.getInstance().getFormController().getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
mErrorTextView = new TextView(context);
mErrorTextView.setId(QuestionWidget.newUniqueId());
mErrorTextView.setText("Selected file is not a valid image");
// setup capture button
mCaptureButton = new Button(getContext());
mCaptureButton.setId(QuestionWidget.newUniqueId());
mCaptureButton.setText(getContext().getString(R.string.capture_image));
mCaptureButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mCaptureButton.setPadding(20, 20, 20, 20);
mCaptureButton.setEnabled(!prompt.isReadOnly());
mCaptureButton.setLayoutParams(params);
// launch capture intent on click
mCaptureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "captureButton",
"click", mPrompt.getIndex());
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent();
i.setComponent(new ComponentName(ODK_CAMERA_INTENT_PACKAGE,
ODK_CAMERA_TAKE_PICTURE_INTENT_COMPONENT));
i.putExtra(FILE_PATH_EXTRA, Collect.CACHE_PATH);
i.putExtra(DIMENSIONS_EXTRA, iArray);
i.putExtra(RETAKE_OPTION_EXTRA, false);
// We give the camera an absolute filename/path where to put the
// picture because of bug:
// http://code.google.com/p/android/issues/detail?id=1480
// The bug appears to be fixed in Android 2.0+, but as of feb 2,
// 2010, G1 phones only run 1.6. Without specifying the path the
// images returned by the camera in 1.6 (and earlier) are ~1/4
// the size. boo.
// if this gets modified, the onActivityResult in
// FormEntyActivity will also need to be updated.
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.ALIGNED_IMAGE);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "aligned image capture"),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
});
// setup chooser button
mChooseButton = new Button(getContext());
mChooseButton.setId(QuestionWidget.newUniqueId());
mChooseButton.setText(getContext().getString(R.string.choose_image));
mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mChooseButton.setPadding(20, 20, 20, 20);
mChooseButton.setEnabled(!prompt.isReadOnly());
mChooseButton.setLayoutParams(params);
// launch capture intent on click
mChooseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "chooseButton",
"click", mPrompt.getIndex());
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("image/*");
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.IMAGE_CHOOSER);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "choose image"),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
}
});
// finish complex layout
addView(mCaptureButton);
addView(mChooseButton);
addView(mErrorTextView);
// and hide the capture and choose button if read-only
if ( prompt.isReadOnly() ) {
mCaptureButton.setVisibility(View.GONE);
mChooseButton.setVisibility(View.GONE);
}
mErrorTextView.setVisibility(View.GONE);
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
// Only add the imageView if the user has taken a picture
if (mBinaryName != null) {
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f, screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance().getActivityLogger().logInstanceAction(this, "viewButton",
"click", mPrompt.getIndex());
Intent i = new Intent("android.intent.action.VIEW");
Uri uri = MediaUtils.getImageUriFromMediaProvider(mInstanceFolder + File.separator + mBinaryName);
if ( uri != null ) {
Log.i(t,"setting view path to: " + uri);
i.setDataAndType(uri, "image/*");
try {
getContext().startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(getContext(),
getContext().getString(R.string.activity_not_found, "view image"),
Toast.LENGTH_SHORT).show();
}
}
}
});
addView(mImageView);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder + File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
// reset buttons
mCaptureButton.setText(getContext().getString(R.string.capture_image));
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
@Override
public void setBinaryData(Object newImageObj) {
// you are replacing an answer. delete the previous image using the
// content provider.
if (mBinaryName != null) {
deleteMedia();
}
File newImage = (File) newImageObj;
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
Uri imageURI = getContext().getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
mBinaryName = newImage.getName();
Log.i(t, "Setting current answer to " + newImage.getName());
} else {
Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
}
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mCaptureButton.setOnLongClickListener(l);
mChooseButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mCaptureButton.cancelLongPress();
mChooseButton.cancelLongPress();
if (mImageView != null) {
mImageView.cancelLongPress();
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
/**
* Interface implemented by widgets that need binary data.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public interface IBinaryWidget {
public void setBinaryData(Object answer);
public void cancelWaitingForBinaryData();
public boolean isWaitingForBinaryData();
}
/*TODO carlhartung: we might want to move this into the QuestionWidget abstract class?
*
*/
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.widgets;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import java.util.Vector;
/**
* SpinnerMultiWidget, like SelectMultiWidget handles multiple selection fields using checkboxes,
* but the user clicks a button to see the checkboxes. The goal is to be more compact. If images,
* audio, or video are specified in the select answers they are ignored. WARNING: There is a bug in
* android versions previous to 2.0 that affects this widget. You can find the report here:
* http://code.google.com/p/android/issues/detail?id=922 This bug causes text to be white in alert
* boxes, which makes the select options invisible in this widget. For this reason, this widget
* should not be used on phones with android versions lower than 2.0.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class SpinnerMultiWidget extends QuestionWidget {
Vector<SelectChoice> mItems;
// The possible select answers
CharSequence[] answer_items;
// The button to push to display the answers to choose from
Button button;
// Defines which answers are selected
boolean[] selections;
// The alert box that contains the answer selection view
AlertDialog.Builder alert_builder;
// Displays the current selections below the button
TextView selectionText;
@SuppressWarnings("unchecked")
public SpinnerMultiWidget(final Context context, FormEntryPrompt prompt) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mPrompt = prompt;
selections = new boolean[mItems.size()];
answer_items = new CharSequence[mItems.size()];
alert_builder = new AlertDialog.Builder(context);
button = new Button(context);
selectionText = new TextView(getContext());
// Build View
for (int i = 0; i < mItems.size(); i++) {
answer_items[i] = prompt.getSelectChoiceText(mItems.get(i));
}
selectionText.setText(context.getString(R.string.selected));
selectionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
selectionText.setVisibility(View.GONE);
button.setText(context.getString(R.string.select_answer));
button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
button.setPadding(0, 0, 0, 7);
// Give the button a click listener. This defines the alert as well. All the
// click and selection behavior is defined here.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
alert_builder.setTitle(mPrompt.getQuestionText()).setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
boolean first = true;
selectionText.setText("");
for (int i = 0; i < selections.length; i++) {
if (selections[i]) {
if (first) {
first = false;
selectionText.setText(context.getString(R.string.selected)
+ answer_items[i].toString());
selectionText.setVisibility(View.VISIBLE);
} else {
selectionText.setText(selectionText.getText() + ", "
+ answer_items[i].toString());
}
}
}
}
});
alert_builder.setMultiChoiceItems(answer_items, selections,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
selections[which] = isChecked;
}
});
AlertDialog alert = alert_builder.create();
alert.show();
}
});
// Fill in previous answers
Vector<Selection> ve = new Vector<Selection>();
if (prompt.getAnswerValue() != null) {
ve = (Vector<Selection>) prompt.getAnswerValue().getValue();
}
if (ve != null) {
boolean first = true;
for (int i = 0; i < selections.length; ++i) {
String value = mItems.get(i).getValue();
boolean found = false;
for (Selection s : ve) {
if (value.equals(s.getValue())) {
found = true;
break;
}
}
selections[i] = found;
if (found) {
if (first) {
first = false;
selectionText.setText(context.getString(R.string.selected)
+ answer_items[i].toString());
selectionText.setVisibility(View.VISIBLE);
} else {
selectionText.setText(selectionText.getText() + ", "
+ answer_items[i].toString());
}
}
}
}
addView(button);
addView(selectionText);
}
@Override
public IAnswerData getAnswer() {
clearFocus();
Vector<Selection> vc = new Vector<Selection>();
for (int i = 0; i < mItems.size(); i++) {
if (selections[i]) {
SelectChoice sc = mItems.get(i);
vc.add(new Selection(sc));
}
}
if (vc.size() == 0) {
return null;
} else {
return new SelectMultiData(vc);
}
}
@Override
public void clearAnswer() {
selectionText.setText(R.string.selected);
selectionText.setVisibility(View.GONE);
for (int i = 0; i < selections.length; i++) {
selections[i] = false;
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
button.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
button.cancelLongPress();
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import android.content.Context;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.util.TypedValue;
/**
* Widget that restricts values to integers.
*
* @author Carl Hartung (carlhartung@gmail.com)
*/
public class StringNumberWidget extends StringWidget {
public StringNumberWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt, true);
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswer.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED);
// needed to make long readonly text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
mAnswer.setKeyListener(new DigitsKeyListener() {
@Override
protected char[] getAcceptedChars() {
char[] accepted = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '-', '+', ' ', ','
};
return accepted;
}
});
if (prompt.isReadOnly()) {
setBackgroundDrawable(null);
setFocusable(false);
setClickable(false);
}
String s = null;
if (prompt.getAnswerValue() != null)
s = (String) prompt.getAnswerValue().getValue();
if (s != null) {
mAnswer.setText(s);
}
setupChangeListener();
}
@Override
public IAnswerData getAnswer() {
clearFocus();
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
return new StringData(s);
} catch (Exception NumberFormatException) {
return null;
}
}
}
}
| Java |
/*
* Copyright (C) 2012 University of Washington
*
* 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.odk.collect.android.widgets;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.method.TextKeyListener;
import android.text.method.TextKeyListener.Capitalize;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.Toast;
/**
* <p>Launch an external app to supply a string value. If the app
* does not launch, enable the text area for regular data entry.</p>
*
* <p>The default button text is "Launch"
*
* <p>You may override the button text and the error text that is
* displayed when the app is missing by using jr:itext() values.
*
* <p>To use this widget, define an appearance on the <input/>
* tag that begins "ex:" and then contains the intent action to lauch.
*
* <p>e.g.,
*
* <pre>
* <input appearance="ex:change.uw.android.TEXTANSWER" ref="/form/passPhrase" >
* </pre>
* <p>or, to customize the button text and error strings with itext:
* <pre>
* ...
* <bind nodeset="/form/passPhrase" type="string" />
* ...
* <itext>
* <translation lang="English">
* <text id="textAnswer">
* <value form="short">Text question</value>
* <value form="long">Enter your pass phrase</value>
* <value form="buttonText">Get Pass Phrase</value>
* <value form="noAppErrorString">Pass Phrase Tool is not installed!
* Please proceed to manually enter pass phrase.</value>
* </text>
* </translation>
* </itext>
* ...
* <input appearance="ex:change.uw.android.TEXTANSWER" ref="/form/passPhrase">
* <label ref="jr:itext('textAnswer')"/>
* </input>
* </pre>
*
* @author mitchellsundt@gmail.com
*
*/
public class ExStringWidget extends QuestionWidget implements IBinaryWidget {
private boolean mHasExApp = true;
private Button mLaunchIntentButton;
private Drawable mTextBackground;
protected EditText mAnswer;
public ExStringWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
// set text formatting
mAnswer = new EditText(context);
mAnswer.setId(QuestionWidget.newUniqueId());
mAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswer.setLayoutParams(params);
mTextBackground = mAnswer.getBackground();
mAnswer.setBackgroundDrawable(null);
// capitalize nothing
mAnswer.setKeyListener(new TextKeyListener(Capitalize.NONE, false));
// needed to make long read only text scroll
mAnswer.setHorizontallyScrolling(false);
mAnswer.setSingleLine(false);
String s = prompt.getAnswerText();
if (s != null) {
mAnswer.setText(s);
}
if (mPrompt.isReadOnly()) {
mAnswer.setBackgroundDrawable(null);
}
if (mPrompt.isReadOnly() || mHasExApp) {
mAnswer.setFocusable(false);
mAnswer.setClickable(false);
}
String appearance = prompt.getAppearanceHint();
String[] attrs = appearance.split(":");
final String intentName = attrs[1];
final String buttonText;
final String errorString;
String v = mPrompt.getSpecialFormQuestionText("buttonText");
buttonText = (v != null) ? v : context.getString(R.string.launch_app);
v = mPrompt.getSpecialFormQuestionText("noAppErrorString");
errorString = (v != null) ? v : context.getString(R.string.no_app);
// set button formatting
mLaunchIntentButton = new Button(getContext());
mLaunchIntentButton.setId(QuestionWidget.newUniqueId());
mLaunchIntentButton.setText(buttonText);
mLaunchIntentButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mLaunchIntentButton.setPadding(20, 20, 20, 20);
mLaunchIntentButton.setEnabled(!mPrompt.isReadOnly());
mLaunchIntentButton.setLayoutParams(params);
mLaunchIntentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(intentName);
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
fireActivity(i);
} catch (ActivityNotFoundException e) {
mHasExApp = false;
if ( !mPrompt.isReadOnly() ) {
mAnswer.setBackgroundDrawable(mTextBackground);
mAnswer.setFocusable(true);
mAnswer.setFocusableInTouchMode(true);
mAnswer.setClickable(true);
}
mLaunchIntentButton.setEnabled(false);
mLaunchIntentButton.setFocusable(false);
Collect.getInstance().getFormController().setIndexWaitingForData(null);
Toast.makeText(getContext(),
errorString, Toast.LENGTH_SHORT)
.show();
ExStringWidget.this.mAnswer.requestFocus();
}
}
});
// finish complex layout
addView(mLaunchIntentButton);
addView(mAnswer);
}
protected void fireActivity(Intent i) throws ActivityNotFoundException {
i.putExtra("value", mPrompt.getAnswerText());
Collect.getInstance().getActivityLogger().logInstanceAction(this, "launchIntent",
i.getAction(), mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.EX_STRING_CAPTURE);
}
@Override
public void clearAnswer() {
mAnswer.setText(null);
}
@Override
public IAnswerData getAnswer() {
String s = mAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
mAnswer.setText((String) answer);
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Put focus on text input field and display soft keyboard if appropriate.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if ( mHasExApp ) {
// hide keyboard
inputManager.hideSoftInputFromWindow(mAnswer.getWindowToken(), 0);
// focus on launch button
mLaunchIntentButton.requestFocus();
} else {
if (!mPrompt.isReadOnly()) {
mAnswer.requestFocus();
inputManager.showSoftInput(mAnswer, 0);
/*
* If you do a multi-question screen after a "add another group" dialog, this won't
* automatically pop up. It's an Android issue.
*
* That is, if I have an edit text in an activity, and pop a dialog, and in that
* dialog's button's OnClick() I call edittext.requestFocus() and
* showSoftInput(edittext, 0), showSoftinput() returns false. However, if the edittext
* is focused before the dialog pops up, everything works fine. great.
*/
} else {
inputManager.hideSoftInputFromWindow(mAnswer.getWindowToken(), 0);
}
}
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isAltPressed() == true) {
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAnswer.setOnLongClickListener(l);
mLaunchIntentButton.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mAnswer.cancelLongPress();
mLaunchIntentButton.cancelLongPress();
}
}
| Java |
/*
* Copyright (C) 2012 University of Washington
*
* 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.odk.collect.android.widgets;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.Toast;
/**
* <p>Use the ODK Sensors framework to print data to a connected printer.</p>
*
* <p>The default button text is "Print Label"
*
* <p>You may override the button text and the error text that is
* displayed when the app is missing by using jr:itext() values. The
* special itext form values are 'buttonText' and 'noPrinterErrorString',
* respectively.</p>
*
* <p>To use via XLSForm, specify a 'note' type with a 'calculation' that defines
* the data to be printed and with an 'appearance' as described below.
*
* <p>Within the XForms XML, to use this widget, define an appearance on the
* <input/> tag that begins "printer:" and then contains the intent
* action to launch. That intent starts the printer app. The data to print
* is sent via a broadcast intent to intentname.data The printer then pops
* a UI to initiate the actual printing (or change the destination printer).
* </p>
*
* <p>Implementation-wise, this widget is an ExStringWidget that is read-only.</p>
*
* <p>The ODK Sensors Zebra printer uses this appearance (intent):</p>
* <pre>
* "printer:org.opendatakit.sensors.ZebraPrinter"
* </pre>
*
* <p>The data that is printed should be defined in the calculate attribute
* of the bind. The structure of that string is a <br> separated list
* of values consisting of:</p>
* <ul><li>numeric barcode to emit (optional)</li>
* <li>string qrcode to emit (optional)</li>
* <li>text line 1 (optional)</li>
* <li>additional text line (repeat as needed)</li></ul>
*
* <p>E.g., if you wanted to emit a barcode of 123, a qrcode of "mycode" and
* two text lines of "line 1" and "line 2", you would define the calculate
* as:</p>
*
* <pre>
* <bind nodeset="/printerForm/printme" type="string" readonly="true()"
* calculate="concat('123','<br>','mycode','<br>','line 1','<br>','line 2')" />
* </pre>
*
* <p>Depending upon what you supply, the printer may print just a
* barcode, just a qrcode, just text, or some combination of all 3.</p>
*
* <p>Despite using <br> as a separator, the supplied Zebra
* printer does not recognize html.</p>
*
* <pre>
* <input appearance="ex:change.uw.android.TEXTANSWER" ref="/printerForm/printme" >
* </pre>
* <p>or, to customize the button text and error strings with itext:
* <pre>
* ...
* <bind nodeset="/printerForm/printme" type="string" readonly="true()" calculate="concat('<br>',
* /printerForm/some_text ,'<br>Text: ', /printerForm/shortened_text ,'<br>Integer: ',
* /printerForm/a_integer ,'<br>Decimal: ', /printerForm/a_decimal )"/>
* ...
* <itext>
* <translation lang="English">
* <text id="printAnswer">
* <value form="short">Print your label</value>
* <value form="long">Print your label</value>
* <value form="buttonText">Print now</value>
* <value form="noPrinterErrorString">ODK Sensors Zebra Printer is not installed!
* Please install ODK Sensors Framework and ODK Sensors Zebra Printer from Google Play.</value>
* </text>
* </translation>
* </itext>
* ...
* <input appearance="printer:org.opendatakit.sensors.ZebraPrinter" ref="/form/printme">
* <label ref="jr:itext('printAnswer')"/>
* </input>
* </pre>
*
* @author mitchellsundt@gmail.com
*
*/
public class ExPrinterWidget extends QuestionWidget implements IBinaryWidget {
private Button mLaunchIntentButton;
public ExPrinterWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
String appearance = prompt.getAppearanceHint();
String[] attrs = appearance.split(":");
final String intentName = (attrs.length < 2 || attrs[1].length() == 0) ? "org.opendatakit.sensors.ZebraPrinter" : attrs[1];
final String buttonText;
final String errorString;
String v = mPrompt.getSpecialFormQuestionText("buttonText");
buttonText = (v != null) ? v : context.getString(R.string.launch_printer);
v = mPrompt.getSpecialFormQuestionText("noPrinterErrorString");
errorString = (v != null) ? v : context.getString(R.string.no_printer);
// set button formatting
mLaunchIntentButton = new Button(getContext());
mLaunchIntentButton.setId(QuestionWidget.newUniqueId());
mLaunchIntentButton.setText(buttonText);
mLaunchIntentButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mLaunchIntentButton.setPadding(20, 20, 20, 20);
mLaunchIntentButton.setLayoutParams(params);
mLaunchIntentButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
firePrintingActivity(intentName);
} catch (ActivityNotFoundException e) {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
Toast.makeText(getContext(),
errorString, Toast.LENGTH_SHORT)
.show();
}
}
});
// finish complex layout
addView(mLaunchIntentButton);
}
protected void firePrintingActivity(String intentName) throws ActivityNotFoundException {
String s = mPrompt.getAnswerText();
Collect.getInstance().getActivityLogger().logInstanceAction(this, "launchPrinter",
intentName, mPrompt.getIndex());
Intent i = new Intent(intentName);
((Activity) getContext()).startActivity(i);
String[] splits;
if ( s != null ) {
splits = s.split("<br>");
} else {
splits = null;
}
Bundle printDataBundle = new Bundle();
String e;
if (splits != null) {
if ( splits.length >= 1 ) {
e = splits[0];
if ( e.length() > 0) {
printDataBundle.putString("BARCODE", e);
}
}
if ( splits.length >= 2 ) {
e = splits[1];
if ( e.length() > 0) {
printDataBundle.putString("QRCODE", e);
}
}
if ( splits.length > 2 ) {
String[] text = new String[splits.length-2];
for ( int j = 2 ; j < splits.length ; ++j ) {
e = splits[j];
text[j-2] = e;
}
printDataBundle.putStringArray("TEXT-STRINGS", text);
}
}
//send the printDataBundle to the activity via broadcast intent
Intent bcastIntent = new Intent(intentName + ".data");
bcastIntent.putExtra("DATA", printDataBundle);
((Activity) getContext()).sendBroadcast(bcastIntent);
}
@Override
public void clearAnswer() {
}
@Override
public IAnswerData getAnswer() {
return mPrompt.getAnswerValue();
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// focus on launch button
mLaunchIntentButton.requestFocus();
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(Collect.getInstance().getFormController().getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.isAltPressed() == true) {
return false;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mLaunchIntentButton.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mLaunchIntentButton.cancelLongPress();
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.widgets;
import java.io.File;
import java.util.Vector;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.utilities.FileUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* The Label Widget does not return an answer. The purpose of this widget is to be the top entry in
* a field-list with a bunch of list widgets below. This widget provides the labels, so that the
* list widgets can hide their labels and reduce the screen clutter. This class is essentially
* ListWidget with all the answer generating code removed.
*
* @author Jeff Beorse
*/
public class LabelWidget extends QuestionWidget {
private static final String t = "LabelWidget";
LinearLayout buttonLayout;
LinearLayout questionLayout;
Vector<SelectChoice> mItems;
private TextView mQuestionText;
private TextView mMissingImage;
private ImageView mImageView;
private TextView label;
public LabelWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mPrompt = prompt;
buttonLayout = new LinearLayout(context);
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
String imageURI = null;
imageURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_IMAGE);
// build image view (if an image is provided)
mImageView = null;
mMissingImage = null;
final int labelId = QuestionWidget.newUniqueId();
// Now set up the image view
String errorMsg = null;
if (imageURI != null) {
try {
String imageFilename =
ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Bitmap b = null;
try {
Display display =
((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
b =
FileUtils.getBitmapScaledToDisplay(imageFile, screenHeight,
screenWidth);
} catch (OutOfMemoryError e) {
errorMsg = "ERROR: " + e.getMessage();
}
if (b != null) {
mImageView = new ImageView(getContext());
mImageView.setPadding(2, 2, 2, 2);
mImageView.setAdjustViewBounds(true);
mImageView.setImageBitmap(b);
mImageView.setId(labelId);
} else if (errorMsg == null) {
// An error hasn't been logged and loading the image failed, so it's
// likely
// a bad file.
errorMsg = getContext().getString(R.string.file_invalid, imageFile);
}
} else if (errorMsg == null) {
// An error hasn't been logged. We should have an image, but the file
// doesn't
// exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
if (errorMsg != null) {
// errorMsg is only set when an error has occured
Log.e(t, errorMsg);
mMissingImage = new TextView(getContext());
mMissingImage.setText(errorMsg);
mMissingImage.setPadding(2, 2, 2, 2);
mMissingImage.setId(labelId);
}
} catch (InvalidReferenceException e) {
Log.e(t, "image invalid reference exception");
e.printStackTrace();
}
} else {
// There's no imageURI listed, so just ignore it.
}
// build text label. Don't assign the text to the built in label to he
// button because it aligns horizontally, and we want the label on top
label = new TextView(getContext());
label.setText(prompt.getSelectChoiceText(mItems.get(i)));
label.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
label.setGravity(Gravity.CENTER_HORIZONTAL);
// answer layout holds the label text/image on top and the radio button on bottom
RelativeLayout answer = new RelativeLayout(getContext());
RelativeLayout.LayoutParams headerParams =
new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
headerParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
headerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
if (mImageView != null) {
mImageView.setScaleType(ScaleType.CENTER);
answer.addView(mImageView, headerParams);
} else if (mMissingImage != null) {
answer.addView(mMissingImage, headerParams);
} else {
label.setId(labelId);
answer.addView(label, headerParams);
}
answer.setPadding(4, 0, 4, 0);
// Each button gets equal weight
LinearLayout.LayoutParams answerParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
answerParams.weight = 1;
buttonLayout.addView(answer, answerParams);
}
}
// Align the buttons so that they appear horizonally and are right justified
// buttonLayout.setGravity(Gravity.RIGHT);
buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
// LinearLayout.LayoutParams params = new
// LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
// buttonLayout.setLayoutParams(params);
// The buttons take up the right half of the screen
LinearLayout.LayoutParams buttonParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
buttonParams.weight = 1;
questionLayout.addView(buttonLayout, buttonParams);
addView(questionLayout);
}
@Override
public void clearAnswer() {
// Do nothing, no answers to clear
}
@Override
public IAnswerData getAnswer() {
return null;
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
// Override QuestionWidget's add question text. Build it the same
// but add it to the relative layout
protected void addQuestionText(FormEntryPrompt p) {
// Add the text view. Textview always exists, regardless of whether there's text.
mQuestionText = new TextView(getContext());
mQuestionText.setText(p.getLongText());
mQuestionText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontsize);
mQuestionText.setTypeface(null, Typeface.BOLD);
mQuestionText.setPadding(0, 0, 0, 7);
mQuestionText.setId(QuestionWidget.newUniqueId()); // assign random id
// Wrap to the size of the parent view
mQuestionText.setHorizontallyScrolling(false);
if (p.getLongText() == null) {
mQuestionText.setVisibility(GONE);
}
// Put the question text on the left half of the screen
LinearLayout.LayoutParams labelParams =
new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
labelParams.weight = 1;
questionLayout = new LinearLayout(getContext());
questionLayout.setOrientation(LinearLayout.HORIZONTAL);
questionLayout.addView(mQuestionText, labelParams);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mQuestionText.cancelLongPress();
if (mMissingImage != null) {
mMissingImage.cancelLongPress();
}
if (mImageView != null) {
mImageView.cancelLongPress();
}
if (label != null) {
label.cancelLongPress();
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mQuestionText.setOnLongClickListener(l);
if (mMissingImage != null) {
mMissingImage.setOnLongClickListener(l);
}
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
if (label != null) {
label.setOnLongClickListener(l);
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.views.MediaLayout;
import android.content.Context;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.Vector;
/**
* SelctMultiWidget handles multiple selection fields using checkboxes.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class SelectMultiWidget extends QuestionWidget {
private boolean mCheckboxInit = true;
Vector<SelectChoice> mItems;
private ArrayList<CheckBox> mCheckboxes;
@SuppressWarnings("unchecked")
public SelectMultiWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mPrompt = prompt;
mCheckboxes = new ArrayList<CheckBox>();
mItems = prompt.getSelectChoices();
setOrientation(LinearLayout.VERTICAL);
Vector<Selection> ve = new Vector<Selection>();
if (prompt.getAnswerValue() != null) {
ve = (Vector<Selection>) prompt.getAnswerValue().getValue();
}
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
// no checkbox group so id by answer + offset
CheckBox c = new CheckBox(getContext());
c.setTag(Integer.valueOf(i));
c.setId(QuestionWidget.newUniqueId());
c.setText(prompt.getSelectChoiceText(mItems.get(i)));
c.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
c.setFocusable(!prompt.isReadOnly());
c.setEnabled(!prompt.isReadOnly());
for (int vi = 0; vi < ve.size(); vi++) {
// match based on value, not key
if (mItems.get(i).getValue().equals(ve.elementAt(vi).getValue())) {
c.setChecked(true);
break;
}
}
mCheckboxes.add(c);
// when clicked, check for readonly before toggling
c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!mCheckboxInit && mPrompt.isReadOnly()) {
if (buttonView.isChecked()) {
buttonView.setChecked(false);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
} else {
buttonView.setChecked(true);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
}
}
}
});
String audioURI = null;
audioURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_AUDIO);
String imageURI = null;
imageURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_IMAGE);
String videoURI = null;
videoURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "video");
String bigImageURI = null;
bigImageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "big-image");
MediaLayout mediaLayout = new MediaLayout(getContext());
mediaLayout.setAVT(prompt.getIndex(), "." + Integer.toString(i), c, audioURI, imageURI, videoURI, bigImageURI);
addView(mediaLayout);
// Last, add the dividing line between elements (except for the last element)
ImageView divider = new ImageView(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
if (i != mItems.size() - 1) {
addView(divider);
}
}
}
mCheckboxInit = false;
}
@Override
public void clearAnswer() {
for ( CheckBox c : mCheckboxes ) {
if ( c.isChecked() ) {
c.setChecked(false);
}
}
}
@Override
public IAnswerData getAnswer() {
Vector<Selection> vc = new Vector<Selection>();
for ( int i = 0; i < mCheckboxes.size() ; ++i ) {
CheckBox c = mCheckboxes.get(i);
if ( c.isChecked() ) {
vc.add(new Selection(mItems.get(i)));
}
}
if (vc.size() == 0) {
return null;
} else {
return new SelectMultiData(vc);
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (CheckBox c : mCheckboxes) {
c.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (CheckBox c : mCheckboxes) {
c.cancelLongPress();
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.Toast;
import java.io.File;
/**
* Widget that allows user to take pictures, sounds or video and add them to the
* form.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class VideoWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "MediaWidget";
private Button mCaptureButton;
private Button mPlayButton;
private Button mChooseButton;
private String mBinaryName;
private String mInstanceFolder;
public VideoWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mInstanceFolder = Collect.getInstance().getFormController()
.getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
// setup capture button
mCaptureButton = new Button(getContext());
mCaptureButton.setId(QuestionWidget.newUniqueId());
mCaptureButton.setText(getContext().getString(R.string.capture_video));
mCaptureButton
.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mCaptureButton.setPadding(20, 20, 20, 20);
mCaptureButton.setEnabled(!prompt.isReadOnly());
mCaptureButton.setLayoutParams(params);
// launch capture intent on click
mCaptureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(VideoWidget.this, "captureButton",
"click", mPrompt.getIndex());
Intent i = new Intent(
android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Video.Media.EXTERNAL_CONTENT_URI.toString());
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.VIDEO_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"capture video"), Toast.LENGTH_SHORT)
.show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
});
// setup capture button
mChooseButton = new Button(getContext());
mChooseButton.setId(QuestionWidget.newUniqueId());
mChooseButton.setText(getContext().getString(R.string.choose_video));
mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mChooseButton.setPadding(20, 20, 20, 20);
mChooseButton.setEnabled(!prompt.isReadOnly());
mChooseButton.setLayoutParams(params);
// launch capture intent on click
mChooseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(VideoWidget.this, "chooseButton",
"click", mPrompt.getIndex());
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("video/*");
// Intent i =
// new Intent(Intent.ACTION_PICK,
// android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.VIDEO_CHOOSER);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"choose video "), Toast.LENGTH_SHORT)
.show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
});
// setup play button
mPlayButton = new Button(getContext());
mPlayButton.setId(QuestionWidget.newUniqueId());
mPlayButton.setText(getContext().getString(R.string.play_video));
mPlayButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mPlayButton.setPadding(20, 20, 20, 20);
mPlayButton.setLayoutParams(params);
// on play, launch the appropriate viewer
mPlayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(VideoWidget.this, "playButton",
"click", mPrompt.getIndex());
Intent i = new Intent("android.intent.action.VIEW");
File f = new File(mInstanceFolder + File.separator
+ mBinaryName);
i.setDataAndType(Uri.fromFile(f), "video/*");
try {
((Activity) getContext()).startActivity(i);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"video video"), Toast.LENGTH_SHORT).show();
}
}
});
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
if (mBinaryName != null) {
mPlayButton.setEnabled(true);
} else {
mPlayButton.setEnabled(false);
}
// finish complex layout
addView(mCaptureButton);
addView(mChooseButton);
addView(mPlayButton);
// and hide the capture and choose button if read-only
if (mPrompt.isReadOnly()) {
mCaptureButton.setVisibility(View.GONE);
mChooseButton.setVisibility(View.GONE);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteVideoFileFromMediaProvider(mInstanceFolder + File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
// reset buttons
mPlayButton.setEnabled(false);
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
private String getPathFromUri(Uri uri) {
if (uri.toString().startsWith("file")) {
return uri.toString().substring(6);
} else {
String[] videoProjection = { Video.Media.DATA };
Cursor c = null;
try {
c = getContext().getContentResolver().query(uri,
videoProjection, null, null, null);
int column_index = c.getColumnIndexOrThrow(Video.Media.DATA);
String videoPath = null;
if (c.getCount() > 0) {
c.moveToFirst();
videoPath = c.getString(column_index);
}
return videoPath;
} finally {
if (c != null) {
c.close();
}
}
}
}
@Override
public void setBinaryData(Object binaryuri) {
// you are replacing an answer. remove the media.
if (mBinaryName != null) {
deleteMedia();
}
// get the file path and create a copy in the instance folder
String binaryPath = getPathFromUri((Uri) binaryuri);
String extension = binaryPath.substring(binaryPath.lastIndexOf("."));
String destVideoPath = mInstanceFolder + File.separator
+ System.currentTimeMillis() + extension;
File source = new File(binaryPath);
File newVideo = new File(destVideoPath);
FileUtils.copyFile(source, newVideo);
if (newVideo.exists()) {
// Add the copy to the content provier
ContentValues values = new ContentValues(6);
values.put(Video.Media.TITLE, newVideo.getName());
values.put(Video.Media.DISPLAY_NAME, newVideo.getName());
values.put(Video.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Video.Media.DATA, newVideo.getAbsolutePath());
Uri VideoURI = getContext().getContentResolver().insert(
Video.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting VIDEO returned uri = " + VideoURI.toString());
} else {
Log.e(t, "Inserting Video file FAILED");
}
mBinaryName = newVideo.getName();
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(
Collect.getInstance().getFormController()
.getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mCaptureButton.setOnLongClickListener(l);
mChooseButton.setOnLongClickListener(l);
mPlayButton.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mCaptureButton.cancelLongPress();
mChooseButton.cancelLongPress();
mPlayButton.cancelLongPress();
}
}
| Java |
/*
* Copyright (C) 2011 University of Washington
*
* 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.odk.collect.android.widgets;
import java.io.File;
import java.util.Vector;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.core.reference.InvalidReferenceException;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.AdvanceToNextListener;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.views.AudioButton.AudioHandler;
import org.odk.collect.android.views.ExpandedHeightGridView;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
/**
* GridWidget handles select-one fields using a grid of icons. The user clicks the desired icon and
* the background changes from black to orange. If text, audio, or video are specified in the select
* answers they are ignored.
*
* @author Jeff Beorse (jeff@beorse.net)
*/
public class GridWidget extends QuestionWidget {
// The RGB value for the orange background
public static final int orangeRedVal = 255;
public static final int orangeGreenVal = 140;
public static final int orangeBlueVal = 0;
private static final int HORIZONTAL_PADDING = 7;
private static final int VERTICAL_PADDING = 5;
private static final int SPACING = 2;
private static final int IMAGE_PADDING = 8;
private static final int SCROLL_WIDTH = 16;
Vector<SelectChoice> mItems;
// The possible select choices
String[] choices;
// The Gridview that will hold the icons
ExpandedHeightGridView gridview;
// Defines which icon is selected
boolean[] selected;
// The image views for each of the icons
View[] imageViews;
AudioHandler[] audioHandlers;
// The number of columns in the grid, can be user defined (<= 0 if unspecified)
int numColumns;
// Whether to advance immediately after the image is clicked
boolean quickAdvance;
AdvanceToNextListener listener;
int resizeWidth;
public GridWidget(Context context, FormEntryPrompt prompt, int numColumns,
final boolean quickAdvance) {
super(context, prompt);
mItems = prompt.getSelectChoices();
mPrompt = prompt;
listener = (AdvanceToNextListener) context;
selected = new boolean[mItems.size()];
choices = new String[mItems.size()];
gridview = new ExpandedHeightGridView(context);
imageViews = new View[mItems.size()];
audioHandlers = new AudioHandler[mItems.size()];
// The max width of an icon in a given column. Used to line
// up the columns and automatically fit the columns in when
// they are chosen automatically
int maxColumnWidth = -1;
int maxCellHeight = -1;
this.numColumns = numColumns;
for (int i = 0; i < mItems.size(); i++) {
imageViews[i] = new ImageView(getContext());
}
this.quickAdvance = quickAdvance;
Display display =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
if ( display.getOrientation() % 2 == 1 ) {
// rotated 90 degrees...
int temp = screenWidth;
screenWidth = screenHeight;
screenHeight = temp;
}
if ( numColumns > 0 ) {
resizeWidth = ((screenWidth - 2*HORIZONTAL_PADDING - SCROLL_WIDTH - (IMAGE_PADDING+SPACING)*numColumns) / numColumns );
}
// Build view
for (int i = 0; i < mItems.size(); i++) {
SelectChoice sc = mItems.get(i);
int curHeight = -1;
// Create an audioHandler iff there is an audio prompt associated with this selection.
String audioURI =
prompt.getSpecialFormSelectChoiceText(sc, FormEntryCaption.TEXT_FORM_AUDIO);
if ( audioURI != null) {
audioHandlers[i] = new AudioHandler(prompt.getIndex(), sc.getValue(), audioURI);
} else {
audioHandlers[i] = null;
}
// Read the image sizes and set maxColumnWidth. This allows us to make sure all of our
// columns are going to fit
String imageURI =
prompt.getSpecialFormSelectChoiceText(sc, FormEntryCaption.TEXT_FORM_IMAGE);
String errorMsg = null;
if (imageURI != null) {
choices[i] = imageURI;
String imageFilename;
try {
imageFilename = ReferenceManager._().DeriveReference(imageURI).getLocalURI();
final File imageFile = new File(imageFilename);
if (imageFile.exists()) {
Bitmap b =
FileUtils
.getBitmapScaledToDisplay(imageFile, screenHeight, screenWidth);
if (b != null) {
if (b.getWidth() > maxColumnWidth) {
maxColumnWidth = b.getWidth();
}
ImageView imageView = (ImageView) imageViews[i];
imageView.setBackgroundColor(Color.WHITE);
if ( numColumns > 0 ) {
int resizeHeight = (b.getHeight() * resizeWidth) / b.getWidth();
b = Bitmap.createScaledBitmap(b, resizeWidth, resizeHeight, false);
}
imageView.setPadding(IMAGE_PADDING, IMAGE_PADDING, IMAGE_PADDING, IMAGE_PADDING);
imageView.setImageBitmap(b);
imageView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.WRAP_CONTENT, ListView.LayoutParams.WRAP_CONTENT));
imageView.setScaleType(ScaleType.FIT_XY);
imageView.measure(0, 0);
curHeight = imageView.getMeasuredHeight();
} else {
// Loading the image failed, so it's likely a bad file.
errorMsg = getContext().getString(R.string.file_invalid, imageFile);
}
} else {
// We should have an image, but the file doesn't exist.
errorMsg = getContext().getString(R.string.file_missing, imageFile);
}
} catch (InvalidReferenceException e) {
Log.e("GridWidget", "image invalid reference exception");
e.printStackTrace();
}
} else {
errorMsg = "";
}
if (errorMsg != null) {
choices[i] = prompt.getSelectChoiceText(sc);
TextView missingImage = new TextView(getContext());
missingImage.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
missingImage.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
missingImage.setPadding(IMAGE_PADDING, IMAGE_PADDING, IMAGE_PADDING, IMAGE_PADDING);
if ( choices[i] != null && choices[i].length() != 0 ) {
missingImage.setText(choices[i]);
} else {
// errorMsg is only set when an error has occurred
Log.e("GridWidget", errorMsg);
missingImage.setText(errorMsg);
}
if ( numColumns > 0 ) {
maxColumnWidth = resizeWidth;
// force max width to find needed height...
missingImage.setMaxWidth(resizeWidth);
missingImage.measure(MeasureSpec.makeMeasureSpec(resizeWidth, MeasureSpec.EXACTLY), 0);
curHeight = missingImage.getMeasuredHeight();
} else {
missingImage.measure(0, 0);
int width = missingImage.getMeasuredWidth();
if (width > maxColumnWidth) {
maxColumnWidth = width;
}
curHeight = missingImage.getMeasuredHeight();
}
imageViews[i] = missingImage;
}
// if we get a taller image/text, force all cells to be that height
// could also set cell heights on a per-row basis if user feedback requests it.
if ( curHeight > maxCellHeight ) {
maxCellHeight = curHeight;
for ( int j = 0 ; j < i ; j++ ) {
imageViews[j].setMinimumHeight(maxCellHeight);
}
}
imageViews[i].setMinimumHeight(maxCellHeight);
}
// Read the screen dimensions and fit the grid view to them. It is important that the grid
// knows how far out it can stretch.
if ( numColumns > 0 ) {
// gridview.setNumColumns(numColumns);
gridview.setNumColumns(GridView.AUTO_FIT);
} else {
resizeWidth = maxColumnWidth;
gridview.setNumColumns(GridView.AUTO_FIT);
}
gridview.setColumnWidth(resizeWidth);
gridview.setPadding(HORIZONTAL_PADDING, VERTICAL_PADDING, HORIZONTAL_PADDING, VERTICAL_PADDING);
gridview.setHorizontalSpacing(SPACING);
gridview.setVerticalSpacing(SPACING);
gridview.setGravity(Gravity.CENTER);
gridview.setScrollContainer(false);
gridview.setStretchMode(GridView.NO_STRETCH);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Imitate the behavior of a radio button. Clear all buttons
// and then check the one clicked by the user. Update the
// background color accordingly
for (int i = 0; i < selected.length; i++) {
// if we have an audio handler, be sure audio is stopped.
if ( selected[i] && (audioHandlers[i] != null)) {
audioHandlers[i].stopPlaying();
}
selected[i] = false;
if (imageViews[i] != null) {
imageViews[i].setBackgroundColor(Color.WHITE);
}
}
selected[position] = true;
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
mItems.get(position).getValue(), mPrompt.getIndex());
imageViews[position].setBackgroundColor(Color.rgb(orangeRedVal, orangeGreenVal,
orangeBlueVal));
if (quickAdvance) {
listener.advance();
} else if ( audioHandlers[position] != null ) {
audioHandlers[position].playAudio(getContext());
}
}
});
// Fill in answer
String s = null;
if (prompt.getAnswerValue() != null) {
s = ((Selection) prompt.getAnswerValue().getValue()).getValue();
}
for (int i = 0; i < mItems.size(); ++i) {
String sMatch = mItems.get(i).getValue();
selected[i] = sMatch.equals(s);
if (selected[i]) {
imageViews[i].setBackgroundColor(Color.rgb(orangeRedVal, orangeGreenVal,
orangeBlueVal));
} else {
imageViews[i].setBackgroundColor(Color.WHITE);
}
}
// Use the custom image adapter and initialize the grid view
ImageAdapter ia = new ImageAdapter(getContext(), choices);
gridview.setAdapter(ia);
addView(gridview, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
@Override
public IAnswerData getAnswer() {
for (int i = 0; i < choices.length; ++i) {
if (selected[i]) {
SelectChoice sc = mItems.elementAt(i);
return new SelectOneData(new Selection(sc));
}
}
return null;
}
@Override
public void clearAnswer() {
for (int i = 0; i < mItems.size(); ++i) {
selected[i] = false;
imageViews[i].setBackgroundColor(Color.WHITE);
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
// Custom image adapter. Most of the code is copied from
// media layout for using a picture.
private class ImageAdapter extends BaseAdapter {
private String[] choices;
public ImageAdapter(Context c, String[] choices) {
this.choices = choices;
}
public int getCount() {
return choices.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
if ( position < imageViews.length ) {
return imageViews[position];
} else {
return convertView;
}
}
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
gridview.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
gridview.cancelLongPress();
}
}
| Java |
/*
* Copyright (C) 2012 University of Washington
*
* 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.odk.collect.android.widgets;
import java.io.File;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.DrawActivity;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Image widget that supports annotations on the image.
*
* @author BehrAtherton@gmail.com
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*
*/
public class AnnotateWidget extends QuestionWidget implements IBinaryWidget {
private final static String t = "AnnotateWidget";
private Button mCaptureButton;
private Button mChooseButton;
private Button mAnnotateButton;
private ImageView mImageView;
private String mBinaryName;
private String mInstanceFolder;
private TextView mErrorTextView;
public AnnotateWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mInstanceFolder = Collect.getInstance().getFormController()
.getInstancePath().getParent();
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
mErrorTextView = new TextView(context);
mErrorTextView.setId(QuestionWidget.newUniqueId());
mErrorTextView.setText("Selected file is not a valid image");
// setup capture button
mCaptureButton = new Button(getContext());
mCaptureButton.setId(QuestionWidget.newUniqueId());
mCaptureButton.setText(getContext().getString(R.string.capture_image));
mCaptureButton
.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mCaptureButton.setPadding(20, 20, 20, 20);
mCaptureButton.setEnabled(!prompt.isReadOnly());
mCaptureButton.setLayoutParams(params);
// launch capture intent on click
mCaptureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "captureButton", "click",
mPrompt.getIndex());
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// We give the camera an absolute filename/path where to put the
// picture because of bug:
// http://code.google.com/p/android/issues/detail?id=1480
// The bug appears to be fixed in Android 2.0+, but as of feb 2,
// 2010, G1 phones only run 1.6. Without specifying the path the
// images returned by the camera in 1.6 (and earlier) are ~1/4
// the size. boo.
// if this gets modified, the onActivityResult in
// FormEntyActivity will also need to be updated.
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.IMAGE_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"image capture"), Toast.LENGTH_SHORT)
.show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
});
// setup chooser button
mChooseButton = new Button(getContext());
mChooseButton.setId(QuestionWidget.newUniqueId());
mChooseButton.setText(getContext().getString(R.string.choose_image));
mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mChooseButton.setPadding(20, 20, 20, 20);
mChooseButton.setEnabled(!prompt.isReadOnly());
mChooseButton.setLayoutParams(params);
// launch capture intent on click
mChooseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "chooseButton", "click",
mPrompt.getIndex());
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("image/*");
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.IMAGE_CHOOSER);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"choose image"), Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
});
// setup Blank Image Button
mAnnotateButton = new Button(getContext());
mAnnotateButton.setId(QuestionWidget.newUniqueId());
mAnnotateButton.setText(getContext().getString(R.string.markup_image));
mAnnotateButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP,
mAnswerFontsize);
mAnnotateButton.setPadding(20, 20, 20, 20);
mAnnotateButton.setEnabled(false);
mAnnotateButton.setLayoutParams(params);
// launch capture intent on click
mAnnotateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "annotateButton", "click",
mPrompt.getIndex());
launchAnnotateActivity();
}
});
// finish complex layout
addView(mCaptureButton);
addView(mChooseButton);
addView(mAnnotateButton);
addView(mErrorTextView);
// and hide the capture, choose and annotate button if read-only
if (prompt.isReadOnly()) {
mCaptureButton.setVisibility(View.GONE);
mChooseButton.setVisibility(View.GONE);
mAnnotateButton.setVisibility(View.GONE);
}
mErrorTextView.setVisibility(View.GONE);
// retrieve answer from data model and update ui
mBinaryName = prompt.getAnswerText();
// Only add the imageView if the user has taken a picture
if (mBinaryName != null) {
if (!prompt.isReadOnly()) {
mAnnotateButton.setEnabled(true);
}
mImageView = new ImageView(getContext());
mImageView.setId(QuestionWidget.newUniqueId());
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
File f = new File(mInstanceFolder + File.separator + mBinaryName);
if (f.exists()) {
Bitmap bmp = FileUtils.getBitmapScaledToDisplay(f,
screenHeight, screenWidth);
if (bmp == null) {
mErrorTextView.setVisibility(View.VISIBLE);
}
mImageView.setImageBitmap(bmp);
} else {
mImageView.setImageBitmap(null);
}
mImageView.setPadding(10, 10, 10, 10);
mImageView.setAdjustViewBounds(true);
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "viewImage", "click",
mPrompt.getIndex());
launchAnnotateActivity();
}
});
addView(mImageView);
}
}
private void launchAnnotateActivity() {
mErrorTextView.setVisibility(View.GONE);
Intent i = new Intent(getContext(), DrawActivity.class);
i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_ANNOTATE);
// copy...
if (mBinaryName != null) {
File f = new File(mInstanceFolder + File.separator + mBinaryName);
i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f));
}
i.putExtra(DrawActivity.EXTRA_OUTPUT,
Uri.fromFile(new File(Collect.TMPFILE_PATH)));
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.ANNOTATE_IMAGE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(R.string.activity_not_found,
"annotate image"), Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
private void deleteMedia() {
// get the file path and delete the file
String name = mBinaryName;
// clean up variables
mBinaryName = null;
// delete from media provider
int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder
+ File.separator + name);
Log.i(t, "Deleted " + del + " rows from media content provider");
}
@Override
public void clearAnswer() {
// remove the file
deleteMedia();
mImageView.setImageBitmap(null);
mErrorTextView.setVisibility(View.GONE);
if (!mPrompt.isReadOnly()) {
mAnnotateButton.setEnabled(false);
}
// reset buttons
mCaptureButton.setText(getContext().getString(R.string.capture_image));
}
@Override
public IAnswerData getAnswer() {
if (mBinaryName != null) {
return new StringData(mBinaryName.toString());
} else {
return null;
}
}
@Override
public void setBinaryData(Object newImageObj) {
// you are replacing an answer. delete the previous image using the
// content provider.
if (mBinaryName != null) {
deleteMedia();
}
File newImage = (File) newImageObj;
if (newImage.exists()) {
// Add the new image to the Media content provider so that the
// viewing is fast in Android 2.0+
ContentValues values = new ContentValues(6);
values.put(Images.Media.TITLE, newImage.getName());
values.put(Images.Media.DISPLAY_NAME, newImage.getName());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpeg");
values.put(Images.Media.DATA, newImage.getAbsolutePath());
Uri imageURI = getContext().getContentResolver().insert(
Images.Media.EXTERNAL_CONTENT_URI, values);
Log.i(t, "Inserting image returned uri = " + imageURI.toString());
mBinaryName = newImage.getName();
Log.i(t, "Setting current answer to " + newImage.getName());
} else {
Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
}
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(
Collect.getInstance().getFormController()
.getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mCaptureButton.setOnLongClickListener(l);
mChooseButton.setOnLongClickListener(l);
mAnnotateButton.setOnLongClickListener(l);
if (mImageView != null) {
mImageView.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mCaptureButton.cancelLongPress();
mChooseButton.cancelLongPress();
mAnnotateButton.cancelLongPress();
if (mImageView != null) {
mImageView.cancelLongPress();
}
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* Widget that allows user to scan barcodes and add them to the form.
*
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class BarcodeWidget extends QuestionWidget implements IBinaryWidget {
private Button mGetBarcodeButton;
private TextView mStringAnswer;
public BarcodeWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
// set button formatting
mGetBarcodeButton = new Button(getContext());
mGetBarcodeButton.setId(QuestionWidget.newUniqueId());
mGetBarcodeButton.setText(getContext().getString(R.string.get_barcode));
mGetBarcodeButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP,
mAnswerFontsize);
mGetBarcodeButton.setPadding(20, 20, 20, 20);
mGetBarcodeButton.setEnabled(!prompt.isReadOnly());
mGetBarcodeButton.setLayoutParams(params);
// launch barcode capture intent on click
mGetBarcodeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "recordBarcode", "click",
mPrompt.getIndex());
Intent i = new Intent("com.google.zxing.client.android.SCAN");
try {
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.BARCODE_CAPTURE);
} catch (ActivityNotFoundException e) {
Toast.makeText(
getContext(),
getContext().getString(
R.string.barcode_scanner_error),
Toast.LENGTH_SHORT).show();
Collect.getInstance().getFormController()
.setIndexWaitingForData(null);
}
}
});
// set text formatting
mStringAnswer = new TextView(getContext());
mStringAnswer.setId(QuestionWidget.newUniqueId());
mStringAnswer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mStringAnswer.setGravity(Gravity.CENTER);
String s = prompt.getAnswerText();
if (s != null) {
mGetBarcodeButton.setText(getContext().getString(
R.string.replace_barcode));
mStringAnswer.setText(s);
}
// finish complex layout
addView(mGetBarcodeButton);
addView(mStringAnswer);
}
@Override
public void clearAnswer() {
mStringAnswer.setText(null);
mGetBarcodeButton.setText(getContext().getString(R.string.get_barcode));
}
@Override
public IAnswerData getAnswer() {
String s = mStringAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
return new StringData(s);
}
}
/**
* Allows answer to be set externally in {@Link FormEntryActivity}.
*/
@Override
public void setBinaryData(Object answer) {
mStringAnswer.setText((String) answer);
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(
Collect.getInstance().getFormController()
.getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mStringAnswer.setOnLongClickListener(l);
mGetBarcodeButton.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mGetBarcodeButton.cancelLongPress();
mStringAnswer.cancelLongPress();
}
}
| Java |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
import java.text.DecimalFormat;
import org.javarosa.core.model.data.GeoPointData;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.activities.GeoPointActivity;
import org.odk.collect.android.activities.GeoPointMapActivity;
import org.odk.collect.android.application.Collect;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
/**
* GeoPointWidget is the widget that allows the user to get GPS readings.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class GeoPointWidget extends QuestionWidget implements IBinaryWidget {
public static final String LOCATION = "gp";
public static final String ACCURACY_THRESHOLD = "accuracyThreshold";
public static final double DEFAULT_LOCATION_ACCURACY = 5.0;
private Button mGetLocationButton;
private Button mViewButton;
private TextView mStringAnswer;
private TextView mAnswerDisplay;
private boolean mUseMaps;
private String mAppearance;
private double mAccuracyThreshold;
public GeoPointWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mUseMaps = false;
mAppearance = prompt.getAppearanceHint();
String acc = prompt.getQuestion().getAdditionalAttribute(null, ACCURACY_THRESHOLD);
if ( acc != null && acc.length() != 0 ) {
mAccuracyThreshold = Double.parseDouble(acc);
} else {
mAccuracyThreshold = DEFAULT_LOCATION_ACCURACY;
}
setOrientation(LinearLayout.VERTICAL);
TableLayout.LayoutParams params = new TableLayout.LayoutParams();
params.setMargins(7, 5, 7, 5);
mGetLocationButton = new Button(getContext());
mGetLocationButton.setId(QuestionWidget.newUniqueId());
mGetLocationButton.setPadding(20, 20, 20, 20);
mGetLocationButton.setText(getContext()
.getString(R.string.get_location));
mGetLocationButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP,
mAnswerFontsize);
mGetLocationButton.setEnabled(!prompt.isReadOnly());
mGetLocationButton.setLayoutParams(params);
if ( prompt.isReadOnly()) {
mGetLocationButton.setVisibility(View.GONE);
}
// setup play button
mViewButton = new Button(getContext());
mViewButton.setId(QuestionWidget.newUniqueId());
mViewButton.setText(getContext().getString(R.string.show_location));
mViewButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mViewButton.setPadding(20, 20, 20, 20);
mViewButton.setLayoutParams(params);
// on play, launch the appropriate viewer
mViewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "showLocation", "click",
mPrompt.getIndex());
String s = mStringAnswer.getText().toString();
String[] sa = s.split(" ");
double gp[] = new double[4];
gp[0] = Double.valueOf(sa[0]).doubleValue();
gp[1] = Double.valueOf(sa[1]).doubleValue();
gp[2] = Double.valueOf(sa[2]).doubleValue();
gp[3] = Double.valueOf(sa[3]).doubleValue();
Intent i = new Intent(getContext(), GeoPointMapActivity.class);
i.putExtra(LOCATION, gp);
i.putExtra(ACCURACY_THRESHOLD, mAccuracyThreshold);
((Activity) getContext()).startActivity(i);
}
});
mStringAnswer = new TextView(getContext());
mStringAnswer.setId(QuestionWidget.newUniqueId());
mAnswerDisplay = new TextView(getContext());
mAnswerDisplay.setId(QuestionWidget.newUniqueId());
mAnswerDisplay
.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
mAnswerDisplay.setGravity(Gravity.CENTER);
String s = prompt.getAnswerText();
if (s != null && !s.equals("")) {
mGetLocationButton.setText(getContext().getString(
R.string.replace_location));
setBinaryData(s);
mViewButton.setEnabled(true);
} else {
mViewButton.setEnabled(false);
}
// use maps or not
if (mAppearance != null && mAppearance.equalsIgnoreCase("maps")) {
try {
// do google maps exist on the device
Class.forName("com.google.android.maps.MapActivity");
mUseMaps = true;
} catch (ClassNotFoundException e) {
mUseMaps = false;
}
}
// when you press the button
mGetLocationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "recordLocation", "click",
mPrompt.getIndex());
Intent i = null;
if (mUseMaps) {
i = new Intent(getContext(), GeoPointMapActivity.class);
} else {
i = new Intent(getContext(), GeoPointActivity.class);
}
i.putExtra(ACCURACY_THRESHOLD, mAccuracyThreshold);
Collect.getInstance().getFormController()
.setIndexWaitingForData(mPrompt.getIndex());
((Activity) getContext()).startActivityForResult(i,
FormEntryActivity.LOCATION_CAPTURE);
}
});
// finish complex layout
// retrieve answer from data model and update ui
addView(mGetLocationButton);
if (mUseMaps) {
addView(mViewButton);
}
addView(mAnswerDisplay);
}
@Override
public void clearAnswer() {
mStringAnswer.setText(null);
mAnswerDisplay.setText(null);
mGetLocationButton.setText(getContext()
.getString(R.string.get_location));
}
@Override
public IAnswerData getAnswer() {
String s = mStringAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
// segment lat and lon
String[] sa = s.split(" ");
double gp[] = new double[4];
gp[0] = Double.valueOf(sa[0]).doubleValue();
gp[1] = Double.valueOf(sa[1]).doubleValue();
gp[2] = Double.valueOf(sa[2]).doubleValue();
gp[3] = Double.valueOf(sa[3]).doubleValue();
return new GeoPointData(gp);
} catch (Exception NumberFormatException) {
return null;
}
}
}
private String truncateDouble(String s) {
DecimalFormat df = new DecimalFormat("#.##");
return df.format(Double.valueOf(s));
}
private String formatGps(double coordinates, String type) {
String location = Double.toString(coordinates);
String degreeSign = "\u00B0";
String degree = location.substring(0, location.indexOf("."))
+ degreeSign;
location = "0." + location.substring(location.indexOf(".") + 1);
double temp = Double.valueOf(location) * 60;
location = Double.toString(temp);
String mins = location.substring(0, location.indexOf(".")) + "'";
location = "0." + location.substring(location.indexOf(".") + 1);
temp = Double.valueOf(location) * 60;
location = Double.toString(temp);
String secs = location.substring(0, location.indexOf(".")) + '"';
if (type.equalsIgnoreCase("lon")) {
if (degree.startsWith("-")) {
degree = "W " + degree.replace("-", "") + mins + secs;
} else
degree = "E " + degree.replace("-", "") + mins + secs;
} else {
if (degree.startsWith("-")) {
degree = "S " + degree.replace("-", "") + mins + secs;
} else
degree = "N " + degree.replace("-", "") + mins + secs;
}
return degree;
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setBinaryData(Object answer) {
String s = (String) answer;
mStringAnswer.setText(s);
String[] sa = s.split(" ");
mAnswerDisplay.setText(getContext().getString(R.string.latitude) + ": "
+ formatGps(Double.parseDouble(sa[0]), "lat") + "\n"
+ getContext().getString(R.string.longitude) + ": "
+ formatGps(Double.parseDouble(sa[1]), "lon") + "\n"
+ getContext().getString(R.string.altitude) + ": "
+ truncateDouble(sa[2]) + "m\n"
+ getContext().getString(R.string.accuracy) + ": "
+ truncateDouble(sa[3]) + "m");
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public boolean isWaitingForBinaryData() {
return mPrompt.getIndex().equals(
Collect.getInstance().getFormController()
.getIndexWaitingForData());
}
@Override
public void cancelWaitingForBinaryData() {
Collect.getInstance().getFormController().setIndexWaitingForData(null);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mViewButton.setOnLongClickListener(l);
mGetLocationButton.setOnLongClickListener(l);
mStringAnswer.setOnLongClickListener(l);
mAnswerDisplay.setOnLongClickListener(l);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mViewButton.cancelLongPress();
mGetLocationButton.cancelLongPress();
mStringAnswer.cancelLongPress();
mAnswerDisplay.cancelLongPress();
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.